@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,572 @@
1
+ import { login } from "./auth.js";
2
+ import { seal, unseal } from "./seal.js";
3
+ import { base64url, fromBase64url } from "./security.js";
4
+ export class MemoryPasskeyStore {
5
+ #creds = new Map();
6
+ add(c) {
7
+ this.#creds.set(c.id, structuredClone(c));
8
+ }
9
+ get(id) {
10
+ const c = this.#creds.get(id);
11
+ return c ? structuredClone(c) : null;
12
+ }
13
+ list(user) {
14
+ return [...this.#creds.values()].filter((c) => c.user === user).map((c) => structuredClone(c));
15
+ }
16
+ update(id, patch) {
17
+ const c = this.#creds.get(id);
18
+ if (c)
19
+ Object.assign(c, patch);
20
+ }
21
+ remove(id) {
22
+ return this.#creds.delete(id);
23
+ }
24
+ }
25
+ export class SqlPasskeyStore {
26
+ db;
27
+ table;
28
+ constructor(db, table = "weft_passkeys") {
29
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {
30
+ throw new Error(`SqlPasskeyStore: bad table name ${table}`);
31
+ }
32
+ this.db = db;
33
+ this.table = table;
34
+ db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, handle TEXT NOT NULL, ` +
35
+ `public_key TEXT NOT NULL, alg INTEGER NOT NULL, sign_count INTEGER NOT NULL, transports TEXT NOT NULL, ` +
36
+ `backed_up INTEGER NOT NULL, name TEXT NOT NULL, created INTEGER NOT NULL, last_used INTEGER)`);
37
+ db.exec(`CREATE INDEX IF NOT EXISTS ${table}_user ON ${table} (user_id)`);
38
+ }
39
+ row(r) {
40
+ if (!r || typeof r !== "object")
41
+ return null;
42
+ const o = r;
43
+ return {
44
+ id: String(o.id),
45
+ user: String(o.user_id),
46
+ handle: String(o.handle),
47
+ publicKey: JSON.parse(String(o.public_key)),
48
+ alg: Number(o.alg),
49
+ signCount: Number(o.sign_count),
50
+ transports: JSON.parse(String(o.transports)),
51
+ backedUp: Number(o.backed_up) === 1,
52
+ name: String(o.name),
53
+ created: Number(o.created),
54
+ lastUsed: o.last_used === null || o.last_used === undefined ? null : Number(o.last_used),
55
+ };
56
+ }
57
+ add(c) {
58
+ this.db
59
+ .prepare(`INSERT INTO ${this.table} (id, user_id, handle, public_key, alg, sign_count, transports, backed_up, name, created, last_used) ` +
60
+ `VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
61
+ .run(c.id, c.user, c.handle, JSON.stringify(c.publicKey), c.alg, c.signCount, JSON.stringify(c.transports), c.backedUp ? 1 : 0, c.name, c.created, c.lastUsed);
62
+ }
63
+ get(id) {
64
+ return this.row(this.db.prepare(`SELECT * FROM ${this.table} WHERE id = ?`).all(id)[0]);
65
+ }
66
+ list(user) {
67
+ return this.db
68
+ .prepare(`SELECT * FROM ${this.table} WHERE user_id = ? ORDER BY created`)
69
+ .all(user)
70
+ .map((r) => this.row(r));
71
+ }
72
+ update(id, patch) {
73
+ const cols = { signCount: "sign_count", lastUsed: "last_used", backedUp: "backed_up", name: "name" };
74
+ for (const [k, v] of Object.entries(patch)) {
75
+ const col = cols[k];
76
+ if (!col)
77
+ continue;
78
+ const value = typeof v === "boolean" ? (v ? 1 : 0) : v;
79
+ this.db.prepare(`UPDATE ${this.table} SET ${col} = ? WHERE id = ?`).run(value, id);
80
+ }
81
+ }
82
+ remove(id) {
83
+ return this.db.prepare(`DELETE FROM ${this.table} WHERE id = ? RETURNING id`).all(id).length > 0;
84
+ }
85
+ }
86
+ export class PasskeyError extends Error {
87
+ code;
88
+ constructor(code, message, opts) {
89
+ super(message, opts);
90
+ this.name = "PasskeyError";
91
+ this.code = code;
92
+ }
93
+ }
94
+ export function decodeCbor(buf, pos = 0, depth = 0) {
95
+ if (depth > 16)
96
+ throw new Error("CBOR nested too deeply");
97
+ const need = (n) => {
98
+ if (pos + n > buf.length)
99
+ throw new Error("CBOR truncated");
100
+ };
101
+ need(1);
102
+ const head = buf[pos++];
103
+ const major = head >> 5;
104
+ const info = head & 31;
105
+ let arg;
106
+ if (info < 24)
107
+ arg = info;
108
+ else if (info === 24) {
109
+ need(1);
110
+ arg = buf[pos++];
111
+ }
112
+ else if (info === 25) {
113
+ need(2);
114
+ arg = (buf[pos] << 8) | buf[pos + 1];
115
+ pos += 2;
116
+ }
117
+ else if (info === 26) {
118
+ need(4);
119
+ arg = ((buf[pos] << 24) >>> 0) + (buf[pos + 1] << 16) + (buf[pos + 2] << 8) + buf[pos + 3];
120
+ pos += 4;
121
+ }
122
+ else if (info === 27) {
123
+ need(8);
124
+ let v = 0n;
125
+ for (let i = 0; i < 8; i++)
126
+ v = (v << 8n) | BigInt(buf[pos + i]);
127
+ pos += 8;
128
+ arg = v <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : v;
129
+ }
130
+ else
131
+ throw new Error("CBOR indefinite lengths are not supported");
132
+ const len = () => {
133
+ if (typeof arg !== "number" || arg > buf.length)
134
+ throw new Error("CBOR length too large");
135
+ return arg;
136
+ };
137
+ switch (major) {
138
+ case 0:
139
+ return { value: arg, end: pos };
140
+ case 1:
141
+ return { value: typeof arg === "number" ? -1 - arg : -1n - arg, end: pos };
142
+ case 2: {
143
+ const n = len();
144
+ need(n);
145
+ return { value: buf.slice(pos, pos + n), end: pos + n };
146
+ }
147
+ case 3: {
148
+ const n = len();
149
+ need(n);
150
+ return { value: new TextDecoder("utf-8", { fatal: true }).decode(buf.subarray(pos, pos + n)), end: pos + n };
151
+ }
152
+ case 4: {
153
+ const n = len();
154
+ const out = [];
155
+ for (let i = 0; i < n; i++) {
156
+ const r = decodeCbor(buf, pos, depth + 1);
157
+ out.push(r.value);
158
+ pos = r.end;
159
+ }
160
+ return { value: out, end: pos };
161
+ }
162
+ case 5: {
163
+ const n = len();
164
+ const out = new Map();
165
+ for (let i = 0; i < n; i++) {
166
+ const k = decodeCbor(buf, pos, depth + 1);
167
+ const v = decodeCbor(buf, k.end, depth + 1);
168
+ if (out.has(k.value))
169
+ throw new Error("CBOR duplicate map key");
170
+ out.set(k.value, v.value);
171
+ pos = v.end;
172
+ }
173
+ return { value: out, end: pos };
174
+ }
175
+ case 6:
176
+ return decodeCbor(buf, pos, depth + 1);
177
+ default:
178
+ if (info === 20)
179
+ return { value: false, end: pos };
180
+ if (info === 21)
181
+ return { value: true, end: pos };
182
+ if (info === 22)
183
+ return { value: null, end: pos };
184
+ if (info === 23)
185
+ return { value: undefined, end: pos };
186
+ throw new Error("CBOR floats and simple values are not supported");
187
+ }
188
+ }
189
+ const FLAG_UP = 0x01;
190
+ const FLAG_UV = 0x04;
191
+ const FLAG_BS = 0x10;
192
+ const FLAG_AT = 0x40;
193
+ export function coseToJwk(key) {
194
+ if (!(key instanceof Map))
195
+ throw new Error("credential key is not a COSE key");
196
+ const kty = key.get(1);
197
+ const alg = key.get(3);
198
+ const bytes = (label, size) => {
199
+ const v = key.get(label);
200
+ if (!(v instanceof Uint8Array) || (size !== undefined && v.length !== size))
201
+ throw new Error("credential key is malformed");
202
+ return base64url(v);
203
+ };
204
+ if (kty === 2 && alg === -7 && key.get(-1) === 1) {
205
+ return { jwk: { kty: "EC", crv: "P-256", x: bytes(-2, 32), y: bytes(-3, 32) }, alg };
206
+ }
207
+ if (kty === 1 && alg === -8 && key.get(-1) === 6) {
208
+ return { jwk: { kty: "OKP", crv: "Ed25519", x: bytes(-2, 32) }, alg };
209
+ }
210
+ if (kty === 3 && alg === -257) {
211
+ const n = key.get(-1);
212
+ if (!(n instanceof Uint8Array) || (n[0] === 0 ? n.length - 1 : n.length) < 256)
213
+ throw new Error("RSA credential keys must be 2048 bits or more");
214
+ return { jwk: { kty: "RSA", n: bytes(-1), e: bytes(-2) }, alg };
215
+ }
216
+ throw new Error("credential key algorithm is not supported");
217
+ }
218
+ export function parseAuthData(buf) {
219
+ if (buf.length < 37)
220
+ throw new Error("authenticator data is too short");
221
+ const flags = buf[32];
222
+ const signCount = ((buf[33] << 24) >>> 0) + (buf[34] << 16) + (buf[35] << 8) + buf[36];
223
+ const out = { rpIdHash: buf.slice(0, 32), flags, signCount };
224
+ if (flags & FLAG_AT) {
225
+ if (buf.length < 55)
226
+ throw new Error("attested credential data is too short");
227
+ const idLen = (buf[53] << 8) | buf[54];
228
+ if (idLen < 16 || idLen > 1023 || 55 + idLen > buf.length)
229
+ throw new Error("credential id has a bad length");
230
+ const id = buf.slice(55, 55 + idLen);
231
+ const { value } = decodeCbor(buf, 55 + idLen);
232
+ out.credential = { id, ...(({ jwk, alg }) => ({ publicKey: jwk, alg }))(coseToJwk(value)) };
233
+ }
234
+ return out;
235
+ }
236
+ export function derToRaw(der, size) {
237
+ let p = 0;
238
+ const fail = () => {
239
+ throw new Error("signature is not DER");
240
+ };
241
+ if (der[p++] !== 0x30)
242
+ fail();
243
+ let total = der[p++];
244
+ if (total & 0x80) {
245
+ if (total !== 0x81)
246
+ fail();
247
+ total = der[p++];
248
+ }
249
+ if (p + total !== der.length)
250
+ fail();
251
+ const int = () => {
252
+ if (der[p++] !== 0x02)
253
+ fail();
254
+ const n = der[p++];
255
+ if (n === 0 || n > size + 1 || p + n > der.length)
256
+ fail();
257
+ let v = der.subarray(p, p + n);
258
+ p += n;
259
+ while (v.length > size && v[0] === 0)
260
+ v = v.subarray(1);
261
+ if (v.length > size)
262
+ fail();
263
+ const out = new Uint8Array(size);
264
+ out.set(v, size - v.length);
265
+ return out;
266
+ };
267
+ const r = int();
268
+ const s = int();
269
+ if (p !== der.length)
270
+ fail();
271
+ const raw = new Uint8Array(size * 2);
272
+ raw.set(r, 0);
273
+ raw.set(s, size);
274
+ return raw;
275
+ }
276
+ async function verifySignature(alg, jwk, sig, signed) {
277
+ const data = new Uint8Array(signed);
278
+ try {
279
+ if (alg === -7) {
280
+ const key = await crypto.subtle.importKey("jwk", jwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
281
+ return await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, new Uint8Array(derToRaw(sig, 32)), data);
282
+ }
283
+ if (alg === -8) {
284
+ const key = await crypto.subtle.importKey("jwk", jwk, { name: "Ed25519" }, false, ["verify"]);
285
+ return await crypto.subtle.verify({ name: "Ed25519" }, key, new Uint8Array(sig), data);
286
+ }
287
+ if (alg === -257) {
288
+ const key = await crypto.subtle.importKey("jwk", jwk, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
289
+ return await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, new Uint8Array(sig), data);
290
+ }
291
+ }
292
+ catch {
293
+ return false;
294
+ }
295
+ return false;
296
+ }
297
+ const TTL_MS = 5 * 60_000;
298
+ const enc = new TextEncoder();
299
+ const dec = new TextDecoder("utf-8", { fatal: true });
300
+ const sha256 = async (data) => new Uint8Array(await crypto.subtle.digest("SHA-256", typeof data === "string" ? enc.encode(data) : new Uint8Array(data)));
301
+ function equalBytes(a, b) {
302
+ if (a.length !== b.length)
303
+ return false;
304
+ let d = 0;
305
+ for (let i = 0; i < a.length; i++)
306
+ d |= a[i] ^ b[i];
307
+ return d === 0;
308
+ }
309
+ function actorId(ctx) {
310
+ const id = ctx.user?.id;
311
+ return typeof id === "string" && id !== "" ? id : null;
312
+ }
313
+ function bytesField(o, key) {
314
+ const v = o[key];
315
+ const b = typeof v === "string" && v.length <= 65_536 ? fromBase64url(v) : null;
316
+ if (!b)
317
+ throw new Error(`credential ${key} is missing`);
318
+ return b;
319
+ }
320
+ function parseResponse(raw) {
321
+ if (typeof raw !== "string" || raw.length > 131_072)
322
+ throw new Error("credential is missing or too large");
323
+ let cred;
324
+ try {
325
+ cred = JSON.parse(raw);
326
+ }
327
+ catch {
328
+ throw new Error("credential is not JSON");
329
+ }
330
+ if (typeof cred !== "object" || cred === null)
331
+ throw new Error("credential is not an object");
332
+ const c = cred;
333
+ if (c.type !== "public-key" || typeof c.id !== "string")
334
+ throw new Error("credential is not a public key credential");
335
+ const rawId = bytesField(c, "rawId");
336
+ if (base64url(rawId) !== c.id)
337
+ throw new Error("credential id and rawId differ");
338
+ const fields = c.response;
339
+ if (typeof fields !== "object" || fields === null)
340
+ throw new Error("credential has no response");
341
+ const f = fields;
342
+ const clientDataBytes = bytesField(f, "clientDataJSON");
343
+ let clientData;
344
+ try {
345
+ clientData = JSON.parse(dec.decode(clientDataBytes));
346
+ }
347
+ catch {
348
+ throw new Error("client data is not JSON");
349
+ }
350
+ if (typeof clientData !== "object" || clientData === null)
351
+ throw new Error("client data is not an object");
352
+ return { id: c.id, rawId, clientData: clientData, clientDataBytes, fields: f };
353
+ }
354
+ export class Passkeys {
355
+ #origin;
356
+ #rpId;
357
+ #name;
358
+ #store;
359
+ #uv;
360
+ #max;
361
+ #now;
362
+ #used = new Map();
363
+ constructor(o) {
364
+ let u;
365
+ try {
366
+ u = new URL(o.url);
367
+ }
368
+ catch {
369
+ throw new Error("definePasskeys: `url` is the app's public origin, such as https://app.example");
370
+ }
371
+ const local = u.hostname === "localhost";
372
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && local)) {
373
+ throw new Error("definePasskeys: `url` must use https (http only for localhost, as browsers require)");
374
+ }
375
+ const rpId = o.rpId ?? u.hostname;
376
+ if (rpId !== u.hostname && !u.hostname.endsWith(`.${rpId}`)) {
377
+ throw new Error(`definePasskeys: rpId ${rpId} must be ${u.hostname} or a parent domain of it`);
378
+ }
379
+ if (typeof o.name !== "string" || o.name.trim() === "" || o.name.length > 64) {
380
+ throw new Error("definePasskeys: `name` is the app's name, 1-64 characters");
381
+ }
382
+ const max = o.maxPerUser ?? 20;
383
+ if (!Number.isInteger(max) || max < 1 || max > 100)
384
+ throw new Error("definePasskeys: maxPerUser is 1 to 100");
385
+ this.#origin = u.origin;
386
+ this.#rpId = rpId;
387
+ this.#name = o.name;
388
+ this.#store = o.store ?? new MemoryPasskeyStore();
389
+ this.#uv = o.userVerification ?? true;
390
+ this.#max = max;
391
+ this.#now = o.now ?? Date.now;
392
+ }
393
+ #fresh() {
394
+ const now = this.#now();
395
+ for (const [c, exp] of this.#used)
396
+ if (exp <= now)
397
+ this.#used.delete(c);
398
+ return base64url(crypto.getRandomValues(new Uint8Array(32)));
399
+ }
400
+ async #challenge(ctx, state, purpose) {
401
+ const v = (await unseal(ctx, typeof state === "string" ? state : null, { purpose, session: true }));
402
+ if (!v || typeof v.c !== "string")
403
+ return null;
404
+ if (this.#used.has(v.c))
405
+ return null;
406
+ this.#used.set(v.c, this.#now() + TTL_MS);
407
+ return { c: v.c, u: typeof v.u === "string" ? v.u : undefined, h: typeof v.h === "string" ? v.h : undefined };
408
+ }
409
+ #checkClient(p, type, challenge) {
410
+ const cd = p.clientData;
411
+ if (cd.type !== type)
412
+ throw new Error(`client data is not ${type}`);
413
+ if (typeof cd.challenge !== "string" || cd.challenge !== challenge)
414
+ throw new Error("challenge does not match");
415
+ if (cd.origin !== this.#origin)
416
+ throw new Error("origin does not match");
417
+ if (cd.crossOrigin === true)
418
+ throw new Error("cross-origin use is not allowed");
419
+ }
420
+ async #checkAuthData(ad) {
421
+ if (!equalBytes(ad.rpIdHash, await sha256(this.#rpId)))
422
+ throw new Error("relying party id does not match");
423
+ if (!(ad.flags & FLAG_UP))
424
+ throw new Error("user was not present");
425
+ if (this.#uv && !(ad.flags & FLAG_UV))
426
+ throw new Error("user was not verified");
427
+ }
428
+ async registrationOptions(ctx, opts = {}) {
429
+ const user = actorId(ctx);
430
+ if (!user)
431
+ throw new PasskeyError("signed-out", "Sign in to add a passkey");
432
+ const existing = await this.#store.list(user);
433
+ if (existing.length >= this.#max)
434
+ throw new PasskeyError("limit", "You have too many passkeys; remove one first");
435
+ const handle = existing[0]?.handle ?? base64url(crypto.getRandomValues(new Uint8Array(32)));
436
+ const challenge = this.#fresh();
437
+ const name = (opts.userName ?? user).slice(0, 64);
438
+ return {
439
+ state: await seal(ctx, { c: challenge, u: user, h: handle }, { purpose: "passkey-add", ttlMs: TTL_MS, session: true }),
440
+ publicKey: {
441
+ rp: { id: this.#rpId, name: this.#name },
442
+ user: { id: handle, name, displayName: (opts.displayName ?? name).slice(0, 64) },
443
+ challenge,
444
+ pubKeyCredParams: [-8, -7, -257].map((alg) => ({ type: "public-key", alg })),
445
+ timeout: TTL_MS,
446
+ attestation: "none",
447
+ authenticatorSelection: { residentKey: "required", requireResidentKey: true, userVerification: this.#uv ? "required" : "preferred" },
448
+ excludeCredentials: existing.map((c) => ({ type: "public-key", id: c.id, transports: c.transports })),
449
+ },
450
+ };
451
+ }
452
+ async register(ctx, state, credential, opts = {}) {
453
+ const user = actorId(ctx);
454
+ if (!user)
455
+ throw new PasskeyError("signed-out", "Sign in to add a passkey");
456
+ const ch = await this.#challenge(ctx, state, "passkey-add");
457
+ if (!ch || ch.u !== user || !ch.h)
458
+ throw new PasskeyError("expired", "That took too long; try again");
459
+ let cred;
460
+ try {
461
+ const p = parseResponse(credential);
462
+ this.#checkClient(p, "webauthn.create", ch.c);
463
+ const att = decodeCbor(bytesField(p.fields, "attestationObject"));
464
+ if (!(att.value instanceof Map))
465
+ throw new Error("attestation object is not a map");
466
+ const authData = att.value.get("authData");
467
+ if (!(authData instanceof Uint8Array))
468
+ throw new Error("attestation object has no authenticator data");
469
+ const ad = parseAuthData(authData);
470
+ await this.#checkAuthData(ad);
471
+ if (!ad.credential)
472
+ throw new Error("no credential was created");
473
+ if (!equalBytes(ad.credential.id, p.rawId))
474
+ throw new Error("credential id differs from the authenticator's");
475
+ const transports = Array.isArray(p.fields.transports)
476
+ ? p.fields.transports.filter((t) => typeof t === "string" && /^[a-z-]{1,16}$/.test(t)).slice(0, 8)
477
+ : [];
478
+ cred = {
479
+ id: p.id,
480
+ user,
481
+ handle: ch.h,
482
+ publicKey: ad.credential.publicKey,
483
+ alg: ad.credential.alg,
484
+ signCount: ad.signCount,
485
+ transports,
486
+ backedUp: (ad.flags & FLAG_BS) !== 0,
487
+ name: (opts.name ?? "Passkey").slice(0, 64),
488
+ created: this.#now(),
489
+ lastUsed: null,
490
+ };
491
+ }
492
+ catch (err) {
493
+ throw new PasskeyError("invalid", "That passkey could not be added", { cause: err });
494
+ }
495
+ if (await this.#store.get(cred.id))
496
+ throw new PasskeyError("conflict", "That passkey is already registered");
497
+ if ((await this.#store.list(user)).length >= this.#max)
498
+ throw new PasskeyError("limit", "You have too many passkeys; remove one first");
499
+ await this.#store.add(cred);
500
+ return cred;
501
+ }
502
+ async signInOptions(ctx) {
503
+ const challenge = this.#fresh();
504
+ return {
505
+ state: await seal(ctx, { c: challenge }, { purpose: "passkey-in", ttlMs: TTL_MS, session: true }),
506
+ publicKey: { challenge, rpId: this.#rpId, timeout: TTL_MS, userVerification: this.#uv ? "required" : "preferred", allowCredentials: [] },
507
+ };
508
+ }
509
+ async signIn(ctx, state, credential, onReject) {
510
+ const user = await this.verify(ctx, state, credential, onReject);
511
+ if (user === null)
512
+ return false;
513
+ await login(ctx, user, { multiFactor: this.#uv });
514
+ return true;
515
+ }
516
+ async verify(ctx, state, credential, onReject) {
517
+ const reject = (reason) => {
518
+ onReject?.(new Error(reason));
519
+ return null;
520
+ };
521
+ const ch = await this.#challenge(ctx, state, "passkey-in");
522
+ if (!ch)
523
+ return reject("the challenge expired or was used");
524
+ try {
525
+ const p = parseResponse(credential);
526
+ this.#checkClient(p, "webauthn.get", ch.c);
527
+ const stored = await this.#store.get(p.id);
528
+ if (!stored)
529
+ return reject("unknown credential");
530
+ const handle = p.fields.userHandle;
531
+ if (handle !== undefined && handle !== null && handle !== stored.handle)
532
+ return reject("user handle does not match");
533
+ const authData = bytesField(p.fields, "authenticatorData");
534
+ const ad = parseAuthData(authData);
535
+ await this.#checkAuthData(ad);
536
+ const signed = new Uint8Array(authData.length + 32);
537
+ signed.set(authData, 0);
538
+ signed.set(await sha256(p.clientDataBytes), authData.length);
539
+ if (!(await verifySignature(stored.alg, stored.publicKey, bytesField(p.fields, "signature"), signed))) {
540
+ return reject("bad signature");
541
+ }
542
+ if ((ad.signCount !== 0 || stored.signCount !== 0) && ad.signCount <= stored.signCount) {
543
+ return reject("signature counter went back: a cloned authenticator?");
544
+ }
545
+ await this.#store.update(stored.id, { signCount: ad.signCount, lastUsed: this.#now(), backedUp: (ad.flags & FLAG_BS) !== 0 });
546
+ return stored.user;
547
+ }
548
+ catch (err) {
549
+ return reject(err.message);
550
+ }
551
+ }
552
+ async list(user) {
553
+ return (await this.#store.list(user)).map(({ publicKey: _k, handle: _h, ...rest }) => rest);
554
+ }
555
+ async rename(user, id, name) {
556
+ const c = await this.#store.get(id);
557
+ if (!c || c.user !== user)
558
+ throw new PasskeyError("not-found", "No such passkey");
559
+ if (typeof name !== "string" || name.trim() === "" || name.length > 64)
560
+ throw new PasskeyError("invalid", "A name is 1-64 characters");
561
+ await this.#store.update(id, { name: name.trim() });
562
+ }
563
+ async remove(user, id) {
564
+ const c = await this.#store.get(id);
565
+ if (!c || c.user !== user)
566
+ throw new PasskeyError("not-found", "No such passkey");
567
+ await this.#store.remove(id);
568
+ }
569
+ }
570
+ export function definePasskeys(o) {
571
+ return new Passkeys(o);
572
+ }
@@ -0,0 +1,8 @@
1
+ export interface PasswordOptions {
2
+ ln?: number;
3
+ r?: number;
4
+ p?: number;
5
+ }
6
+ export declare function hashPassword(password: string, opts?: PasswordOptions): Promise<string>;
7
+ export declare function verifyPassword(password: string, stored: string | null | undefined): Promise<boolean>;
8
+ export declare function needsRehash(stored: string, opts?: PasswordOptions): boolean;
@@ -0,0 +1,65 @@
1
+ import { randomBytes, scrypt as scryptCb, timingSafeEqual } from "node:crypto";
2
+ const DEFAULT = { ln: 15, r: 8, p: 1 };
3
+ const MAX_LN = 20;
4
+ const MAX_PASSWORD_BYTES = 1024;
5
+ const enc = new TextEncoder();
6
+ function scrypt(password, salt, len, o) {
7
+ return new Promise((resolve, reject) => scryptCb(password, salt, len, o, (err, key) => (err ? reject(err) : resolve(key))));
8
+ }
9
+ function b64(bytes) {
10
+ return Buffer.from(bytes).toString("base64").replace(/=+$/, "");
11
+ }
12
+ function passwordBytes(password) {
13
+ if (typeof password !== "string" || password.length === 0) {
14
+ throw new TypeError("@weft-framework/server: a password must be a non-empty string");
15
+ }
16
+ const bytes = enc.encode(password.normalize("NFC"));
17
+ if (bytes.length > MAX_PASSWORD_BYTES) {
18
+ throw new RangeError(`@weft-framework/server: passwords are limited to ${MAX_PASSWORD_BYTES} bytes`);
19
+ }
20
+ return bytes;
21
+ }
22
+ function scryptOptions(ln, r, p) {
23
+ return { N: 2 ** ln, r, p, maxmem: 256 * 2 ** ln * r + 1024 * 1024 };
24
+ }
25
+ export async function hashPassword(password, opts = {}) {
26
+ const { ln, r, p } = { ...DEFAULT, ...opts };
27
+ if (!Number.isInteger(ln) || ln < 10 || ln > MAX_LN || !Number.isInteger(r) || r < 1 || !Number.isInteger(p) || p < 1) {
28
+ throw new RangeError("@weft-framework/server: bad scrypt parameters");
29
+ }
30
+ const salt = randomBytes(16);
31
+ const key = await scrypt(passwordBytes(password), salt, 32, scryptOptions(ln, r, p));
32
+ return `$scrypt$ln=${ln},r=${r},p=${p}$${b64(salt)}$${b64(key)}`;
33
+ }
34
+ const FORMAT = /^\$scrypt\$ln=(\d{1,2}),r=(\d{1,2}),p=(\d{1,2})\$([A-Za-z0-9+/]{22})\$([A-Za-z0-9+/]{43})$/;
35
+ function parse(stored) {
36
+ const m = typeof stored === "string" ? FORMAT.exec(stored) : null;
37
+ if (!m) {
38
+ return null;
39
+ }
40
+ const [ln, r, p] = [Number(m[1]), Number(m[2]), Number(m[3])];
41
+ if (ln < 10 || ln > MAX_LN || r < 1 || p < 1) {
42
+ return null;
43
+ }
44
+ return { ln, r, p, salt: Buffer.from(m[4], "base64"), key: Buffer.from(m[5], "base64") };
45
+ }
46
+ let dummy = null;
47
+ export async function verifyPassword(password, stored) {
48
+ let bytes;
49
+ try {
50
+ bytes = passwordBytes(password);
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ const real = stored ? parse(stored) : null;
56
+ dummy ??= hashPassword("weft-dummy-password");
57
+ const target = real ?? parse(await dummy);
58
+ const key = await scrypt(bytes, target.salt, target.key.length, scryptOptions(target.ln, target.r, target.p));
59
+ return real !== null && key.length === real.key.length && timingSafeEqual(key, real.key);
60
+ }
61
+ export function needsRehash(stored, opts = {}) {
62
+ const want = { ...DEFAULT, ...opts };
63
+ const got = parse(stored);
64
+ return !got || got.ln < want.ln || got.r < want.r || got.p < want.p;
65
+ }
package/dist/pdf.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ export declare class PdfError extends Error {
2
+ }
3
+ declare const PAPER: {
4
+ readonly A3: readonly [11.69, 16.54];
5
+ readonly A4: readonly [8.27, 11.69];
6
+ readonly A5: readonly [5.83, 8.27];
7
+ readonly Letter: readonly [8.5, 11];
8
+ readonly Legal: readonly [8.5, 14];
9
+ };
10
+ export type PaperFormat = keyof typeof PAPER;
11
+ export interface PdfRouteOptions {
12
+ filename?: string;
13
+ format?: PaperFormat;
14
+ landscape?: boolean;
15
+ }
16
+ export interface PrintJob {
17
+ url: string;
18
+ html: string;
19
+ fetch(url: string): Promise<Response>;
20
+ format?: PaperFormat;
21
+ landscape?: boolean;
22
+ }
23
+ export interface CaptureJob {
24
+ url: string;
25
+ html: string;
26
+ fetch(url: string): Promise<Response>;
27
+ width: number;
28
+ height: number;
29
+ }
30
+ export interface PdfPrinter {
31
+ print(job: PrintJob): Promise<Uint8Array>;
32
+ capture?(job: CaptureJob): Promise<Uint8Array>;
33
+ close(): Promise<void>;
34
+ }
35
+ export interface PdfOptions {
36
+ browser?: string;
37
+ concurrency?: number;
38
+ timeoutMs?: number;
39
+ maxBytes?: number;
40
+ args?: string[];
41
+ }
42
+ export declare function checkPdfRoute(raw: unknown, where: string): true | PdfRouteOptions;
43
+ export declare function pdfFilename(path: string, spec: true | PdfRouteOptions): string;
44
+ export declare function findBrowser(env?: Record<string, string | undefined>): string | null;
45
+ export declare function definePdf(o?: PdfOptions): PdfPrinter;
46
+ export {};