@ar.io/sdk 3.11.0-alpha.12 → 3.11.0-alpha.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundles/web.bundle.min.js +120 -123
- package/lib/cjs/common/ant-versions.js +3 -2
- package/lib/cjs/common/index.js +0 -2
- package/lib/cjs/common/io.js +13 -9
- package/lib/cjs/common/turbo.js +1 -1
- package/lib/cjs/types/index.js +0 -1
- package/lib/cjs/utils/ao.js +2 -1
- package/lib/cjs/version.js +1 -1
- package/lib/esm/common/ant-versions.js +3 -2
- package/lib/esm/common/index.js +0 -2
- package/lib/esm/common/io.js +13 -9
- package/lib/esm/common/turbo.js +1 -1
- package/lib/esm/types/index.js +0 -1
- package/lib/esm/utils/ao.js +2 -1
- package/lib/esm/version.js +1 -1
- package/lib/types/common/ant-versions.d.ts +3 -5
- package/lib/types/common/index.d.ts +0 -1
- package/lib/types/types/index.d.ts +0 -1
- package/lib/types/version.d.ts +1 -1
- package/package.json +1 -1
- package/lib/cjs/common/wayfinder/gateways/trusted-gateways.js +0 -106
- package/lib/cjs/common/wayfinder/gateways.js +0 -86
- package/lib/cjs/common/wayfinder/index.js +0 -44
- package/lib/cjs/common/wayfinder/routers/priority.js +0 -29
- package/lib/cjs/common/wayfinder/routers/priority.test.js +0 -155
- package/lib/cjs/common/wayfinder/routers/random.js +0 -23
- package/lib/cjs/common/wayfinder/routers/random.test.js +0 -25
- package/lib/cjs/common/wayfinder/routers/simple-cache.js +0 -25
- package/lib/cjs/common/wayfinder/routers/simple-cache.test.js +0 -41
- package/lib/cjs/common/wayfinder/routers/static.js +0 -14
- package/lib/cjs/common/wayfinder/routers/static.test.js +0 -14
- package/lib/cjs/common/wayfinder/verification/data-root-verifier.js +0 -139
- package/lib/cjs/common/wayfinder/verification/hash-verifier.js +0 -50
- package/lib/cjs/common/wayfinder/wayfinder.js +0 -596
- package/lib/cjs/common/wayfinder/wayfinder.test.js +0 -500
- package/lib/cjs/types/wayfinder.js +0 -3
- package/lib/esm/common/wayfinder/gateways/trusted-gateways.js +0 -102
- package/lib/esm/common/wayfinder/gateways.js +0 -80
- package/lib/esm/common/wayfinder/index.js +0 -28
- package/lib/esm/common/wayfinder/routers/priority.js +0 -25
- package/lib/esm/common/wayfinder/routers/priority.test.js +0 -153
- package/lib/esm/common/wayfinder/routers/random.js +0 -19
- package/lib/esm/common/wayfinder/routers/random.test.js +0 -23
- package/lib/esm/common/wayfinder/routers/simple-cache.js +0 -21
- package/lib/esm/common/wayfinder/routers/simple-cache.test.js +0 -39
- package/lib/esm/common/wayfinder/routers/static.js +0 -10
- package/lib/esm/common/wayfinder/routers/static.test.js +0 -12
- package/lib/esm/common/wayfinder/verification/data-root-verifier.js +0 -130
- package/lib/esm/common/wayfinder/verification/hash-verifier.js +0 -46
- package/lib/esm/common/wayfinder/wayfinder.js +0 -584
- package/lib/esm/common/wayfinder/wayfinder.test.js +0 -495
- package/lib/esm/types/wayfinder.js +0 -2
- package/lib/types/common/wayfinder/gateways/trusted-gateways.d.ts +0 -51
- package/lib/types/common/wayfinder/gateways.d.ts +0 -53
- package/lib/types/common/wayfinder/index.d.ts +0 -23
- package/lib/types/common/wayfinder/routers/priority.d.ts +0 -29
- package/lib/types/common/wayfinder/routers/priority.test.d.ts +0 -1
- package/lib/types/common/wayfinder/routers/random.d.ts +0 -27
- package/lib/types/common/wayfinder/routers/random.test.d.ts +0 -1
- package/lib/types/common/wayfinder/routers/simple-cache.d.ts +0 -28
- package/lib/types/common/wayfinder/routers/simple-cache.test.d.ts +0 -1
- package/lib/types/common/wayfinder/routers/static.d.ts +0 -24
- package/lib/types/common/wayfinder/routers/static.test.d.ts +0 -1
- package/lib/types/common/wayfinder/verification/data-root-verifier.d.ts +0 -31
- package/lib/types/common/wayfinder/verification/hash-verifier.d.ts +0 -27
- package/lib/types/common/wayfinder/wayfinder.d.ts +0 -265
- package/lib/types/common/wayfinder/wayfinder.test.d.ts +0 -1
- package/lib/types/types/wayfinder.d.ts +0 -62
|
@@ -1,584 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
|
|
3
|
-
*
|
|
4
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
-
* you may not use this file except in compliance with the License.
|
|
6
|
-
* You may obtain a copy of the License at
|
|
7
|
-
*
|
|
8
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
*
|
|
10
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
* See the License for the specific language governing permissions and
|
|
14
|
-
* limitations under the License.
|
|
15
|
-
*/
|
|
16
|
-
import EventEmitter from 'node:events';
|
|
17
|
-
import { PassThrough, Readable } from 'node:stream';
|
|
18
|
-
import { ARIO } from '../io.js';
|
|
19
|
-
import { Logger } from '../logger.js';
|
|
20
|
-
import { NetworkGatewaysProvider, SimpleCacheGatewaysProvider, StaticGatewaysProvider, } from './gateways.js';
|
|
21
|
-
import { TrustedGatewaysHashProvider } from './gateways/trusted-gateways.js';
|
|
22
|
-
import { RandomGatewayRouter } from './routers/random.js';
|
|
23
|
-
import { HashVerifier } from './verification/hash-verifier.js';
|
|
24
|
-
// known regexes for wayfinder urls
|
|
25
|
-
export const arnsRegex = /^[a-z0-9_-]{1,51}$/;
|
|
26
|
-
export const txIdRegex = /^[A-Za-z0-9_-]{43}$/;
|
|
27
|
-
/**
|
|
28
|
-
* Core function to resolve a wayfinder url against a target gateway
|
|
29
|
-
* @param originalUrl - the wayfinder url to resolve
|
|
30
|
-
* @param targetGateway - the target gateway to resolve the url against
|
|
31
|
-
* @returns the resolved url that can be used to make a request
|
|
32
|
-
*/
|
|
33
|
-
export const resolveWayfinderUrl = async ({ originalUrl, targetGateway, logger, }) => {
|
|
34
|
-
if (originalUrl.toString().startsWith('ar://')) {
|
|
35
|
-
logger?.debug(`Applying wayfinder routing protocol to ${originalUrl}`, {
|
|
36
|
-
originalUrl,
|
|
37
|
-
});
|
|
38
|
-
const targetGatewayUrl = new URL(await targetGateway());
|
|
39
|
-
logger?.debug(`Selected target gateway: ${targetGatewayUrl}`, {
|
|
40
|
-
originalUrl,
|
|
41
|
-
targetGateway: targetGatewayUrl,
|
|
42
|
-
});
|
|
43
|
-
const [, path] = originalUrl.toString().split('ar://');
|
|
44
|
-
// e.g. ar:///info should route to the info endpoint of the target gateway
|
|
45
|
-
if (path.startsWith('/')) {
|
|
46
|
-
logger?.debug(`Routing to ${path.slice(1)} on ${targetGatewayUrl}`, {
|
|
47
|
-
originalUrl,
|
|
48
|
-
targetGateway: targetGatewayUrl,
|
|
49
|
-
});
|
|
50
|
-
return new URL(path.slice(1), targetGatewayUrl);
|
|
51
|
-
}
|
|
52
|
-
// TODO: this breaks 43 character named arns names - we should check a a local name cache list before resolving raw transaction ids
|
|
53
|
-
if (txIdRegex.test(path)) {
|
|
54
|
-
const [txId, ...rest] = path.split('/');
|
|
55
|
-
return new URL(`${txId}${rest.join('/')}`, targetGatewayUrl);
|
|
56
|
-
}
|
|
57
|
-
if (arnsRegex.test(path)) {
|
|
58
|
-
// TODO: tests to ensure arns names support query params and paths
|
|
59
|
-
const [name, ...rest] = path.split('/');
|
|
60
|
-
const arnsUrl = `${targetGatewayUrl.protocol}//${name}.${targetGatewayUrl.hostname}${targetGatewayUrl.port ? `:${targetGatewayUrl.port}` : ''}`;
|
|
61
|
-
logger?.debug(`Routing to ${path} on ${arnsUrl}`, {
|
|
62
|
-
originalUrl,
|
|
63
|
-
targetGateway: targetGatewayUrl,
|
|
64
|
-
});
|
|
65
|
-
return new URL(rest.join('/'), arnsUrl);
|
|
66
|
-
}
|
|
67
|
-
// TODO: support .eth addresses
|
|
68
|
-
// TODO: "gasless" routing via DNS TXT records (e.g. ar://gatewaypie.com -> TXT record lookup for TX ID and redirect to that gateway)
|
|
69
|
-
}
|
|
70
|
-
logger?.debug('No wayfinder routing protocol applied', {
|
|
71
|
-
originalUrl,
|
|
72
|
-
});
|
|
73
|
-
// return the original url if it's not a wayfinder url (allows you to use the wayfinder client with non-wayfinder urls)
|
|
74
|
-
return new URL(originalUrl);
|
|
75
|
-
};
|
|
76
|
-
export class WayfinderEmitter extends EventEmitter {
|
|
77
|
-
constructor({ onVerificationPassed, onVerificationFailed, onVerificationProgress,
|
|
78
|
-
// TODO: continue this pattern for all events
|
|
79
|
-
} = {}) {
|
|
80
|
-
super();
|
|
81
|
-
if (onVerificationPassed) {
|
|
82
|
-
this.on('verification-passed', onVerificationPassed);
|
|
83
|
-
}
|
|
84
|
-
if (onVerificationFailed) {
|
|
85
|
-
this.on('verification-failed', onVerificationFailed);
|
|
86
|
-
}
|
|
87
|
-
if (onVerificationProgress) {
|
|
88
|
-
this.on('verification-progress', onVerificationProgress);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
emit(event, payload) {
|
|
92
|
-
return super.emit(event, payload);
|
|
93
|
-
}
|
|
94
|
-
on(event, listener) {
|
|
95
|
-
return super.on(event, listener);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
export function tapAndVerifyStream({ originalStream, contentLength, verifyData, txId, emitter, }) {
|
|
99
|
-
// taps node streams
|
|
100
|
-
if (originalStream instanceof Readable &&
|
|
101
|
-
typeof originalStream.pipe === 'function') {
|
|
102
|
-
const tappedClientStream = new PassThrough();
|
|
103
|
-
const streamToVerify = new PassThrough();
|
|
104
|
-
// kick off the verification promise, this will be awaited when the original stream ends
|
|
105
|
-
const verificationPromise = verifyData({
|
|
106
|
-
data: streamToVerify,
|
|
107
|
-
txId,
|
|
108
|
-
});
|
|
109
|
-
let bytesProcessed = 0;
|
|
110
|
-
// pipe the original stream to the verifier and the client stream
|
|
111
|
-
originalStream.on('data', (chunk) => {
|
|
112
|
-
streamToVerify.write(chunk);
|
|
113
|
-
tappedClientStream.write(chunk);
|
|
114
|
-
bytesProcessed += chunk.length;
|
|
115
|
-
// only emit if contentLength is not 0
|
|
116
|
-
if (contentLength !== 0) {
|
|
117
|
-
emitter?.emit('verification-progress', {
|
|
118
|
-
txId,
|
|
119
|
-
totalBytes: contentLength,
|
|
120
|
-
processedBytes: bytesProcessed,
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
});
|
|
124
|
-
originalStream.on('end', async () => {
|
|
125
|
-
streamToVerify.end(); // triggers verifier completion and completes the verification promise
|
|
126
|
-
try {
|
|
127
|
-
await verificationPromise;
|
|
128
|
-
emitter?.emit('verification-passed', {
|
|
129
|
-
txId,
|
|
130
|
-
});
|
|
131
|
-
tappedClientStream.end();
|
|
132
|
-
}
|
|
133
|
-
catch (error) {
|
|
134
|
-
emitter?.emit('verification-failed', {
|
|
135
|
-
error,
|
|
136
|
-
txId,
|
|
137
|
-
});
|
|
138
|
-
tappedClientStream.destroy(error);
|
|
139
|
-
}
|
|
140
|
-
});
|
|
141
|
-
originalStream.on('error', (err) => {
|
|
142
|
-
emitter?.emit('verification-failed', {
|
|
143
|
-
error: err,
|
|
144
|
-
txId,
|
|
145
|
-
});
|
|
146
|
-
streamToVerify.destroy(err);
|
|
147
|
-
tappedClientStream.destroy(err);
|
|
148
|
-
});
|
|
149
|
-
// send the stream to the verify function and if it errors end the client stream
|
|
150
|
-
return tappedClientStream;
|
|
151
|
-
}
|
|
152
|
-
// taps web readable streams
|
|
153
|
-
if (originalStream instanceof ReadableStream &&
|
|
154
|
-
typeof originalStream.tee === 'function') {
|
|
155
|
-
const [verifyBranch, clientBranch] = originalStream.tee();
|
|
156
|
-
// setup our promise to verify the data
|
|
157
|
-
const verificationPromise = verifyData({
|
|
158
|
-
data: verifyBranch,
|
|
159
|
-
txId,
|
|
160
|
-
});
|
|
161
|
-
let bytesProcessed = 0;
|
|
162
|
-
const reader = clientBranch.getReader();
|
|
163
|
-
const clientStreamWithVerification = new ReadableStream({
|
|
164
|
-
async pull(controller) {
|
|
165
|
-
const { done, value } = await reader.read();
|
|
166
|
-
if (done) {
|
|
167
|
-
try {
|
|
168
|
-
// due to backpressure, if the client does not consume the stream, the verification will not complete (particularly important for fetch, where the response body needs to be awaited for verification to complete)
|
|
169
|
-
await verificationPromise;
|
|
170
|
-
emitter?.emit('verification-passed', {
|
|
171
|
-
txId,
|
|
172
|
-
});
|
|
173
|
-
controller.close();
|
|
174
|
-
}
|
|
175
|
-
catch (err) {
|
|
176
|
-
emitter?.emit('verification-failed', {
|
|
177
|
-
txId,
|
|
178
|
-
error: err,
|
|
179
|
-
});
|
|
180
|
-
controller.error(err);
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
else {
|
|
184
|
-
bytesProcessed += value.length;
|
|
185
|
-
emitter?.emit('verification-progress', {
|
|
186
|
-
txId,
|
|
187
|
-
totalBytes: contentLength,
|
|
188
|
-
processedBytes: bytesProcessed,
|
|
189
|
-
});
|
|
190
|
-
controller.enqueue(value);
|
|
191
|
-
}
|
|
192
|
-
},
|
|
193
|
-
cancel(reason) {
|
|
194
|
-
reader.cancel(reason);
|
|
195
|
-
emitter?.emit('verification-failed', {
|
|
196
|
-
txId,
|
|
197
|
-
error: new Error('Verification cancelled', {
|
|
198
|
-
cause: {
|
|
199
|
-
reason,
|
|
200
|
-
},
|
|
201
|
-
}),
|
|
202
|
-
});
|
|
203
|
-
},
|
|
204
|
-
});
|
|
205
|
-
return clientStreamWithVerification;
|
|
206
|
-
}
|
|
207
|
-
throw new Error('Unsupported body type for cloning');
|
|
208
|
-
}
|
|
209
|
-
export function wrapVerifiedResponse(original, newBody, txId) {
|
|
210
|
-
// Clone headers (Header objects aren't serializable)
|
|
211
|
-
const headers = new Headers();
|
|
212
|
-
original.headers.forEach((value, key) => headers.set(key, value));
|
|
213
|
-
// Create a new Response with the new body and cloned headers
|
|
214
|
-
const wrapped = new Response(newBody, {
|
|
215
|
-
status: original.status,
|
|
216
|
-
statusText: original.statusText,
|
|
217
|
-
headers,
|
|
218
|
-
});
|
|
219
|
-
// Attach txId for downstream tracking
|
|
220
|
-
wrapped.txId = txId;
|
|
221
|
-
wrapped.redirectedFrom = original.url;
|
|
222
|
-
return wrapped;
|
|
223
|
-
}
|
|
224
|
-
/**
|
|
225
|
-
* Creates a wrapped http client that supports ar:// protocol
|
|
226
|
-
*
|
|
227
|
-
* This function leverages a Proxy to intercept calls to the http client
|
|
228
|
-
* and redirects them to the target gateway using the resolveUrl function url.
|
|
229
|
-
* It also supports the http client methods like get(), post(), put(), delete(), etc.
|
|
230
|
-
*
|
|
231
|
-
* Any URLs provided that are not wayfinder urls will be returned as is.
|
|
232
|
-
*
|
|
233
|
-
* @param httpClient - the http client to wrap (e.g. axios, fetch, got, etc.)
|
|
234
|
-
* @param resolveUrl - the function to construct the redirect url for ar:// requests
|
|
235
|
-
* @returns a wrapped http client that supports ar:// protocol
|
|
236
|
-
*/
|
|
237
|
-
export const createWayfinderClient = ({ httpClient, resolveUrl, verifyData, emitter = new WayfinderEmitter(), logger, }) => {
|
|
238
|
-
const wayfinderRedirect = async (fn, rawArgs) => {
|
|
239
|
-
// TODO: handle if first arg is not a string (i.e. just return the result of the function call)
|
|
240
|
-
const [originalUrl, ...rest] = rawArgs;
|
|
241
|
-
if (typeof originalUrl !== 'string') {
|
|
242
|
-
logger?.debug('Original URL is not a string, skipping routing', {
|
|
243
|
-
originalUrl,
|
|
244
|
-
});
|
|
245
|
-
return fn(...rawArgs);
|
|
246
|
-
}
|
|
247
|
-
emitter?.emit('routing-started', {
|
|
248
|
-
originalUrl: originalUrl.toString(),
|
|
249
|
-
});
|
|
250
|
-
// route the request to the target gateway
|
|
251
|
-
const redirectUrl = await resolveUrl({
|
|
252
|
-
originalUrl,
|
|
253
|
-
logger,
|
|
254
|
-
});
|
|
255
|
-
emitter?.emit('routing-succeeded', {
|
|
256
|
-
originalUrl,
|
|
257
|
-
targetGateway: redirectUrl.toString(),
|
|
258
|
-
});
|
|
259
|
-
logger?.debug(`Redirecting request to ${redirectUrl}`, {
|
|
260
|
-
originalUrl,
|
|
261
|
-
redirectUrl,
|
|
262
|
-
});
|
|
263
|
-
// make the request to the target gateway using the redirect url and http client
|
|
264
|
-
const response = await fn(redirectUrl.toString(), ...rest);
|
|
265
|
-
// TODO: trigger a routing event with the raw response object?
|
|
266
|
-
logger?.debug(`Successfully routed request to ${redirectUrl}`, {
|
|
267
|
-
redirectUrl,
|
|
268
|
-
originalUrl,
|
|
269
|
-
});
|
|
270
|
-
// only verify data if the redirect url is different from the original url
|
|
271
|
-
if (response && redirectUrl.toString() !== originalUrl.toString()) {
|
|
272
|
-
if (verifyData) {
|
|
273
|
-
// if the headers do not have .get on them, we need to parse the headers manually
|
|
274
|
-
const headers = new Headers();
|
|
275
|
-
let headersObject = response.headers ?? {};
|
|
276
|
-
if (typeof headersObject.get !== 'function') {
|
|
277
|
-
headersObject = Object.fromEntries(headersObject);
|
|
278
|
-
for (const [key, value] of Object.entries(headersObject)) {
|
|
279
|
-
headers.set(key, value);
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
else {
|
|
283
|
-
for (const [key, value] of headersObject.entries()) {
|
|
284
|
-
headers.set(key, value);
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
// transaction id is either in the response headers or the path of the request as the first parameter
|
|
288
|
-
// TODO: we may want to move this parsing to be returned by the resolveUrl function depending on the redirect URL we've constructed
|
|
289
|
-
const txId = headers.get('x-arns-resolved-id') ??
|
|
290
|
-
redirectUrl.pathname.split('/')[1];
|
|
291
|
-
// TODO: validate nodes return content length for all responses
|
|
292
|
-
const contentLength = +(headers.get('content-length') ?? 0);
|
|
293
|
-
if (!txIdRegex.test(txId)) {
|
|
294
|
-
// no transaction id found, skip verification
|
|
295
|
-
logger?.debug('No transaction id found, skipping verification', {
|
|
296
|
-
redirectUrl,
|
|
297
|
-
originalUrl,
|
|
298
|
-
});
|
|
299
|
-
emitter?.emit('verification-skipped', {
|
|
300
|
-
originalUrl,
|
|
301
|
-
});
|
|
302
|
-
return response;
|
|
303
|
-
}
|
|
304
|
-
emitter?.emit('identified-transaction-id', {
|
|
305
|
-
originalUrl,
|
|
306
|
-
targetGateway: redirectUrl.toString(),
|
|
307
|
-
txId,
|
|
308
|
-
});
|
|
309
|
-
// parse out the key that contains the response body, we'll use it later when updating the response object
|
|
310
|
-
const responseDataKey = response.body
|
|
311
|
-
? 'body'
|
|
312
|
-
: response.data
|
|
313
|
-
? 'data'
|
|
314
|
-
: undefined;
|
|
315
|
-
if (responseDataKey === undefined) {
|
|
316
|
-
throw new Error('No data body or data provided, skipping verification', {
|
|
317
|
-
cause: {
|
|
318
|
-
redirectUrl: redirectUrl.toString(),
|
|
319
|
-
originalUrl: originalUrl.toString(),
|
|
320
|
-
},
|
|
321
|
-
});
|
|
322
|
-
}
|
|
323
|
-
const responseBody = response[responseDataKey];
|
|
324
|
-
// TODO: determine if it is data item or L1 transaction, and tell the verifier accordingly, just drop in hit to graphql now
|
|
325
|
-
if (txId === undefined) {
|
|
326
|
-
throw new Error('Failed to parse data hash from response headers', {
|
|
327
|
-
cause: {
|
|
328
|
-
redirectUrl: redirectUrl.toString(),
|
|
329
|
-
originalUrl: originalUrl.toString(),
|
|
330
|
-
txId,
|
|
331
|
-
},
|
|
332
|
-
});
|
|
333
|
-
}
|
|
334
|
-
else if (responseBody === undefined) {
|
|
335
|
-
throw new Error('No data body provided, skipping verification', {
|
|
336
|
-
cause: {
|
|
337
|
-
redirectUrl: redirectUrl.toString(),
|
|
338
|
-
originalUrl: originalUrl.toString(),
|
|
339
|
-
txId,
|
|
340
|
-
},
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
|
-
else {
|
|
344
|
-
logger?.debug('Verifying data hash for txId', {
|
|
345
|
-
redirectUrl: redirectUrl.toString(),
|
|
346
|
-
originalUrl: originalUrl.toString(),
|
|
347
|
-
txId,
|
|
348
|
-
});
|
|
349
|
-
const newClientStream = tapAndVerifyStream({
|
|
350
|
-
originalStream: responseBody,
|
|
351
|
-
contentLength,
|
|
352
|
-
verifyData,
|
|
353
|
-
txId,
|
|
354
|
-
emitter,
|
|
355
|
-
});
|
|
356
|
-
if (responseBody instanceof ReadableStream) {
|
|
357
|
-
// specific to fetch
|
|
358
|
-
return wrapVerifiedResponse(response, newClientStream, txId);
|
|
359
|
-
}
|
|
360
|
-
else if (responseBody instanceof Readable) {
|
|
361
|
-
// overwrite the response body with the new client stream
|
|
362
|
-
response.txId = txId;
|
|
363
|
-
response.body = newClientStream;
|
|
364
|
-
return response;
|
|
365
|
-
}
|
|
366
|
-
else {
|
|
367
|
-
// TODO: content-application/json and it's smaller than 10mb
|
|
368
|
-
// TODO: add tests and verify this works for all non-Readable/streamed responses
|
|
369
|
-
try {
|
|
370
|
-
// if strict set to true
|
|
371
|
-
await verifyData({
|
|
372
|
-
data: responseBody,
|
|
373
|
-
txId,
|
|
374
|
-
});
|
|
375
|
-
emitter?.emit('verification-passed', {
|
|
376
|
-
txId,
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
|
-
catch (error) {
|
|
380
|
-
logger?.debug('Failed to verify data hash', {
|
|
381
|
-
error,
|
|
382
|
-
txId,
|
|
383
|
-
});
|
|
384
|
-
emitter?.emit('verification-failed', {
|
|
385
|
-
txId,
|
|
386
|
-
error,
|
|
387
|
-
});
|
|
388
|
-
}
|
|
389
|
-
return response;
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
// TODO: if strict - wait for verification to finish and succeed before returning the response
|
|
395
|
-
return response;
|
|
396
|
-
};
|
|
397
|
-
return new Proxy(httpClient, {
|
|
398
|
-
// support direct calls: fetch('ar://…', options)
|
|
399
|
-
// axios() or got()
|
|
400
|
-
apply: (_target, _thisArg, argArray) => wayfinderRedirect(httpClient, argArray),
|
|
401
|
-
// support http clients that use functions like `got.get`, `got.post`, `axios.get`, etc. while still using the wayfinder redirect function
|
|
402
|
-
get: (target, prop, receiver) => {
|
|
403
|
-
const value = Reflect.get(target, prop, receiver);
|
|
404
|
-
if (typeof value === 'function') {
|
|
405
|
-
return (...inner) => wayfinderRedirect(value.bind(target), inner);
|
|
406
|
-
}
|
|
407
|
-
return value; // numbers, objects, symbols pass through untouched
|
|
408
|
-
},
|
|
409
|
-
});
|
|
410
|
-
};
|
|
411
|
-
/**
|
|
412
|
-
* The main class for the wayfinder
|
|
413
|
-
* @param router - the router to use for requests
|
|
414
|
-
* @param httpClient - the http client to use for requests
|
|
415
|
-
* @param blocklist - the blocklist of gateways to avoid
|
|
416
|
-
*/
|
|
417
|
-
export class Wayfinder {
|
|
418
|
-
/**
|
|
419
|
-
* The router to use for requests
|
|
420
|
-
*
|
|
421
|
-
* @example
|
|
422
|
-
* const wayfinder = new Wayfinder({
|
|
423
|
-
* router: new RandomGatewayRouter({
|
|
424
|
-
* gatewaysProvider: new SimpleCacheGatewaysProvider({
|
|
425
|
-
* gatewaysProvider: new NetworkGatewaysProvider({ ario: ARIO.mainnet() }),
|
|
426
|
-
* ttlSeconds: 60 * 60 * 24, // 1 day
|
|
427
|
-
* }),
|
|
428
|
-
* }),
|
|
429
|
-
* });
|
|
430
|
-
*
|
|
431
|
-
* // Returns a target gateway based on the routing strategy
|
|
432
|
-
* const targetGateway = await wayfinder.router.getTargetGateway();
|
|
433
|
-
*/
|
|
434
|
-
router;
|
|
435
|
-
/**
|
|
436
|
-
* The native http client used by wayfinder
|
|
437
|
-
*
|
|
438
|
-
* @example
|
|
439
|
-
* const wayfinder = new Wayfinder({
|
|
440
|
-
* router: new RandomGatewayRouter({
|
|
441
|
-
* gatewaysProvider: new SimpleCacheGatewaysProvider({
|
|
442
|
-
* gatewaysProvider: new NetworkGatewaysProvider({ ario: ARIO.mainnet() }),
|
|
443
|
-
* ttlSeconds: 60 * 60 * 24, // 1 day
|
|
444
|
-
* }),
|
|
445
|
-
* }),
|
|
446
|
-
* httpClient: axios,
|
|
447
|
-
* });
|
|
448
|
-
*
|
|
449
|
-
*/
|
|
450
|
-
httpClient;
|
|
451
|
-
/**
|
|
452
|
-
* The function that resolves the redirect url for ar:// requests to a target gateway
|
|
453
|
-
*
|
|
454
|
-
* @example
|
|
455
|
-
* const wayfinder = new Wayfinder({
|
|
456
|
-
* router: new RandomGatewayRouter({
|
|
457
|
-
* gatewaysProvider: new SimpleCacheGatewaysProvider({
|
|
458
|
-
* gatewaysProvider: new NetworkGatewaysProvider({ ario: ARIO.mainnet() }),
|
|
459
|
-
* ttlSeconds: 60 * 60 * 24, // 1 day
|
|
460
|
-
* }),
|
|
461
|
-
* }),
|
|
462
|
-
* httpClient: axios,
|
|
463
|
-
* });
|
|
464
|
-
*
|
|
465
|
-
* // returns the redirected URL based on the routing strategy and the original url
|
|
466
|
-
* const redirectUrl = await wayfinder.resolveUrl({ originalUrl: 'ar://example' });
|
|
467
|
-
*/
|
|
468
|
-
resolveUrl;
|
|
469
|
-
/**
|
|
470
|
-
* A wrapped http client that supports ar:// protocol
|
|
471
|
-
*
|
|
472
|
-
* @example
|
|
473
|
-
* const { request: wayfind } = new Wayfinder({
|
|
474
|
-
* router: new RandomGatewayRouter({
|
|
475
|
-
* gatewaysProvider: new SimpleCacheGatewaysProvider({
|
|
476
|
-
* gatewaysProvider: new NetworkGatewaysProvider({ ario: ARIO.mainnet() }),
|
|
477
|
-
* ttlSeconds: 60 * 60 * 24, // 1 day
|
|
478
|
-
* }),
|
|
479
|
-
* }),
|
|
480
|
-
* httpClient: axios,
|
|
481
|
-
* });;
|
|
482
|
-
*
|
|
483
|
-
* const response = await wayfind('ar://example', {
|
|
484
|
-
* method: 'POST',
|
|
485
|
-
* data: {
|
|
486
|
-
* name: 'John Doe',
|
|
487
|
-
* },
|
|
488
|
-
* })
|
|
489
|
-
*/
|
|
490
|
-
request;
|
|
491
|
-
// TODO: stats provider
|
|
492
|
-
// TODO: metricsProvider for otel/prom support
|
|
493
|
-
verifyData;
|
|
494
|
-
/**
|
|
495
|
-
* The event emitter for wayfinder that emits verification events.
|
|
496
|
-
*
|
|
497
|
-
* const wayfinder = new Wayfinder()
|
|
498
|
-
*
|
|
499
|
-
* wayfinder.emitter.on('verification-passed', (event) => {
|
|
500
|
-
* console.log('Verification passed!', event);
|
|
501
|
-
* })
|
|
502
|
-
*
|
|
503
|
-
* wayfinder.emitter.on('verification-failed', (event) => {
|
|
504
|
-
* console.log('Verification failed!', event);
|
|
505
|
-
* })
|
|
506
|
-
*
|
|
507
|
-
* or implement the events interface and pass it in, using callback functions
|
|
508
|
-
*
|
|
509
|
-
* const wayfinder = new Wayfinder({
|
|
510
|
-
* events: {
|
|
511
|
-
* onVerificationPassed: (event) => {
|
|
512
|
-
* console.log('Verification passed!', event);
|
|
513
|
-
* },
|
|
514
|
-
* onVerificationFailed: (event) => {
|
|
515
|
-
* console.log('Verification failed!', event);
|
|
516
|
-
* },
|
|
517
|
-
* onVerificationProgress: (event) => {
|
|
518
|
-
* console.log('Verification progress!', event);
|
|
519
|
-
* },
|
|
520
|
-
* }
|
|
521
|
-
* })
|
|
522
|
-
*
|
|
523
|
-
* const response = await wayfind('ar://example');
|
|
524
|
-
*/
|
|
525
|
-
// TODO: consider changing this to events or event emitter
|
|
526
|
-
emitter;
|
|
527
|
-
constructor({ httpClient,
|
|
528
|
-
// TODO: consider changing router to routingStrategy or strategy
|
|
529
|
-
router = new RandomGatewayRouter({
|
|
530
|
-
gatewaysProvider: new SimpleCacheGatewaysProvider({
|
|
531
|
-
gatewaysProvider: new NetworkGatewaysProvider({ ario: ARIO.mainnet() }),
|
|
532
|
-
ttlSeconds: 60 * 60 * 24, // 1 day
|
|
533
|
-
}),
|
|
534
|
-
}), logger = Logger.default,
|
|
535
|
-
// TODO: support disabling verification or create some PassThroughVerifier like thing
|
|
536
|
-
verifier = new HashVerifier({
|
|
537
|
-
trustedHashProvider: new TrustedGatewaysHashProvider({
|
|
538
|
-
gatewaysProvider: new StaticGatewaysProvider({
|
|
539
|
-
gateways: ['https://permagate.io'],
|
|
540
|
-
}),
|
|
541
|
-
}),
|
|
542
|
-
}), events,
|
|
543
|
-
// TODO: stats provider
|
|
544
|
-
}) {
|
|
545
|
-
this.router = router;
|
|
546
|
-
this.httpClient = httpClient;
|
|
547
|
-
this.emitter = new WayfinderEmitter(events);
|
|
548
|
-
this.verifyData = verifier.verifyData.bind(verifier);
|
|
549
|
-
this.resolveUrl = async ({ originalUrl, logger }) => {
|
|
550
|
-
return resolveWayfinderUrl({
|
|
551
|
-
originalUrl,
|
|
552
|
-
targetGateway: async () => await this.router.getTargetGateway(),
|
|
553
|
-
logger,
|
|
554
|
-
});
|
|
555
|
-
};
|
|
556
|
-
this.request = createWayfinderClient({
|
|
557
|
-
httpClient,
|
|
558
|
-
resolveUrl: this.resolveUrl,
|
|
559
|
-
verifyData: this.verifyData,
|
|
560
|
-
emitter: this.emitter,
|
|
561
|
-
logger,
|
|
562
|
-
});
|
|
563
|
-
logger?.debug(`Wayfinder initialized with ${router.name} routing strategy`);
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
// TODO: add a chart for verification strategies and what they do
|
|
567
|
-
// include complexity, performance, and security
|
|
568
|
-
// explain use cases that each strategy is best for
|
|
569
|
-
// e.g.
|
|
570
|
-
/**
|
|
571
|
-
*
|
|
572
|
-
* type | complexity | performance | security
|
|
573
|
-
* ---------|------------|-------------|---------
|
|
574
|
-
* hash | low | high | low
|
|
575
|
-
* ---------|------------|-------------|---------
|
|
576
|
-
* data root | medium | medium | low | only L1
|
|
577
|
-
* ---------|------------|-------------|---------
|
|
578
|
-
* signature | medium | medium | medium
|
|
579
|
-
* ---------|------------|-------------|---------
|
|
580
|
-
* composite | high | low | high
|
|
581
|
-
* ---------|------------|-------------|---------
|
|
582
|
-
*
|
|
583
|
-
*
|
|
584
|
-
*/
|