Repository navigation
Expand file tree
/
Copy pathvite.config.ts
More file actions
325 lines (307 loc) · 10.4 KB
/
Copy pathvite.config.ts
File metadata and controls
325 lines (307 loc) · 10.4 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
import fs from "node:fs";
import type { IncomingMessage, ServerResponse } from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
import { defineConfig, type Plugin } from "vite";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
/** Prefer sibling open-wallet checkout when developing packages locally. */
const siblingSignerSrc = path.resolve(
__dirname,
"../prf-wallet/packages/ows-signer/src",
);
const siblingSignerUtilsEntry = path.resolve(
__dirname,
"../prf-wallet/packages/ows-signer-utils/dist/index.js",
);
/** Keep npm copies for deps of aliased sibling packages (see localOwsAliases). */
const npmOwsTypesEntry = path.resolve(
__dirname,
"node_modules/@1shotapi/ows-types/dist/index.js",
);
const npmOwsWalletUtilsEntry = path.resolve(
__dirname,
"node_modules/@1shotapi/ows-wallet-utils/dist/index.js",
);
const signerPkgSrc = fs.existsSync(siblingSignerSrc)
? siblingSignerSrc
: path.resolve(__dirname, "node_modules/@1shotapi/ows-signer/src");
const signerPublicDir = path.resolve(__dirname, "signer-static");
/**
* Sibling package aliases rewrite imports to Vite `/@fs/C:/…` URLs on Windows.
* Firefox frequently fails those module loads (especially via ngrok), which
* breaks branding boot (e.g. productEvents barrel). Opt in only when you
* intentionally need unreleased OWS sources: `OWS_LOCAL_PACKAGES=1`.
*/
const useLocalOwsPackages = ["1", "true", "yes"].includes(
(process.env.OWS_LOCAL_PACKAGES ?? "").trim().toLowerCase(),
);
/**
* Only alias ows-signer-utils locally (ceremony host strip / OWSSigner hooks).
* Sibling dist still imports @1shotapi/ows-types; without pinning, Node resolves
* that from ../prf-wallet and Vite dev dies (z.uuid is not a function).
*/
const localOwsAliases: Record<string, string> = {};
if (useLocalOwsPackages) {
if (fs.existsSync(npmOwsTypesEntry)) {
localOwsAliases["@1shotapi/ows-types"] = npmOwsTypesEntry;
}
if (fs.existsSync(npmOwsWalletUtilsEntry)) {
localOwsAliases["@1shotapi/ows-wallet-utils"] = npmOwsWalletUtilsEntry;
}
if (fs.existsSync(siblingSignerUtilsEntry)) {
localOwsAliases["@1shotapi/ows-signer-utils"] = siblingSignerUtilsEntry;
}
if (Object.keys(localOwsAliases).length > 0) {
console.warn(
"[vite] OWS_LOCAL_PACKAGES enabled — aliasing @1shotapi/ows-signer-utils to sibling prf-wallet. " +
"Firefox may fail /@fs/C: module loads; use Chrome or unset the flag for ngrok.",
);
} else if (useLocalOwsPackages) {
console.warn(
"[vite] OWS_LOCAL_PACKAGES is set but no sibling prf-wallet dist was found. " +
"Run `npm run build` in ../prf-wallet (at least ows-signer-utils). " +
"Falling back to npm @1shotapi/* — ceremony host strip may be outdated.",
);
}
}
const MIME: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json",
".map": "application/json",
".svg": "image/svg+xml",
".woff2": "font/woff2",
};
/**
* Canonical Signing Layer CSP (keep in sync with nginx.conf).
*
* `frame-ancestors` is deliberately omitted: CSP checks it against every
* ancestor, so `'self'` would block the supported Host → Branding → Signer
* chain whenever the wallet is embedded on a third-party site. The signer
* enforces "same-origin Branding parent only" at runtime (ows-signer rpc.js
* `isValidParentMessage`), which is what actually keeps foreign Branding
* Layers from driving it.
*/
const SIGNER_CSP =
"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'none'; img-src 'none'; font-src 'none'; media-src 'none'; object-src 'none'; child-src 'none'; frame-src 'none'; worker-src 'none'; manifest-src 'none'; base-uri 'none'; form-action 'none'; upgrade-insecure-requests";
function contentType(filePath: string): string {
return MIME[path.extname(filePath)] ?? "application/octet-stream";
}
function sendFile(res: ServerResponse, filePath: string): void {
const stream = fs.createReadStream(filePath);
stream.once("open", () => {
res.statusCode = 200;
res.setHeader("Content-Type", contentType(filePath));
res.setHeader("Content-Security-Policy", SIGNER_CSP);
// Signer JS changes often during local sibling-package work; avoid sticky
// browser caches that serve stale ceremony-lock logic across refreshes.
res.setHeader("Cache-Control", "no-store");
stream.pipe(res);
});
stream.once("error", (error: NodeJS.ErrnoException) => {
if (res.headersSent) {
res.destroy(error);
return;
}
const notFound = error.code === "ENOENT";
res.statusCode = notFound ? 404 : 500;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end(notFound ? "Not found" : "Internal Server Error");
});
}
/**
* Resolve `rel` under `rootDir`, rejecting path traversal (`..`, encoded separators).
* Returns `undefined` when the result would escape `rootDir`.
*/
function resolveContainedPath(
rootDir: string,
urlRelative: string,
): string | undefined {
let rel: string;
try {
rel = decodeURIComponent(urlRelative);
} catch {
return undefined;
}
if (rel.includes("\0")) {
return undefined;
}
const root = path.resolve(rootDir);
const resolved = path.resolve(root, rel);
const rootPrefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
if (resolved !== root && !resolved.startsWith(rootPrefix)) {
return undefined;
}
return resolved;
}
/** Serve `/signer/` outside Vite `base` so WebAuthn + nest stay same-origin. */
function serveSignerPlugin(): Plugin {
return {
name: "ows-serve-signer",
configureServer(server) {
server.middlewares.use((req: IncomingMessage, res: ServerResponse, next) => {
const url = req.url?.split("?")[0] ?? "";
if (!url.startsWith("/signer")) {
next();
return;
}
if (url === "/signer" || url === "/signer/") {
sendFile(res, path.join(signerPublicDir, "index.html"));
return;
}
if (url.startsWith("/signer/src/")) {
const filePath = resolveContainedPath(
signerPkgSrc,
url.slice("/signer/src/".length),
);
if (!filePath || !fs.existsSync(filePath)) {
res.statusCode = 404;
res.end("Not found");
return;
}
sendFile(res, filePath);
return;
}
const filePath = resolveContainedPath(
signerPublicDir,
url.slice("/signer/".length),
);
if (!filePath || !fs.existsSync(filePath)) {
res.statusCode = 404;
res.end("Not found");
return;
}
sendFile(res, filePath);
});
},
};
}
/**
* Host Layer MPA entries (`/mobile/`, `/create/`) must not get Vite's default
* SPA fallback to Branding `index.html`. That served Branding at the top level
* (no OWSProxy), so nesting became Branding→Signing only and the signer
* rejected with "Must be embedded in a wallet iframe (double iframe)."
*/
function serveHostMpaPlugin(): Plugin {
const entries: Record<string, string> = {
"/mobile": "/mobile/index.html",
"/mobile/": "/mobile/index.html",
"/create": "/create/index.html",
"/create/": "/create/index.html",
};
return {
name: "ows-serve-host-mpa",
configureServer(server) {
server.middlewares.use((req: IncomingMessage, res: ServerResponse, next) => {
const raw = req.url ?? "";
const q = raw.indexOf("?");
const pathname = q === -1 ? raw : raw.slice(0, q);
const search = q === -1 ? "" : raw.slice(q);
const target = entries[pathname];
if (!target) {
next();
return;
}
if (pathname === "/mobile" || pathname === "/create") {
res.statusCode = 301;
res.setHeader("Location", `${pathname}/${search}`);
res.end();
return;
}
req.url = `${target}${search}`;
next();
});
},
};
}
/** Branding Layer production CSP (dev omits this so Vite HMR keeps working). */
const BRANDING_CSP = [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob: https:",
"font-src 'self' data:",
"connect-src 'self' https: wss:",
"frame-src https:",
"worker-src 'self' blob:",
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
].join("; ");
function brandingProductionCspPlugin(): Plugin {
return {
name: "ows-branding-production-csp",
transformIndexHtml: {
order: "pre",
handler(html, ctx) {
if (ctx.server) {
return html;
}
return html.replace(
/<head>/i,
`<head>\n <meta http-equiv="Content-Security-Policy" content="${BRANDING_CSP}" />`,
);
},
},
};
}
export default defineConfig({
// MPA: Branding (`/`), Host create (`/create/`), Host mobile (`/mobile/`).
// Default `spa` history-fallback would rewrite `/mobile` to Branding index
// and break Host → Branding → Signing double-iframe nesting.
appType: "mpa",
base: "/",
publicDir: "public",
plugins: [
react(),
tailwindcss(),
brandingProductionCspPlugin(),
serveHostMpaPlugin(),
serveSignerPlugin(),
],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
...localOwsAliases,
},
},
server: {
port: Number(process.env.PORT ?? 5174),
strictPort: true,
host: "0.0.0.0",
allowedHosts: true,
...(useLocalOwsPackages
? {
fs: {
allow: [
path.resolve(__dirname),
path.resolve(__dirname, "../prf-wallet/packages"),
],
},
}
: {}),
},
preview: {
port: Number(process.env.PORT ?? 5174),
strictPort: true,
host: "0.0.0.0",
},
build: {
outDir: "dist",
emptyOutDir: true,
// Do not ship source maps to the browser — maps embed original sources
// (including crypto PEM-header validation strings) and can leak secrets.
sourcemap: false,
rollupOptions: {
input: {
main: path.resolve(__dirname, "index.html"),
create: path.resolve(__dirname, "create/index.html"),
mobile: path.resolve(__dirname, "mobile/index.html"),
},
},
},
});