@weft-framework/server 0.0.0-stage → 0.0.1

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.
Files changed (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/dist/account.d.ts +124 -0
  4. package/dist/account.js +344 -0
  5. package/dist/action.d.ts +43 -0
  6. package/dist/action.js +135 -0
  7. package/dist/admin.d.ts +99 -0
  8. package/dist/admin.js +431 -0
  9. package/dist/api.d.ts +21 -0
  10. package/dist/api.js +72 -0
  11. package/dist/app.d.ts +202 -0
  12. package/dist/app.js +3692 -0
  13. package/dist/assets.d.ts +4 -0
  14. package/dist/assets.js +91 -0
  15. package/dist/auth.d.ts +150 -0
  16. package/dist/auth.js +215 -0
  17. package/dist/backup.d.ts +46 -0
  18. package/dist/backup.js +345 -0
  19. package/dist/build.d.ts +33 -0
  20. package/dist/build.js +274 -0
  21. package/dist/bun.d.ts +30 -0
  22. package/dist/bun.js +53 -0
  23. package/dist/calendar.d.ts +161 -0
  24. package/dist/calendar.js +690 -0
  25. package/dist/compiler.d.ts +13 -0
  26. package/dist/compiler.js +58 -0
  27. package/dist/compress.d.ts +6 -0
  28. package/dist/compress.js +78 -0
  29. package/dist/config.d.ts +26 -0
  30. package/dist/config.js +317 -0
  31. package/dist/context.d.ts +9 -0
  32. package/dist/context.js +1 -0
  33. package/dist/contract.d.ts +18 -0
  34. package/dist/contract.js +171 -0
  35. package/dist/datamap.d.ts +24 -0
  36. package/dist/datamap.js +365 -0
  37. package/dist/db-backup.d.ts +27 -0
  38. package/dist/db-backup.js +115 -0
  39. package/dist/dev-events.d.ts +14 -0
  40. package/dist/dev-events.js +135 -0
  41. package/dist/dev.d.ts +1 -0
  42. package/dist/dev.js +240 -0
  43. package/dist/devtools-client.d.ts +1 -0
  44. package/dist/devtools-client.js +362 -0
  45. package/dist/devtools.d.ts +87 -0
  46. package/dist/devtools.js +68 -0
  47. package/dist/edge.d.ts +3 -0
  48. package/dist/edge.js +7 -0
  49. package/dist/email-signin.d.ts +92 -0
  50. package/dist/email-signin.js +259 -0
  51. package/dist/env.d.ts +1 -0
  52. package/dist/env.js +15 -0
  53. package/dist/explain.d.ts +12 -0
  54. package/dist/explain.js +217 -0
  55. package/dist/files.d.ts +6 -0
  56. package/dist/files.js +170 -0
  57. package/dist/grants.d.ts +69 -0
  58. package/dist/grants.js +206 -0
  59. package/dist/image/bitmap.d.ts +11 -0
  60. package/dist/image/bitmap.js +172 -0
  61. package/dist/image/jpeg.d.ts +10 -0
  62. package/dist/image/jpeg.js +697 -0
  63. package/dist/image/png.d.ts +8 -0
  64. package/dist/image/png.js +282 -0
  65. package/dist/image/transform.d.ts +20 -0
  66. package/dist/image/transform.js +52 -0
  67. package/dist/image/worker.d.ts +1 -0
  68. package/dist/image/worker.js +11 -0
  69. package/dist/images.d.ts +39 -0
  70. package/dist/images.js +283 -0
  71. package/dist/index.d.ts +64 -0
  72. package/dist/index.js +31 -0
  73. package/dist/inspect-hub.d.ts +42 -0
  74. package/dist/inspect-hub.js +14 -0
  75. package/dist/inspector.d.ts +51 -0
  76. package/dist/inspector.js +193 -0
  77. package/dist/job-admin.d.ts +55 -0
  78. package/dist/job-admin.js +89 -0
  79. package/dist/jobs.d.ts +222 -0
  80. package/dist/jobs.js +789 -0
  81. package/dist/live.d.ts +72 -0
  82. package/dist/live.js +481 -0
  83. package/dist/load-config.d.ts +2 -0
  84. package/dist/load-config.js +41 -0
  85. package/dist/log.d.ts +20 -0
  86. package/dist/log.js +143 -0
  87. package/dist/mail.d.ts +189 -0
  88. package/dist/mail.js +999 -0
  89. package/dist/media.d.ts +129 -0
  90. package/dist/media.js +470 -0
  91. package/dist/meta.d.ts +54 -0
  92. package/dist/meta.js +146 -0
  93. package/dist/middleware.d.ts +20 -0
  94. package/dist/middleware.js +101 -0
  95. package/dist/migrate.d.ts +12 -0
  96. package/dist/migrate.js +88 -0
  97. package/dist/node.d.ts +26 -0
  98. package/dist/node.js +96 -0
  99. package/dist/notice.d.ts +21 -0
  100. package/dist/notice.js +48 -0
  101. package/dist/npm.d.ts +16 -0
  102. package/dist/npm.js +347 -0
  103. package/dist/oauth.d.ts +76 -0
  104. package/dist/oauth.js +408 -0
  105. package/dist/otel.d.ts +57 -0
  106. package/dist/otel.js +293 -0
  107. package/dist/passkey.d.ts +99 -0
  108. package/dist/passkey.js +572 -0
  109. package/dist/password.d.ts +8 -0
  110. package/dist/password.js +65 -0
  111. package/dist/pdf.d.ts +46 -0
  112. package/dist/pdf.js +332 -0
  113. package/dist/personal-data.d.ts +22 -0
  114. package/dist/personal-data.js +148 -0
  115. package/dist/pointers.d.ts +9 -0
  116. package/dist/pointers.js +148 -0
  117. package/dist/postcss.d.ts +3 -0
  118. package/dist/postcss.js +89 -0
  119. package/dist/presence.d.ts +27 -0
  120. package/dist/presence.js +161 -0
  121. package/dist/preview.d.ts +25 -0
  122. package/dist/preview.js +353 -0
  123. package/dist/production.d.ts +16 -0
  124. package/dist/production.js +119 -0
  125. package/dist/project.d.ts +23 -0
  126. package/dist/project.js +536 -0
  127. package/dist/regions.d.ts +47 -0
  128. package/dist/regions.js +511 -0
  129. package/dist/replay.d.ts +44 -0
  130. package/dist/replay.js +259 -0
  131. package/dist/router.d.ts +29 -0
  132. package/dist/router.js +146 -0
  133. package/dist/rules-diff.d.ts +18 -0
  134. package/dist/rules-diff.js +165 -0
  135. package/dist/rules-test.d.ts +17 -0
  136. package/dist/rules-test.js +108 -0
  137. package/dist/saml.d.ts +160 -0
  138. package/dist/saml.js +959 -0
  139. package/dist/seal.d.ts +35 -0
  140. package/dist/seal.js +107 -0
  141. package/dist/secret.d.ts +14 -0
  142. package/dist/secret.js +110 -0
  143. package/dist/security.d.ts +53 -0
  144. package/dist/security.js +250 -0
  145. package/dist/seed.d.ts +16 -0
  146. package/dist/seed.js +94 -0
  147. package/dist/seo.d.ts +42 -0
  148. package/dist/seo.js +175 -0
  149. package/dist/settings.d.ts +79 -0
  150. package/dist/settings.js +212 -0
  151. package/dist/shared.d.ts +15 -0
  152. package/dist/shared.js +283 -0
  153. package/dist/shell.d.ts +12 -0
  154. package/dist/shell.js +118 -0
  155. package/dist/storage.d.ts +13 -0
  156. package/dist/storage.js +55 -0
  157. package/dist/support.d.ts +83 -0
  158. package/dist/support.js +236 -0
  159. package/dist/sync.d.ts +35 -0
  160. package/dist/sync.js +167 -0
  161. package/dist/tailwind.d.ts +14 -0
  162. package/dist/tailwind.js +117 -0
  163. package/dist/two-factor.d.ts +103 -0
  164. package/dist/two-factor.js +435 -0
  165. package/dist/uploads.d.ts +185 -0
  166. package/dist/uploads.js +991 -0
  167. package/dist/webhooks.d.ts +169 -0
  168. package/dist/webhooks.js +758 -0
  169. package/dist/webpush.d.ts +97 -0
  170. package/dist/webpush.js +372 -0
  171. package/dist/wizard.d.ts +141 -0
  172. package/dist/wizard.js +410 -0
  173. package/dist/workflows.d.ts +134 -0
  174. package/dist/workflows.js +511 -0
  175. package/package.json +186 -4
@@ -0,0 +1,259 @@
1
+ import { signInWith } from "./auth.js";
2
+ import { base64url, RateLimiter, timingSafeEqual } from "./security.js";
3
+ import { isSafePath } from "@weft-framework/runtime";
4
+ export class MemoryEmailTokenStore {
5
+ #tokens = new Map();
6
+ add(t) {
7
+ this.#tokens.set(t.id, { ...t });
8
+ }
9
+ get(id) {
10
+ const t = this.#tokens.get(id);
11
+ return t ? { ...t } : null;
12
+ }
13
+ find(session, email) {
14
+ let best = null;
15
+ for (const t of this.#tokens.values()) {
16
+ if (t.session === session && t.email === email && (!best || t.expires > best.expires))
17
+ best = t;
18
+ }
19
+ return best ? { ...best } : null;
20
+ }
21
+ attempt(id) {
22
+ const t = this.#tokens.get(id);
23
+ if (!t)
24
+ return Number.POSITIVE_INFINITY;
25
+ t.attempts += 1;
26
+ return t.attempts;
27
+ }
28
+ take(id) {
29
+ return this.#tokens.delete(id);
30
+ }
31
+ clear(session, email) {
32
+ for (const [id, t] of this.#tokens)
33
+ if (t.session === session && t.email === email)
34
+ this.#tokens.delete(id);
35
+ }
36
+ sweep(now) {
37
+ for (const [id, t] of this.#tokens)
38
+ if (t.expires <= now)
39
+ this.#tokens.delete(id);
40
+ }
41
+ }
42
+ export class SqlEmailTokenStore {
43
+ db;
44
+ table;
45
+ constructor(db, table = "weft_email_tokens") {
46
+ this.db = db;
47
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
48
+ throw new Error(`SqlEmailTokenStore: bad table name ${table}`);
49
+ }
50
+ this.table = table;
51
+ db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id TEXT PRIMARY KEY, email TEXT NOT NULL, code TEXT NOT NULL, ` +
52
+ `session TEXT NOT NULL, next TEXT NOT NULL, expires INTEGER NOT NULL, attempts INTEGER NOT NULL)`);
53
+ db.exec(`CREATE INDEX IF NOT EXISTS ${table}_session ON ${table} (session, email)`);
54
+ }
55
+ row(r) {
56
+ if (!r || typeof r !== "object")
57
+ return null;
58
+ const o = r;
59
+ return {
60
+ id: String(o.id),
61
+ email: String(o.email),
62
+ code: String(o.code),
63
+ session: String(o.session),
64
+ next: String(o.next),
65
+ expires: Number(o.expires),
66
+ attempts: Number(o.attempts),
67
+ };
68
+ }
69
+ add(t) {
70
+ this.db
71
+ .prepare(`INSERT INTO ${this.table} (id, email, code, session, next, expires, attempts) VALUES (?, ?, ?, ?, ?, ?, ?)`)
72
+ .run(t.id, t.email, t.code, t.session, t.next, t.expires, t.attempts);
73
+ }
74
+ get(id) {
75
+ return this.row(this.db.prepare(`SELECT * FROM ${this.table} WHERE id = ?`).all(id)[0]);
76
+ }
77
+ find(session, email) {
78
+ return this.row(this.db.prepare(`SELECT * FROM ${this.table} WHERE session = ? AND email = ? ORDER BY expires DESC LIMIT 1`).all(session, email)[0]);
79
+ }
80
+ attempt(id) {
81
+ this.db.prepare(`UPDATE ${this.table} SET attempts = attempts + 1 WHERE id = ?`).run(id);
82
+ const r = this.db.prepare(`SELECT attempts FROM ${this.table} WHERE id = ?`).all(id)[0];
83
+ return r ? Number(r.attempts) : Number.POSITIVE_INFINITY;
84
+ }
85
+ take(id) {
86
+ return this.db.prepare(`DELETE FROM ${this.table} WHERE id = ? RETURNING id`).all(id).length > 0;
87
+ }
88
+ clear(session, email) {
89
+ this.db.prepare(`DELETE FROM ${this.table} WHERE session = ? AND email = ?`).run(session, email);
90
+ }
91
+ sweep(now) {
92
+ this.db.prepare(`DELETE FROM ${this.table} WHERE expires <= ?`).run(now);
93
+ }
94
+ }
95
+ export class EmailSignInError extends Error {
96
+ code;
97
+ constructor(code, message) {
98
+ super(message);
99
+ this.name = "EmailSignInError";
100
+ this.code = code;
101
+ }
102
+ }
103
+ export const EMAIL_PATH = "/_weft/auth/email";
104
+ const MAX_EMAIL = 254;
105
+ const EMAIL = /^[^\s@<>()[\]\\,;:"]{1,64}@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;
106
+ const enc = new TextEncoder();
107
+ async function sha256(s) {
108
+ return base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(s))));
109
+ }
110
+ function digits(n) {
111
+ let out = "";
112
+ const buf = new Uint8Array(1);
113
+ while (out.length < n) {
114
+ crypto.getRandomValues(buf);
115
+ if (buf[0] < 250)
116
+ out += String(buf[0] % 10);
117
+ }
118
+ return out;
119
+ }
120
+ export function normalizeEmail(raw) {
121
+ if (typeof raw !== "string")
122
+ return null;
123
+ const email = raw.trim().toLowerCase();
124
+ return email.length <= MAX_EMAIL && EMAIL.test(email) ? email : null;
125
+ }
126
+ export class EmailSignIn {
127
+ #o;
128
+ page;
129
+ #store;
130
+ #now;
131
+ #origin;
132
+ #byEmail;
133
+ #bySession;
134
+ #swept = 0;
135
+ constructor(o) {
136
+ let origin;
137
+ try {
138
+ origin = new URL(o.url);
139
+ }
140
+ catch {
141
+ throw new Error("emailSignIn: `url` is the app's public origin, such as https://app.example");
142
+ }
143
+ const local = origin.hostname === "localhost" || origin.hostname === "127.0.0.1" || origin.hostname === "[::1]";
144
+ if (origin.protocol !== "https:" && !(origin.protocol === "http:" && local)) {
145
+ throw new Error("emailSignIn: `url` must use https (http only for localhost)");
146
+ }
147
+ if (typeof o.send !== "function")
148
+ throw new Error("emailSignIn: `send` delivers the message");
149
+ if (typeof o.page !== "string" || !isSafePath(o.page) || /[?#]/.test(o.page) || o.page.startsWith("/_weft/")) {
150
+ throw new Error("emailSignIn: `page` is the path of the app's confirmation page, such as /sign-in/confirm");
151
+ }
152
+ this.page = o.page;
153
+ const ttlMs = o.ttlMs ?? 15 * 60_000;
154
+ if (!Number.isFinite(ttlMs) || ttlMs < 60_000 || ttlMs > 3_600_000)
155
+ throw new Error("emailSignIn: ttlMs is 1 minute to 1 hour");
156
+ const codeLength = o.codeLength ?? 6;
157
+ if (!Number.isInteger(codeLength) || codeLength < 6 || codeLength > 10)
158
+ throw new Error("emailSignIn: codeLength is 6 to 10");
159
+ const maxAttempts = o.maxAttempts ?? 5;
160
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > 10)
161
+ throw new Error("emailSignIn: maxAttempts is 1 to 10");
162
+ const perEmail = o.perEmail ?? 5;
163
+ const perSession = o.perSession ?? 10;
164
+ for (const [k, v] of [["perEmail", perEmail], ["perSession", perSession]]) {
165
+ if (!Number.isInteger(v) || v < 1)
166
+ throw new Error(`emailSignIn: ${k} is a whole number of requests per hour`);
167
+ }
168
+ this.#o = { url: o.url, page: o.page, send: o.send, allow: o.allow, ttlMs, codeLength, maxAttempts, perEmail, perSession };
169
+ this.#origin = origin.origin;
170
+ this.#store = o.store ?? new MemoryEmailTokenStore();
171
+ this.#now = o.now ?? Date.now;
172
+ this.#byEmail = new RateLimiter({ capacity: perEmail, refillPerSecond: perEmail / 3600 });
173
+ this.#bySession = new RateLimiter({ capacity: perSession, refillPerSecond: perSession / 3600 });
174
+ }
175
+ async #sweep(now) {
176
+ if (now - this.#swept > 60_000) {
177
+ this.#swept = now;
178
+ await this.#store.sweep(now);
179
+ }
180
+ }
181
+ async request(ctx, email, opts = {}) {
182
+ const address = normalizeEmail(email);
183
+ if (!address)
184
+ throw new EmailSignInError("invalid", "That is not an email address");
185
+ const now = this.#now();
186
+ if (!this.#bySession.take(ctx.session, now) || !this.#byEmail.take(address, now)) {
187
+ throw new EmailSignInError("limit", "Too many sign-in emails; try again later");
188
+ }
189
+ await this.#sweep(now);
190
+ if (this.#o.allow && !(await this.#o.allow(address)))
191
+ return;
192
+ const next = opts.next !== undefined && isSafePath(opts.next) ? opts.next : "/";
193
+ const token = base64url(crypto.getRandomValues(new Uint8Array(32)));
194
+ const id = await sha256(`link:${token}`);
195
+ const code = digits(this.#o.codeLength);
196
+ const expires = now + this.#o.ttlMs;
197
+ await this.#store.clear(ctx.session, address);
198
+ await this.#store.add({ id, email: address, code: await sha256(`code:${id}:${code}`), session: ctx.session, next, expires, attempts: 0 });
199
+ const link = `${this.#origin}${this.page}?t=${token}`;
200
+ try {
201
+ await this.#o.send({ email: address, link, code, expires: new Date(expires) });
202
+ }
203
+ catch (err) {
204
+ await this.#store.take(id);
205
+ throw err;
206
+ }
207
+ }
208
+ async verify(ctx, email, code) {
209
+ const address = normalizeEmail(email);
210
+ if (!address || typeof code !== "string")
211
+ return false;
212
+ const typed = code.replace(/[\s-]/g, "");
213
+ const t = await this.#store.find(ctx.session, address);
214
+ if (!t || t.expires <= this.#now())
215
+ return false;
216
+ if ((await this.#store.attempt(t.id)) > this.#o.maxAttempts) {
217
+ await this.#store.take(t.id);
218
+ return false;
219
+ }
220
+ if (!/^\d+$/.test(typed) || !timingSafeEqual(await sha256(`code:${t.id}:${typed}`), t.code))
221
+ return false;
222
+ if (!(await this.#store.take(t.id)))
223
+ return false;
224
+ return (await signInWith(ctx, identityFor(address))) === "ok";
225
+ }
226
+ async pending(ctx) {
227
+ if (ctx.url.pathname !== this.page)
228
+ return null;
229
+ const token = ctx.url.searchParams.get("t") ?? "";
230
+ const t = await this.#lookup(token);
231
+ return t ? { email: t.email, token, action: EMAIL_PATH } : null;
232
+ }
233
+ async consume(token) {
234
+ const t = await this.#lookup(token);
235
+ if (!t || !(await this.#store.take(t.id)))
236
+ return null;
237
+ return { email: t.email, next: t.next };
238
+ }
239
+ async #lookup(token) {
240
+ if (typeof token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(token))
241
+ return null;
242
+ const t = await this.#store.get(await sha256(`link:${token}`));
243
+ return t && t.expires > this.#now() ? t : null;
244
+ }
245
+ }
246
+ export function identityFor(email) {
247
+ return Object.freeze({
248
+ provider: "email",
249
+ subject: email,
250
+ email,
251
+ emailVerified: true,
252
+ name: null,
253
+ picture: null,
254
+ claims: Object.freeze({ email }),
255
+ });
256
+ }
257
+ export function emailSignIn(o) {
258
+ return new EmailSignIn(o);
259
+ }
package/dist/env.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function loadEnvFile(file: string, env?: Record<string, string | undefined>): string[];
package/dist/env.js ADDED
@@ -0,0 +1,15 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { parseEnv } from "./secret.js";
3
+ export function loadEnvFile(file, env = process.env) {
4
+ if (!existsSync(file))
5
+ return [];
6
+ const parsed = parseEnv(readFileSync(file, "utf8"), file);
7
+ const set = [];
8
+ for (const [k, v] of Object.entries(parsed)) {
9
+ if (env[k] === undefined) {
10
+ env[k] = v;
11
+ set.push(k);
12
+ }
13
+ }
14
+ return set;
15
+ }
@@ -0,0 +1,12 @@
1
+ import { type Model, type PolicyExpr } from "@weft-framework/data";
2
+ import { type Compiler } from "./compiler.js";
3
+ export declare class ExplainError extends Error {
4
+ }
5
+ export declare function explainModel(m: Model<unknown>): string;
6
+ export declare function words(e: PolicyExpr): string;
7
+ export declare function constant(e: PolicyExpr): boolean | null;
8
+ export interface ExplainOptions {
9
+ compiler: Compiler;
10
+ tenant?: string;
11
+ }
12
+ export declare function explainProject(root: string, opts: ExplainOptions): Promise<string>;
@@ -0,0 +1,217 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { realpathSync, rmSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ import { useDatabase } from "@weft-framework/data";
7
+ import { CompileError, findCompiler } from "./compiler.js";
8
+ import { ConfigError } from "./config.js";
9
+ import { ProjectError, loadProject } from "./project.js";
10
+ export class ExplainError extends Error {
11
+ }
12
+ const EXPLAIN = Symbol.for("weft.access.explain");
13
+ export function explainModel(m) {
14
+ const c = m.config;
15
+ const rule = (fn, where) => fn === undefined ? "none (nobody)" : where === undefined ? "a rule (checked row by row)" : "a rule, also pushed into SQL";
16
+ const lines = [`Model ${m.name} (key ${m.key})`];
17
+ if (m.tenant !== null)
18
+ lines.push(` tenant: ${m.tenant} (rows stay inside the actor's tenant)`);
19
+ for (const [verb, fn, where] of [
20
+ ["read", c.read, c.readWhere],
21
+ ["write", c.write, c.writeWhere],
22
+ ]) {
23
+ lines.push(` ${verb}: ${rule(fn, where)}`);
24
+ if (fn === undefined)
25
+ continue;
26
+ if (where !== undefined)
27
+ lines.push(` in words: ${words(where)}`);
28
+ else
29
+ lines.push(` as code: ${code(fn)}`);
30
+ }
31
+ for (const [field, fn] of m.fieldReads) {
32
+ const a = c.attrs?.[field];
33
+ const consent = a?.consent;
34
+ if (consent !== undefined) {
35
+ const purpose = typeof consent === "string" ? consent : consent.purpose;
36
+ const whose = typeof consent === "object" && consent.subject ? `the person in \`${consent.subject}\`` : "the reader";
37
+ lines.push(` field ${field}: shown only once ${whose} agreed to "${purpose}" (null otherwise)`);
38
+ if (a?.read !== undefined)
39
+ lines.push(` and by its own rule, as code: ${code(a.read)}`);
40
+ continue;
41
+ }
42
+ lines.push(` field ${field}: read by whom its own rule admits (null for anyone else)`);
43
+ lines.push(` as code: ${code(fn)}`);
44
+ }
45
+ for (const [verb, fn, where] of [
46
+ ["read", c.read, c.readWhere],
47
+ ["write", c.write, c.writeWhere],
48
+ ]) {
49
+ if (fn === undefined)
50
+ continue;
51
+ if (where !== undefined && constant(where) === false) {
52
+ lines.push(` warning: the ${verb} rule can never pass (dead rule)`);
53
+ }
54
+ else if (passesForAnyone(m, fn)) {
55
+ const what = verb === "read" ? "every row may be public" : "anyone may write";
56
+ lines.push(` warning: the ${verb} rule passes with no actor, on a row with every field empty (${what})`);
57
+ }
58
+ }
59
+ return lines.join("\n");
60
+ }
61
+ export function words(e) {
62
+ const operand = (o) => {
63
+ if ("value" in o)
64
+ return o.value === null ? "empty" : JSON.stringify(o.value);
65
+ if ("field" in o)
66
+ return `the row's ${o.field.join(".")}`;
67
+ return o.actor.length === 0 ? "the actor" : `the actor's ${o.actor.join(".")}`;
68
+ };
69
+ const inner = (x) => ("or" in x || "and" in x ? `(${words(x)})` : words(x));
70
+ if ("or" in e)
71
+ return e.or.map(inner).join(", or ");
72
+ if ("and" in e)
73
+ return e.and.map(inner).join(", and ");
74
+ if ("not" in e)
75
+ return `not ${inner(e.not)}`;
76
+ if ("truthy" in e)
77
+ return "value" in e.truthy ? (e.truthy.value ? "always" : "never") : `${operand(e.truthy)} is set`;
78
+ const verb = { "==": "is", "!=": "is not", "<": "is less than", "<=": "is at most", ">": "is more than", ">=": "is at least" }[e.cmp];
79
+ return `${operand(e.l)} ${verb} ${operand(e.r)}`;
80
+ }
81
+ function code(fn) {
82
+ const s = String(fn).replace(/\s+/g, " ").trim();
83
+ return s.length > 160 ? s.slice(0, 159) + "…" : s;
84
+ }
85
+ export function constant(e) {
86
+ const operand = (o) => ("value" in o ? { v: o.value } : null);
87
+ if ("or" in e) {
88
+ const vs = e.or.map(constant);
89
+ if (vs.includes(true))
90
+ return true;
91
+ return vs.every((v) => v === false) ? false : null;
92
+ }
93
+ if ("and" in e) {
94
+ const vs = e.and.map(constant);
95
+ if (vs.includes(false))
96
+ return false;
97
+ return vs.every((v) => v === true) ? true : null;
98
+ }
99
+ if ("not" in e) {
100
+ const v = constant(e.not);
101
+ return v === null ? null : !v;
102
+ }
103
+ if ("truthy" in e) {
104
+ const o = operand(e.truthy);
105
+ return o === null ? null : Boolean(o.v);
106
+ }
107
+ const l = operand(e.l);
108
+ const r = operand(e.r);
109
+ if (l === null || r === null)
110
+ return null;
111
+ const a = l.v;
112
+ const b = r.v;
113
+ switch (e.cmp) {
114
+ case "==":
115
+ return a === b;
116
+ case "!=":
117
+ return a !== b;
118
+ default:
119
+ if (a === null || b === null)
120
+ return false;
121
+ return e.cmp === "<" ? a < b : e.cmp === "<=" ? a <= b : e.cmp === ">" ? a > b : a >= b;
122
+ }
123
+ }
124
+ function passesForAnyone(m, fn) {
125
+ const row = Object.fromEntries(m.fields.map((f) => [f.name, null]));
126
+ const yes = (actor) => {
127
+ try {
128
+ return fn(actor, { ...row }) === true;
129
+ }
130
+ catch {
131
+ return false;
132
+ }
133
+ };
134
+ return yes(null) && yes({});
135
+ }
136
+ export async function explainProject(root, opts) {
137
+ root = resolve(root);
138
+ const outDir = join(root, ".weft", "explain", randomUUID());
139
+ try {
140
+ const project = await loadProject(root, { compiler: opts.compiler, outDir, browserAssets: false, cacheKey: outDir });
141
+ const models = Object.values(project.models);
142
+ const access = new Set();
143
+ const own = [];
144
+ for (const m of models) {
145
+ const ex = m[EXPLAIN];
146
+ if (typeof ex === "function")
147
+ access.add(ex);
148
+ else
149
+ own.push(m);
150
+ }
151
+ if (access.size > 1)
152
+ throw new ExplainError("src/models exports the models of more than one access configuration");
153
+ let close = () => { };
154
+ if (opts.tenant !== undefined) {
155
+ if (access.size === 0)
156
+ throw new ExplainError("--tenant needs @weft-framework/core's models in src/models");
157
+ if (project.database === undefined || project.database === ":memory:") {
158
+ throw new ExplainError("--tenant needs a `database` file in weft.config.ts");
159
+ }
160
+ const { openSqlite } = await import("@weft-framework/data/sqlite");
161
+ const db = openSqlite(project.database, { readOnly: true });
162
+ close = () => db.close();
163
+ useDatabase(db, models, { migrate: false, onWarning: () => { } });
164
+ }
165
+ try {
166
+ const parts = [];
167
+ parts.push(own.length ? own.sort((a, b) => a.name.localeCompare(b.name)).map(explainModel).join("\n\n") : "No models in src/models.");
168
+ for (const ex of access) {
169
+ try {
170
+ parts.push(ex(opts.tenant).trimEnd());
171
+ }
172
+ catch (e) {
173
+ if (e instanceof Error && e.code === "not-found")
174
+ throw new ExplainError(`no tenant ${opts.tenant}`);
175
+ throw e;
176
+ }
177
+ }
178
+ return parts.join("\n\n") + "\n";
179
+ }
180
+ finally {
181
+ close();
182
+ }
183
+ }
184
+ finally {
185
+ rmSync(outDir, { recursive: true, force: true });
186
+ }
187
+ }
188
+ async function main() {
189
+ const { values, positionals } = parseArgs({ allowPositionals: true, options: { tenant: { type: "string" } } });
190
+ const root = resolve(positionals[0] ?? ".");
191
+ try {
192
+ process.stdout.write(await explainProject(root, { compiler: findCompiler(root), tenant: values.tenant }));
193
+ }
194
+ catch (err) {
195
+ if (err instanceof CompileError) {
196
+ console.error(err.diagnostics);
197
+ }
198
+ else if (err instanceof ExplainError || err instanceof ProjectError || err instanceof ConfigError) {
199
+ console.error(`[weft] ${err.message}`);
200
+ }
201
+ else {
202
+ console.error("[weft] explain:", err instanceof Error ? err.message : err);
203
+ }
204
+ process.exit(1);
205
+ }
206
+ }
207
+ function isEntry() {
208
+ try {
209
+ return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
210
+ }
211
+ catch {
212
+ return false;
213
+ }
214
+ }
215
+ if (isEntry()) {
216
+ await main();
217
+ }
@@ -0,0 +1,6 @@
1
+ export interface PublicFilesOptions {
2
+ cacheControl?: string;
3
+ }
4
+ export type FileHandler = (path: string, req: Request) => Promise<Response | null>;
5
+ export declare function publicFiles(dir: string, opts?: PublicFilesOptions): FileHandler;
6
+ export declare function assetManifest(dir: string): Promise<Record<string, string>>;
package/dist/files.js ADDED
@@ -0,0 +1,170 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import { readdir, realpath, stat } from "node:fs/promises";
4
+ import { extname, join, sep } from "node:path";
5
+ import { Readable } from "node:stream";
6
+ import { splitPath } from "./router.js";
7
+ const TYPES = {
8
+ ".html": "text/html; charset=utf-8",
9
+ ".css": "text/css; charset=utf-8",
10
+ ".js": "text/javascript; charset=utf-8",
11
+ ".mjs": "text/javascript; charset=utf-8",
12
+ ".json": "application/json",
13
+ ".map": "application/json",
14
+ ".webmanifest": "application/manifest+json",
15
+ ".txt": "text/plain; charset=utf-8",
16
+ ".xml": "application/xml",
17
+ ".svg": "image/svg+xml",
18
+ ".png": "image/png",
19
+ ".jpg": "image/jpeg",
20
+ ".jpeg": "image/jpeg",
21
+ ".gif": "image/gif",
22
+ ".webp": "image/webp",
23
+ ".avif": "image/avif",
24
+ ".ico": "image/x-icon",
25
+ ".woff": "font/woff",
26
+ ".woff2": "font/woff2",
27
+ ".ttf": "font/ttf",
28
+ ".otf": "font/otf",
29
+ ".mp4": "video/mp4",
30
+ ".webm": "video/webm",
31
+ ".mp3": "audio/mpeg",
32
+ ".ogg": "audio/ogg",
33
+ ".wav": "audio/wav",
34
+ ".pdf": "application/pdf",
35
+ ".wasm": "application/wasm",
36
+ };
37
+ const HASHED = /^(.*)\.([a-f0-9]{16})(\.[a-z0-9]{1,8})?$/i;
38
+ const IMMUTABLE = "public, max-age=31536000, immutable";
39
+ const hashes = new Map();
40
+ async function contentHash(file, size, mtimeMs) {
41
+ const sig = `${size}:${mtimeMs}`;
42
+ const hit = hashes.get(file);
43
+ if (hit?.sig === sig) {
44
+ return hit.hash;
45
+ }
46
+ const hash = await new Promise((resolve, reject) => {
47
+ const digest = createHash("sha256");
48
+ const stream = createReadStream(file);
49
+ stream.on("error", reject);
50
+ stream.on("data", (chunk) => digest.update(chunk));
51
+ stream.on("end", () => resolve(digest.digest("hex").slice(0, 16)));
52
+ });
53
+ hashes.set(file, { sig, hash });
54
+ if (hashes.size > 10_000) {
55
+ const oldest = hashes.keys().next().value;
56
+ if (oldest !== undefined) {
57
+ hashes.delete(oldest);
58
+ }
59
+ }
60
+ return hash;
61
+ }
62
+ export function publicFiles(dir, opts = {}) {
63
+ const cacheControl = opts.cacheControl ?? "public, max-age=0, must-revalidate";
64
+ let rootP = null;
65
+ const root = () => (rootP ??= realpath(dir).catch(() => null));
66
+ return async (path, req) => {
67
+ const requested = splitPath(path);
68
+ if (!requested || requested.length === 0) {
69
+ return null;
70
+ }
71
+ for (const [i, p] of requested.entries()) {
72
+ if (p.includes("/") || p.includes("\\") || (p.startsWith(".") && !(i === 0 && p === ".well-known"))) {
73
+ return null;
74
+ }
75
+ }
76
+ let parts = requested;
77
+ let fingerprint = null;
78
+ const hashed = HASHED.exec(requested[requested.length - 1]);
79
+ if (hashed && hashed[1] !== "") {
80
+ fingerprint = hashed[2].toLowerCase();
81
+ parts = requested.slice(0, -1).concat(hashed[1] + (hashed[3] ?? ""));
82
+ }
83
+ const base = await root();
84
+ if (!base) {
85
+ return null;
86
+ }
87
+ let file;
88
+ try {
89
+ file = await realpath(join(base, ...parts));
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ if (!file.startsWith(base + sep)) {
95
+ return null;
96
+ }
97
+ const st = await stat(file).catch(() => null);
98
+ if (!st || !st.isFile()) {
99
+ return null;
100
+ }
101
+ if (fingerprint !== null && (await contentHash(file, st.size, st.mtimeMs)) !== fingerprint) {
102
+ return null;
103
+ }
104
+ const etag = `W/"${st.size.toString(16)}-${Math.floor(st.mtimeMs).toString(16)}"`;
105
+ const headers = new Headers({
106
+ "content-type": TYPES[extname(file).toLowerCase()] ?? "application/octet-stream",
107
+ "content-length": String(st.size),
108
+ "cache-control": fingerprint ? IMMUTABLE : cacheControl,
109
+ etag,
110
+ "last-modified": st.mtime.toUTCString(),
111
+ "x-content-type-options": "nosniff",
112
+ });
113
+ if (extname(file).toLowerCase() === ".svg") {
114
+ headers.set("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox");
115
+ }
116
+ const inm = req.headers.get("if-none-match");
117
+ if (inm && inm.split(",").some((t) => t.trim() === etag)) {
118
+ headers.delete("content-length");
119
+ return new Response(null, { status: 304, headers });
120
+ }
121
+ if (req.method === "HEAD") {
122
+ return new Response(null, { headers });
123
+ }
124
+ const body = Readable.toWeb(createReadStream(file));
125
+ return new Response(body, { headers });
126
+ };
127
+ }
128
+ export async function assetManifest(dir) {
129
+ const base = await realpath(dir).catch(() => null);
130
+ if (!base) {
131
+ return {};
132
+ }
133
+ const out = {};
134
+ const walk = async (rel, realDir) => {
135
+ for (const name of (await readdir(realDir)).sort()) {
136
+ if (name.includes("\0") || name.includes("/") || name.includes("\\")) {
137
+ continue;
138
+ }
139
+ if (name.startsWith(".") && !(rel.length === 0 && name === ".well-known")) {
140
+ continue;
141
+ }
142
+ const child = join(realDir, name);
143
+ const st = await stat(child).catch(() => null);
144
+ if (!st) {
145
+ continue;
146
+ }
147
+ if (st.isDirectory()) {
148
+ const next = await realpath(child).catch(() => null);
149
+ if (!next || !next.startsWith(base + sep)) {
150
+ continue;
151
+ }
152
+ await walk([...rel, name], next);
153
+ continue;
154
+ }
155
+ if (!st.isFile()) {
156
+ continue;
157
+ }
158
+ const file = await realpath(child).catch(() => null);
159
+ if (!file || !file.startsWith(base + sep)) {
160
+ continue;
161
+ }
162
+ const hash = await contentHash(file, st.size, st.mtimeMs);
163
+ const dot = name.lastIndexOf(".");
164
+ const hashed = dot > 0 ? `${name.slice(0, dot)}.${hash}${name.slice(dot)}` : `${name}.${hash}`;
165
+ out["/" + [...rel, name].join("/")] = "/" + [...rel, hashed].join("/");
166
+ }
167
+ };
168
+ await walk([], base);
169
+ return out;
170
+ }