GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — http: add isValidHeaderName() and isValidHeaderValue() · nodejs/node@44ba289

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • doc/api
    • http.md
  • lib
    • _http_outgoing.js
    • http.js
  • test/parallel
    • test-http-is-valid-header.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎doc/api/http.md‎

Copy file name to clipboardExpand all lines: doc/api/http.md
+86Lines changed: 86 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -4403,6 +4403,89 @@ request. Specifically, the `'error'` event will be emitted with an error with
44034403
the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'`
44044404
and the `cause`, if one was provided.
44054405
4406+
## `http.isValidHeaderName(name)`
4407+
4408+
<!-- YAML
4409+
added: REPLACEME
4410+
-->
4411+
4412+
* `name` {any}
4413+
* Returns: {boolean}
4414+
4415+
Returns `true` if `name` is a valid HTTP header name (a non-empty string that
4416+
is an HTTP [token][]), and `false` otherwise. This is the same check that
4417+
[`http.validateHeaderName()`][] performs, but the result is returned instead of
4418+
an error being thrown, so it is suitable for use in hot paths where invalid
4419+
input is expected.
4420+
4421+
HTTP methods are also tokens, so this function can validate them as well.
4422+
4423+
```mjs
4424+
import { isValidHeaderName } from 'node:http';
4425+
4426+
console.log(isValidHeaderName('content-type')); // true
4427+
console.log(isValidHeaderName('X-Request-Id')); // true
4428+
console.log(isValidHeaderName('')); // false
4429+
console.log(isValidHeaderName('bad header')); // false
4430+
console.log(isValidHeaderName(42)); // false
4431+
```
4432+
4433+
```cjs
4434+
const { isValidHeaderName } = require('node:http');
4435+
4436+
console.log(isValidHeaderName('content-type')); // true
4437+
console.log(isValidHeaderName('X-Request-Id')); // true
4438+
console.log(isValidHeaderName('')); // false
4439+
console.log(isValidHeaderName('bad header')); // false
4440+
console.log(isValidHeaderName(42)); // false
4441+
```
4442+
4443+
## `http.isValidHeaderValue(value[, options])`
4444+
4445+
<!-- YAML
4446+
added: REPLACEME
4447+
-->
4448+
4449+
* `value` {any}
4450+
* `options` {Object}
4451+
* `httpValidation` {string} Validation strictness, one of `'strict'` or
4452+
`'relaxed'`. These have the same meaning as the `httpValidation` option of
4453+
[`http.createServer()`][] and [`http.request()`][]. **Default:** `'strict'`.
4454+
* Returns: {boolean}
4455+
4456+
Returns `true` if `value` is a valid HTTP header value, and `false` otherwise.
4457+
With the default options this is the same check that
4458+
[`http.validateHeaderValue()`][] performs, but the result is returned instead
4459+
of an error being thrown.
4460+
4461+
`undefined` and symbols are never valid header values. Other non-string
4462+
values are converted to strings before being checked, as they are when passed
4463+
to [`outgoingMessage.setHeader(name, value)`][].
4464+
4465+
Passing an invalid `options` argument throws.
4466+
4467+
```mjs
4468+
import { isValidHeaderValue } from 'node:http';
4469+
4470+
console.log(isValidHeaderValue('text/html')); // true
4471+
console.log(isValidHeaderValue(123)); // true
4472+
console.log(isValidHeaderValue(undefined)); // false
4473+
console.log(isValidHeaderValue('a\r\nb')); // false
4474+
console.log(isValidHeaderValue('a\x01b')); // false
4475+
console.log(isValidHeaderValue('a\x01b', { httpValidation: 'relaxed' })); // true
4476+
```
4477+
4478+
```cjs
4479+
const { isValidHeaderValue } = require('node:http');
4480+
4481+
console.log(isValidHeaderValue('text/html')); // true
4482+
console.log(isValidHeaderValue(123)); // true
4483+
console.log(isValidHeaderValue(undefined)); // false
4484+
console.log(isValidHeaderValue('a\r\nb')); // false
4485+
console.log(isValidHeaderValue('a\x01b')); // false
4486+
console.log(isValidHeaderValue('a\x01b', { httpValidation: 'relaxed' })); // true
4487+
```
4488+
44064489
## `http.validateHeaderName(name[, label])`
44074490
44084491
<!-- YAML
@@ -4795,6 +4878,8 @@ const agent2 = new http.Agent({ proxyEnv: process.env });
47954878
[`http.globalAgent`]: #httpglobalagent
47964879
[`http.request()`]: #httprequestoptions-callback
47974880
[`http.setGlobalProxyFromEnv()`]: #httpsetglobalproxyfromenvproxyenv
4881+
[`http.validateHeaderName()`]: #httpvalidateheadernamename-label
4882+
[`http.validateHeaderValue()`]: #httpvalidateheadervaluename-value
47984883
[`message.headers`]: #messageheaders
47994884
[`message.rawHeaders`]: #messagerawheaders
48004885
[`message.socket`]: #messagesocket
@@ -4857,3 +4942,4 @@ const agent2 = new http.Agent({ proxyEnv: process.env });
48574942
[information event]: #event-information
48584943
[initial delay]: net.md#socketsetkeepaliveenable-initialdelay-interval-count
48594944
[request target]: https://datatracker.ietf.org/doc/html/rfc9112#section-3.2
4945+
[token]: https://datatracker.ietf.org/doc/html/rfc9110#section-5.6.2
Collapse file

‎lib/_http_outgoing.js‎

Copy file name to clipboardExpand all lines: lib/_http_outgoing.js
+42-2Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,11 @@ const {
7171
},
7272
hideStackFrames,
7373
} = require('internal/errors');
74-
const { validateString } = require('internal/validators');
74+
const {
75+
validateObject,
76+
validateOneOf,
77+
validateString,
78+
} = require('internal/validators');
7579
const {
7680
assignFunctionName,
7781
deprecateInstantiation,
@@ -723,11 +727,45 @@ function matchHeader(self, state, field, value) {
723727
}
724728

725729
const validateHeaderName = assignFunctionName('validateHeaderName', hideStackFrames((name, label) => {
726-
if (typeof name !== 'string' || !name || !checkIsHttpToken(name)) {
730+
if (!isValidHeaderName(name)) {
727731
throw new ERR_INVALID_HTTP_TOKEN.HideStackFramesError(label || 'Header name', name);
728732
}
729733
}));
730734

735+
/**
736+
* Non-throwing counterpart of `validateHeaderName()`.
737+
* @param {any} name
738+
* @returns {boolean}
739+
*/
740+
function isValidHeaderName(name) {
741+
return typeof name === 'string' && checkIsHttpToken(name);
742+
}
743+
744+
const kHttpValidationValues = ['strict', 'relaxed'];
745+
746+
/**
747+
* Non-throwing counterpart of `validateHeaderValue()`.
748+
* @param {any} value
749+
* @param {{ httpValidation?: 'strict' | 'relaxed' }} [options]
750+
* @returns {boolean}
751+
*/
752+
function isValidHeaderValue(value, options) {
753+
let lenient = false;
754+
if (options !== undefined) {
755+
validateObject(options, 'options');
756+
const { httpValidation } = options;
757+
if (httpValidation === 'relaxed') {
758+
lenient = true;
759+
} else if (httpValidation !== undefined && httpValidation !== 'strict') {
760+
validateOneOf(httpValidation, 'options.httpValidation', kHttpValidationValues);
761+
}
762+
}
763+
if (value === undefined || typeof value === 'symbol') {
764+
return false;
765+
}
766+
return !checkInvalidHeaderChar(value, lenient);
767+
}
768+
731769
const validateHeaderValue = assignFunctionName('validateHeaderValue', hideStackFrames((name, value, lenient) => {
732770
if (value === undefined) {
733771
throw new ERR_HTTP_INVALID_HEADER_VALUE.HideStackFramesError(value, name);
@@ -1424,6 +1462,8 @@ module.exports = {
14241462
kHighWaterMark,
14251463
kUniqueHeaders,
14261464
parseUniqueHeadersOption,
1465+
isValidHeaderName,
1466+
isValidHeaderValue,
14271467
validateHeaderName,
14281468
validateHeaderValue,
14291469
OutgoingMessage,
Collapse file

‎lib/http.js‎

Copy file name to clipboardExpand all lines: lib/http.js
+4Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ const { methods, parsers } = require('_http_common');
3232
const { IncomingMessage } = require('_http_incoming');
3333
const { ERR_PROXY_INVALID_CONFIG } = require('internal/errors').codes;
3434
const {
35+
isValidHeaderName,
36+
isValidHeaderValue,
3537
validateHeaderName,
3638
validateHeaderValue,
3739
OutgoingMessage,
@@ -192,6 +194,8 @@ module.exports = {
192194
Server,
193195
ServerResponse,
194196
createServer,
197+
isValidHeaderName,
198+
isValidHeaderValue,
195199
validateHeaderName,
196200
validateHeaderValue,
197201
get,
Collapse file

‎test/parallel/test-http-is-valid-header.js‎

Copy file name to clipboard
+168Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
'use strict';
2+
require('../common');
3+
const assert = require('assert');
4+
const {
5+
isValidHeaderName,
6+
isValidHeaderValue,
7+
validateHeaderName,
8+
validateHeaderValue,
9+
} = require('http');
10+
11+
function succeeds(fn) {
12+
try {
13+
fn();
14+
return true;
15+
} catch {
16+
return false;
17+
}
18+
}
19+
20+
// isValidHeaderName
21+
{
22+
const valid = [
23+
'a',
24+
'user-agent',
25+
'USER-AGENT',
26+
'User-Agent',
27+
'x-forwarded-for',
28+
'x-request-id-with-a-long-name',
29+
"!#$%&'*+-.^_`|~",
30+
'0123456789',
31+
];
32+
const invalid = [
33+
'',
34+
' ',
35+
'bad header',
36+
'bad:header',
37+
'x-forwarded-fםr',
38+
'איקס-פורוורד-פור',
39+
'x\r\ny',
40+
'x\0',
41+
'(comment)',
42+
'"quoted"',
43+
'a,b',
44+
'long-invalid-header-name\u00e9',
45+
];
46+
const nonStrings = [
47+
undefined, null, 0, 1, true, false, {}, [], ['a'],
48+
Symbol('a'), () => {}, 1n, Buffer.from('a'),
49+
];
50+
51+
for (const name of valid) {
52+
assert.strictEqual(isValidHeaderName(name), true, name);
53+
}
54+
for (const name of [...invalid, ...nonStrings]) {
55+
assert.strictEqual(isValidHeaderName(name), false, String(name?.toString?.()));
56+
}
57+
58+
// Must agree with validateHeaderName() for every input.
59+
for (const name of [...valid, ...invalid, ...nonStrings]) {
60+
assert.strictEqual(
61+
isValidHeaderName(name),
62+
succeeds(() => validateHeaderName(name)),
63+
);
64+
}
65+
66+
// Every single-character name agrees with validateHeaderName(), for both
67+
// the short (lookup table) and long (regexp) code paths.
68+
for (let c = 0; c <= 0x10ff; c++) {
69+
const ch = String.fromCharCode(c);
70+
for (const name of [ch, `${ch}xxxxxxxxxxxx`]) {
71+
assert.strictEqual(
72+
isValidHeaderName(name),
73+
succeeds(() => validateHeaderName(name)),
74+
`char code ${c}`,
75+
);
76+
}
77+
}
78+
}
79+
80+
// isValidHeaderValue
81+
{
82+
const valid = [
83+
'',
84+
'text/html',
85+
'a b\tc',
86+
'\u00e9\u00ff',
87+
'\x80',
88+
1,
89+
0,
90+
null,
91+
true,
92+
['a', 'b'],
93+
];
94+
const invalid = [
95+
undefined,
96+
'a\r\nb',
97+
'a\nb',
98+
'a\rb',
99+
'a\0b',
100+
'a\x01b',
101+
'a\x7fb',
102+
'לא תקין',
103+
'\u0100',
104+
['a', 'b\n'],
105+
Symbol('a'),
106+
];
107+
108+
for (const value of valid) {
109+
assert.strictEqual(isValidHeaderValue(value), true, String(value));
110+
}
111+
for (const value of invalid) {
112+
assert.strictEqual(isValidHeaderValue(value), false, String(value));
113+
}
114+
115+
// Must agree with validateHeaderValue() for every input.
116+
for (const value of [...valid, ...invalid]) {
117+
assert.strictEqual(
118+
isValidHeaderValue(value),
119+
succeeds(() => validateHeaderValue('x-test', value)),
120+
);
121+
}
122+
123+
for (let c = 0; c <= 0x10ff; c++) {
124+
const value = `a${String.fromCharCode(c)}b`;
125+
assert.strictEqual(
126+
isValidHeaderValue(value),
127+
succeeds(() => validateHeaderValue('x-test', value)),
128+
`char code ${c}`,
129+
);
130+
// Explicit 'strict' is the same as the default.
131+
assert.strictEqual(
132+
isValidHeaderValue(value, { httpValidation: 'strict' }),
133+
isValidHeaderValue(value),
134+
`char code ${c}`,
135+
);
136+
}
137+
138+
// 'relaxed' follows the Fetch spec: only NUL, CR, LF and code points above
139+
// U+00FF are rejected.
140+
const relaxed = { httpValidation: 'relaxed' };
141+
for (let c = 0; c <= 0x10ff; c++) {
142+
const expected = !(c === 0x00 || c === 0x0a || c === 0x0d || c > 0xff);
143+
assert.strictEqual(
144+
isValidHeaderValue(`a${String.fromCharCode(c)}b`, relaxed),
145+
expected,
146+
`char code ${c}`,
147+
);
148+
}
149+
assert.strictEqual(isValidHeaderValue(undefined, relaxed), false);
150+
assert.strictEqual(isValidHeaderValue('a\x01b', relaxed), true);
151+
assert.strictEqual(isValidHeaderValue('a\x7fb', relaxed), true);
152+
153+
// An empty options object uses the default.
154+
assert.strictEqual(isValidHeaderValue('a\x01b', {}), false);
155+
assert.strictEqual(isValidHeaderValue('a\x01b', { httpValidation: undefined }), false);
156+
157+
// Invalid options throw.
158+
for (const options of [null, 1, 'relaxed', true]) {
159+
assert.throws(() => isValidHeaderValue('a', options), {
160+
code: 'ERR_INVALID_ARG_TYPE',
161+
});
162+
}
163+
for (const httpValidation of ['insecure', 'RELAXED', '', 1, null]) {
164+
assert.throws(() => isValidHeaderValue('a', { httpValidation }), {
165+
code: 'ERR_INVALID_ARG_VALUE',
166+
});
167+
}
168+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.