-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathhttp_request.ts
333 lines (299 loc) · 10.1 KB
/
http_request.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/**
* Implement the HttpRequest to Canisters Proposal.
*
* TODO: Add support for streaming.
*/
import { Actor, IDL, HttpAgent } from '@dfinity/agent';
import { Principal } from '@dfinity/principal';
import { validateBody } from './validation';
import * as base64Arraybuffer from 'base64-arraybuffer';
import * as pako from 'pako';
const hostnameCanisterIdMap: Record<string, [string, string]> = {
'identity.ic0.app': ['rdmx6-jaaaa-aaaaa-aaadq-cai', 'ic0.app'],
'nns.ic0.app': ['qoctq-giaaa-aaaaa-aaaea-cai', 'ic0.app'],
'dscvr.ic0.app': ['h5aet-waaaa-aaaab-qaamq-cai', 'ic0.page'],
};
const shouldFetchRootKey: boolean = !!process.env.FORCE_FETCH_ROOT_KEY || false;
const swLocation = new URL(self.location.toString());
const [_swCanisterId, swDomains] = (() => {
const maybeSplit = splitHostnameForCanisterId(swLocation.hostname);
if (maybeSplit) {
return maybeSplit;
} else {
return [null, swLocation.hostname];
}
})() as [Principal | null, string];
/**
* Split a hostname up-to the first valid canister ID from the right.
* @param hostname The hostname to analyze.
* @returns A canister ID followed by all subdomains that are after it, or null if no
* canister ID were found.
*/
function splitHostnameForCanisterId(hostname: string): [Principal, string] | null {
const maybeFixed = hostnameCanisterIdMap[hostname];
if (maybeFixed) {
return [Principal.fromText(maybeFixed[0]), maybeFixed[1]];
}
const subdomains = hostname.split('.').reverse();
const topdomains = [];
for (const domain of subdomains) {
try {
const principal = Principal.fromText(domain);
return [principal, topdomains.reverse().join('.')];
} catch (_) {
topdomains.push(domain);
}
}
return null;
}
/**
* Try to resolve the Canister ID to contact in the domain name.
* @param hostname The domain name to look up.
* @returns A Canister ID or null if none were found.
*/
function maybeResolveCanisterIdFromHostName(hostname: string): Principal | null {
// Try to resolve from the right to the left.
const maybeCanisterId = splitHostnameForCanisterId(hostname);
if (maybeCanisterId && swDomains === maybeCanisterId[1]) {
return maybeCanisterId[0];
}
return null;
}
/**
* Try to resolve the Canister ID to contact in the search params.
* @param searchParams The URL Search params.
* @param isLocal Whether to resolve headers as if we were running locally.
* @returns A Canister ID or null if none were found.
*/
function maybeResolveCanisterIdFromSearchParam(
searchParams: URLSearchParams,
isLocal: boolean,
): Principal | null {
// Skip this if we're not on localhost.
if (!isLocal) {
return null;
}
const maybeCanisterId = searchParams.get('canisterId');
if (maybeCanisterId) {
try {
return Principal.fromText(maybeCanisterId);
} catch (e) {
// Do nothing.
}
}
return null;
}
/**
* Try to resolve the Canister ID to contact from a URL string.
* @param urlString The URL in string format (normally from the request).
* @param isLocal Whether to resolve headers as if we were running locally.
* @returns A Canister ID or null if none were found.
*/
function resolveCanisterIdFromUrl(urlString: string, isLocal: boolean): Principal | null {
try {
const url = new URL(urlString);
return (
maybeResolveCanisterIdFromHostName(url.hostname) ||
maybeResolveCanisterIdFromSearchParam(url.searchParams, isLocal)
);
} catch (_) {
return null;
}
}
/**
* Try to resolve the Canister ID to contact from headers.
* @param headers Headers from the HttpRequest.
* @param isLocal Whether to resolve headers as if we were running locally.
* @returns A Canister ID or null if none were found.
*/
function maybeResolveCanisterIdFromHeaders(headers: Headers, isLocal: boolean): Principal | null {
const maybeHostHeader = headers.get('host');
if (maybeHostHeader) {
// Remove the port.
const maybeCanisterId = maybeResolveCanisterIdFromHostName(
maybeHostHeader.replace(/:\d+$/, ''),
);
if (maybeCanisterId) {
return maybeCanisterId;
}
}
if (isLocal) {
const maybeRefererHeader = headers.get('referer');
if (maybeRefererHeader) {
const maybeCanisterId = resolveCanisterIdFromUrl(maybeRefererHeader, isLocal);
if (maybeCanisterId) {
return maybeCanisterId;
}
}
}
return null;
}
function maybeResolveCanisterIdFromHttpRequest(request: Request, isLocal: boolean) {
return (
(isLocal && resolveCanisterIdFromUrl(request.referrer, isLocal)) ||
maybeResolveCanisterIdFromHeaders(request.headers, isLocal) ||
resolveCanisterIdFromUrl(request.url, isLocal)
);
}
const canisterIdlFactory: IDL.InterfaceFactory = ({ IDL }) => {
const HeaderField = IDL.Tuple(IDL.Text, IDL.Text);
const HttpRequest = IDL.Record({
method: IDL.Text,
url: IDL.Text,
headers: IDL.Vec(HeaderField),
body: IDL.Vec(IDL.Nat8),
});
const HttpResponse = IDL.Record({
status_code: IDL.Nat16,
headers: IDL.Vec(HeaderField),
body: IDL.Vec(IDL.Nat8),
// TODO: Support streaming in JavaScript.
});
return IDL.Service({
http_request: IDL.Func([HttpRequest], [HttpResponse], ['query']),
});
};
/**
* Decode a body (ie. deflate or gunzip it) based on its content-encoding.
* @param body The body to decode.
* @param encoding Its content-encoding associated header.
*/
function decodeBody(body: Uint8Array, encoding: string): Uint8Array {
switch (encoding) {
case 'identity':
case '':
return body;
case 'gzip':
return pako.ungzip(body);
case 'deflate':
return pako.inflate(body);
default:
throw new Error(`Unsupported encoding: "${encoding}"`);
}
}
/**
* Box a request, send it to the canister, and handle its response, creating a Response
* object.
* @param request The request received from the browser.
* @returns The response to send to the browser.
* @throws If an internal error happens.
*/
export async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url);
/**
* We forward all requests to /api/ to the replica, as is.
*/
if (url.pathname.startsWith('/api/')) {
return await fetch(request);
}
/**
* We refuse any request to /_/*
*/
if (url.pathname.startsWith('/_/')) {
return new Response(null, { status: 404 });
}
/**
* We try to do an HTTP Request query.
*/
const isLocal = swDomains === 'localhost';
const maybeCanisterId = maybeResolveCanisterIdFromHttpRequest(request, isLocal);
if (maybeCanisterId) {
try {
const replicaUrl = new URL(url.origin);
const agent = new HttpAgent({ host: replicaUrl.toString() });
const actor = Actor.createActor(canisterIdlFactory, {
agent,
canisterId: maybeCanisterId,
});
const requestHeaders: [string, string][] = [];
request.headers.forEach((value, key) => requestHeaders.push([key, value]));
// If the accept encoding isn't given, add it because we want to save bandwidth.
if (!request.headers.has('Accept-Encoding')) {
requestHeaders.push(['Accept-Encoding', 'gzip, deflate, identity']);
}
const httpRequest = {
method: request.method,
url: url.pathname + url.search,
headers: requestHeaders,
body: [...new Uint8Array(await request.arrayBuffer())],
};
const httpResponse: any = await actor.http_request(httpRequest);
const headers = new Headers();
let certificate: ArrayBuffer | undefined;
let tree: ArrayBuffer | undefined;
let encoding = '';
for (const [key, value] of httpResponse.headers) {
switch (key.trim().toLowerCase()) {
case 'ic-certificate':
{
const fields = value.split(/,/);
for (const f of fields) {
const [_0, name, b64Value] = [...f.match(/^(.*)=:(.*):$/)].map(x => x.trim());
const value = base64Arraybuffer.decode(b64Value);
if (name === 'certificate') {
certificate = value;
} else if (name === 'tree') {
tree = value;
}
}
}
continue;
case 'content-encoding':
encoding = value.trim();
break;
}
headers.append(key, value);
}
const body = new Uint8Array(httpResponse.body);
const identity = decodeBody(body, encoding);
let bodyValid = false;
if (certificate && tree) {
// Try to validate the body as is.
bodyValid = await validateBody(
maybeCanisterId,
url.pathname,
body.buffer,
certificate,
tree,
agent,
shouldFetchRootKey,
);
if (!bodyValid) {
// If that didn't work, try to validate its identity version. This is for
// backward compatibility.
bodyValid = await validateBody(
maybeCanisterId,
url.pathname,
identity.buffer,
certificate,
tree,
agent,
isLocal,
);
}
}
if (bodyValid) {
return new Response(identity.buffer, {
status: httpResponse.status_code,
headers,
});
} else {
console.error('BODY DOES NOT PASS VERIFICATION');
return new Response('Body does not pass verification', { status: 500 });
}
} catch (e) {
console.error('An error happened:', e);
return new Response(null, { status: 500 });
}
}
// Last check. IF this is not part of the same domain, then we simply let it load as is.
// The same domain will always load using our service worker, and not the same domain
// would load by reference. If you want security for your users at that point you
// should use SRI to make sure the resource matches.
if (!url.hostname.endsWith(swDomains)) {
// todo: Do we need to check for headers and certify the content here?
return await fetch(request);
}
console.error(`URL ${JSON.stringify(url.toString())} did not resolve to a canister ID.`);
return new Response('Could not find the canister ID.', { status: 404 });
}