-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.ts
287 lines (266 loc) · 7.95 KB
/
main.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
import './setup-logger'; // This should be first
import { Realm, VirtualNetwork, logger } from '@cardstack/runtime-common';
import { NodeAdapter } from './node-realm';
import yargs from 'yargs';
import { RealmServer } from './server';
import { resolve, join } from 'path';
import { makeFastBootIndexRunner } from './fastboot';
import { RunnerOptionsManager } from '@cardstack/runtime-common/search-index';
import { readFileSync } from 'fs-extra';
import { shimExternals } from './lib/externals';
import { type RealmPermissions as RealmPermissionsInterface } from '@cardstack/runtime-common/realm';
import * as Sentry from '@sentry/node';
import { setErrorReporter } from '@cardstack/runtime-common/realm';
import fs from 'fs';
let log = logger('main');
if (process.env.REALM_SENTRY_DSN) {
log.info('Setting up Sentry.');
Sentry.init({
dsn: process.env.REALM_SENTRY_DSN,
environment: process.env.REALM_SENTRY_ENVIRONMENT || 'development',
});
setErrorReporter(Sentry.captureException);
} else {
log.warn(
`No REALM_SENTRY_DSN environment variable found, skipping Sentry setup.`,
);
}
const REALM_SECRET_SEED = process.env.REALM_SECRET_SEED;
if (!REALM_SECRET_SEED) {
console.error(
`The REALM_SECRET_SEED environment variable is not set. Please make sure this env var has a value`,
);
process.exit(-1);
}
let {
port,
distDir = join(__dirname, '..', 'host', 'dist'),
distURL,
path: paths,
fromUrl: fromUrls,
toUrl: toUrls,
useTestingDomain,
username: usernames,
password: passwords,
matrixURL: matrixURLs,
} = yargs(process.argv.slice(2))
.usage('Start realm server')
.options({
port: {
description: 'port number',
demandOption: true,
type: 'number',
},
fromUrl: {
description: 'the source of the realm URL proxy',
demandOption: true,
type: 'array',
},
toUrl: {
description: 'the target of the realm URL proxy',
demandOption: true,
type: 'array',
},
path: {
description: 'realm directory path',
demandOption: true,
type: 'array',
},
distDir: {
description:
"the dist/ folder of the host app. Defaults to '../host/dist'",
type: 'string',
},
distURL: {
description:
'the URL of a deployed host app. (This can be provided instead of the --distPath)',
type: 'string',
},
useTestingDomain: {
description:
'relaxes document domain rules so that cross origin scripting can be used for test assertions across iframe boundaries',
type: 'boolean',
},
matrixURL: {
description: 'The matrix homeserver for the realm',
demandOption: true,
type: 'array',
},
username: {
description: 'The matrix username for the realm user',
demandOption: true,
type: 'array',
},
password: {
description: 'The matrix password for the realm user',
demandOption: true,
type: 'array',
},
})
.parseSync();
if (fromUrls.length !== toUrls.length) {
console.error(
`Mismatched number of URLs, the --fromUrl params must be matched to the --toUrl params`,
);
process.exit(-1);
}
if (fromUrls.length < paths.length) {
console.error(
`not enough url pairs were provided to satisfy the paths provided. There must be at least one --fromUrl/--toUrl pair for each --path parameter`,
);
process.exit(-1);
}
if (
paths.length !== usernames.length ||
usernames.length !== passwords.length ||
paths.length !== matrixURLs.length
) {
console.error(
`not enough username/password pairs were provided to satisfy the paths provided. There must be at least one --username/--password/--matrixURL set for each --path parameter`,
);
process.exit(-1);
}
let virtualNetwork = new VirtualNetwork();
let loader = virtualNetwork.createLoader();
shimExternals(virtualNetwork);
let urlMappings = fromUrls.map((fromUrl, i) => [
new URL(String(fromUrl), `http://localhost:${port}`),
new URL(String(toUrls[i]), `http://localhost:${port}`),
]);
for (let [from, to] of urlMappings) {
loader.addURLMapping(from, to);
}
let hrefs = urlMappings.map(([from, to]) => [from.href, to.href]);
let dist: string | URL;
if (distURL) {
dist = new URL(distURL);
} else {
dist = resolve(distDir);
}
(async () => {
let realms: Realm[] = [];
for (let [i, path] of paths.entries()) {
let url = hrefs[i][0];
let manager = new RunnerOptionsManager();
let matrixURL = String(matrixURLs[i]);
if (matrixURL.length === 0) {
console.error(`missing matrix URL for realm ${url}`);
process.exit(-1);
}
let username = String(usernames[i]);
if (username.length === 0) {
console.error(`missing username for realm ${url}`);
process.exit(-1);
}
let password = String(passwords[i]);
if (password.length === 0) {
console.error(`missing password for realm ${url}`);
process.exit(-1);
}
let { getRunner, distPath } = await makeFastBootIndexRunner(
dist,
manager.getOptions.bind(manager),
);
let realmPermissions = getRealmPermissions(url);
realms.push(
new Realm(
{
url,
adapter: new NodeAdapter(resolve(String(path))),
loader,
indexRunner: getRunner,
runnerOptsMgr: manager,
getIndexHTML: async () =>
readFileSync(join(distPath, 'index.html')).toString(),
matrix: { url: new URL(matrixURL), username, password },
realmSecretSeed: REALM_SECRET_SEED,
permissions: realmPermissions.users,
},
{
deferStartUp: true,
...(useTestingDomain
? {
useTestingDomain,
}
: {}),
},
),
);
}
let server = new RealmServer(realms, {
...(distURL ? { assetsURL: new URL(distURL) } : {}),
});
server.listen(port);
log.info(`Realm server listening on port ${port}:`);
let additionalMappings = hrefs.slice(paths.length);
for (let [index, { url }] of realms.entries()) {
log.info(` ${url} => ${hrefs[index][1]}, serving path ${paths[index]}`);
}
if (additionalMappings.length) {
log.info('Additional URL mappings:');
for (let [from, to] of additionalMappings) {
log.info(` ${from} => ${to}`);
}
}
log.info(`Using host dist path: '${distDir}' for card pre-rendering`);
for (let realm of realms) {
log.info(`Starting realm ${realm.url}...`);
await realm.start();
log.info(
`Realm ${realm.url} has started (${JSON.stringify(
realm.searchIndex.stats,
null,
2,
)})`,
);
}
})().catch((e: any) => {
console.error(
`Unexpected error encountered starting realm, stopping server`,
e,
);
process.exit(1);
});
function getRealmPermissions(realmUrl: string) {
let userPermissions = {} as {
[realmUrl: string]: { users: RealmPermissionsInterface };
};
let userPermissionsjsonContent;
if (['development', 'test'].includes(process.env.NODE_ENV || '')) {
userPermissionsjsonContent = fs.readFileSync(
`.realms.json.${process.env.NODE_ENV}`,
'utf-8',
);
} else {
userPermissionsjsonContent = process.env.REALM_USER_PERMISSIONS;
if (!userPermissionsjsonContent) {
throw new Error(
`REALM_USER_PERMISSIONS env var is blank. It should have a JSON string value that looks like this:
{
"https://realm-url-1/": {
"users":{
"*":["read"],
"@hassan:boxel.ai":["read", "write"],
...
}
},
"https://realm-url-2/": { ... }
}
`,
);
}
}
try {
userPermissions = JSON.parse(userPermissionsjsonContent);
} catch (error: any) {
throw new Error(
`Error while JSON parsing user permissions: ${userPermissionsjsonContent}`,
);
}
if (!userPermissions[realmUrl]) {
throw new Error(
`Missing permissions for realm ${realmUrl} in config ${userPermissionsjsonContent}`,
);
}
return userPermissions[realmUrl];
}