-
Notifications
You must be signed in to change notification settings - Fork 88
/
index.ts
467 lines (413 loc) · 14.8 KB
/
index.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
import { JsonObject } from '@dfinity/candid';
import { Principal } from '@dfinity/principal';
import { AgentError } from '../../errors';
import { AnonymousIdentity, Identity } from '../../auth';
import * as cbor from '../../cbor';
import { requestIdOf } from '../../request_id';
import { fromHex } from '../../utils/buffer';
import {
Agent,
QueryFields,
QueryResponse,
ReadStateOptions,
ReadStateResponse,
SubmitResponse,
} from '../api';
import { Expiry, makeNonceTransform } from './transforms';
import {
CallRequest,
Endpoint,
HttpAgentRequest,
HttpAgentRequestTransformFn,
HttpAgentSubmitRequest,
makeNonce,
QueryRequest,
ReadRequestType,
SubmitRequestType,
} from './types';
export * from './transforms';
export { Nonce, makeNonce } from './types';
export enum RequestStatusResponseStatus {
Received = 'received',
Processing = 'processing',
Replied = 'replied',
Rejected = 'rejected',
Unknown = 'unknown',
Done = 'done',
}
// Default delta for ingress expiry is 5 minutes.
const DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS = 5 * 60 * 1000;
// Root public key for the IC, encoded as hex
const IC_ROOT_KEY =
'308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814' +
'c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d968' +
'5f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484' +
'b01291091c5f87b98883463f98091a0baaae';
// IC0 domain info
const IC0_DOMAIN = 'ic0.app';
const IC0_SUB_DOMAIN = '.ic0.app';
class HttpDefaultFetchError extends AgentError {
constructor(public readonly message: string) {
super(message);
}
}
export class IdentityInvalidError extends AgentError {
constructor(public readonly message: string) {
super(message);
}
}
// HttpAgent options that can be used at construction.
export interface HttpAgentOptions {
// Another HttpAgent to inherit configuration (pipeline and fetch) of. This
// is only used at construction.
source?: HttpAgent;
// A surrogate to the global fetch function. Useful for testing.
fetch?: typeof fetch;
// The host to use for the client. By default, uses the same host as
// the current page.
host?: string;
// The principal used to send messages. This cannot be empty at the request
// time (will throw).
identity?: Identity | Promise<Identity>;
credentials?: {
name: string;
password?: string;
};
/**
* Prevents the agent from providing a unique {@link Nonce} with each call.
* Enabling may cause rate limiting of identical requests
* at the boundary nodes.
*
* To add your own nonce generation logic, you can use the following:
* @example
* import {makeNonceTransform, makeNonce} from '@dfinity/agent';
* const agent = new HttpAgent({ disableNonce: true });
* agent.addTransform(makeNonceTransform(makeNonce);
* @default false
*/
disableNonce?: boolean;
}
function getDefaultFetch(): typeof fetch {
let defaultFetch;
if (typeof window !== 'undefined') {
// Browser context
if (window.fetch) {
defaultFetch = window.fetch.bind(window);
} else {
throw new HttpDefaultFetchError(
'Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present.',
);
}
} else if (typeof global !== 'undefined') {
// Node context
if (global.fetch) {
defaultFetch = global.fetch.bind(global);
} else {
throw new HttpDefaultFetchError(
'Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available.',
);
}
} else if (typeof self !== 'undefined') {
if (self.fetch) {
defaultFetch = self.fetch.bind(self);
}
}
if (defaultFetch) {
return defaultFetch;
}
throw new HttpDefaultFetchError(
'Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context.',
);
}
// A HTTP agent allows users to interact with a client of the internet computer
// using the available methods. It exposes an API that closely follows the
// public view of the internet computer, and is not intended to be exposed
// directly to the majority of users due to its low-level interface.
//
// There is a pipeline to apply transformations to the request before sending
// it to the client. This is to decouple signature, nonce generation and
// other computations so that this class can stay as simple as possible while
// allowing extensions.
export class HttpAgent implements Agent {
public rootKey = fromHex(IC_ROOT_KEY);
private readonly _pipeline: HttpAgentRequestTransformFn[] = [];
private _identity: Promise<Identity> | null;
private readonly _fetch: typeof fetch;
private readonly _host: URL;
private readonly _credentials: string | undefined;
private _rootKeyFetched = false;
constructor(options: HttpAgentOptions = {}) {
if (options.source) {
if (!(options.source instanceof HttpAgent)) {
throw new Error("An Agent's source can only be another HttpAgent");
}
this._pipeline = [...options.source._pipeline];
this._identity = options.source._identity;
this._fetch = options.source._fetch;
this._host = options.source._host;
this._credentials = options.source._credentials;
} else {
this._fetch = options.fetch || getDefaultFetch() || fetch.bind(global);
}
if (options.host !== undefined) {
if (!options.host.match(/^[a-z]+:/) && typeof window !== 'undefined') {
this._host = new URL(window.location.protocol + '//' + options.host);
} else {
this._host = new URL(options.host);
}
} else if (options.source !== undefined) {
// Safe to ignore here.
this._host = options.source._host;
} else {
const location = typeof window !== 'undefined' ? window.location : undefined;
if (!location) {
throw new Error('Must specify a host to connect to.');
}
this._host = new URL(location + '');
}
// Rewrite to avoid redirects
if (this._host.hostname.endsWith(IC0_SUB_DOMAIN)) {
this._host.hostname = IC0_DOMAIN;
}
if (options.credentials) {
const { name, password } = options.credentials;
this._credentials = `${name}${password ? ':' + password : ''}`;
}
this._identity = Promise.resolve(options.identity || new AnonymousIdentity());
// Add a nonce transform to ensure calls are unique
if (!options.disableNonce) {
this.addTransform(makeNonceTransform(makeNonce));
}
}
public addTransform(fn: HttpAgentRequestTransformFn, priority = fn.priority || 0): void {
// Keep the pipeline sorted at all time, by priority.
const i = this._pipeline.findIndex(x => (x.priority || 0) < priority);
this._pipeline.splice(i >= 0 ? i : this._pipeline.length, 0, Object.assign(fn, { priority }));
}
public async getPrincipal(): Promise<Principal> {
if (!this._identity) {
throw new IdentityInvalidError(
"This identity has expired due this application's security policy. Please refresh your authentication.",
);
}
return (await this._identity).getPrincipal();
}
public async call(
canisterId: Principal | string,
options: {
methodName: string;
arg: ArrayBuffer;
effectiveCanisterId?: Principal | string;
},
identity?: Identity | Promise<Identity>,
): Promise<SubmitResponse> {
const id = await (identity !== undefined ? await identity : await this._identity);
if (!id) {
throw new IdentityInvalidError(
"This identity has expired due this application's security policy. Please refresh your authentication.",
);
}
const canister = Principal.from(canisterId);
const ecid = options.effectiveCanisterId
? Principal.from(options.effectiveCanisterId)
: canister;
const sender: Principal = id.getPrincipal() || Principal.anonymous();
const submit: CallRequest = {
request_type: SubmitRequestType.Call,
canister_id: canister,
method_name: options.methodName,
arg: options.arg,
sender,
ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let transformedRequest: any = (await this._transform({
request: {
body: null,
method: 'POST',
headers: {
'Content-Type': 'application/cbor',
...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),
},
},
endpoint: Endpoint.Call,
body: submit,
})) as HttpAgentSubmitRequest;
// Apply transform for identity.
transformedRequest = await id.transformRequest(transformedRequest);
const body = cbor.encode(transformedRequest.body);
// Run both in parallel. The fetch is quite expensive, so we have plenty of time to
// calculate the requestId locally.
const [response, requestId] = await Promise.all([
this._fetch('' + new URL(`/api/v2/canister/${ecid.toText()}/call`, this._host), {
...transformedRequest.request,
body,
}),
requestIdOf(submit),
]);
if (!response.ok) {
throw new Error(
`Server returned an error:\n` +
` Code: ${response.status} (${response.statusText})\n` +
` Body: ${await response.text()}\n`,
);
}
return {
requestId,
response: {
ok: response.ok,
status: response.status,
statusText: response.statusText,
},
};
}
public async query(
canisterId: Principal | string,
fields: QueryFields,
identity?: Identity | Promise<Identity>,
): Promise<QueryResponse> {
const id = await (identity !== undefined ? await identity : await this._identity);
if (!id) {
throw new IdentityInvalidError(
"This identity has expired due this application's security policy. Please refresh your authentication.",
);
}
const canister = typeof canisterId === 'string' ? Principal.fromText(canisterId) : canisterId;
const sender = id?.getPrincipal() || Principal.anonymous();
const request: QueryRequest = {
request_type: ReadRequestType.Query,
canister_id: canister,
method_name: fields.methodName,
arg: fields.arg,
sender,
ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),
};
// TODO: remove this any. This can be a Signed or UnSigned request.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let transformedRequest: any = await this._transform({
request: {
method: 'POST',
headers: {
'Content-Type': 'application/cbor',
...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),
},
},
endpoint: Endpoint.Query,
body: request,
});
// Apply transform for identity.
transformedRequest = await id?.transformRequest(transformedRequest);
const body = cbor.encode(transformedRequest.body);
const response = await this._fetch(
'' + new URL(`/api/v2/canister/${canister.toText()}/query`, this._host),
{
...transformedRequest.request,
body,
},
);
if (!response.ok) {
throw new Error(
`Server returned an error:\n` +
` Code: ${response.status} (${response.statusText})\n` +
` Body: ${await response.text()}\n`,
);
}
return cbor.decode(await response.arrayBuffer());
}
public async createReadStateRequest(
fields: ReadStateOptions,
identity?: Identity | Promise<Identity>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> {
const id = await (identity !== undefined ? await identity : await this._identity);
if (!id) {
throw new IdentityInvalidError(
"This identity has expired due this application's security policy. Please refresh your authentication.",
);
}
const sender = id?.getPrincipal() || Principal.anonymous();
// TODO: remove this any. This can be a Signed or UnSigned request.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const transformedRequest: any = await this._transform({
request: {
method: 'POST',
headers: {
'Content-Type': 'application/cbor',
...(this._credentials ? { Authorization: 'Basic ' + btoa(this._credentials) } : {}),
},
},
endpoint: Endpoint.ReadState,
body: {
request_type: ReadRequestType.ReadState,
paths: fields.paths,
sender,
ingress_expiry: new Expiry(DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS),
},
});
// Apply transform for identity.
return id?.transformRequest(transformedRequest);
}
public async readState(
canisterId: Principal | string,
fields: ReadStateOptions,
identity?: Identity | Promise<Identity>,
// eslint-disable-next-line
request?: any,
): Promise<ReadStateResponse> {
const canister = typeof canisterId === 'string' ? Principal.fromText(canisterId) : canisterId;
const transformedRequest = request ?? (await this.createReadStateRequest(fields, identity));
const body = cbor.encode(transformedRequest.body);
const response = await this._fetch(
'' + new URL(`/api/v2/canister/${canister}/read_state`, this._host),
{
...transformedRequest.request,
body,
},
);
if (!response.ok) {
throw new Error(
`Server returned an error:\n` +
` Code: ${response.status} (${response.statusText})\n` +
` Body: ${await response.text()}\n`,
);
}
return cbor.decode(await response.arrayBuffer());
}
public async status(): Promise<JsonObject> {
const headers: Record<string, string> = this._credentials
? {
Authorization: 'Basic ' + btoa(this._credentials),
}
: {};
const response = await this._fetch('' + new URL(`/api/v2/status`, this._host), { headers });
if (!response.ok) {
throw new Error(
`Server returned an error:\n` +
` Code: ${response.status} (${response.statusText})\n` +
` Body: ${await response.text()}\n`,
);
}
return cbor.decode(await response.arrayBuffer());
}
public async fetchRootKey(): Promise<ArrayBuffer> {
if (!this._rootKeyFetched) {
// Hex-encoded version of the replica root key
this.rootKey = ((await this.status()) as any).root_key;
this._rootKeyFetched = true;
}
return this.rootKey;
}
public invalidateIdentity(): void {
this._identity = null;
}
public replaceIdentity(identity: Identity): void {
this._identity = Promise.resolve(identity);
}
protected _transform(request: HttpAgentRequest): Promise<HttpAgentRequest> {
let p = Promise.resolve(request);
for (const fn of this._pipeline) {
p = p.then(r => fn(r).then(r2 => r2 || r));
}
return p;
}
}