Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
a139dc1
docs(devforge): investigation and proposed fix for issue #479
claude Jul 1, 2026
cbab1e3
fix: decode response header values as UTF-8 with ISO-8859-1 fallback
claude Jul 1, 2026
7c52daf
fix: correct header-decode doctest and formatting
claude Jul 1, 2026
5233130
chore(devforge): record iter-2 reviewer pass and final-review phase
claude Jul 1, 2026
db37ee1
refactor: avoid redundant copy in header-value decode
claude Jul 1, 2026
0d0ec07
chore(devforge): record final-review pass (loop converged)
claude Jul 1, 2026
d236997
docs(devforge): revise design to per-ecosystem decode + raw-bytes acc…
claude Jul 1, 2026
4a0e40e
feat: per-ecosystem header decoding + raw-header-bytes accessor
claude Jul 1, 2026
1b52315
test: cover Python from_async header decode + raw_headers over a real…
claude Jul 1, 2026
b54d354
chore(devforge): enter final review (inner loop converged, rev 2)
claude Jul 1, 2026
750e31a
chore(devforge): record thermonuclear final review (rev 2, round 1)
claude Jul 1, 2026
82d8756
fix: preserve rawHeaders across clone(), declare it in .d.ts, correct…
claude Jul 1, 2026
6a40868
docs: align raw-header field comments with the accessor's documented …
claude Jul 1, 2026
e8289e5
chore(devforge): final review converged (rev 2, both reviewers PASS)
claude Jul 1, 2026
3bc991f
chore(devforge): record create-PR approval
claude Jul 1, 2026
dd95522
chore(devforge): record PR #492 and finish run
claude Jul 1, 2026
b773362
chore: remove stray napi-0.2.1.zip committed by mistake
claude Jul 1, 2026
f64e62b
chore: drop .devforge working files from the PR and gitignore them
claude Jul 1, 2026
deac557
fix(python): declare raw_headers in the type stub
claude Jul 1, 2026
060101a
chore: drop .devforge from committed .gitignore
claude Jul 1, 2026
22f1133
refactor: address review — drop node rawHeaders, expose httpx-style h…
claude Jul 3, 2026
2a84f46
docs: note that response.headers is a read view (mutations do not per…
claude Jul 3, 2026
88018ac
refactor: remove decode_header_value; header decoding lives in the Py…
claude Jul 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions impit-node/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ impl<'env> ImpitResponse {
.canonical_reason()
.unwrap_or("")
.to_string();
// JS Fetch semantics: header values are decoded as ISO-8859-1 (each byte 0x00..=0xFF maps to
// the code point U+0000..=U+00FF). Since that mapping is a bijection, the string stays
// byte-recoverable via `Buffer.from(value, 'latin1')`.
let mut headers_vec: Vec<(String, String)> = Vec::new();
for (k, v) in response.headers().iter() {
headers_vec.push((
Expand Down
12 changes: 12 additions & 0 deletions impit-node/test/basics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,18 @@ describe.each([
t.expect(response.headers.get('x-non-ascii')).toBe(routes.nonAsciiHeader.headerValue);
});

test('UTF-8 header values stay ISO-8859-1 and are byte-recoverable (Fetch-style)', async (t) => {
const response = await impit.fetch(new URL(routes.utf8Header.path, "http://127.0.0.1:3001").href);

// Fetch semantics: the string form is ISO-8859-1, so a UTF-8 value reads back as mojibake.
const latin1 = response.headers.get('x-utf8');
t.expect(latin1).not.toBe(routes.utf8Header.headerValue);

// ISO-8859-1 is a bijection, so the exact wire bytes are recoverable, and re-decoding
// as UTF-8 yields the real value — no dedicated raw-header accessor needed.
t.expect(Buffer.from(latin1!, 'latin1').toString('utf8')).toBe(routes.utf8Header.headerValue);
});

test('.json() method works', async (t) => {
const response = await impit.fetch(getHttpBinUrl('/json'));
const json = await response.json();
Expand Down
20 changes: 20 additions & 0 deletions impit-node/test/mock.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ export const routes = {
path: '/non-ascii-header',
headerValue: 'Dienstag, 31. März 2026',
},
utf8Header: {
path: '/utf8-header',
headerValue: 'attachment; filename="naïve.pdf"',
},
}

function parseMultipart(body: Buffer, boundary: string): Record<string, string> {
Expand Down Expand Up @@ -117,6 +121,22 @@ export async function runServer(port: number): Promise<Server> {
socket.end();
});

app.get(routes.utf8Header.path, (req, res) => {
const socket = res.socket!;
socket.write('HTTP/1.1 200 OK\r\n');
socket.write('Content-Type: text/plain\r\n');
// Header value carrying UTF-8 bytes (the ï is 0xC3 0xAF).
socket.write(Buffer.concat([
Buffer.from('X-Utf8: '),
Buffer.from(routes.utf8Header.headerValue, 'utf-8'),
Buffer.from('\r\n'),
]));
socket.write('Content-Length: 2\r\n');
socket.write('\r\n');
socket.write('ok');
socket.end();
});

app.get('/socket', (req, res) => {
const socket = req.socket;
const clientAddress = socket.remoteAddress;
Expand Down
2 changes: 2 additions & 0 deletions impit-python/python/impit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import Literal

from .cookies import Cookies
from .headers import Headers
from .impit import (
USE_CLIENT_DEFAULT,
AsyncClient,
Expand Down Expand Up @@ -61,6 +62,7 @@
'DecodingError',
'HTTPError',
'HTTPStatusError',
'Headers',
'InvalidURL',
'LocalProtocolError',
'NetworkError',
Expand Down
226 changes: 226 additions & 0 deletions impit-python/python/impit/headers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
"""Copyright © 2019, [Encode OSS Ltd](https://www.encode.io/).

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
# ruff: noqa: D102, D105, E501, FBT001, FBT002, PERF203, PLW1641, SIM118, SLF001

## The Headers class below is a modification of the `httpx.Headers` class, licensed under the BSD 3-Clause "New" License.

from __future__ import annotations

import typing
from collections.abc import Mapping

HeaderTypes = typing.Union[
'Headers',
typing.Mapping[str, str],
typing.Mapping[bytes, bytes],
typing.Sequence[tuple[str, str]],
typing.Sequence[tuple[bytes, bytes]],
]

SENSITIVE_HEADERS = {'authorization', 'proxy-authorization'}


def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes:
return key if isinstance(key, bytes) else key.encode(encoding or 'ascii')


def _normalize_header_value(value: str | bytes, encoding: str | None = None) -> bytes:
return value if isinstance(value, bytes) else value.encode(encoding or 'ascii')


def _obfuscate_sensitive_headers(
items: typing.Iterable[tuple[str, str]],
) -> typing.Iterator[tuple[str, str]]:
for k, v in items:
yield k, ('[secure]' if k.lower() in SENSITIVE_HEADERS else v)


class Headers(typing.MutableMapping[str, str]):
"""HTTP headers, as a case-insensitive multi-dict.

Mirrors the `httpx.Headers` interface, including the `raw` property that exposes the exact
header value bytes received on the wire.
"""

def __init__(self, headers: HeaderTypes | None = None, encoding: str | None = None) -> None:
self._list: list[tuple[bytes, bytes, bytes]] = []

if isinstance(headers, Headers):
self._list = list(headers._list)
elif isinstance(headers, Mapping):
for k, v in headers.items():
bytes_key = _normalize_header_key(k, encoding)
bytes_value = _normalize_header_value(v, encoding)
self._list.append((bytes_key, bytes_key.lower(), bytes_value))
elif headers is not None:
for k, v in headers:
bytes_key = _normalize_header_key(k, encoding)
bytes_value = _normalize_header_value(v, encoding)
self._list.append((bytes_key, bytes_key.lower(), bytes_value))

self._encoding = encoding

@property
def encoding(self) -> str:
"""Header encoding is mandated as ascii, but we allow fallbacks to utf-8 or iso-8859-1."""
if self._encoding is None:
for encoding in ['ascii', 'utf-8']:
for key, value in self.raw:
try:
key.decode(encoding)
value.decode(encoding)
except UnicodeDecodeError:
break
else:
self._encoding = encoding
break
else:
# ISO-8859-1 covers all 256 byte values, so it never raises decode errors.
self._encoding = 'iso-8859-1'
return self._encoding

@encoding.setter
def encoding(self, value: str) -> None:
self._encoding = value

@property
def raw(self) -> list[tuple[bytes, bytes]]:
"""Return the raw header items, as `(name, value)` byte pairs."""
return [(raw_key, value) for raw_key, _, value in self._list]

def keys(self) -> typing.KeysView[str]:
return {key.decode(self.encoding): None for _, key, value in self._list}.keys()

def values(self) -> typing.ValuesView[str]:
values_dict: dict[str, str] = {}
for _, key, value in self._list:
str_key = key.decode(self.encoding)
str_value = value.decode(self.encoding)
if str_key in values_dict:
values_dict[str_key] += f', {str_value}'
else:
values_dict[str_key] = str_value
return values_dict.values()

def items(self) -> typing.ItemsView[str, str]:
"""Return `(key, value)` items, concatenating repeated keys with commas."""
values_dict: dict[str, str] = {}
for _, key, value in self._list:
str_key = key.decode(self.encoding)
str_value = value.decode(self.encoding)
if str_key in values_dict:
values_dict[str_key] += f', {str_value}'
else:
values_dict[str_key] = str_value
return values_dict.items()

def multi_items(self) -> list[tuple[str, str]]:
"""Return `(key, value)` pairs without concatenating repeated keys."""
return [(key.decode(self.encoding), value.decode(self.encoding)) for _, key, value in self._list]

def get(self, key: str, default: typing.Any = None) -> typing.Any:
"""Return a header value, concatenating repeated occurrences with commas."""
try:
return self[key]
except KeyError:
return default

def get_list(self, key: str, split_commas: bool = False) -> list[str]:
"""Return all header values for `key`, optionally splitting on commas."""
get_header_key = key.lower().encode(self.encoding)
values = [
item_value.decode(self.encoding)
for _, item_key, item_value in self._list
if item_key.lower() == get_header_key
]
if not split_commas:
return values
split_values = []
for value in values:
split_values.extend([item.strip() for item in value.split(',')])
return split_values

def update(self, headers: HeaderTypes | None = None) -> None: # type: ignore[override]
headers = Headers(headers)
for key in headers.keys():
if key in self:
self.pop(key)
self._list.extend(headers._list)

def copy(self) -> Headers:
return Headers(self, encoding=self.encoding)

def __getitem__(self, key: str) -> str:
"""Return a single header value; repeated keys are joined with commas (RFC 7230 §3.2.2)."""
normalized_key = key.lower().encode(self.encoding)
items = [
header_value.decode(self.encoding)
for _, header_key, header_value in self._list
if header_key == normalized_key
]
if items:
return ', '.join(items)
raise KeyError(key)

def __setitem__(self, key: str, value: str) -> None:
"""Set `key` to `value`, removing duplicates and retaining insertion order."""
set_key = key.encode(self._encoding or 'utf-8')
set_value = value.encode(self._encoding or 'utf-8')
lookup_key = set_key.lower()
found_indexes = [idx for idx, (_, item_key, _) in enumerate(self._list) if item_key == lookup_key]
for idx in reversed(found_indexes[1:]):
del self._list[idx]
if found_indexes:
idx = found_indexes[0]
self._list[idx] = (set_key, lookup_key, set_value)
else:
self._list.append((set_key, lookup_key, set_value))

def __delitem__(self, key: str) -> None:
"""Remove the header `key`."""
del_key = key.lower().encode(self.encoding)
pop_indexes = [idx for idx, (_, item_key, _) in enumerate(self._list) if item_key.lower() == del_key]
if not pop_indexes:
raise KeyError(key)
for idx in reversed(pop_indexes):
del self._list[idx]

def __contains__(self, key: typing.Any) -> bool:
header_key = key.lower().encode(self.encoding)
return header_key in [key for _, key, _ in self._list]

def __iter__(self) -> typing.Iterator[typing.Any]:
return iter(self.keys())

def __len__(self) -> int:
return len(self._list)

def __eq__(self, other: object) -> bool:
try:
other_headers = Headers(other) # type: ignore[arg-type]
except ValueError:
return False
self_list = [(key, value) for _, key, value in self._list]
other_list = [(key, value) for _, key, value in other_headers._list]
return sorted(self_list) == sorted(other_list)

def __repr__(self) -> str:
class_name = self.__class__.__name__
encoding_str = f', encoding={self.encoding!r}' if self.encoding != 'ascii' else ''
as_list = list(_obfuscate_sensitive_headers(self.multi_items()))
as_dict = dict(as_list)
if len(as_dict) == len(as_list):
return f'{class_name}({as_dict!r}{encoding_str})'
return f'{class_name}({as_list!r}{encoding_str})'
14 changes: 11 additions & 3 deletions impit-python/python/impit/impit.pyi
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations
from http.cookiejar import CookieJar
from .cookies import Cookies
from .headers import Headers

from typing import Literal, Any
from collections.abc import Iterator, AsyncIterator
Expand Down Expand Up @@ -171,13 +172,20 @@ class Response:
print(response.http_version) # 'HTTP/2'
"""

headers: dict[str, str]
"""Response headers as a Python dictionary.
headers: Headers
"""Response headers as an httpx-style :class:`Headers` object.

Provides case-insensitive ``str`` access, plus a ``.raw`` property exposing the exact header
value bytes received on the wire (useful for UTF-8 header values or signature/HMAC checks).

This is a read view: each access rebuilds the object from the response, so in-place mutations
(``response.headers['x'] = ...``) do not persist on the response.

.. code-block:: python

response = await client.get("https://crawlee.dev")
print(response.headers) # {'content-type': 'text/html; charset=utf-8', ... }
print(response.headers['content-type']) # 'text/html; charset=utf-8'
print(response.headers.raw) # [(b'content-type', b'text/html; charset=utf-8'), ... ]
"""

text: str
Expand Down
Loading
Loading