Skip to content

Commit dfe7e0c

Browse files
Accept mislabeled public text documents
1 parent 547f1ba commit dfe7e0c

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

index.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1123,13 +1123,21 @@ async function fetchPublicDocument(inputUrl) {
11231123
}
11241124
if (!response.ok) throw new Error('The document returned HTTP ' + response.status + '.');
11251125
const type = (response.headers.get('content-type') || '').toLowerCase();
1126-
if (!['text/', 'application/json', 'application/xml', 'application/xhtml+xml'].some(prefix => type.startsWith(prefix))) {
1126+
if (/^(application\/pdf|image\/|audio\/|video\/|application\/(zip|gzip|x-rar|x-7z))/.test(type)) {
11271127
throw new Error('That link is not a readable text document. PDF and image-only files are not supported yet.');
11281128
}
11291129
const length = Number(response.headers.get('content-length') || 0);
11301130
if (length > 1000000) throw new Error('That document is too large. The limit is 1 MB.');
11311131
const source = (await response.text()).slice(0, 1000000);
1132-
const text = extractDocumentText(source, type).slice(0, 18000);
1132+
// Some government document servers label HTML as application/octet-stream.
1133+
// Accept it when the bytes are clearly text, but keep rejecting binary data.
1134+
const sample = source.slice(0, 4096);
1135+
const controlChars = (sample.match(/[\x00-\x08\x0E-\x1F]/g) || []).length;
1136+
if (!sample || controlChars > Math.max(4, sample.length * 0.01)) {
1137+
throw new Error('That link is not a readable text document. PDF and image-only files are not supported yet.');
1138+
}
1139+
const effectiveType = type.includes('html') || /<!doctype\s+html|<html[\s>]|<body[\s>]/i.test(sample) ? 'text/html' : type;
1140+
const text = extractDocumentText(source, effectiveType).slice(0, 18000);
11331141
if (text.length < 20) throw new Error('No readable text was found at that link.');
11341142
return { text, finalUrl: current.toString(), truncated: source.length > 18000 };
11351143
}

0 commit comments

Comments
 (0)