dsh-message-actions 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/http.cjs ADDED
@@ -0,0 +1,131 @@
1
+ // dsh-message-actions 通用 HTTP 工具
2
+ //
3
+ // 无宿主依赖(仅依赖 shared.cjs 的纯函数),便于在离线测试中直接用
4
+ // 假的 req/res 验证 413 排空、请求体上限与统一响应头。
5
+
6
+ 'use strict';
7
+
8
+ const shared = require('./shared.cjs');
9
+ const { ERROR_LABELS, MAX_BODY_BYTES, bodyTooLarge } = shared;
10
+
11
+ /**
12
+ * 统一 JSON 响应头。除类型与长度外,附加防缓存 / 防嗅探 / 禁引用 / 禁嵌入,
13
+ * 避免含会话正文与财务数据的响应被浏览器缓存、被嗅探成其它类型或在页面里被内联执行。
14
+ */
15
+ function jsonHeaders(bodyLength) {
16
+ return {
17
+ 'content-type': 'application/json; charset=utf-8',
18
+ 'content-length': bodyLength,
19
+ 'cache-control': 'no-store',
20
+ 'x-content-type-options': 'nosniff',
21
+ 'referrer-policy': 'no-referrer',
22
+ 'cross-origin-resource-policy': 'same-origin',
23
+ 'content-security-policy': "default-src 'none'; frame-ancestors 'none'"
24
+ };
25
+ }
26
+
27
+ function sendJson(res, status, payload, extraHeaders) {
28
+ if (res.headersSent) return;
29
+ const body = JSON.stringify(payload);
30
+ res.writeHead(status, Object.assign({}, extraHeaders || {}, jsonHeaders(Buffer.byteLength(body))));
31
+ res.end(body);
32
+ }
33
+
34
+ /**
35
+ * 提前拒绝时主动排空请求体。
36
+ * 不排空会让同一个 keep-alive 连接上的剩余字节污染后续请求解析。
37
+ */
38
+ function drainRequest(req) {
39
+ try {
40
+ if (typeof req.resume === 'function') req.resume();
41
+ } catch {
42
+ /* 连接已断开 */
43
+ }
44
+ }
45
+
46
+ function errorMessage(code) {
47
+ return ERROR_LABELS.en[code] || code;
48
+ }
49
+
50
+ function sendError(res, status, code) {
51
+ sendJson(res, status, { ok: false, error: { code, message: errorMessage(code) } });
52
+ }
53
+
54
+ function sendBadRequest(res) {
55
+ sendError(res, 400, 'INVALID_REQUEST');
56
+ }
57
+
58
+ function sendForbidden(res) {
59
+ sendError(res, 403, 'FORBIDDEN');
60
+ }
61
+
62
+ /** 405 也走统一安全头与 JSON 错误体,避免与其它接口的安全策略不一致。 */
63
+ function sendMethodNotAllowed(res, allow) {
64
+ sendJson(
65
+ res,
66
+ 405,
67
+ { ok: false, error: { code: 'METHOD_NOT_ALLOWED', message: errorMessage('METHOD_NOT_ALLOWED') } },
68
+ { allow }
69
+ );
70
+ }
71
+
72
+ /** 读取 JSON 请求体(1MB 上限 + 断连处理);提前拒绝时一律排空。 */
73
+ async function readJsonBody(req, res) {
74
+ const contentLength = req.headers['content-length'];
75
+ if (contentLength !== undefined && bodyTooLarge(contentLength)) {
76
+ // 先排空再响应,避免 keep-alive 连接残留字节污染后续请求。
77
+ drainRequest(req);
78
+ sendError(res, 413, 'PAYLOAD_TOO_LARGE');
79
+ return null;
80
+ }
81
+ const chunks = [];
82
+ let total = 0;
83
+ let broken = false;
84
+ const onBreak = () => {
85
+ broken = true;
86
+ };
87
+ req.on('aborted', onBreak);
88
+ req.on('close', onBreak);
89
+ try {
90
+ for await (const chunk of req) {
91
+ total += chunk.length;
92
+ if (total > MAX_BODY_BYTES) {
93
+ drainRequest(req);
94
+ sendError(res, 413, 'PAYLOAD_TOO_LARGE');
95
+ return null;
96
+ }
97
+ chunks.push(chunk);
98
+ }
99
+ } catch {
100
+ return null;
101
+ }
102
+ if (broken && chunks.length === 0) return null;
103
+ if (chunks.length === 0) {
104
+ sendBadRequest(res);
105
+ return null;
106
+ }
107
+ let raw;
108
+ try {
109
+ raw = Buffer.concat(chunks).toString('utf8');
110
+ } catch {
111
+ raw = chunks.map((c) => c.toString('utf8')).join('');
112
+ }
113
+ try {
114
+ return JSON.parse(raw);
115
+ } catch {
116
+ sendBadRequest(res);
117
+ return null;
118
+ }
119
+ }
120
+
121
+ module.exports = {
122
+ jsonHeaders,
123
+ sendJson,
124
+ drainRequest,
125
+ errorMessage,
126
+ sendError,
127
+ sendBadRequest,
128
+ sendForbidden,
129
+ sendMethodNotAllowed,
130
+ readJsonBody
131
+ };