Repository navigation
Expand file tree
/
Copy pathmain.ts
More file actions
261 lines (241 loc) · 8.8 KB
/
Copy pathmain.ts
File metadata and controls
261 lines (241 loc) · 8.8 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
import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
import { extname, join, normalize, sep } from "node:path";
import { pathToFileURL } from "node:url";
import { serve } from "@hono/node-server";
import { Hono, type Context, type Handler } from "hono";
import { secureHeaders } from "hono/secure-headers";
import { createApi } from "./api.js";
import { Auth } from "./auth.js";
import { StellarSource } from "./chain.js";
import type { Networks } from "./concord.js";
import { NETWORK_NAMES, loadConfig, type Config } from "./config.js";
import { Db } from "./db.js";
import { CONTROL_MIGRATIONS } from "./schema.js";
import { Tenants, fileStore } from "./tenants.js";
const MIME: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".svg": "image/svg+xml",
".json": "application/json",
".map": "application/json",
".webmanifest": "application/manifest+json",
".txt": "text/plain; charset=utf-8",
".xml": "application/xml",
".wasm": "application/wasm",
".woff": "font/woff",
".woff2": "font/woff2",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
".avif": "image/avif",
".ico": "image/x-icon",
};
export interface Runtime {
control: Db;
auth: Auth;
tenants: Tenants;
close(): void;
}
/** Identity records, the chain sources for both networks, and the workspaces over them. */
export function openRuntime(config: Config): Runtime {
const control = new Db(join(config.dataDir, "control.db"), CONTROL_MIGRATIONS, config.sqliteSynchronous);
try {
control.check();
} catch (err) {
control.close();
throw err;
}
const auth = new Auth(control, { signup: config.signup, maxInvites: config.maxInvitesPerOrg, ...(config.passwordCost ? { cost: config.passwordCost } : {}) });
const networks: Networks = {};
for (const name of NETWORK_NAMES) {
networks[name] = { passphrase: config.networks[name].passphrase, chain: new StellarSource(config.networks[name]) };
}
const tenants = new Tenants(
fileStore(config.dataDir, { synchronous: config.sqliteSynchronous, checkOnOpen: config.checkOnOpen }),
networks,
(orgId) => auth.orgExists(orgId),
() => auth.orgIds(),
{
syncConcurrency: config.syncConcurrency,
syncAssetBudgetMs: config.syncAssetBudgetSec * 1000,
...(config.signingKey ? { signingKey: config.signingKey } : {}),
},
);
return {
control,
auth,
tenants,
close() {
tenants.close();
control.close();
},
};
}
export function createStaticHandler(webDir: string): Handler {
return (c: Context) => {
if (!existsSync(webDir)) {
return c.text("Concord API is running. Build the dashboard with `pnpm build` to serve it here.");
}
let requested: string;
try {
requested = decodeURIComponent(c.req.path);
} catch {
return c.text("Bad request", 400);
}
// Refuse dotfile segments (e.g. /.hidden, /a/.git/config).
const segments = requested.split("/").filter(Boolean);
if (segments.some((s) => s.startsWith("."))) {
return c.text("Not found", 404);
}
const path = normalize(join(webDir, requested));
// The separator matters: without it a sibling directory sharing the prefix would count as inside.
const inside = path === webDir || path.startsWith(webDir + sep);
const found = inside && existsSync(path) && statSync(path).isFile();
// A build asset that is not there, or any missing file with an extension, is a 404; only extensionless routes fall back to the app shell.
const lastSegment = segments[segments.length - 1] ?? "";
const hasExtension = extname(lastSegment) !== "";
if (!found && (hasExtension || requested.startsWith("/assets/"))) return c.text("Not found", 404);
const file = found ? path : join(webDir, "index.html");
const assetsDir = normalize(join(webDir, "assets"));
const isAsset = found && (path === assetsDir || path.startsWith(assetsDir + sep));
return c.body(new Uint8Array(readFileSync(file)), 200, {
"content-type": MIME[extname(file)] ?? "application/octet-stream",
// Vite names build assets by content hash, so they never change under a given name.
"cache-control": isAsset ? "public, max-age=31536000, immutable" : "no-cache",
});
};
}
export { createStaticHandler as staticHandler };
export function createServerApp(runtime: Runtime, config: Config): Hono {
const secure = config.publicUrl.startsWith("https://");
const app = new Hono();
app.use(
"*",
secureHeaders({
contentSecurityPolicy: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
// React sets element styles inline.
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:"],
fontSrc: ["'self'"],
connectSrc: ["'self'"],
objectSrc: ["'none'"],
baseUri: ["'self'"],
formAction: ["'self'"],
frameAncestors: ["'none'"],
},
strictTransportSecurity: secure ? "max-age=31536000; includeSubDomains" : false,
referrerPolicy: "same-origin",
}),
);
app.route(
"/",
createApi(runtime.tenants, runtime.auth, {
publicUrl: config.publicUrl,
signup: config.signup,
ephemeral: config.ephemeral,
networks: [...NETWORK_NAMES],
defaultNetwork: config.defaultNetwork,
maxAssetsPerOrg: config.maxAssetsPerOrg,
trustProxyHops: config.trustProxyHops,
...(config.google ? { google: config.google } : {}),
}),
);
// The built dashboard, with index.html standing in for client-side routes.
app.get("*", createStaticHandler(config.webDir));
return app;
}
export interface IndexerHandle {
stop(): void;
}
export function startIndexer(
tenants: Pick<Tenants, "syncAll">,
intervalSec: number,
): IndexerHandle {
let timer: NodeJS.Timeout | undefined;
if (intervalSec > 0) {
let busy = false;
const pass = async () => {
if (busy) return;
busy = true;
try {
for (const r of await tenants.syncAll()) {
const where = r.assetId ? `${r.orgId}/${r.assetId.slice(0, 8)}` : r.orgId;
if (r.error) console.error(`sync ${where}: ${r.error}`);
else if (r.added) console.log(`sync ${where}: +${r.added} events${r.more ? " (more next pass)" : ""}`);
}
} catch (err) {
// Nothing here may take the process down; the next pass tries again.
console.error("sync pass failed", err);
} finally {
busy = false;
}
};
void pass();
timer = setInterval(() => void pass(), intervalSec * 1000);
timer.unref();
}
return {
stop() {
if (timer) clearInterval(timer);
},
};
}
export function startServer(config: Config = loadConfig()): void {
const runtime = openRuntime(config);
const secure = config.publicUrl.startsWith("https://");
const app = createServerApp(runtime, config);
const server = serve({ fetch: app.fetch, hostname: config.host, port: config.port }, (info) => {
console.log(`concord · ${config.publicUrl} · listening on ${config.host}:${info.port}`);
console.log(`data ${config.dataDir}`);
if (!secure && config.host !== "127.0.0.1" && config.host !== "localhost") {
console.warn("CONCORD_PUBLIC_URL is not https: sessions travel in the clear. Put TLS in front before anyone signs in.");
}
if (config.ephemeral) console.warn("CONCORD_EPHEMERAL is set: users are told their data does not survive a restart.");
});
// Keep sessions, invitations and one-time tokens bounded even when nobody presents an expired token.
const purge = () => {
try {
const counts = runtime.auth.purgeExpired();
if (counts.sessions || counts.invites || counts.tokens) console.log("identity cleanup", counts);
} catch (err) {
console.error("identity cleanup failed", err);
}
};
purge();
const purgeTimer = setInterval(purge, 60 * 60_000);
purgeTimer.unref();
const indexer = startIndexer(runtime.tenants, config.syncIntervalSec);
let stopping = false;
const stop = (signal: string) => {
if (stopping) return;
stopping = true;
console.log(`${signal}: shutting down`);
indexer.stop();
clearInterval(purgeTimer);
server.close(() => {
runtime.close();
process.exit(0);
});
// A request that will not finish must not hold the databases open for ever.
setTimeout(() => {
runtime.close();
process.exit(0);
}, 8000).unref();
};
process.on("SIGTERM", () => stop("SIGTERM"));
process.on("SIGINT", () => stop("SIGINT"));
}
export function isEntry(argv1: string | undefined, metaUrl: string): boolean {
if (!argv1) return false;
try {
return metaUrl === pathToFileURL(realpathSync(argv1)).href;
} catch {
return false;
}
}
if (isEntry(process.argv[1], import.meta.url)) startServer();