Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat(turnrewind): audit P1 hardening batch (fences, locks, routes, concurrency)

yingtianlan4ebdcd12848e
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts b/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts
index 6fc3da58..49ec5f61 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/apply.ts
@@ -34,8 +34,8 @@ import {
getPendingPlanRow,
getPendingPlanStatus,
getTurn,
+ hasNeedsRecoveryWorkspace,
insertTurn,
- listNeedsRecoveryWorkspaces,
markPendingPlanApplied,
markPendingPlanCancelled,
openLedger,
@@ -190,7 +190,8 @@ export function apply(ctx: HostApplyContext): void {
// validation, conflict checks and the private snapshot repository remain.
const dataRoot = rootDir()
const ledger = openLedger(dataRoot)
- const recoveryWorkspaces = new Set(listNeedsRecoveryWorkspaces(ledger))
+ // P1-6:needs-recovery 围栏改为实时查库(hasNeedsRecoveryWorkspace),
+ // 运行期落围栏的 workspace 立即被拦截,不再依赖启动时加载的内存快照。
// One-shot at startup: consumed notices older than a week have no readers
// left (their dedup window is long gone) and would otherwise accumulate
// without bound on long-lived installs.
@@ -312,7 +313,7 @@ export function apply(ctx: HostApplyContext): void {
}
const workspaceKey = workspaceKeyFor(workspaceDir)
- if (recoveryWorkspaces.has(workspaceKey)) {
+ if (hasNeedsRecoveryWorkspace(ledger, workspaceKey)) {
recordSkipped(key, sessionId, workspaceKey, startedAt, 'TURNREWIND_RECOVERY_REQUIRED: a previous undo or redo was interrupted; inspect the workspace and clear its recovery state before using rewind again')
return undefined
}
@@ -435,12 +436,20 @@ export function apply(ctx: HostApplyContext): void {
// Same-origin HTTP routes powering the ✓/✗ buttons on the undo card: the
// harness page itself is served from this host, so these need no extra
// auth wiring (and mutations are loopback-only on top).
+ // P1-3: planId 必须是 UUID 形态、session 长度受限且无控制字符——
+ // 防止任意字符串进入日志与 SQLite 语义。
+ const PLAN_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+ const validPlanId = (value: string): boolean => PLAN_ID_RE.test(value)
+ const validSessionId = (value: string): boolean =>
+ value.length >= 1 && value.length <= 200 && [...value].every(ch => ch.charCodeAt(0) > 31)
ctx.effect(() => {
function confirmRoute(body: Record<string, unknown>): Promise<[number, unknown]> | [number, unknown] {
const planId = String(body.planId ?? '')
const sessionId = String(body.sessionId ?? '')
if (planId === '' || sessionId === '')
return [400, { error: 'planId and sessionId are required' }]
+ if (!validPlanId(planId) || !validSessionId(sessionId))
+ return [400, { error: 'planId or sessionId is malformed' }]
const previewRow = getPendingPlanRow(ledger, planId)
if (previewRow === undefined)
return [404, { error: 'plan not found — run /undo again' }]
@@ -454,6 +463,9 @@ export function apply(ctx: HostApplyContext): void {
const planRuntime = workspaceStores.get(previewRow.workspace_key)
if (planRuntime === undefined)
return [409, { error: 'the host restarted since this preview; run /undo again' }]
+ // P1-6:实时围栏——预览后落 needs-recovery 的 workspace 立即拒绝执行。
+ if (hasNeedsRecoveryWorkspace(ledger, previewRow.workspace_key))
+ return [409, { error: 'the workspace needs recovery (a previous operation was interrupted) — purge its turnrewind data before retrying' }]
if (planRuntime.undoing || workspaceHasActiveTurn(active, previewRow.workspace_key))
return [409, { error: 'the workspace is busy — wait for the current turn to finish' }]
const claim = claimPendingPlan(ledger, planId, sessionId)
@@ -517,6 +529,8 @@ export function apply(ctx: HostApplyContext): void {
const sessionId = String(body.sessionId ?? '')
if (planId === '' || sessionId === '')
return [400, { error: 'planId and sessionId are required' }]
+ if (!validPlanId(planId) || !validSessionId(sessionId))
+ return [400, { error: 'planId or sessionId is malformed' }]
const removed = markPendingPlanCancelled(ledger, planId, sessionId)
return [200, { ok: true, message: removed ? 'Pending undo cancelled.' : 'No pending plan matched (it may have expired).' }]
}
@@ -527,6 +541,8 @@ export function apply(ctx: HostApplyContext): void {
const sessionId = String(url.searchParams.get('sessionId') ?? '')
if (planId === '' || sessionId === '')
return [400, { error: 'planId and sessionId are required' }]
+ if (!validPlanId(planId) || !validSessionId(sessionId))
+ return [400, { error: 'planId or sessionId is malformed' }]
const status = getPendingPlanStatus(ledger, planId, sessionId)
if (status === undefined)
return [404, { error: 'plan expired, unavailable, or owned by another session — run /undo again' }]
@@ -649,7 +665,7 @@ export function apply(ctx: HostApplyContext): void {
return { kind: 'error', text: 'Undo is unavailable because this session has no workspace.' }
}
const workspaceIdentity = workspaceKeyFor(workspaceDir)
- if (recoveryWorkspaces.has(workspaceIdentity))
+ if (hasNeedsRecoveryWorkspace(ledger, workspaceIdentity))
return { kind: 'error', text: 'Undo is unavailable because a previous undo or redo was interrupted. Inspect the workspace, then purge its turnrewind data before retrying.' }
const issue = workspaceIssue(workspaceDir)
if (issue)
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/routes/index.ts b/packages/dsh-tauri-turnrewind-ts/src/host/routes/index.ts
index 5059d5cd..9bd33a7a 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/routes/index.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/routes/index.ts
@@ -4,6 +4,11 @@
* ✓/✗ 按钮经此驱动两阶段确认:confirm(POST,loopback-only)原子 claim 后执行;
* cancel(POST);status(GET)供卡片轮询 plan 结局。与 worktree 插件的
* jsonRoute 模式一致:方法严格限制、body 上限、变更仅回环。
+ *
+ * P1-3 加固:响应一次性 guard(异常客户端不会触发重复响应/崩溃)、
+ * body 超限立即 413 并断开、mutate 路由校验 JSON Content-Type、
+ * 统一 nosniff/no-store 响应头、处理超时兜底(长 undo 由 status 轮询
+ * 恢复,响应中断不影响服务端继续执行)。
*/
import { Buffer } from 'node:buffer'
@@ -13,7 +18,9 @@ export interface RouteRequest {
method?: string
url?: string
socket?: { remoteAddress?: string }
+ headers?: Record<string, string | string[] | undefined>
on: (event: string, listener: (...args: any[]) => void) => void
+ destroy?: (error?: Error) => void
setHeader?: (name: string, value: string) => void
}
@@ -35,9 +42,14 @@ export interface JsonRouteOptions {
mutate?: boolean
/** 允许的 HTTP 方法(大写)。缺省不限制;mutate 路由隐式限定 POST。 */
methods?: string[]
+ /**
+ * 处理超时(ms)。默认 120s;超时后返回 504,服务端逻辑继续执行,
+ * 客户端经 status 轮询恢复结果。
+ */
+ timeoutMs?: number
}
-export function jsonRoute(path: string, handler: RouteHandler, { mutate = false, methods = [] }: JsonRouteOptions = {}): WebRoute {
+export function jsonRoute(path: string, handler: RouteHandler, { mutate = false, methods = [], timeoutMs = 120000 }: JsonRouteOptions = {}): WebRoute {
const allowed = new Set(methods.map(m => m.toUpperCase()))
if (mutate)
allowed.add('POST')
@@ -45,18 +57,34 @@ export function jsonRoute(path: string, handler: RouteHandler, { mutate = false,
kind: 'exact',
path,
handler(req: RouteRequest, res: RouteResponse) {
+ // P1-3: 一次性响应 guard——'error'/'end' 与超时竞争时绝不二次写出。
+ let responded = false
const send = (code: number, payload: unknown): void => {
+ if (responded)
+ return
+ responded = true
const body = JSON.stringify(payload)
- res.writeHead(code, { 'content-type': 'application/json; charset=utf-8' })
+ res.writeHead(code, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'x-content-type-options': 'nosniff',
+ 'cache-control': 'no-store',
+ })
res.end(body)
}
+ const timeoutPayload = { error: 'request timed out; the operation may still complete — poll /api/turnrewind/status' }
+ const timeout = setTimeout(send, timeoutMs, 504, timeoutPayload)
+ const finish = (): void => {
+ clearTimeout(timeout)
+ }
if (mutate && req.method !== 'POST') {
res.setHeader('allow', 'POST')
+ finish()
send(405, { error: 'mutation routes require POST' })
return
}
if (allowed.size > 0 && !allowed.has((req.method ?? '').toUpperCase())) {
res.setHeader('allow', [...allowed].join(', '))
+ finish()
send(405, { error: 'method not allowed' })
return
}
@@ -70,27 +98,41 @@ export function jsonRoute(path: string, handler: RouteHandler, { mutate = false,
totalBytes += Buffer.byteLength(value, 'utf8')
if (totalBytes > MAX_ROUTE_BODY_BYTES) {
tooLarge = true
+ // P1-3: 超限立即响应并断开,不再消费剩余流。
+ finish()
+ send(413, { error: 'request body too large' })
+ req.destroy?.(new Error('body too large'))
return
}
parts.push(value)
})
- req.on('error', () => send(400, { error: 'request stream failed' }))
+ req.on('error', () => {
+ finish()
+ send(400, { error: 'request stream failed' })
+ })
req.on('end', () => {
void (async () => {
if (tooLarge)
- return send(413, { error: 'request body too large' })
+ return finish()
+ // P1-3: mutate 路由要求 JSON Content-Type(缺省视为不符)。
if (mutate) {
const peer = req.socket?.remoteAddress ?? ''
const loopback = peer === '127.0.0.1' || peer === '::1' || peer === '::ffff:127.0.0.1'
if (!loopback)
return send(403, { error: 'mutation routes only accept loopback calls' })
+ const contentType = req.headers?.['content-type']
+ const type = Array.isArray(contentType) ? contentType[0] : contentType
+ if (!type || !type.toLowerCase().includes('application/json'))
+ return send(415, { error: 'content-type must be application/json' })
}
try {
const parsed = JSON.parse(parts.join('') || '{}') as Record<string, unknown>
const [code, payload] = await handler(parsed, req)
+ finish()
send(code, payload)
}
catch (error) {
+ finish()
send(500, { error: String((error as Error)?.message ?? error) })
}
})()
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
index 3d4e35b3..4db9824f 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/ledger.ts
@@ -135,6 +135,9 @@ export function openLedger(rootDir: string): Ledger {
const path = join(rootDir, 'ledger.sqlite')
mkdirSync(dirname(path), { recursive: true })
const db = new DatabaseSync(path)
+ // P1-7: 并发写遇 SQLITE_BUSY 时等待而非立即抛错——瞬时锁冲突不应被
+ // 上层误判为状态漂移并触发永久围栏。
+ db.exec('PRAGMA busy_timeout = 5000')
db.exec(SCHEMA)
// Older local prototypes may already have the table; add new columns idempotently.
for (const migration of [
@@ -265,7 +268,7 @@ export function claimRewindNotices(db: Ledger, sessionId: string, workspaceKey:
UPDATE rewind_notices SET status = 'consumed', claimed_at = ?
WHERE notice_id = ? AND status = 'pending'
`)
- db.exec('BEGIN')
+ db.exec('BEGIN IMMEDIATE')
try {
for (const notice of notices)
statement.run(claimedAt, notice.notice_id)
@@ -293,13 +296,27 @@ export function listNeedsRecoveryWorkspaces(db: Ledger): string[] {
`).all() as { workspace_key: string }[]).map(row => row.workspace_key)
}
+/**
+ * P1-6:实时围栏查询。needs-recovery 可能发生在任意时刻(账本事务失败的
+ * catch 路径),启动时加载的内存集合会过期——围栏判定一律查库。
+ */
+export function hasNeedsRecoveryWorkspace(db: Ledger, workspaceKey: string): boolean {
+ return db.prepare(`
+ SELECT 1
+ FROM operations o
+ JOIN turns t ON t.turn_id = o.target_turn_id
+ WHERE o.outcome = 'needs-recovery' AND t.workspace_key = ?
+ LIMIT 1
+ `).get(workspaceKey) !== undefined
+}
+
/** 预览路径集的稳定摘要:排序后 sha256。confirm 时校验计划是否漂移(P1-2)。 */
export function planPathsDigest(paths: string[]): string {
return createHash('sha256').update([...paths].sort().join('\0')).digest('hex')
}
export function createPendingPlan(db: Ledger, plan: PendingPlan): string {
- db.exec('BEGIN')
+ db.exec('BEGIN IMMEDIATE')
try {
// One live plan per session+workspace: a newer preview replaces the older.
// 被替换的旧 plan 转 expired 留档(审计可见),不再物理删除。
@@ -455,7 +472,7 @@ export function skipTurn(db: Ledger, turn: { turnId: string, sessionId: string,
/** skipped turn + 每会话/工作区一次性 heads-up(去重由 rewind_notices 承担)。 */
export function recordSkippedTurn(db: Ledger, turn: { turnId: string, sessionId: string, workspaceKey: string, startedAt: string }, reason: string): void {
- db.exec('BEGIN')
+ db.exec('BEGIN IMMEDIATE')
try {
skipTurn(db, turn, reason)
// Queue one heads-up per session and workspace; repeated skips stay silent.
@@ -560,7 +577,7 @@ export function completeUndoTransaction(db: Ledger, completion: UndoCompletion):
const summary = completion.notRestored.length > 0
? completion.notRestored.map(entry => `${entry.path} (${entry.reason})`).join('; ')
: null
- db.exec('BEGIN')
+ db.exec('BEGIN IMMEDIATE')
try {
const turn = db.prepare(`
UPDATE turns SET status = 'undone', settled_at = ?
@@ -628,7 +645,7 @@ export function completeRedoTransaction(db: Ledger, completion: RedoCompletion):
const summary = completion.notRestored.length > 0
? completion.notRestored.map(entry => `${entry.path} (${entry.reason})`).join('; ')
: null
- db.exec('BEGIN')
+ db.exec('BEGIN IMMEDIATE')
try {
const previous = db.prepare(`
UPDATE operations SET outcome = 'redone', settled_at = ?
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts
index 7b22e84c..122a7bad 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/maintenance.ts
@@ -44,7 +44,7 @@ export function purgeWorkspace(rootDir: string, workspaceDir: string): PurgeSumm
if (existsSync(ledgerPath)) {
const db = openLedger(rootDir)
try {
- db.exec('BEGIN')
+ db.exec('BEGIN IMMEDIATE')
const operations = db.prepare('DELETE FROM operations WHERE target_turn_id IN (SELECT turn_id FROM turns WHERE workspace_key = ?)').run(workspaceIdentity)
const notices = db.prepare('DELETE FROM rewind_notices WHERE workspace_key = ?').run(workspaceIdentity)
const plans = db.prepare('DELETE FROM pending_plans WHERE workspace_key = ?').run(workspaceIdentity)
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/planner.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/planner.ts
index adab7945..58cc168a 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/planner.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/planner.ts
@@ -60,12 +60,13 @@ export interface PendingPlanBinding {
/**
* 计划漂移校验(P1-2):确认时的 turn 快照 ref 与重算 diff 必须与预览一致,
- * 即「确认的就是预览时看到的」。三列任一为 NULL 视为旧格式 plan(5 分钟
- * TTL 内自然清空),跳过严格校验保持兼容。返回 undefined 表示未漂移。
+ * 即「确认的就是预览时看到的」。绑定列为 NULL 的旧格式 plan(无从校验)
+ * 从严处理:一律按漂移拒绝并要求重新预览——宁可多看一次预览,
+ * 不可在不可验证的计划上执行恢复。
*/
export function planDrift(plan: PendingPlanBinding, target: TurnRow, currentPaths: string[]): string | undefined {
if (plan.before_ref === null || plan.after_ref === null || plan.paths_digest === null)
- return undefined
+ return 'the plan predates preview binding and cannot be verified'
if (target.before_ref !== plan.before_ref || target.after_ref !== plan.after_ref)
return 'the turn snapshots no longer match the preview'
if (planPathsDigest(currentPaths) !== plan.paths_digest)
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
index 140a106c..bac3c0ab 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/undo.ts
@@ -274,12 +274,29 @@ async function diskMatchesSnapshot(runtime: WorkspaceRuntime, workspaceDir: stri
}
}
+/** 有界并发 map:大路径数的 undo 计划不再一次起满量 git 子进程(P1-7)。 */
+async function mapWithConcurrency<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
+ const results: R[] = Array.from({ length: items.length })
+ let next = 0
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
+ while (next < items.length) {
+ const index = next++
+ results[index] = await fn(items[index]!)
+ }
+ })
+ await Promise.all(workers)
+ return results
+}
+
+/** 单个 plan 的路径并发预算:每条路径内部还有多次 git 子进程调用。 */
+const PLAN_ENTRY_CONCURRENCY = 8
+
/**
* 构建只读 undo 计划:每个路径的变化分类、磁盘是否仍匹配 turn 后快照、
* before 快照是否超限(超限条目恢复时单文件失败,绝不静默)。
*/
export async function buildPlanEntries(runtime: WorkspaceRuntime, workspaceDir: string, target: TurnRow, paths: string[]): Promise<PlanEntry[]> {
- return Promise.all(paths.map(async (path) => {
+ return mapWithConcurrency(paths, PLAN_ENTRY_CONCURRENCY, async (path) => {
const beforeState = await stateAt(runtime.store, target.before_ref!, path)
return {
path,
@@ -288,7 +305,7 @@ export async function buildPlanEntries(runtime: WorkspaceRuntime, workspaceDir:
tooLarge: beforeState.kind === 'tooLarge',
unsupported: beforeState.kind === 'unsupported',
}
- }))
+ })
}
function summarizeChanges(entries: PlanEntry[]): string {
diff --git a/packages/dsh-tauri-turnrewind-ts/src/host/service/workspace-lock.ts b/packages/dsh-tauri-turnrewind-ts/src/host/service/workspace-lock.ts
index 09ff8293..8126e4f8 100644
--- a/packages/dsh-tauri-turnrewind-ts/src/host/service/workspace-lock.ts
+++ b/packages/dsh-tauri-turnrewind-ts/src/host/service/workspace-lock.ts
@@ -56,7 +56,11 @@ function pidAlive(pid: number): boolean {
process.kill(pid, 0)
return true
}
- catch {
+ catch (error) {
+ // P1-5: EPERM 表示进程存在但当前用户无权发信号——视为存活,
+ // 交给 TTL 兜底;ESRCH(及其他)才是真正死亡。
+ if ((error as NodeJS.ErrnoException)?.code === 'EPERM')
+ return true
return false
}
}
@@ -114,6 +118,13 @@ export async function acquireWorkspaceLock(rootDir: string, workspaceDir: string
for (let attempt = 0; attempt < LOCK_MAX_ATTEMPTS; attempt += 1) {
try {
writeLockFile(path, token)
+ // P1-5 发布竞态防护:wx 创建到内容写完之间,其他进程可能读到空文件
+ // 并判 stale 接管。获锁后回读自检——token 不在(已被接管/覆盖)即
+ // 视为未获锁并重试,绝不形成双持锁。
+ if (readLockContent(path)?.token !== token) {
+ rmSync(path, { force: true })
+ continue
+ }
let released = false
return {
release() {
@@ -156,6 +167,11 @@ export function acquireWorkspaceLockSync(rootDir: string, workspaceDir: string):
throw error
throw new WorkspaceLockBusyError(workspaceDir, readLockContent(path))
}
+ // P1-5: 与异步路径一致的回读自检。
+ if (readLockContent(path)?.token !== token) {
+ releaseLockFile(path, token)
+ throw new WorkspaceLockBusyError(workspaceDir, readLockContent(path))
+ }
let released = false
return {
release() {
diff --git a/packages/dsh-tauri-turnrewind-ts/test/planner.test.js b/packages/dsh-tauri-turnrewind-ts/test/planner.test.js
index ddec6a26..5ad2a46f 100644
--- a/packages/dsh-tauri-turnrewind-ts/test/planner.test.js
+++ b/packages/dsh-tauri-turnrewind-ts/test/planner.test.js
@@ -45,8 +45,12 @@ it('detects pending plan drift against the confirmed turn and diff', () => {
planDrift(binding, { ...target, after_ref: 'refs/turnrewind/a2' }, ['a.txt', 'b.txt']),
/snapshots no longer match/u,
)
- // Legacy plans (NULL binding columns) skip strict checks for compatibility.
- assert.equal(planDrift({ before_ref: null, after_ref: null, paths_digest: null }, target, []), undefined)
+ // Legacy plans (NULL binding columns) cannot be verified: they are rejected
+ // (forced re-preview) instead of being trusted without checks.
+ assert.match(
+ planDrift({ before_ref: null, after_ref: null, paths_digest: null }, target, []),
+ /predates preview binding/u,
+ )
})
it('produces a stable order-independent paths digest', () => {
diff --git a/packages/dsh-tauri-turnrewind-ts/test/routes.test.js b/packages/dsh-tauri-turnrewind-ts/test/routes.test.js
new file mode 100644
index 00000000..e8a5eb1f
--- /dev/null
+++ b/packages/dsh-tauri-turnrewind-ts/test/routes.test.js
@@ -0,0 +1,104 @@
+import assert from 'node:assert/strict'
+import { it } from 'vitest'
+import { jsonRoute } from '../src/host/routes'
+
+function makeReq({ method = 'POST', headers = { 'content-type': 'application/json' } } = {}) {
+ const listeners = new Map()
+ const req = {
+ method,
+ url: '/',
+ socket: { remoteAddress: '127.0.0.1' },
+ headers,
+ on(event, listener) {
+ listeners.set(event, listener)
+ return () => {}
+ },
+ destroy() {},
+ }
+ const emit = (event, payload) => {
+ listeners.get(event)?.(payload)
+ }
+ return {
+ req,
+ emit,
+ end: async () => {
+ listeners.get('end')?.()
+ await Promise.resolve()
+ },
+ }
+}
+
+function makeRes() {
+ const res = {
+ statusCode: undefined,
+ body: undefined,
+ headers: {},
+ responses: 0,
+ writeHead(code, headers) {
+ res.statusCode = code
+ Object.assign(res.headers, headers)
+ },
+ setHeader(name, value) {
+ res.headers[name] = value
+ },
+ end(body) {
+ res.responses += 1
+ res.body = body
+ },
+ destroy() {},
+ }
+ return res
+}
+
+const okHandler = async () => [200, { ok: true }]
+
+it('enforces method restrictions on mutate routes', async () => {
+ const route = jsonRoute('/api/x', okHandler, { mutate: true })
+ const { req, end } = makeReq({ method: 'GET' })
+ const res = makeRes()
+ route.handler(req, res)
+ await end()
+ assert.equal(res.statusCode, 405)
+ assert.equal(res.responses, 1)
+})
+
+it('rejects oversized bodies immediately with 413', async () => {
+ const route = jsonRoute('/api/x', okHandler, { mutate: true })
+ const { req, emit } = makeReq()
+ const res = makeRes()
+ route.handler(req, res)
+ emit('data', 'x'.repeat(20000))
+ assert.equal(res.statusCode, 413)
+ assert.equal(res.responses, 1)
+})
+
+it('returns 415 for non-JSON content types on mutate routes', async () => {
+ const route = jsonRoute('/api/x', okHandler, { mutate: true })
+ const { req, end } = makeReq({ headers: { 'content-type': 'text/plain' } })
+ const res = makeRes()
+ route.handler(req, res)
+ await end()
+ assert.equal(res.statusCode, 415)
+})
+
+it('sets nosniff and no-store headers on every response', async () => {
+ const route = jsonRoute('/api/x', okHandler, { mutate: true })
+ const { req, end } = makeReq()
+ const res = makeRes()
+ route.handler(req, res)
+ await end()
+ assert.equal(res.statusCode, 200)
+ assert.equal(res.headers['x-content-type-options'], 'nosniff')
+ assert.equal(res.headers['cache-control'], 'no-store')
+})
+
+it('never responds twice when the stream errors after a response', async () => {
+ const route = jsonRoute('/api/x', okHandler, { mutate: true })
+ const { req, end, emit } = makeReq()
+ const res = makeRes()
+ route.handler(req, res)
+ await end()
+ emit('error', new Error('late stream error'))
+ assert.equal(res.statusCode, 200)
+ assert.equal(res.responses, 1)
+})