Skip to content
This repository was archived by the owner on Jun 6, 2024. It is now read-only.

Commit 7fb0721

Browse files
authored
Merge pull request #112 from HubSpot/keep-original-cf-property
Keep original cf property of request
2 parents 5c983db + 7dbeb1a commit 7fb0721

File tree

2 files changed

+49
-11
lines changed

2 files changed

+49
-11
lines changed

lib/__tests__/cloudworker.test.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,4 +129,40 @@ describe('cloudworker', () => {
129129
expect(res.headers.get('x-colo')).toEqual('LAX')
130130
done()
131131
})
132+
133+
test('dispatch respects existing cf property', async done => {
134+
const script = `
135+
addEventListener('fetch', event => {
136+
const req = event.request
137+
const cloned = req.clone()
138+
const resp = new Response('', {
139+
headers: {
140+
'x-tlsVersion': cloned.cf.tlsVersion,
141+
'x-tlsCipher': cloned.cf.tlsCipher,
142+
'x-country': cloned.cf.country,
143+
'x-colo': cloned.cf.colo,
144+
}
145+
})
146+
event.respondWith(resp)
147+
})
148+
`
149+
const cw = new Cloudworker(script)
150+
const req = new runtime.Request('https://myfancywebsite.com/someurl')
151+
Object.defineProperty(req, 'cf', {
152+
value: {
153+
tlsVersion: 'TLSv1.1',
154+
tlsCipher: 'ACDHE-ECDSA-CHACHA20-POLY1305',
155+
country: 'CA',
156+
colo: 'YYZ',
157+
},
158+
writable: false,
159+
enumerable: false,
160+
})
161+
const res = await cw.dispatch(req)
162+
expect(res.headers.get('x-tlsversion')).toEqual('TLSv1.1')
163+
expect(res.headers.get('x-tlscipher')).toEqual('ACDHE-ECDSA-CHACHA20-POLY1305')
164+
expect(res.headers.get('x-country')).toEqual('CA')
165+
expect(res.headers.get('x-colo')).toEqual('YYZ')
166+
done()
167+
})
132168
})

lib/runtime/fetch.js

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -68,24 +68,26 @@ class ShimRequest extends Request {
6868
freezeHeaders(req.headers)
6969
}
7070
if (this.cf) {
71-
bindCfProperty(req)
71+
Object.defineProperty(req, 'cf', {value: this.cf, writable: false, enumerable: false})
7272
}
7373

7474
return req
7575
}
7676
}
7777

7878
function bindCfProperty (req) {
79-
Object.defineProperty(req, 'cf', {
80-
value: {
81-
tlsVersion: 'TLSv1.2',
82-
tlsCipher: 'ECDHE-ECDSA-CHACHA20-POLY1305',
83-
country: 'US',
84-
colo: 'LAX',
85-
},
86-
writable: false,
87-
enumerable: false,
88-
})
79+
if (!req.cf) {
80+
Object.defineProperty(req, 'cf', {
81+
value: {
82+
tlsVersion: 'TLSv1.2',
83+
tlsCipher: 'ECDHE-ECDSA-CHACHA20-POLY1305',
84+
country: 'US',
85+
colo: 'LAX',
86+
},
87+
writable: false,
88+
enumerable: false,
89+
})
90+
}
8991
}
9092

9193
module.exports.fetch = fetchShim

0 commit comments

Comments
 (0)