forked from vgrichina/web4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
389 lines (327 loc) · 13.2 KB
/
app.js
File metadata and controls
389 lines (327 loc) · 13.2 KB
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
const {
connect,
keyStores: { InMemoryKeyStore },
transactions: { Transaction, functionCall },
KeyPair,
} = require('near-api-js');
const { PublicKey } = require('near-api-js/lib/utils');
const { signInURL, signTransactionsURL } = require('./util/web-wallet-api');
const fetch = require('node-fetch');
const qs = require('querystring');
const MAX_PRELOAD_HOPS = 5;
const IPFS_GATEWAY_URL = process.env.IPFS_GATEWAY_URL || 'https://ipfs.near.social';
const config = require('./config')(process.env.NODE_ENV || 'development')
async function withDebug(ctx, next) {
ctx.debug = require('debug')(`web4:${ctx.host}${ctx.path}?${qs.stringify(ctx.query)}`);
await next();
}
async function withNear(ctx, next) {
// TODO: Why no default keyStore?
const keyStore = new InMemoryKeyStore();
const near = await connect({...config, keyStore});
Object.assign(ctx, { config, keyStore, near });
try {
await next();
} catch (e) {
switch (e.type) {
case 'AccountDoesNotExist':
ctx.throw(404, e.message);
case 'UntypedError':
default:
ctx.throw(400, e.message);
}
}
}
async function withAccountId(ctx, next) {
const accountId = ctx.cookies.get('web4_account_id');
ctx.accountId = accountId;
await next();
}
async function requireAccountId(ctx, next) {
if (!ctx.accountId) {
ctx.redirect('/web4/login');
return;
}
await next();
}
const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
const koaBody = require('koa-body')();
const FAST_NEAR_URL = process.env.FAST_NEAR_URL;
const callViewFunction = async ({ near }, contractId, methodName, methodParams) => {
if (FAST_NEAR_URL) {
const res = await fetch(`${FAST_NEAR_URL}/account/${contractId}/view/${methodName}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(methodParams)
});
if (!res.ok) {
throw new Error(await res.text());
}
return await res.json();
}
const account = await near.account(contractId);
return await account.viewFunction(contractId, methodName, methodParams);
}
router.get('/web4/contract/:contractId/:methodName', withNear, async ctx => {
const {
params: { contractId, methodName },
query
} = ctx;
const methodParams = Object.keys(query)
.map(key => key.endsWith('.json')
? { [key.replace(/\.json$/, '')]: JSON.parse(query[key]) }
: { [key] : query[key] })
.reduce((a, b) => ({...a, ...b}), {});
ctx.body = await callViewFunction(ctx, contractId, methodName, methodParams);
});
router.get('/web4/login', withNear, withContractId, async ctx => {
let {
contractId,
query: { web4_callback_url, web4_contract_id }
} = ctx;
const keyPair = KeyPair.fromRandom('ed25519');
ctx.cookies.set('web4_private_key', keyPair.toString(), { httpOnly: false });
ctx.cookies.set('web4_account_id', null, { httpOnly: false });
const callbackUrl = new URL(web4_callback_url || ctx.get('referrer') || '/', ctx.origin).toString();
const loginCompleteUrl = `${ctx.origin}/web4/login/complete?${qs.stringify({ web4_callback_url: callbackUrl })}`;
ctx.redirect(signInURL({
walletUrl: config.walletUrl,
contractId: web4_contract_id || contractId,
publicKey: keyPair.getPublicKey().toString(),
successUrl: loginCompleteUrl,
failureUrl: loginCompleteUrl
}));
});
router.get('/web4/login/complete', async ctx => {
const { account_id, web4_callback_url } = ctx.query;
if (account_id) {
ctx.cookies.set('web4_account_id', account_id, { httpOnly: false });
ctx.body = `Logged in as ${account_id}`;
} else {
ctx.body = `Couldn't login`;
}
if (!web4_callback_url) {
ctx.throw(400, 'Missing web4_callback_url');
}
ctx.redirect(web4_callback_url);
});
router.get('/web4/logout', async ctx => {
let {
query: { web4_callback_url }
} = ctx;
ctx.cookies.set('web4_account_id');
ctx.cookies.set('web4_private_key');
const callbackUrl = new URL(web4_callback_url || ctx.get('referrer') || '/', ctx.origin).toString();
ctx.redirect(callbackUrl);
});
const DEFAULT_GAS = '300' + '000000000000';
router.post('/web4/contract/:contractId/:methodName', koaBody, withNear, withAccountId, requireAccountId, async ctx => {
// TODO: Accept both json and form submission
const accountId = ctx.accountId;
const appPrivateKey = ctx.cookies.get('web4_private_key');
const { contractId, methodName } = ctx.params;
const { body } = ctx.request;
const { web4_gas: gas, web4_deposit: deposit, web4_callback_url } = body;
const args = Object.keys(body)
.filter(key => !key.startsWith('web4_'))
.map(key => ({ [key]: body[key] }))
.reduce((a, b) => ({...a, ...b}), {});
const callbackUrl = new URL(web4_callback_url || ctx.get('referrer') || '/', ctx.origin).toString()
// Check if can be signed without wallet
if (appPrivateKey && (!deposit || deposit == '0')) {
const keyPair = KeyPair.fromString(appPrivateKey);
const appKeyStore = new InMemoryKeyStore();
await appKeyStore.setKey(ctx.near.connection.networkId, accountId, keyPair);
const near = await connect({ ...ctx.near.config, keyStore: appKeyStore });
const { permission: { FunctionCall }} = await near.connection.provider.query({
request_type: 'view_access_key',
account_id: accountId,
public_key: keyPair.getPublicKey().toString(),
finality: 'optimistic'
});
if (FunctionCall && FunctionCall.receiver_id == contractId) {
const account = await near.account(accountId);
const result = await account.functionCall({ contractId, methodName, args, gas: gas || DEFAULT_GAS, deposit: deposit || '0' });
// TODO: when used from fetch, etc shouldn't really redirect. Judge based on Accepts header?
if (ctx.request.type == 'application/x-www-form-urlencoded') {
ctx.redirect(callbackUrl);
// TODO: Pass transaction hashes, etc to callback?
} else {
// TODO: Decide what exactly to return
ctx.body = result;
}
return;
}
}
// NOTE: publicKey, nonce, blockHash keys are faked as reconstructed by wallet
const transaction = new Transaction({
signerId: accountId,
publicKey: new PublicKey({ type: 0, data: Buffer.from(new Array(32))}),
nonce: 0,
receiverId: contractId,
actions: [
functionCall(methodName, args, gas || DEFAULT_GAS, deposit || '0')
],
blockHash: Buffer.from(new Array(32))
});
const url = signTransactionsURL({
walletUrl: config.walletUrl,
transactions: [transaction],
callbackUrl
});
ctx.redirect(url);
// TODO: Need to do something else than wallet redirect for CORS-enabled fetch
});
async function withContractId(ctx, next) {
let contractId = process.env.CONTRACT_NAME;
if (ctx.host.endsWith('.near.page')) {
contractId = ctx.host.replace(/.page$/, '');
}
if (ctx.host.endsWith('.testnet.page')) {
contractId = ctx.host.replace(/.page$/, '');
}
ctx.contractId = contractId;
return await next();
}
// TODO: Do contract method call according to mapping returned by web4_routes contract method
// TODO: Use web4_get method in smart contract as catch all if no mapping?
// TODO: Or is mapping enough?
router.get('/(.*)', withNear, withContractId, withAccountId, async ctx => {
const {
debug,
accountId,
path,
query
} = ctx;
let { contractId } = ctx;
const methodParams = {
request: {
accountId,
path,
query: Object.keys(query)
.map(key => ({ [key] : Array.isArray(query[key]) ? query[key] : [query[key]] }))
.reduce((a, b) => ({...a, ...b}), {})
}
};
debug('methodParams', methodParams);
for (let i = 0; i < MAX_PRELOAD_HOPS; i++) {
debug('hop', i);
let res;
try {
res = await callViewFunction(ctx, contractId, 'web4_get', methodParams);
} catch (e) {
// Support hosting web4 contract on subaccount like web4.vlad.near
// TODO: Cache whether given account needs this
// TODO: remove nearcore error check after full migration to fast-near
if (e.message.includes('FunctionCallError(CompilationError(CodeDoesNotExist')
|| e.message.includes('FunctionCallError(MethodResolveError(MethodNotFound))')
|| e.message.startsWith('codeNotFound')
|| e.message.includes('method web4_get not found')) {
if (i == 0) {
contractId = `web4.${contractId}`;
continue;
}
}
if (e.toString().includes('block height')) {
console.error('error', e);
}
throw e;
}
const { contentType, status, body, bodyUrl, preloadUrls, cacheControl } = res;
debug('response: %j', { status, contentType, body: !!body, bodyUrl, preloadUrls, cacheControl });
if (status) {
ctx.status = status;
if (!body && !bodyUrl) {
ctx.body = ctx.message;
return;
}
}
if (body) {
ctx.type = contentType;
ctx.body = Buffer.from(body, 'base64');
return;
}
if (bodyUrl) {
let absoluteUrl = new URL(bodyUrl, ctx.origin).toString();
if (absoluteUrl.startsWith('ipfs:')) {
const { hostname, pathname, search } = new URL(absoluteUrl);
absoluteUrl = `${IPFS_GATEWAY_URL}/ipfs/${hostname}${pathname}${search}`;
}
debug('Loading', absoluteUrl);
const referer = `https://${ctx.host}${ctx.path}`;
console.log('referer', referer);
const res = await fetch(absoluteUrl, { headers: { Referer: referer } });
debug('Loaded', absoluteUrl);
// TODO: Pass through error?
if (!status) {
ctx.status = res.status;
}
const needToUncompress = !!res.headers.get('content-encoding');
for (let [key, value] of res.headers.entries()) {
if (needToUncompress && ['content-encoding', 'content-length'].includes(key)) {
// NOTE: fetch returns Gunzip stream, so response doesn't get compressed + content length is off
// TODO: Figure out how to relay compressed stream instead
continue;
}
if (key == 'cache-control') {
// NOTE: Underlying storage (IPFS) might be immutable, but smart contract can change where it's pointing to
continue;
}
ctx.set(key, value);
}
if (contentType) {
ctx.type = contentType;
}
if (cacheControl) {
ctx.set('cache-control', cacheControl);
} else {
// Set reasonable defaults based on content type
if (ctx.type.startsWith('image/') || ctx.type.startsWith('video/') || ctx.type.startsWith('audio/') ||
ctx.type === 'application/javascript' || ctx.type === 'text/css' ) {
// NOTE: modern web apps typically have these static with a unique URL, so can cache for a long time (1 hour)
ctx.set('cache-control', 'public, max-age=3600');
}
if (ctx.type === 'text/html') {
// NOTE: HTML is typically generated on the fly, so can't cache for too long (1 minute)
ctx.set('cache-control', 'public, max-age=60'); // 1 minute
}
}
ctx.body = res.body;
return;
}
if (preloadUrls) {
const preloads = await Promise.all(preloadUrls.map(async url => {
const absoluteUrl = new URL(url, ctx.origin).toString();
const res = await fetch(absoluteUrl);
return [url, {
contentType: res.headers.get('content-type'),
body: (await res.buffer()).toString('base64')
}];
}));
methodParams.request.preloads = preloads.map(([key, value]) => ({[key] : value}))
.reduce((a, b) => ({...a, ...b}), {});
continue;
}
break;
}
ctx.throw(502, 'too many preloads');
});
// TODO: submit transaction mapping path to method name
router.post('/(.*)', ctx => {
ctx.body = ctx.path;
});
// TODO: Need to query smart contract for rewrites config
app
.use(withDebug)
.use(async (ctx, next) => {
console.log(ctx.method, ctx.host, ctx.path);
await next();
})
.use(router.routes())
.use(router.allowedMethods());
module.exports = app;