Skip to content

Commit b6431cd

Browse files
committed
1 parent 017a5fd commit b6431cd

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

lib/Encoder.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import createBoundary from "./util/createBoundary"
2+
import escape from "./util/escapeName"
23
import isFormData from "./util/isFormData"
34
import isFile from "./util/isFile"
45

@@ -96,10 +97,10 @@ export class Encoder {
9697
let header = ""
9798

9899
header += `${this.#DASHES}${this.boundary}${this.#CRLF}`
99-
header += `Content-Disposition: form-data; name="${name}"`
100+
header += `Content-Disposition: form-data; name="${escape(name)}"`
100101

101102
if (isFile(value)) {
102-
header += `; filename="${value.name}"${this.#CRLF}`
103+
header += `; filename="${escape(value.name)}"${this.#CRLF}`
103104
header += `Content-Type: ${value.type || "application/octet-stream"}`
104105
}
105106

lib/util/escapeName.test.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import test from "ava"
2+
3+
import escapeName from "./escapeName"
4+
5+
const CR = "%0D"
6+
const LF = "%0A"
7+
const Q = "%22"
8+
9+
test("Escapes all the CRs in the name", t => {
10+
t.is<string>(escapeName("\rna\rme\r"), `${CR}na${CR}me${CR}`)
11+
})
12+
13+
test("Keeps escaped CR as is", t => {
14+
const expected = `name${CR}`
15+
16+
t.is<string>(escapeName(expected), expected)
17+
})
18+
19+
test("Escapes all the LFs in the name", t => {
20+
t.is<string>(escapeName("nam\ne\n"), `nam${LF}e${LF}`)
21+
})
22+
23+
test("Keeps escaped LF as is", t => {
24+
const expected = `name${LF}`
25+
26+
t.is<string>(escapeName(expected), expected)
27+
})
28+
29+
test("Escapes all double quotes in the name", t => {
30+
t.is<string>(escapeName("\"name\""), `${Q}name${Q}`)
31+
})

lib/util/escapeName.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
const escapeName = (name: unknown) => String(name)
2+
.replace(/\r/g, "%0D") // CR
3+
.replace(/\n/g, "%0A") // LF
4+
.replace(/"/g, "%22")
5+
6+
export default escapeName

0 commit comments

Comments
 (0)