@weft-framework/server 0.0.0-stage → 0.0.3
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.
- package/LICENSE +21 -0
- package/README.md +4 -2
- package/dist/account.d.ts +124 -0
- package/dist/account.js +344 -0
- package/dist/action.d.ts +43 -0
- package/dist/action.js +135 -0
- package/dist/admin.d.ts +99 -0
- package/dist/admin.js +431 -0
- package/dist/api.d.ts +21 -0
- package/dist/api.js +72 -0
- package/dist/app.d.ts +202 -0
- package/dist/app.js +3692 -0
- package/dist/assets.d.ts +4 -0
- package/dist/assets.js +91 -0
- package/dist/auth.d.ts +150 -0
- package/dist/auth.js +215 -0
- package/dist/backup.d.ts +46 -0
- package/dist/backup.js +345 -0
- package/dist/build.d.ts +33 -0
- package/dist/build.js +274 -0
- package/dist/bun.d.ts +30 -0
- package/dist/bun.js +53 -0
- package/dist/calendar.d.ts +161 -0
- package/dist/calendar.js +690 -0
- package/dist/compiler.d.ts +13 -0
- package/dist/compiler.js +58 -0
- package/dist/compress.d.ts +6 -0
- package/dist/compress.js +78 -0
- package/dist/config.d.ts +26 -0
- package/dist/config.js +317 -0
- package/dist/context.d.ts +9 -0
- package/dist/context.js +1 -0
- package/dist/contract.d.ts +18 -0
- package/dist/contract.js +171 -0
- package/dist/datamap.d.ts +24 -0
- package/dist/datamap.js +365 -0
- package/dist/db-backup.d.ts +27 -0
- package/dist/db-backup.js +115 -0
- package/dist/dev-events.d.ts +14 -0
- package/dist/dev-events.js +135 -0
- package/dist/dev.d.ts +1 -0
- package/dist/dev.js +240 -0
- package/dist/devtools-client.d.ts +1 -0
- package/dist/devtools-client.js +362 -0
- package/dist/devtools.d.ts +87 -0
- package/dist/devtools.js +68 -0
- package/dist/edge.d.ts +3 -0
- package/dist/edge.js +7 -0
- package/dist/email-signin.d.ts +92 -0
- package/dist/email-signin.js +259 -0
- package/dist/env.d.ts +1 -0
- package/dist/env.js +15 -0
- package/dist/explain.d.ts +12 -0
- package/dist/explain.js +217 -0
- package/dist/files.d.ts +6 -0
- package/dist/files.js +170 -0
- package/dist/grants.d.ts +69 -0
- package/dist/grants.js +206 -0
- package/dist/image/bitmap.d.ts +11 -0
- package/dist/image/bitmap.js +172 -0
- package/dist/image/jpeg.d.ts +10 -0
- package/dist/image/jpeg.js +697 -0
- package/dist/image/png.d.ts +8 -0
- package/dist/image/png.js +282 -0
- package/dist/image/transform.d.ts +20 -0
- package/dist/image/transform.js +52 -0
- package/dist/image/worker.d.ts +1 -0
- package/dist/image/worker.js +11 -0
- package/dist/images.d.ts +39 -0
- package/dist/images.js +283 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +31 -0
- package/dist/inspect-hub.d.ts +42 -0
- package/dist/inspect-hub.js +14 -0
- package/dist/inspector.d.ts +51 -0
- package/dist/inspector.js +193 -0
- package/dist/job-admin.d.ts +55 -0
- package/dist/job-admin.js +89 -0
- package/dist/jobs.d.ts +222 -0
- package/dist/jobs.js +789 -0
- package/dist/live.d.ts +72 -0
- package/dist/live.js +481 -0
- package/dist/load-config.d.ts +2 -0
- package/dist/load-config.js +41 -0
- package/dist/log.d.ts +20 -0
- package/dist/log.js +143 -0
- package/dist/mail.d.ts +189 -0
- package/dist/mail.js +999 -0
- package/dist/media.d.ts +129 -0
- package/dist/media.js +470 -0
- package/dist/meta.d.ts +54 -0
- package/dist/meta.js +146 -0
- package/dist/middleware.d.ts +20 -0
- package/dist/middleware.js +101 -0
- package/dist/migrate.d.ts +12 -0
- package/dist/migrate.js +88 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +96 -0
- package/dist/notice.d.ts +21 -0
- package/dist/notice.js +48 -0
- package/dist/npm.d.ts +16 -0
- package/dist/npm.js +347 -0
- package/dist/oauth.d.ts +76 -0
- package/dist/oauth.js +408 -0
- package/dist/otel.d.ts +57 -0
- package/dist/otel.js +293 -0
- package/dist/passkey.d.ts +99 -0
- package/dist/passkey.js +572 -0
- package/dist/password.d.ts +8 -0
- package/dist/password.js +65 -0
- package/dist/pdf.d.ts +46 -0
- package/dist/pdf.js +332 -0
- package/dist/personal-data.d.ts +22 -0
- package/dist/personal-data.js +148 -0
- package/dist/pointers.d.ts +9 -0
- package/dist/pointers.js +148 -0
- package/dist/postcss.d.ts +3 -0
- package/dist/postcss.js +89 -0
- package/dist/presence.d.ts +27 -0
- package/dist/presence.js +161 -0
- package/dist/preview.d.ts +25 -0
- package/dist/preview.js +353 -0
- package/dist/production.d.ts +16 -0
- package/dist/production.js +119 -0
- package/dist/project.d.ts +23 -0
- package/dist/project.js +536 -0
- package/dist/regions.d.ts +47 -0
- package/dist/regions.js +511 -0
- package/dist/replay.d.ts +44 -0
- package/dist/replay.js +259 -0
- package/dist/router.d.ts +29 -0
- package/dist/router.js +146 -0
- package/dist/rules-diff.d.ts +18 -0
- package/dist/rules-diff.js +165 -0
- package/dist/rules-test.d.ts +17 -0
- package/dist/rules-test.js +108 -0
- package/dist/saml.d.ts +160 -0
- package/dist/saml.js +959 -0
- package/dist/seal.d.ts +35 -0
- package/dist/seal.js +107 -0
- package/dist/secret.d.ts +14 -0
- package/dist/secret.js +110 -0
- package/dist/security.d.ts +53 -0
- package/dist/security.js +250 -0
- package/dist/seed.d.ts +16 -0
- package/dist/seed.js +94 -0
- package/dist/seo.d.ts +42 -0
- package/dist/seo.js +175 -0
- package/dist/settings.d.ts +79 -0
- package/dist/settings.js +212 -0
- package/dist/shared.d.ts +15 -0
- package/dist/shared.js +283 -0
- package/dist/shell.d.ts +12 -0
- package/dist/shell.js +118 -0
- package/dist/storage.d.ts +13 -0
- package/dist/storage.js +55 -0
- package/dist/support.d.ts +83 -0
- package/dist/support.js +236 -0
- package/dist/sync.d.ts +35 -0
- package/dist/sync.js +167 -0
- package/dist/tailwind.d.ts +14 -0
- package/dist/tailwind.js +117 -0
- package/dist/two-factor.d.ts +103 -0
- package/dist/two-factor.js +435 -0
- package/dist/uploads.d.ts +185 -0
- package/dist/uploads.js +991 -0
- package/dist/webhooks.d.ts +169 -0
- package/dist/webhooks.js +758 -0
- package/dist/webpush.d.ts +97 -0
- package/dist/webpush.js +372 -0
- package/dist/wizard.d.ts +141 -0
- package/dist/wizard.js +410 -0
- package/dist/workflows.d.ts +134 -0
- package/dist/workflows.js +511 -0
- package/package.json +186 -4
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { authState, completeTwoFactor } from "./auth.js";
|
|
2
|
+
import { seal, unseal } from "./seal.js";
|
|
3
|
+
import { isSecret } from "./secret.js";
|
|
4
|
+
import { base64url, fromBase64url, MIN_SECRET_LENGTH } from "./security.js";
|
|
5
|
+
export class MemoryTwoFactorStore {
|
|
6
|
+
#records = new Map();
|
|
7
|
+
#recovery = new Map();
|
|
8
|
+
get(user) {
|
|
9
|
+
const r = this.#records.get(user);
|
|
10
|
+
return r ? { ...r } : null;
|
|
11
|
+
}
|
|
12
|
+
add(r) {
|
|
13
|
+
if (this.#records.has(r.user))
|
|
14
|
+
return false;
|
|
15
|
+
this.#records.set(r.user, { ...r });
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
remove(user) {
|
|
19
|
+
this.#recovery.delete(user);
|
|
20
|
+
return this.#records.delete(user);
|
|
21
|
+
}
|
|
22
|
+
advance(user, step) {
|
|
23
|
+
const r = this.#records.get(user);
|
|
24
|
+
if (!r || r.lastStep >= step)
|
|
25
|
+
return false;
|
|
26
|
+
r.lastStep = step;
|
|
27
|
+
r.failures = 0;
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
fail(user, max, until) {
|
|
31
|
+
const r = this.#records.get(user);
|
|
32
|
+
if (!r)
|
|
33
|
+
return false;
|
|
34
|
+
r.failures++;
|
|
35
|
+
if (r.failures < max)
|
|
36
|
+
return false;
|
|
37
|
+
r.failures = 0;
|
|
38
|
+
r.lockedUntil = until;
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
succeed(user) {
|
|
42
|
+
const r = this.#records.get(user);
|
|
43
|
+
if (r)
|
|
44
|
+
r.failures = 0;
|
|
45
|
+
}
|
|
46
|
+
setRecovery(user, hashes) {
|
|
47
|
+
this.#recovery.set(user, new Set(hashes));
|
|
48
|
+
}
|
|
49
|
+
useRecovery(user, hash) {
|
|
50
|
+
return this.#recovery.get(user)?.delete(hash) ?? false;
|
|
51
|
+
}
|
|
52
|
+
countRecovery(user) {
|
|
53
|
+
return this.#recovery.get(user)?.size ?? 0;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
export class SqlTwoFactorStore {
|
|
57
|
+
#db;
|
|
58
|
+
#t;
|
|
59
|
+
#r;
|
|
60
|
+
constructor(db, table = "weft_two_factor") {
|
|
61
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table))
|
|
62
|
+
throw new Error(`@weft-framework/server: not a valid table name: ${table}`);
|
|
63
|
+
this.#db = db;
|
|
64
|
+
this.#t = `"${table}"`;
|
|
65
|
+
this.#r = `"${table}_recovery"`;
|
|
66
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${this.#t} (user_id TEXT PRIMARY KEY NOT NULL, secret TEXT NOT NULL, ` +
|
|
67
|
+
`last_step INTEGER NOT NULL, failures INTEGER NOT NULL, locked_until INTEGER NOT NULL, created INTEGER NOT NULL)`);
|
|
68
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${this.#r} (user_id TEXT NOT NULL, hash TEXT NOT NULL, PRIMARY KEY (user_id, hash))`);
|
|
69
|
+
}
|
|
70
|
+
get(user) {
|
|
71
|
+
const row = this.#db
|
|
72
|
+
.prepare(`SELECT secret, last_step, failures, locked_until, created FROM ${this.#t} WHERE user_id = ?`)
|
|
73
|
+
.all(user)[0];
|
|
74
|
+
if (!row)
|
|
75
|
+
return null;
|
|
76
|
+
return {
|
|
77
|
+
user,
|
|
78
|
+
secret: String(row.secret),
|
|
79
|
+
lastStep: Number(row.last_step),
|
|
80
|
+
failures: Number(row.failures),
|
|
81
|
+
lockedUntil: Number(row.locked_until),
|
|
82
|
+
created: Number(row.created),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
add(r) {
|
|
86
|
+
const added = this.#db
|
|
87
|
+
.prepare(`INSERT INTO ${this.#t} (user_id, secret, last_step, failures, locked_until, created) VALUES (?, ?, ?, ?, ?, ?) ` +
|
|
88
|
+
`ON CONFLICT(user_id) DO NOTHING RETURNING user_id`)
|
|
89
|
+
.all(r.user, r.secret, r.lastStep, r.failures, r.lockedUntil, r.created);
|
|
90
|
+
return added.length === 1;
|
|
91
|
+
}
|
|
92
|
+
remove(user) {
|
|
93
|
+
this.#db.prepare(`DELETE FROM ${this.#r} WHERE user_id = ?`).run(user);
|
|
94
|
+
return this.#db.prepare(`DELETE FROM ${this.#t} WHERE user_id = ? RETURNING user_id`).all(user).length === 1;
|
|
95
|
+
}
|
|
96
|
+
advance(user, step) {
|
|
97
|
+
return (this.#db
|
|
98
|
+
.prepare(`UPDATE ${this.#t} SET last_step = ?, failures = 0 WHERE user_id = ? AND last_step < ? RETURNING user_id`)
|
|
99
|
+
.all(step, user, step).length === 1);
|
|
100
|
+
}
|
|
101
|
+
fail(user, max, until) {
|
|
102
|
+
const row = this.#db
|
|
103
|
+
.prepare(`UPDATE ${this.#t} SET failures = CASE WHEN failures + 1 >= ? THEN 0 ELSE failures + 1 END, ` +
|
|
104
|
+
`locked_until = CASE WHEN failures + 1 >= ? THEN ? ELSE locked_until END WHERE user_id = ? ` +
|
|
105
|
+
`RETURNING failures, locked_until`)
|
|
106
|
+
.all(max, max, until, user)[0];
|
|
107
|
+
return row !== undefined && Number(row.failures) === 0 && Number(row.locked_until) === until;
|
|
108
|
+
}
|
|
109
|
+
succeed(user) {
|
|
110
|
+
this.#db.prepare(`UPDATE ${this.#t} SET failures = 0 WHERE user_id = ?`).run(user);
|
|
111
|
+
}
|
|
112
|
+
setRecovery(user, hashes) {
|
|
113
|
+
this.#db.prepare(`DELETE FROM ${this.#r} WHERE user_id = ?`).run(user);
|
|
114
|
+
const add = this.#db.prepare(`INSERT INTO ${this.#r} (user_id, hash) VALUES (?, ?)`);
|
|
115
|
+
for (const h of hashes)
|
|
116
|
+
add.run(user, h);
|
|
117
|
+
}
|
|
118
|
+
useRecovery(user, hash) {
|
|
119
|
+
return this.#db.prepare(`DELETE FROM ${this.#r} WHERE user_id = ? AND hash = ? RETURNING hash`).all(user, hash).length === 1;
|
|
120
|
+
}
|
|
121
|
+
countRecovery(user) {
|
|
122
|
+
const row = this.#db.prepare(`SELECT count(*) AS n FROM ${this.#r} WHERE user_id = ?`).all(user)[0];
|
|
123
|
+
return Number(row.n);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
export class TwoFactorError extends Error {
|
|
127
|
+
code;
|
|
128
|
+
until;
|
|
129
|
+
constructor(code, message, until) {
|
|
130
|
+
super(message);
|
|
131
|
+
this.name = "TwoFactorError";
|
|
132
|
+
this.code = code;
|
|
133
|
+
if (until !== undefined)
|
|
134
|
+
this.until = until;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const STEP_MS = 30_000;
|
|
138
|
+
const SETUP_TTL_MS = 10 * 60_000;
|
|
139
|
+
const SECRET_BYTES = 20;
|
|
140
|
+
const RECOVERY = "0123456789abcdefghjkmnpqrstvwxyz";
|
|
141
|
+
const B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
142
|
+
const enc = new TextEncoder();
|
|
143
|
+
export function base32(bytes) {
|
|
144
|
+
let out = "";
|
|
145
|
+
let bits = 0;
|
|
146
|
+
let value = 0;
|
|
147
|
+
for (const b of bytes) {
|
|
148
|
+
value = (value << 8) | b;
|
|
149
|
+
bits += 8;
|
|
150
|
+
while (bits >= 5) {
|
|
151
|
+
out += B32[(value >>> (bits - 5)) & 31];
|
|
152
|
+
bits -= 5;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (bits > 0)
|
|
156
|
+
out += B32[(value << (5 - bits)) & 31];
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
export function fromBase32(s) {
|
|
160
|
+
const clean = s.toUpperCase().replace(/[\s=]/g, "");
|
|
161
|
+
const out = [];
|
|
162
|
+
let bits = 0;
|
|
163
|
+
let value = 0;
|
|
164
|
+
for (const ch of clean) {
|
|
165
|
+
const i = B32.indexOf(ch);
|
|
166
|
+
if (i < 0)
|
|
167
|
+
return null;
|
|
168
|
+
value = ((value << 5) | i) & 0xffff;
|
|
169
|
+
bits += 5;
|
|
170
|
+
if (bits >= 8) {
|
|
171
|
+
out.push((value >>> (bits - 8)) & 255);
|
|
172
|
+
bits -= 8;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return new Uint8Array(out);
|
|
176
|
+
}
|
|
177
|
+
export async function totp(secret, step, digits = 6) {
|
|
178
|
+
const key = await crypto.subtle.importKey("raw", new Uint8Array(secret), { name: "HMAC", hash: "SHA-1" }, false, ["sign"]);
|
|
179
|
+
const msg = new Uint8Array(8);
|
|
180
|
+
new DataView(msg.buffer).setBigUint64(0, BigInt(step));
|
|
181
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, msg));
|
|
182
|
+
const o = mac[19] & 15;
|
|
183
|
+
const n = (((mac[o] & 0x7f) << 24) | (mac[o + 1] << 16) | (mac[o + 2] << 8) | mac[o + 3]) % 10 ** digits;
|
|
184
|
+
return String(n).padStart(digits, "0");
|
|
185
|
+
}
|
|
186
|
+
function sameString(a, b) {
|
|
187
|
+
if (a.length !== b.length)
|
|
188
|
+
return false;
|
|
189
|
+
let d = 0;
|
|
190
|
+
for (let i = 0; i < a.length; i++)
|
|
191
|
+
d |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
192
|
+
return d === 0;
|
|
193
|
+
}
|
|
194
|
+
export class TwoFactor {
|
|
195
|
+
page;
|
|
196
|
+
#issuer;
|
|
197
|
+
#store;
|
|
198
|
+
#require;
|
|
199
|
+
#digits;
|
|
200
|
+
#window;
|
|
201
|
+
#max;
|
|
202
|
+
#lockMs;
|
|
203
|
+
#codes;
|
|
204
|
+
#now;
|
|
205
|
+
#keys;
|
|
206
|
+
constructor(o) {
|
|
207
|
+
const raw = isSecret(o.key) ? o.key.reveal() : o.key;
|
|
208
|
+
if (typeof raw !== "string" || raw.length < MIN_SECRET_LENGTH) {
|
|
209
|
+
throw new Error(`defineTwoFactor: \`key\` must be at least ${MIN_SECRET_LENGTH} characters`);
|
|
210
|
+
}
|
|
211
|
+
if (typeof o.issuer !== "string" || o.issuer.trim() === "" || o.issuer.length > 64 || o.issuer.includes(":")) {
|
|
212
|
+
throw new Error("defineTwoFactor: `issuer` is the app's name, 1-64 characters without ':'");
|
|
213
|
+
}
|
|
214
|
+
if (typeof o.page !== "string" || !o.page.startsWith("/") || o.page.startsWith("//") || o.page.includes("\\")) {
|
|
215
|
+
throw new Error("defineTwoFactor: `page` is a same-origin path such as /two-factor");
|
|
216
|
+
}
|
|
217
|
+
if (o.require !== undefined && typeof o.require !== "function")
|
|
218
|
+
throw new Error("defineTwoFactor: `require` is a function");
|
|
219
|
+
const digits = o.digits ?? 6;
|
|
220
|
+
if (digits !== 6 && digits !== 8)
|
|
221
|
+
throw new Error("defineTwoFactor: digits is 6 or 8");
|
|
222
|
+
const range = (name, v, lo, hi) => {
|
|
223
|
+
if (!Number.isInteger(v) || v < lo || v > hi)
|
|
224
|
+
throw new Error(`defineTwoFactor: ${name} is ${lo} to ${hi}`);
|
|
225
|
+
return v;
|
|
226
|
+
};
|
|
227
|
+
this.page = o.page;
|
|
228
|
+
this.#issuer = o.issuer;
|
|
229
|
+
this.#store = o.store ?? new MemoryTwoFactorStore();
|
|
230
|
+
this.#require = o.require;
|
|
231
|
+
this.#digits = digits;
|
|
232
|
+
this.#window = range("window", o.window ?? 1, 0, 2);
|
|
233
|
+
this.#max = range("maxAttempts", o.maxAttempts ?? 5, 3, 20);
|
|
234
|
+
this.#lockMs = range("lockMs", o.lockMs ?? 15 * 60_000, 60_000, 24 * 3600_000);
|
|
235
|
+
this.#codes = range("recoveryCodes", o.recoveryCodes ?? 10, 4, 20);
|
|
236
|
+
this.#now = o.now ?? Date.now;
|
|
237
|
+
this.#keys = (async () => {
|
|
238
|
+
const base = await crypto.subtle.importKey("raw", enc.encode(raw), "HKDF", false, ["deriveKey"]);
|
|
239
|
+
const derive = (info, alg, use) => crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: enc.encode("weft two-factor"), info: enc.encode(info) }, base, alg, false, use);
|
|
240
|
+
return {
|
|
241
|
+
aes: await derive("secret", { name: "AES-GCM", length: 256 }, ["encrypt", "decrypt"]),
|
|
242
|
+
mac: await derive("recovery", { name: "HMAC", hash: "SHA-256", length: 256 }, ["sign"]),
|
|
243
|
+
};
|
|
244
|
+
})();
|
|
245
|
+
}
|
|
246
|
+
async needed(user, tenant) {
|
|
247
|
+
if (await this.#store.get(user))
|
|
248
|
+
return true;
|
|
249
|
+
return this.#require ? (await this.#require(user, tenant)) === true : false;
|
|
250
|
+
}
|
|
251
|
+
async enabled(user) {
|
|
252
|
+
return Boolean(await this.#store.get(user));
|
|
253
|
+
}
|
|
254
|
+
async status(ctx) {
|
|
255
|
+
const s = await authState(ctx);
|
|
256
|
+
if (!s)
|
|
257
|
+
return null;
|
|
258
|
+
const enabled = await this.enabled(s.user);
|
|
259
|
+
return {
|
|
260
|
+
user: s.user,
|
|
261
|
+
pending: s.pending,
|
|
262
|
+
enabled,
|
|
263
|
+
required: enabled || (this.#require ? (await this.#require(s.user, s.tenant)) === true : false),
|
|
264
|
+
mfa: s.mfa,
|
|
265
|
+
recoveryLeft: enabled ? await this.#store.countRecovery(s.user) : 0,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
async setup(ctx, o = {}) {
|
|
269
|
+
const s = await this.#who(ctx);
|
|
270
|
+
if (await this.#store.get(s.user))
|
|
271
|
+
throw new TwoFactorError("conflict", "Two-factor sign-in is already on");
|
|
272
|
+
const account = o.account ?? s.user;
|
|
273
|
+
if (typeof account !== "string" || account === "" || account.length > 128) {
|
|
274
|
+
throw new TypeError("twoFactor.setup: `account` is 1-128 characters");
|
|
275
|
+
}
|
|
276
|
+
const secret = base32(crypto.getRandomValues(new Uint8Array(SECRET_BYTES)));
|
|
277
|
+
const label = `${encodeURIComponent(this.#issuer)}:${encodeURIComponent(account)}`;
|
|
278
|
+
const q = new URLSearchParams({ secret, issuer: this.#issuer, algorithm: "SHA1", digits: String(this.#digits), period: "30" });
|
|
279
|
+
const state = await seal(ctx, { u: s.user, s: secret }, { purpose: "two-factor-setup", ttlMs: SETUP_TTL_MS, session: true });
|
|
280
|
+
return { secret, uri: `otpauth://totp/${label}?${q.toString().replace(/\+/g, "%20")}`, state };
|
|
281
|
+
}
|
|
282
|
+
async enable(ctx, state, code) {
|
|
283
|
+
const s = await this.#who(ctx);
|
|
284
|
+
const v = (await unseal(ctx, typeof state === "string" ? state : null, { purpose: "two-factor-setup", session: true }));
|
|
285
|
+
if (!v || v.u !== s.user || typeof v.s !== "string")
|
|
286
|
+
throw new TwoFactorError("expired", "Start setting it up again");
|
|
287
|
+
const secret = fromBase32(v.s);
|
|
288
|
+
if (!secret || secret.length !== SECRET_BYTES)
|
|
289
|
+
throw new TwoFactorError("invalid", "Not a two-factor secret");
|
|
290
|
+
const step = await this.#match(secret, code, -1);
|
|
291
|
+
if (step === null)
|
|
292
|
+
return null;
|
|
293
|
+
const added = await this.#store.add({
|
|
294
|
+
user: s.user,
|
|
295
|
+
secret: await this.#encrypt(s.user, secret),
|
|
296
|
+
lastStep: step,
|
|
297
|
+
failures: 0,
|
|
298
|
+
lockedUntil: 0,
|
|
299
|
+
created: this.#now(),
|
|
300
|
+
});
|
|
301
|
+
if (!added)
|
|
302
|
+
throw new TwoFactorError("conflict", "Two-factor sign-in is already on");
|
|
303
|
+
const codes = await this.#newRecovery(s.user);
|
|
304
|
+
await completeTwoFactor(ctx);
|
|
305
|
+
return codes;
|
|
306
|
+
}
|
|
307
|
+
async verify(ctx, code) {
|
|
308
|
+
const s = await authState(ctx);
|
|
309
|
+
if (!s || !s.pending)
|
|
310
|
+
throw new TwoFactorError("signed-out", "No sign-in is waiting for a code");
|
|
311
|
+
if (!(await this.#check(s.user, code, true)))
|
|
312
|
+
return false;
|
|
313
|
+
await completeTwoFactor(ctx);
|
|
314
|
+
return true;
|
|
315
|
+
}
|
|
316
|
+
async confirm(ctx, code) {
|
|
317
|
+
const s = await this.#signedIn(ctx);
|
|
318
|
+
if (!(await this.#check(s.user, code, false)))
|
|
319
|
+
return false;
|
|
320
|
+
await completeTwoFactor(ctx);
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
async regenerateRecoveryCodes(ctx, code) {
|
|
324
|
+
const s = await this.#signedIn(ctx);
|
|
325
|
+
if (!(await this.#check(s.user, code, false)))
|
|
326
|
+
return null;
|
|
327
|
+
return this.#newRecovery(s.user);
|
|
328
|
+
}
|
|
329
|
+
async disable(ctx, code) {
|
|
330
|
+
const s = await this.#signedIn(ctx);
|
|
331
|
+
if (this.#require && (await this.#require(s.user, s.tenant)) === true) {
|
|
332
|
+
throw new TwoFactorError("required", "Two-factor sign-in is required for this account");
|
|
333
|
+
}
|
|
334
|
+
if (!(await this.#check(s.user, code, false)))
|
|
335
|
+
return false;
|
|
336
|
+
return this.#store.remove(s.user);
|
|
337
|
+
}
|
|
338
|
+
async reset(user) {
|
|
339
|
+
return this.#store.remove(user);
|
|
340
|
+
}
|
|
341
|
+
async #who(ctx) {
|
|
342
|
+
const s = await authState(ctx);
|
|
343
|
+
if (!s)
|
|
344
|
+
throw new TwoFactorError("signed-out", "Sign in first");
|
|
345
|
+
return s;
|
|
346
|
+
}
|
|
347
|
+
async #signedIn(ctx) {
|
|
348
|
+
const s = await authState(ctx);
|
|
349
|
+
if (!s || s.pending)
|
|
350
|
+
throw new TwoFactorError("signed-out", "Sign in first");
|
|
351
|
+
if (!(await this.#store.get(s.user)))
|
|
352
|
+
throw new TwoFactorError("not-enrolled", "Two-factor sign-in is not on");
|
|
353
|
+
return s;
|
|
354
|
+
}
|
|
355
|
+
async #check(user, input, recovery) {
|
|
356
|
+
const rec = await this.#store.get(user);
|
|
357
|
+
if (!rec)
|
|
358
|
+
throw new TwoFactorError("not-enrolled", "Set up two-factor sign-in first");
|
|
359
|
+
const now = this.#now();
|
|
360
|
+
if (rec.lockedUntil > now) {
|
|
361
|
+
throw new TwoFactorError("locked", "Too many wrong codes; try again later", rec.lockedUntil);
|
|
362
|
+
}
|
|
363
|
+
const code = typeof input === "string" ? input.replace(/[\s-]/g, "").toLowerCase() : "";
|
|
364
|
+
let ok = false;
|
|
365
|
+
if (/^\d+$/.test(code) && code.length === this.#digits) {
|
|
366
|
+
const secret = await this.#decrypt(user, rec.secret);
|
|
367
|
+
const step = await this.#match(secret, code, rec.lastStep);
|
|
368
|
+
ok = step !== null && (await this.#store.advance(user, step));
|
|
369
|
+
}
|
|
370
|
+
else if (recovery && code.length === 10) {
|
|
371
|
+
const typed = code.replace(/o/g, "0").replace(/[il]/g, "1");
|
|
372
|
+
ok = [...typed].every((c) => RECOVERY.includes(c)) && (await this.#store.useRecovery(user, await this.#hash(user, typed)));
|
|
373
|
+
if (ok)
|
|
374
|
+
await this.#store.succeed(user);
|
|
375
|
+
}
|
|
376
|
+
if (!ok) {
|
|
377
|
+
if (await this.#store.fail(user, this.#max, now + this.#lockMs)) {
|
|
378
|
+
throw new TwoFactorError("locked", "Too many wrong codes; try again later", now + this.#lockMs);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
return ok;
|
|
382
|
+
}
|
|
383
|
+
async #match(secret, input, after) {
|
|
384
|
+
const code = typeof input === "string" ? input.replace(/[\s-]/g, "") : "";
|
|
385
|
+
if (!/^\d+$/.test(code) || code.length !== this.#digits)
|
|
386
|
+
return null;
|
|
387
|
+
const now = Math.floor(this.#now() / STEP_MS);
|
|
388
|
+
let found = null;
|
|
389
|
+
for (let w = -this.#window; w <= this.#window; w++) {
|
|
390
|
+
const step = now + w;
|
|
391
|
+
if (sameString(await totp(secret, step, this.#digits), code) && step > after && found === null)
|
|
392
|
+
found = step;
|
|
393
|
+
}
|
|
394
|
+
return found;
|
|
395
|
+
}
|
|
396
|
+
async #newRecovery(user) {
|
|
397
|
+
const codes = [];
|
|
398
|
+
const hashes = [];
|
|
399
|
+
for (let i = 0; i < this.#codes; i++) {
|
|
400
|
+
const raw = [...crypto.getRandomValues(new Uint8Array(10))].map((b) => RECOVERY[b & 31]).join("");
|
|
401
|
+
codes.push(`${raw.slice(0, 5)}-${raw.slice(5)}`);
|
|
402
|
+
hashes.push(await this.#hash(user, raw));
|
|
403
|
+
}
|
|
404
|
+
await this.#store.setRecovery(user, hashes);
|
|
405
|
+
return codes;
|
|
406
|
+
}
|
|
407
|
+
async #hash(user, code) {
|
|
408
|
+
const { mac } = await this.#keys;
|
|
409
|
+
return base64url(new Uint8Array(await crypto.subtle.sign("HMAC", mac, enc.encode(`${user}\n${code}`))));
|
|
410
|
+
}
|
|
411
|
+
async #encrypt(user, secret) {
|
|
412
|
+
const { aes } = await this.#keys;
|
|
413
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
414
|
+
const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(user) }, aes, new Uint8Array(secret));
|
|
415
|
+
return `v1.${base64url(iv)}.${base64url(new Uint8Array(ct))}`;
|
|
416
|
+
}
|
|
417
|
+
async #decrypt(user, stored) {
|
|
418
|
+
const [v, iv, ct] = stored.split(".");
|
|
419
|
+
const ivb = fromBase64url(iv ?? "");
|
|
420
|
+
const ctb = fromBase64url(ct ?? "");
|
|
421
|
+
if (v !== "v1" || !ivb || !ctb)
|
|
422
|
+
throw new Error("@weft-framework/server: a stored two-factor secret is malformed");
|
|
423
|
+
const { aes } = await this.#keys;
|
|
424
|
+
try {
|
|
425
|
+
const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: new Uint8Array(ivb), additionalData: enc.encode(user) }, aes, new Uint8Array(ctb));
|
|
426
|
+
return new Uint8Array(pt);
|
|
427
|
+
}
|
|
428
|
+
catch (err) {
|
|
429
|
+
throw new Error("@weft-framework/server: a stored two-factor secret does not open with this key (or belongs to another user)", { cause: err });
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
export function defineTwoFactor(o) {
|
|
434
|
+
return new TwoFactor(o);
|
|
435
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { type FileRef, type SqlDatabase } from "@weft-framework/data";
|
|
2
|
+
import { ActionError } from "./action.js";
|
|
3
|
+
import type { PageContext } from "./context.js";
|
|
4
|
+
import { type Secret } from "./secret.js";
|
|
5
|
+
export declare const MB: number;
|
|
6
|
+
export declare const GB: number;
|
|
7
|
+
export type FileStatus = "uploading" | "ready";
|
|
8
|
+
export interface FileRecord {
|
|
9
|
+
id: string;
|
|
10
|
+
kind: string;
|
|
11
|
+
owner: string;
|
|
12
|
+
name: string;
|
|
13
|
+
type: string;
|
|
14
|
+
size: number;
|
|
15
|
+
partBytes: number;
|
|
16
|
+
status: FileStatus;
|
|
17
|
+
upload: string;
|
|
18
|
+
claimed: boolean;
|
|
19
|
+
created: number;
|
|
20
|
+
}
|
|
21
|
+
export interface FileInfo {
|
|
22
|
+
id: string;
|
|
23
|
+
kind: string;
|
|
24
|
+
name: string;
|
|
25
|
+
type: string;
|
|
26
|
+
size: number;
|
|
27
|
+
}
|
|
28
|
+
export interface FileStore {
|
|
29
|
+
put(r: FileRecord): void | Promise<void>;
|
|
30
|
+
get(id: string): FileRecord | null | Promise<FileRecord | null>;
|
|
31
|
+
remove(id: string): void | Promise<void>;
|
|
32
|
+
pending(owner: string): number | Promise<number>;
|
|
33
|
+
stale(uploadingBefore: number, unclaimedBefore: number, limit: number): FileRecord[] | Promise<FileRecord[]>;
|
|
34
|
+
}
|
|
35
|
+
export declare class MemoryFileStore implements FileStore {
|
|
36
|
+
#private;
|
|
37
|
+
put(r: FileRecord): void;
|
|
38
|
+
get(id: string): FileRecord | null;
|
|
39
|
+
remove(id: string): void;
|
|
40
|
+
pending(owner: string): number;
|
|
41
|
+
stale(uploadingBefore: number, unclaimedBefore: number, limit: number): FileRecord[];
|
|
42
|
+
}
|
|
43
|
+
export declare class SqlFileStore implements FileStore {
|
|
44
|
+
#private;
|
|
45
|
+
constructor(db: SqlDatabase, table?: string);
|
|
46
|
+
put(r: FileRecord): void;
|
|
47
|
+
get(id: string): FileRecord | null;
|
|
48
|
+
remove(id: string): void;
|
|
49
|
+
pending(owner: string): number;
|
|
50
|
+
stale(uploadingBefore: number, unclaimedBefore: number, limit: number): FileRecord[];
|
|
51
|
+
}
|
|
52
|
+
export interface PartTarget {
|
|
53
|
+
url: string;
|
|
54
|
+
headers: Record<string, string>;
|
|
55
|
+
}
|
|
56
|
+
export interface UploadStorage {
|
|
57
|
+
begin(key: string, type: string): Promise<string>;
|
|
58
|
+
partTarget(key: string, upload: string, index: number, size: number, expiresSeconds: number): Promise<PartTarget | null>;
|
|
59
|
+
putPart?(key: string, upload: string, index: number, body: ReadableStream<Uint8Array>, size: number): Promise<void>;
|
|
60
|
+
parts(key: string, upload: string): Promise<{
|
|
61
|
+
index: number;
|
|
62
|
+
etag: string;
|
|
63
|
+
size: number;
|
|
64
|
+
}[]>;
|
|
65
|
+
complete(key: string, upload: string, parts: {
|
|
66
|
+
index: number;
|
|
67
|
+
etag: string;
|
|
68
|
+
}[]): Promise<number>;
|
|
69
|
+
abort(key: string, upload: string): Promise<void>;
|
|
70
|
+
read(key: string, range?: {
|
|
71
|
+
start: number;
|
|
72
|
+
end: number;
|
|
73
|
+
}): Promise<ReadableStream<Uint8Array> | null>;
|
|
74
|
+
size(key: string): Promise<number | null>;
|
|
75
|
+
remove(key: string): Promise<void>;
|
|
76
|
+
downloadUrl?(key: string, o: {
|
|
77
|
+
expiresSeconds: number;
|
|
78
|
+
type: string;
|
|
79
|
+
disposition: string;
|
|
80
|
+
}): Promise<string>;
|
|
81
|
+
}
|
|
82
|
+
export declare function diskStorage(o: {
|
|
83
|
+
dir: string;
|
|
84
|
+
}): UploadStorage;
|
|
85
|
+
export interface S3Options {
|
|
86
|
+
endpoint: string;
|
|
87
|
+
region: string;
|
|
88
|
+
bucket: string;
|
|
89
|
+
accessKeyId: string;
|
|
90
|
+
secretAccessKey: string | Secret;
|
|
91
|
+
sessionToken?: string | Secret;
|
|
92
|
+
pathStyle?: boolean;
|
|
93
|
+
prefix?: string;
|
|
94
|
+
fetch?: (url: string, init: RequestInit) => Promise<Response>;
|
|
95
|
+
now?: () => Date;
|
|
96
|
+
}
|
|
97
|
+
export declare function presignS3(r: {
|
|
98
|
+
method: string;
|
|
99
|
+
url: string;
|
|
100
|
+
region: string;
|
|
101
|
+
accessKeyId: string;
|
|
102
|
+
secretAccessKey: string;
|
|
103
|
+
sessionToken?: string;
|
|
104
|
+
expiresSeconds: number;
|
|
105
|
+
headers?: Record<string, string>;
|
|
106
|
+
now?: Date;
|
|
107
|
+
}): Promise<string>;
|
|
108
|
+
export declare function s3Storage(o: S3Options): UploadStorage;
|
|
109
|
+
export declare function sniffType(head: Uint8Array): string | null;
|
|
110
|
+
export declare function contentMatches(type: string, head: Uint8Array): boolean;
|
|
111
|
+
export interface UploadKind {
|
|
112
|
+
maxBytes: number;
|
|
113
|
+
types: readonly string[];
|
|
114
|
+
anonymous?: boolean;
|
|
115
|
+
}
|
|
116
|
+
export interface ScanInput {
|
|
117
|
+
id: string;
|
|
118
|
+
kind: string;
|
|
119
|
+
name: string;
|
|
120
|
+
type: string;
|
|
121
|
+
size: number;
|
|
122
|
+
read(): Promise<ReadableStream<Uint8Array>>;
|
|
123
|
+
}
|
|
124
|
+
export interface UploadsOptions<K extends string> {
|
|
125
|
+
key: string | Secret;
|
|
126
|
+
storage: UploadStorage;
|
|
127
|
+
kinds: Record<K, UploadKind>;
|
|
128
|
+
store?: FileStore;
|
|
129
|
+
partBytes?: number;
|
|
130
|
+
maxPending?: number;
|
|
131
|
+
pendingTtlMs?: number;
|
|
132
|
+
unclaimedTtlMs?: number;
|
|
133
|
+
scan?(file: ScanInput): boolean | string | Promise<boolean | string>;
|
|
134
|
+
now?(): number;
|
|
135
|
+
}
|
|
136
|
+
export declare class UploadError extends ActionError {
|
|
137
|
+
readonly code: "invalid" | "forbidden" | "not-found" | "too-large" | "type" | "limit" | "rejected";
|
|
138
|
+
constructor(code: UploadError["code"], message: string);
|
|
139
|
+
}
|
|
140
|
+
declare const UPLOADS = "/_weft/uploads/";
|
|
141
|
+
declare const FILES = "/_weft/files/";
|
|
142
|
+
export declare class Uploads<K extends string = string> {
|
|
143
|
+
#private;
|
|
144
|
+
readonly kinds: Readonly<Record<K, Readonly<UploadKind>>>;
|
|
145
|
+
constructor(o: UploadsOptions<K>);
|
|
146
|
+
start(ctx: PageContext, kindName: K, file: {
|
|
147
|
+
name: string;
|
|
148
|
+
size: number;
|
|
149
|
+
type: string;
|
|
150
|
+
}): Promise<{
|
|
151
|
+
id: string;
|
|
152
|
+
partBytes: number;
|
|
153
|
+
parts: number;
|
|
154
|
+
}>;
|
|
155
|
+
part(ctx: PageContext, id: string, index: number): Promise<PartTarget>;
|
|
156
|
+
status(ctx: PageContext, id: string): Promise<FileInfo & {
|
|
157
|
+
parts: number;
|
|
158
|
+
partBytes: number;
|
|
159
|
+
received: number[];
|
|
160
|
+
ready: boolean;
|
|
161
|
+
}>;
|
|
162
|
+
complete(ctx: PageContext, id: string): Promise<FileInfo>;
|
|
163
|
+
abort(ctx: PageContext, id: string): Promise<boolean>;
|
|
164
|
+
claim(ctx: PageContext, id: string, kind?: K): Promise<FileInfo & {
|
|
165
|
+
id: FileRef;
|
|
166
|
+
}>;
|
|
167
|
+
track(onError?: (err: unknown) => void): () => void;
|
|
168
|
+
link(id: string | null | undefined, o?: {
|
|
169
|
+
ttlSeconds?: number;
|
|
170
|
+
download?: boolean;
|
|
171
|
+
}): Promise<(FileInfo & {
|
|
172
|
+
url: string;
|
|
173
|
+
}) | null>;
|
|
174
|
+
info(id: string): Promise<FileInfo | null>;
|
|
175
|
+
remove(id: string): Promise<boolean>;
|
|
176
|
+
url(id: string | null | undefined, o?: {
|
|
177
|
+
ttlSeconds?: number;
|
|
178
|
+
download?: boolean;
|
|
179
|
+
}): Promise<string | null>;
|
|
180
|
+
sweep(limit?: number): Promise<number>;
|
|
181
|
+
handle(ctx: PageContext, req: Request, path: string): Promise<Response>;
|
|
182
|
+
serve(req: Request, path: string): Promise<Response>;
|
|
183
|
+
}
|
|
184
|
+
export declare function defineUploads<const K extends string>(o: UploadsOptions<K>): Uploads<K>;
|
|
185
|
+
export { UPLOADS as UPLOADS_PATH, FILES as FILES_PATH };
|