@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
package/dist/seal.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Grant } from "@weft-framework/data";
|
|
2
|
+
import type { PageContext } from "./context.js";
|
|
3
|
+
import { type Key } from "./security.js";
|
|
4
|
+
export interface SealOptions {
|
|
5
|
+
purpose: string;
|
|
6
|
+
ttlMs?: number;
|
|
7
|
+
session?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface UnsealOptions {
|
|
10
|
+
purpose: string;
|
|
11
|
+
session?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export declare const MAX_TOKEN = 8192;
|
|
14
|
+
export declare function sealWith(key: Key, value: unknown, opts: SealOptions, sid?: string | null): Promise<string>;
|
|
15
|
+
export declare function openWith(key: Key, token: string | null | undefined, opts: UnsealOptions, sid?: string | null): Promise<{
|
|
16
|
+
value: unknown;
|
|
17
|
+
expires: number;
|
|
18
|
+
} | null>;
|
|
19
|
+
export interface SealControl {
|
|
20
|
+
key(): Promise<Key>;
|
|
21
|
+
session(): string;
|
|
22
|
+
}
|
|
23
|
+
export declare function attachSeal(ctx: PageContext, control: SealControl): void;
|
|
24
|
+
export declare function seal(ctx: PageContext, value: unknown, opts: SealOptions): Promise<string>;
|
|
25
|
+
export declare function unseal(ctx: PageContext, token: string | null | undefined, opts: UnsealOptions): Promise<unknown>;
|
|
26
|
+
export interface GrantOptions {
|
|
27
|
+
ttlMs?: number;
|
|
28
|
+
session?: boolean;
|
|
29
|
+
}
|
|
30
|
+
export declare function grantToken(ctx: PageContext, model: string | {
|
|
31
|
+
name: string;
|
|
32
|
+
}, key: string | number, rights: "read" | "write", opts?: GrantOptions): Promise<string>;
|
|
33
|
+
export declare function acceptGrant(ctx: PageContext, token: string | null | undefined, opts?: {
|
|
34
|
+
session?: boolean;
|
|
35
|
+
}): Promise<Grant | null>;
|
package/dist/seal.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { base64url, fromBase64url, macBytes } from "./security.js";
|
|
2
|
+
const DAY = 24 * 60 * 60 * 1000;
|
|
3
|
+
const PURPOSE = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
4
|
+
export const MAX_TOKEN = 8192;
|
|
5
|
+
const enc = new TextEncoder();
|
|
6
|
+
const dec = new TextDecoder("utf-8", { fatal: true });
|
|
7
|
+
function checkPurpose(purpose) {
|
|
8
|
+
if (typeof purpose !== "string" || !PURPOSE.test(purpose)) {
|
|
9
|
+
throw new Error("seal: purpose is 1-64 letters, digits, `_`, `-` or `.`");
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function tagInput(purpose, sid, body) {
|
|
13
|
+
return `seal:${purpose}:${sid ?? ""}:${body}`;
|
|
14
|
+
}
|
|
15
|
+
export async function sealWith(key, value, opts, sid = null) {
|
|
16
|
+
checkPurpose(opts.purpose);
|
|
17
|
+
const ttl = opts.ttlMs ?? DAY;
|
|
18
|
+
if (!Number.isFinite(ttl) || ttl <= 0) {
|
|
19
|
+
throw new Error("seal: ttlMs is a positive number of milliseconds");
|
|
20
|
+
}
|
|
21
|
+
const json = JSON.stringify({ v: value, e: Date.now() + ttl });
|
|
22
|
+
if (value === undefined || json === undefined) {
|
|
23
|
+
throw new Error("seal: the value must be JSON");
|
|
24
|
+
}
|
|
25
|
+
const body = base64url(enc.encode(json));
|
|
26
|
+
const token = `${body}.${base64url(await macBytes(key, tagInput(opts.purpose, sid, body)))}`;
|
|
27
|
+
if (token.length > MAX_TOKEN) {
|
|
28
|
+
throw new Error(`seal: the sealed value is over ${MAX_TOKEN} characters`);
|
|
29
|
+
}
|
|
30
|
+
return token;
|
|
31
|
+
}
|
|
32
|
+
export async function openWith(key, token, opts, sid = null) {
|
|
33
|
+
checkPurpose(opts.purpose);
|
|
34
|
+
if (typeof token !== "string" || token.length > MAX_TOKEN)
|
|
35
|
+
return null;
|
|
36
|
+
const dot = token.indexOf(".");
|
|
37
|
+
if (dot <= 0 || token.indexOf(".", dot + 1) !== -1)
|
|
38
|
+
return null;
|
|
39
|
+
const body = token.slice(0, dot);
|
|
40
|
+
const tag = fromBase64url(token.slice(dot + 1));
|
|
41
|
+
const expected = await macBytes(key, tagInput(opts.purpose, sid, body));
|
|
42
|
+
if (!tag || tag.length !== expected.length)
|
|
43
|
+
return null;
|
|
44
|
+
let diff = 0;
|
|
45
|
+
for (let i = 0; i < tag.length; i++)
|
|
46
|
+
diff |= tag[i] ^ expected[i];
|
|
47
|
+
if (diff !== 0)
|
|
48
|
+
return null;
|
|
49
|
+
const raw = fromBase64url(body);
|
|
50
|
+
if (!raw)
|
|
51
|
+
return null;
|
|
52
|
+
let parsed;
|
|
53
|
+
try {
|
|
54
|
+
parsed = JSON.parse(dec.decode(raw));
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const p = parsed;
|
|
60
|
+
if (typeof p !== "object" || p === null || typeof p.e !== "number" || !(p.e > Date.now()))
|
|
61
|
+
return null;
|
|
62
|
+
return { value: p.v, expires: p.e };
|
|
63
|
+
}
|
|
64
|
+
const controls = new WeakMap();
|
|
65
|
+
export function attachSeal(ctx, control) {
|
|
66
|
+
controls.set(ctx, control);
|
|
67
|
+
}
|
|
68
|
+
function control(ctx) {
|
|
69
|
+
const c = controls.get(ctx);
|
|
70
|
+
if (!c)
|
|
71
|
+
throw new Error("@weft-framework/server: seal/unseal need the context of a request being handled");
|
|
72
|
+
return c;
|
|
73
|
+
}
|
|
74
|
+
export async function seal(ctx, value, opts) {
|
|
75
|
+
const c = control(ctx);
|
|
76
|
+
return sealWith(await c.key(), value, opts, opts.session ? c.session() : null);
|
|
77
|
+
}
|
|
78
|
+
export async function unseal(ctx, token, opts) {
|
|
79
|
+
const c = control(ctx);
|
|
80
|
+
const out = await openWith(await c.key(), token, opts, opts.session ? c.session() : null);
|
|
81
|
+
return out?.value;
|
|
82
|
+
}
|
|
83
|
+
const GRANT = "weft.grant";
|
|
84
|
+
export async function grantToken(ctx, model, key, rights, opts = {}) {
|
|
85
|
+
if (rights !== "read" && rights !== "write")
|
|
86
|
+
throw new Error(`grant rights are "read" or "write"`);
|
|
87
|
+
if (typeof key !== "string" && !(typeof key === "number" && Number.isFinite(key))) {
|
|
88
|
+
throw new Error("grant: the key is a string or a finite number");
|
|
89
|
+
}
|
|
90
|
+
const name = typeof model === "string" ? model : model.name;
|
|
91
|
+
return seal(ctx, { m: name, k: key, r: rights }, { purpose: GRANT, ttlMs: opts.ttlMs, session: opts.session });
|
|
92
|
+
}
|
|
93
|
+
export async function acceptGrant(ctx, token, opts = {}) {
|
|
94
|
+
const c = control(ctx);
|
|
95
|
+
const out = await openWith(await c.key(), token, { purpose: GRANT, session: opts.session }, opts.session ? c.session() : null);
|
|
96
|
+
if (!out)
|
|
97
|
+
return null;
|
|
98
|
+
const g = out.value;
|
|
99
|
+
if (typeof g !== "object" ||
|
|
100
|
+
g === null ||
|
|
101
|
+
typeof g.m !== "string" ||
|
|
102
|
+
!(typeof g.k === "string" || typeof g.k === "number") ||
|
|
103
|
+
(g.r !== "read" && g.r !== "write")) {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
return { model: g.m, key: g.k, rights: g.r, expires: out.expires };
|
|
107
|
+
}
|
package/dist/secret.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare class Secret {
|
|
2
|
+
readonly name: string;
|
|
3
|
+
constructor(name: string, value: string);
|
|
4
|
+
reveal(): string;
|
|
5
|
+
toString(): string;
|
|
6
|
+
toJSON(): never;
|
|
7
|
+
[Symbol.toPrimitive](): string;
|
|
8
|
+
}
|
|
9
|
+
export declare function isSecret(v: unknown): v is Secret;
|
|
10
|
+
export declare function secretEnv(name: string, opts?: {
|
|
11
|
+
minLength?: number;
|
|
12
|
+
env?: Record<string, string | undefined>;
|
|
13
|
+
}): Secret;
|
|
14
|
+
export declare function parseEnv(text: string, file?: string): Record<string, string>;
|
package/dist/secret.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
const REDACTED = "[secret]";
|
|
2
|
+
const values = new WeakMap();
|
|
3
|
+
export class Secret {
|
|
4
|
+
name;
|
|
5
|
+
constructor(name, value) {
|
|
6
|
+
this.name = name;
|
|
7
|
+
values.set(this, value);
|
|
8
|
+
Object.freeze(this);
|
|
9
|
+
}
|
|
10
|
+
reveal() {
|
|
11
|
+
return values.get(this);
|
|
12
|
+
}
|
|
13
|
+
toString() {
|
|
14
|
+
return REDACTED;
|
|
15
|
+
}
|
|
16
|
+
toJSON() {
|
|
17
|
+
throw new TypeError(`secret ${this.name} cannot be serialised`);
|
|
18
|
+
}
|
|
19
|
+
[Symbol.toPrimitive]() {
|
|
20
|
+
return REDACTED;
|
|
21
|
+
}
|
|
22
|
+
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
23
|
+
return `Secret(${this.name})`;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export function isSecret(v) {
|
|
27
|
+
return v instanceof Secret;
|
|
28
|
+
}
|
|
29
|
+
export function secretEnv(name, opts = {}) {
|
|
30
|
+
const env = opts.env ?? globalThis.process?.env ?? {};
|
|
31
|
+
const value = env[name];
|
|
32
|
+
if (value === undefined || value === "") {
|
|
33
|
+
throw new Error(`environment variable ${name} is not set`);
|
|
34
|
+
}
|
|
35
|
+
if (value.length < (opts.minLength ?? 1)) {
|
|
36
|
+
throw new Error(`environment variable ${name} must be at least ${opts.minLength} characters`);
|
|
37
|
+
}
|
|
38
|
+
return new Secret(name, value);
|
|
39
|
+
}
|
|
40
|
+
function blankOrComment(s) {
|
|
41
|
+
let i = 0;
|
|
42
|
+
while (i < s.length && (s[i] === " " || s[i] === "\t"))
|
|
43
|
+
i++;
|
|
44
|
+
return i === s.length || s[i] === "#";
|
|
45
|
+
}
|
|
46
|
+
function envLine(raw) {
|
|
47
|
+
let i = 0;
|
|
48
|
+
while (i < raw.length && (raw[i] === " " || raw[i] === "\t"))
|
|
49
|
+
i++;
|
|
50
|
+
if (i === raw.length || raw[i] === "#")
|
|
51
|
+
return ["", ""];
|
|
52
|
+
if (raw.startsWith("export", i) && (raw[i + 6] === " " || raw[i + 6] === "\t")) {
|
|
53
|
+
i += 6;
|
|
54
|
+
while (i < raw.length && (raw[i] === " " || raw[i] === "\t"))
|
|
55
|
+
i++;
|
|
56
|
+
}
|
|
57
|
+
const start = i;
|
|
58
|
+
const first = raw.charCodeAt(i);
|
|
59
|
+
if (!(first === 95 || (first >= 65 && first <= 90) || (first >= 97 && first <= 122)))
|
|
60
|
+
return null;
|
|
61
|
+
i++;
|
|
62
|
+
while (i < raw.length) {
|
|
63
|
+
const c = raw.charCodeAt(i);
|
|
64
|
+
if (c === 95 || (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122))
|
|
65
|
+
i++;
|
|
66
|
+
else
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
const key = raw.slice(start, i);
|
|
70
|
+
while (i < raw.length && (raw[i] === " " || raw[i] === "\t"))
|
|
71
|
+
i++;
|
|
72
|
+
if (raw[i] !== "=")
|
|
73
|
+
return null;
|
|
74
|
+
i++;
|
|
75
|
+
while (i < raw.length && (raw[i] === " " || raw[i] === "\t"))
|
|
76
|
+
i++;
|
|
77
|
+
return [key, raw.slice(i)];
|
|
78
|
+
}
|
|
79
|
+
export function parseEnv(text, file = ".env") {
|
|
80
|
+
const out = {};
|
|
81
|
+
const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
|
|
82
|
+
lines.forEach((raw, i) => {
|
|
83
|
+
const parsed = envLine(raw);
|
|
84
|
+
if (parsed && parsed[0] === "")
|
|
85
|
+
return;
|
|
86
|
+
if (!parsed)
|
|
87
|
+
throw new Error(`${file}:${i + 1}: expected KEY=value`);
|
|
88
|
+
const m = parsed;
|
|
89
|
+
let v = m[1].trimEnd();
|
|
90
|
+
const q = v[0];
|
|
91
|
+
if (q === '"' || q === "'") {
|
|
92
|
+
const end = v.lastIndexOf(q);
|
|
93
|
+
if (end === 0 || !blankOrComment(v.slice(end + 1)))
|
|
94
|
+
throw new Error(`${file}:${i + 1}: unterminated quote`);
|
|
95
|
+
v = v.slice(1, end);
|
|
96
|
+
if (q === '"') {
|
|
97
|
+
v = v.replace(/\\([nrt"\\])/g, (_s, c) => ({ n: "\n", r: "\r", t: "\t", '"': '"', "\\": "\\" })[c]);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
const hash = v.search(/\s#/);
|
|
102
|
+
if (hash >= 0)
|
|
103
|
+
v = v.slice(0, hash).trimEnd();
|
|
104
|
+
}
|
|
105
|
+
if (m[0] === "__proto__")
|
|
106
|
+
throw new Error(`${file}:${i + 1}: __proto__ is not a variable name`);
|
|
107
|
+
out[m[0]] = v;
|
|
108
|
+
});
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export declare const MIN_SECRET_LENGTH = 32;
|
|
2
|
+
export type Key = CryptoKey;
|
|
3
|
+
export declare function importSecret(secret: string): Promise<Key>;
|
|
4
|
+
export declare function base64url(bytes: Uint8Array): string;
|
|
5
|
+
export declare function randomId(bytes?: number): string;
|
|
6
|
+
export declare function macBytes(key: Key, data: string): Promise<Uint8Array>;
|
|
7
|
+
export declare function fromBase64url(s: string): Uint8Array | null;
|
|
8
|
+
export declare function timingSafeEqual(a: string, b: string): boolean;
|
|
9
|
+
export declare function signSession(key: Key, sid: string): Promise<string>;
|
|
10
|
+
export declare function verifySession(key: Key, value: string | undefined): Promise<string | null>;
|
|
11
|
+
export declare function csrfToken(key: Key, sid: string): Promise<string>;
|
|
12
|
+
export declare function verifyCsrf(key: Key, sid: string, token: string | null): Promise<boolean>;
|
|
13
|
+
export declare function parseCookies(header: string | null): Record<string, string>;
|
|
14
|
+
export interface CookieOptions {
|
|
15
|
+
secure: boolean;
|
|
16
|
+
maxAgeSeconds?: number;
|
|
17
|
+
}
|
|
18
|
+
export declare function sessionCookie(name: string, value: string, opts: CookieOptions): string;
|
|
19
|
+
export declare function sameOrigin(req: Request): boolean;
|
|
20
|
+
export interface RateLimitOptions {
|
|
21
|
+
capacity: number;
|
|
22
|
+
refillPerSecond: number;
|
|
23
|
+
maxKeys?: number;
|
|
24
|
+
}
|
|
25
|
+
export declare class RateLimiter {
|
|
26
|
+
private readonly opts;
|
|
27
|
+
private readonly buckets;
|
|
28
|
+
constructor(opts: RateLimitOptions);
|
|
29
|
+
take(key: string, now?: number): boolean;
|
|
30
|
+
}
|
|
31
|
+
export interface CspSources {
|
|
32
|
+
connect?: readonly string[];
|
|
33
|
+
img?: readonly string[];
|
|
34
|
+
media?: readonly string[];
|
|
35
|
+
font?: readonly string[];
|
|
36
|
+
frame?: readonly string[];
|
|
37
|
+
style?: readonly string[];
|
|
38
|
+
form?: readonly string[];
|
|
39
|
+
worker?: readonly string[];
|
|
40
|
+
}
|
|
41
|
+
export declare function checkCspSources(raw: unknown, where: string): CspSources;
|
|
42
|
+
export declare function mergeCspSources(...sets: (CspSources | undefined)[]): CspSources;
|
|
43
|
+
export interface HeaderOptions {
|
|
44
|
+
nonce: string;
|
|
45
|
+
hashes?: {
|
|
46
|
+
script: readonly string[];
|
|
47
|
+
style: readonly string[];
|
|
48
|
+
};
|
|
49
|
+
secure: boolean;
|
|
50
|
+
sources?: CspSources;
|
|
51
|
+
report?: string;
|
|
52
|
+
}
|
|
53
|
+
export declare function securityHeaders(opts: HeaderOptions): Record<string, string>;
|
package/dist/security.js
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
const enc = new TextEncoder();
|
|
2
|
+
export const MIN_SECRET_LENGTH = 32;
|
|
3
|
+
export async function importSecret(secret) {
|
|
4
|
+
if (typeof secret !== "string" || secret.length < MIN_SECRET_LENGTH) {
|
|
5
|
+
throw new Error(`@weft-framework/server: the secret must be at least ${MIN_SECRET_LENGTH} characters of random data`);
|
|
6
|
+
}
|
|
7
|
+
return crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
|
|
8
|
+
"sign",
|
|
9
|
+
]);
|
|
10
|
+
}
|
|
11
|
+
export function base64url(bytes) {
|
|
12
|
+
let bin = "";
|
|
13
|
+
for (const b of bytes) {
|
|
14
|
+
bin += String.fromCharCode(b);
|
|
15
|
+
}
|
|
16
|
+
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
17
|
+
}
|
|
18
|
+
export function randomId(bytes = 18) {
|
|
19
|
+
return base64url(crypto.getRandomValues(new Uint8Array(bytes)));
|
|
20
|
+
}
|
|
21
|
+
export async function macBytes(key, data) {
|
|
22
|
+
return new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(data)));
|
|
23
|
+
}
|
|
24
|
+
async function mac(key, data) {
|
|
25
|
+
return base64url(await macBytes(key, data));
|
|
26
|
+
}
|
|
27
|
+
export function fromBase64url(s) {
|
|
28
|
+
if (!/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1) {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (s.length % 4)) % 4));
|
|
33
|
+
const out = new Uint8Array(bin.length);
|
|
34
|
+
for (let i = 0; i < bin.length; i++) {
|
|
35
|
+
out[i] = bin.charCodeAt(i);
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export function timingSafeEqual(a, b) {
|
|
44
|
+
if (a.length !== b.length) {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
let diff = 0;
|
|
48
|
+
for (let i = 0; i < a.length; i++) {
|
|
49
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
50
|
+
}
|
|
51
|
+
return diff === 0;
|
|
52
|
+
}
|
|
53
|
+
const SID_RE = /^[A-Za-z0-9_-]{16,64}$/;
|
|
54
|
+
export async function signSession(key, sid) {
|
|
55
|
+
return `${sid}.${await mac(key, "sid:" + sid)}`;
|
|
56
|
+
}
|
|
57
|
+
export async function verifySession(key, value) {
|
|
58
|
+
if (!value) {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
const dot = value.indexOf(".");
|
|
62
|
+
if (dot < 0) {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
const sid = value.slice(0, dot);
|
|
66
|
+
if (!SID_RE.test(sid)) {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
const expected = await mac(key, "sid:" + sid);
|
|
70
|
+
return timingSafeEqual(value.slice(dot + 1), expected) ? sid : null;
|
|
71
|
+
}
|
|
72
|
+
export async function csrfToken(key, sid) {
|
|
73
|
+
const raw = await macBytes(key, "csrf:" + sid);
|
|
74
|
+
const pad = crypto.getRandomValues(new Uint8Array(raw.length));
|
|
75
|
+
const out = new Uint8Array(raw.length * 2);
|
|
76
|
+
out.set(pad);
|
|
77
|
+
for (let i = 0; i < raw.length; i++) {
|
|
78
|
+
out[raw.length + i] = raw[i] ^ pad[i];
|
|
79
|
+
}
|
|
80
|
+
return base64url(out);
|
|
81
|
+
}
|
|
82
|
+
export async function verifyCsrf(key, sid, token) {
|
|
83
|
+
const bytes = token ? fromBase64url(token) : null;
|
|
84
|
+
const raw = await macBytes(key, "csrf:" + sid);
|
|
85
|
+
if (!bytes || bytes.length !== raw.length * 2) {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
let diff = 0;
|
|
89
|
+
for (let i = 0; i < raw.length; i++) {
|
|
90
|
+
diff |= bytes[i] ^ bytes[raw.length + i] ^ raw[i];
|
|
91
|
+
}
|
|
92
|
+
return diff === 0;
|
|
93
|
+
}
|
|
94
|
+
export function parseCookies(header) {
|
|
95
|
+
const out = Object.create(null);
|
|
96
|
+
if (!header) {
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
for (const part of header.split(";")) {
|
|
100
|
+
const eq = part.indexOf("=");
|
|
101
|
+
if (eq < 0) {
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const name = part.slice(0, eq).trim();
|
|
105
|
+
if (name && !(name in out)) {
|
|
106
|
+
out[name] = part.slice(eq + 1).trim();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
export function sessionCookie(name, value, opts) {
|
|
112
|
+
const parts = [`${name}=${value}`, "Path=/", "HttpOnly", "SameSite=Lax"];
|
|
113
|
+
if (opts.secure) {
|
|
114
|
+
parts.push("Secure");
|
|
115
|
+
}
|
|
116
|
+
if (opts.maxAgeSeconds !== undefined) {
|
|
117
|
+
parts.push(`Max-Age=${Math.floor(opts.maxAgeSeconds)}`);
|
|
118
|
+
}
|
|
119
|
+
return parts.join("; ");
|
|
120
|
+
}
|
|
121
|
+
export function sameOrigin(req) {
|
|
122
|
+
const own = new URL(req.url).origin;
|
|
123
|
+
const origin = req.headers.get("origin");
|
|
124
|
+
if (origin !== null) {
|
|
125
|
+
return origin === own;
|
|
126
|
+
}
|
|
127
|
+
return req.headers.get("sec-fetch-site") === "same-origin";
|
|
128
|
+
}
|
|
129
|
+
export class RateLimiter {
|
|
130
|
+
opts;
|
|
131
|
+
buckets = new Map();
|
|
132
|
+
constructor(opts) {
|
|
133
|
+
this.opts = { maxKeys: 100_000, ...opts };
|
|
134
|
+
}
|
|
135
|
+
take(key, now = Date.now()) {
|
|
136
|
+
const { capacity, refillPerSecond, maxKeys } = this.opts;
|
|
137
|
+
let b = this.buckets.get(key);
|
|
138
|
+
if (b) {
|
|
139
|
+
b.tokens = Math.min(capacity, b.tokens + ((now - b.at) / 1000) * refillPerSecond);
|
|
140
|
+
b.at = now;
|
|
141
|
+
this.buckets.delete(key);
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
b = { tokens: capacity, at: now };
|
|
145
|
+
if (this.buckets.size >= maxKeys) {
|
|
146
|
+
const oldest = this.buckets.keys().next().value;
|
|
147
|
+
if (oldest !== undefined) {
|
|
148
|
+
this.buckets.delete(oldest);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
this.buckets.set(key, b);
|
|
153
|
+
if (b.tokens < 1) {
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
b.tokens -= 1;
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const CSP_DIRECTIVES = {
|
|
161
|
+
connect: "connect-src",
|
|
162
|
+
img: "img-src",
|
|
163
|
+
media: "media-src",
|
|
164
|
+
font: "font-src",
|
|
165
|
+
frame: "frame-src",
|
|
166
|
+
style: "style-src",
|
|
167
|
+
form: "form-action",
|
|
168
|
+
worker: "worker-src",
|
|
169
|
+
};
|
|
170
|
+
const CSP_SCHEMES = {
|
|
171
|
+
"blob:": ["connect", "img", "media", "worker"],
|
|
172
|
+
"data:": ["img", "media", "font"],
|
|
173
|
+
};
|
|
174
|
+
const CSP_ORIGIN = /^(?:(?:https|wss):\/\/(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,62})(?:\.[a-z0-9](?:[a-z0-9-]{0,62}))*|(?:http|ws):\/\/(?:localhost|127\.0\.0\.1|\[::1\]))(?::\d{1,5})?(?:\/[A-Za-z0-9._~%!$&()*+=:@/-]*)?$/;
|
|
175
|
+
export function checkCspSources(raw, where) {
|
|
176
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
177
|
+
throw new TypeError(`${where}: csp is an object of origin lists, like { connect: ["https://api.example.com"] }`);
|
|
178
|
+
}
|
|
179
|
+
const out = {};
|
|
180
|
+
for (const [key, list] of Object.entries(raw)) {
|
|
181
|
+
if (!(key in CSP_DIRECTIVES)) {
|
|
182
|
+
throw new TypeError(`${where}: csp.${key} is not one of ${Object.keys(CSP_DIRECTIVES).join(", ")}`);
|
|
183
|
+
}
|
|
184
|
+
if (!Array.isArray(list) || list.length > 32) {
|
|
185
|
+
throw new TypeError(`${where}: csp.${key} is a list of at most 32 origins`);
|
|
186
|
+
}
|
|
187
|
+
const kept = [];
|
|
188
|
+
for (const entry of list) {
|
|
189
|
+
const scheme = typeof entry === "string" ? CSP_SCHEMES[entry] : undefined;
|
|
190
|
+
const ok = typeof entry === "string" &&
|
|
191
|
+
entry.length <= 256 &&
|
|
192
|
+
(scheme ? scheme.includes(key) : CSP_ORIGIN.test(entry));
|
|
193
|
+
if (!ok) {
|
|
194
|
+
throw new TypeError(`${where}: csp.${key} entry ${JSON.stringify(entry)} is not an origin this page may reach ` +
|
|
195
|
+
"(https://host or wss://host, optionally *.host, a port and a path; http: only for localhost)");
|
|
196
|
+
}
|
|
197
|
+
if (!kept.includes(entry))
|
|
198
|
+
kept.push(entry);
|
|
199
|
+
}
|
|
200
|
+
if (kept.length)
|
|
201
|
+
out[key] = kept;
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
export function mergeCspSources(...sets) {
|
|
206
|
+
const out = {};
|
|
207
|
+
for (const set of sets) {
|
|
208
|
+
for (const [key, list] of Object.entries(set ?? {})) {
|
|
209
|
+
const into = (out[key] ??= []);
|
|
210
|
+
for (const e of list)
|
|
211
|
+
if (!into.includes(e))
|
|
212
|
+
into.push(e);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return out;
|
|
216
|
+
}
|
|
217
|
+
export function securityHeaders(opts) {
|
|
218
|
+
const s = opts.sources ?? {};
|
|
219
|
+
const add = (base, list) => (list?.length ? `${base} ${list.join(" ")}` : base);
|
|
220
|
+
const directives = [
|
|
221
|
+
"default-src 'self'",
|
|
222
|
+
opts.hashes ? add("script-src 'self'", opts.hashes.script) : `script-src 'nonce-${opts.nonce}' 'self'`,
|
|
223
|
+
add(opts.hashes ? add("style-src 'self'", opts.hashes.style) : `style-src 'self' 'nonce-${opts.nonce}'`, s.style),
|
|
224
|
+
add("img-src 'self' data:", s.img?.filter((e) => e !== "data:")),
|
|
225
|
+
add("connect-src 'self'", s.connect),
|
|
226
|
+
...(s.media?.length ? [add("media-src 'self'", s.media)] : []),
|
|
227
|
+
...(s.font?.length ? [add("font-src 'self'", s.font)] : []),
|
|
228
|
+
...(s.worker?.length ? [add("worker-src 'self'", s.worker)] : []),
|
|
229
|
+
s.frame?.length ? `frame-src ${s.frame.join(" ")}` : "frame-src 'none'",
|
|
230
|
+
"object-src 'none'",
|
|
231
|
+
"base-uri 'none'",
|
|
232
|
+
"frame-ancestors 'none'",
|
|
233
|
+
add("form-action 'self'", s.form),
|
|
234
|
+
];
|
|
235
|
+
if (opts.report)
|
|
236
|
+
directives.push(`report-uri ${opts.report}`, "report-to weft-csp");
|
|
237
|
+
const h = {
|
|
238
|
+
"content-security-policy": directives.join("; "),
|
|
239
|
+
"x-content-type-options": "nosniff",
|
|
240
|
+
"referrer-policy": "strict-origin-when-cross-origin",
|
|
241
|
+
"x-frame-options": "DENY",
|
|
242
|
+
"cross-origin-opener-policy": "same-origin",
|
|
243
|
+
};
|
|
244
|
+
if (opts.report)
|
|
245
|
+
h["reporting-endpoints"] = `weft-csp="${opts.report}"`;
|
|
246
|
+
if (opts.secure) {
|
|
247
|
+
h["strict-transport-security"] = "max-age=63072000; includeSubDomains";
|
|
248
|
+
}
|
|
249
|
+
return h;
|
|
250
|
+
}
|
package/dist/seed.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Model } from "@weft-framework/data";
|
|
2
|
+
import { type Compiler } from "./compiler.js";
|
|
3
|
+
export interface SeedCommandOptions {
|
|
4
|
+
compiler: Compiler;
|
|
5
|
+
reset?: boolean;
|
|
6
|
+
env?: Record<string, string | undefined>;
|
|
7
|
+
}
|
|
8
|
+
export declare class SeedError extends Error {
|
|
9
|
+
}
|
|
10
|
+
export interface SeedContext {
|
|
11
|
+
models: Record<string, Model<unknown>>;
|
|
12
|
+
}
|
|
13
|
+
export declare function seedProject(root: string, opts: SeedCommandOptions): Promise<{
|
|
14
|
+
database: string;
|
|
15
|
+
reset: boolean;
|
|
16
|
+
}>;
|
package/dist/seed.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { existsSync, realpathSync, rmSync } from "node:fs";
|
|
11
|
+
import { join, resolve } from "node:path";
|
|
12
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
13
|
+
import { parseArgs } from "node:util";
|
|
14
|
+
import { CompileError, findCompiler } from "./compiler.js";
|
|
15
|
+
import { ConfigError } from "./config.js";
|
|
16
|
+
import { ProjectError, loadProject } from "./project.js";
|
|
17
|
+
import { ModelStorage } from "./storage.js";
|
|
18
|
+
export class SeedError extends Error {
|
|
19
|
+
}
|
|
20
|
+
export async function seedProject(root, opts) {
|
|
21
|
+
root = resolve(root);
|
|
22
|
+
const env = opts.env ?? process.env;
|
|
23
|
+
const outDir = join(root, ".weft", "seed", randomUUID());
|
|
24
|
+
const storage = new ModelStorage();
|
|
25
|
+
try {
|
|
26
|
+
const project = await loadProject(root, { compiler: opts.compiler, outDir, browserAssets: false, cacheKey: outDir });
|
|
27
|
+
const database = project.database;
|
|
28
|
+
if (database === undefined || database === ":memory:") {
|
|
29
|
+
throw new SeedError("no `database` file in weft.config.ts; rows kept in memory would vanish when this command ends");
|
|
30
|
+
}
|
|
31
|
+
const file = ["seed.ts", "seed.js"].map((name) => join(outDir, name)).find((f) => existsSync(f));
|
|
32
|
+
if (!file) {
|
|
33
|
+
throw new SeedError("no src/seed.ts; export `seed()` from it");
|
|
34
|
+
}
|
|
35
|
+
if (opts.reset) {
|
|
36
|
+
if (env.NODE_ENV === "production") {
|
|
37
|
+
throw new SeedError("refusing to reset with NODE_ENV=production");
|
|
38
|
+
}
|
|
39
|
+
for (const suffix of ["", "-wal", "-shm", "-journal"]) {
|
|
40
|
+
rmSync(database + suffix, { force: true });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
await storage.attach(Object.values(project.models), { database });
|
|
44
|
+
const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(file).href)));
|
|
45
|
+
const seed = mod.seed ?? mod.default;
|
|
46
|
+
if (typeof seed !== "function") {
|
|
47
|
+
throw new SeedError("src/seed: export a function `seed()`");
|
|
48
|
+
}
|
|
49
|
+
await seed({ models: project.models });
|
|
50
|
+
return { database, reset: opts.reset === true };
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
storage.close();
|
|
54
|
+
rmSync(outDir, { recursive: true, force: true });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async function main() {
|
|
58
|
+
const { values, positionals } = parseArgs({
|
|
59
|
+
allowPositionals: true,
|
|
60
|
+
options: { reset: { type: "boolean" }, yes: { type: "boolean" } },
|
|
61
|
+
});
|
|
62
|
+
const root = resolve(positionals[0] ?? ".");
|
|
63
|
+
const reset = values.reset === true;
|
|
64
|
+
try {
|
|
65
|
+
if (reset && values.yes !== true) {
|
|
66
|
+
throw new SeedError("`weft db reset` deletes the database; run it again with --yes");
|
|
67
|
+
}
|
|
68
|
+
const done = await seedProject(root, { compiler: findCompiler(root), reset });
|
|
69
|
+
console.log(`[weft] ${done.reset ? "reset and seeded" : "seeded"} ${done.database}`);
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
if (err instanceof CompileError) {
|
|
73
|
+
console.error(err.diagnostics);
|
|
74
|
+
}
|
|
75
|
+
else if (err instanceof SeedError || err instanceof ProjectError || err instanceof ConfigError) {
|
|
76
|
+
console.error(`[weft] ${err.message}`);
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
console.error("[weft] seed:", err instanceof Error ? (err.stack ?? err.message) : err);
|
|
80
|
+
}
|
|
81
|
+
process.exit(1);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function isEntry() {
|
|
85
|
+
try {
|
|
86
|
+
return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (isEntry()) {
|
|
93
|
+
await main();
|
|
94
|
+
}
|