@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,97 @@
|
|
|
1
|
+
import type { SqlDatabase } from "@weft-framework/data";
|
|
2
|
+
import type { PageContext } from "./context.js";
|
|
3
|
+
import { type Secret } from "./secret.js";
|
|
4
|
+
type Fetch = (input: string, init: RequestInit) => Promise<Response>;
|
|
5
|
+
type Bytes = Uint8Array<ArrayBuffer>;
|
|
6
|
+
export interface PushSubscriptionRecord {
|
|
7
|
+
endpoint: string;
|
|
8
|
+
user: string;
|
|
9
|
+
p256dh: string;
|
|
10
|
+
auth: string;
|
|
11
|
+
created: number;
|
|
12
|
+
}
|
|
13
|
+
export interface PushStore {
|
|
14
|
+
add(r: PushSubscriptionRecord): void | Promise<void>;
|
|
15
|
+
forUser(user: string): PushSubscriptionRecord[] | Promise<PushSubscriptionRecord[]>;
|
|
16
|
+
remove(endpoint: string, user?: string): boolean | Promise<boolean>;
|
|
17
|
+
}
|
|
18
|
+
export declare class MemoryPushStore implements PushStore {
|
|
19
|
+
#private;
|
|
20
|
+
add(r: PushSubscriptionRecord): void;
|
|
21
|
+
forUser(user: string): PushSubscriptionRecord[];
|
|
22
|
+
remove(endpoint: string, user?: string): boolean;
|
|
23
|
+
}
|
|
24
|
+
export declare class SqlPushStore implements PushStore {
|
|
25
|
+
#private;
|
|
26
|
+
constructor(db: SqlDatabase, table?: string);
|
|
27
|
+
add(r: PushSubscriptionRecord): void;
|
|
28
|
+
forUser(user: string): PushSubscriptionRecord[];
|
|
29
|
+
remove(endpoint: string, user?: string): boolean;
|
|
30
|
+
}
|
|
31
|
+
export declare function generateVapidKeys(): Promise<{
|
|
32
|
+
publicKey: string;
|
|
33
|
+
privateKey: string;
|
|
34
|
+
}>;
|
|
35
|
+
export declare function encryptPushPayload(plaintext: Uint8Array, to: {
|
|
36
|
+
p256dh: Bytes;
|
|
37
|
+
auth: Bytes;
|
|
38
|
+
}, test?: {
|
|
39
|
+
local?: CryptoKeyPair;
|
|
40
|
+
salt?: Bytes;
|
|
41
|
+
}): Promise<Bytes>;
|
|
42
|
+
export declare const PUSH_SERVICES: readonly string[];
|
|
43
|
+
export interface WebPushOptions {
|
|
44
|
+
publicKey: string;
|
|
45
|
+
privateKey: string | Secret;
|
|
46
|
+
subject: string;
|
|
47
|
+
store?: PushStore;
|
|
48
|
+
allowHosts?: readonly string[];
|
|
49
|
+
maxPerUser?: number;
|
|
50
|
+
ttlSeconds?: number;
|
|
51
|
+
fetch?: Fetch;
|
|
52
|
+
timeoutMs?: number;
|
|
53
|
+
now?: () => number;
|
|
54
|
+
}
|
|
55
|
+
export interface PushMessage {
|
|
56
|
+
title: string;
|
|
57
|
+
body?: string;
|
|
58
|
+
url?: string;
|
|
59
|
+
tag?: string;
|
|
60
|
+
urgency?: "very-low" | "low" | "normal" | "high";
|
|
61
|
+
}
|
|
62
|
+
export interface PushResult {
|
|
63
|
+
sent: number;
|
|
64
|
+
removed: number;
|
|
65
|
+
failed: number;
|
|
66
|
+
}
|
|
67
|
+
export declare class PushError extends Error {
|
|
68
|
+
readonly permanent: boolean;
|
|
69
|
+
constructor(message: string, permanent: boolean, cause?: unknown);
|
|
70
|
+
}
|
|
71
|
+
export declare class WebPush {
|
|
72
|
+
#private;
|
|
73
|
+
readonly publicKey: string;
|
|
74
|
+
constructor(o: WebPushOptions);
|
|
75
|
+
allowedEndpoint(endpoint: unknown): endpoint is string;
|
|
76
|
+
subscribe(ctx: PageContext, subscription: unknown): Promise<void>;
|
|
77
|
+
unsubscribe(ctx: PageContext, endpoint: string): Promise<boolean>;
|
|
78
|
+
forget(user: string): Promise<number>;
|
|
79
|
+
authorization(endpoint: string): Promise<string>;
|
|
80
|
+
send(user: string, message: PushMessage): Promise<PushResult>;
|
|
81
|
+
channel(label?: string): {
|
|
82
|
+
label: string;
|
|
83
|
+
send(d: {
|
|
84
|
+
user: string;
|
|
85
|
+
notification: {
|
|
86
|
+
title: string;
|
|
87
|
+
body: string;
|
|
88
|
+
url: string | null;
|
|
89
|
+
type: string;
|
|
90
|
+
};
|
|
91
|
+
}): Promise<PushResult>;
|
|
92
|
+
};
|
|
93
|
+
worker(): Response;
|
|
94
|
+
}
|
|
95
|
+
export declare function defineWebPush(o: WebPushOptions): WebPush;
|
|
96
|
+
export declare const PUSH_WORKER_JS = "// Weft push worker (generated by @weft-framework/server).\nself.addEventListener(\"push\", (event) => {\n let d = {};\n try {\n d = event.data ? event.data.json() : {};\n } catch {\n d = {};\n }\n const title = typeof d.title === \"string\" && d.title ? d.title : \"Notification\";\n const options = { body: typeof d.body === \"string\" ? d.body : \"\", data: { url: typeof d.url === \"string\" ? d.url : \"/\" } };\n if (typeof d.tag === \"string\") options.tag = d.tag;\n event.waitUntil(self.registration.showNotification(title, options));\n});\nself.addEventListener(\"notificationclick\", (event) => {\n event.notification.close();\n let url = new URL(\"/\", self.location.origin).href;\n try {\n const u = new URL((event.notification.data && event.notification.data.url) || \"/\", self.location.origin);\n if (u.origin === self.location.origin) url = u.href;\n } catch {\n // keep the site root\n }\n event.waitUntil(\n self.clients.matchAll({ type: \"window\", includeUncontrolled: true }).then((list) => {\n for (const c of list) if (c.url === url && \"focus\" in c) return c.focus();\n return self.clients.openWindow(url);\n }),\n );\n});\n";
|
|
97
|
+
export {};
|
package/dist/webpush.js
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { authState } from "./auth.js";
|
|
2
|
+
import { isSecret } from "./secret.js";
|
|
3
|
+
export class MemoryPushStore {
|
|
4
|
+
#rows = new Map();
|
|
5
|
+
add(r) {
|
|
6
|
+
this.#rows.delete(r.endpoint);
|
|
7
|
+
this.#rows.set(r.endpoint, { ...r });
|
|
8
|
+
}
|
|
9
|
+
forUser(user) {
|
|
10
|
+
return [...this.#rows.values()].filter((r) => r.user === user).map((r) => ({ ...r }));
|
|
11
|
+
}
|
|
12
|
+
remove(endpoint, user) {
|
|
13
|
+
const r = this.#rows.get(endpoint);
|
|
14
|
+
if (!r || (user !== undefined && r.user !== user))
|
|
15
|
+
return false;
|
|
16
|
+
return this.#rows.delete(endpoint);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export class SqlPushStore {
|
|
20
|
+
#db;
|
|
21
|
+
#t;
|
|
22
|
+
constructor(db, table = "weft_push_subscriptions") {
|
|
23
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table))
|
|
24
|
+
throw new Error(`@weft-framework/server: not a valid table name: ${table}`);
|
|
25
|
+
this.#db = db;
|
|
26
|
+
this.#t = `"${table}"`;
|
|
27
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${this.#t} (endpoint TEXT PRIMARY KEY NOT NULL, user_id TEXT NOT NULL, ` +
|
|
28
|
+
`p256dh TEXT NOT NULL, auth TEXT NOT NULL, created INTEGER NOT NULL)`);
|
|
29
|
+
db.exec(`CREATE INDEX IF NOT EXISTS "${table}_user" ON ${this.#t} (user_id)`);
|
|
30
|
+
}
|
|
31
|
+
add(r) {
|
|
32
|
+
this.#db
|
|
33
|
+
.prepare(`INSERT OR REPLACE INTO ${this.#t} (endpoint, user_id, p256dh, auth, created) VALUES (?, ?, ?, ?, ?)`)
|
|
34
|
+
.run(r.endpoint, r.user, r.p256dh, r.auth, r.created);
|
|
35
|
+
}
|
|
36
|
+
forUser(user) {
|
|
37
|
+
return this.#db.prepare(`SELECT * FROM ${this.#t} WHERE user_id = ? ORDER BY created, endpoint`).all(user).map((r) => ({ endpoint: String(r.endpoint), user: String(r.user_id), p256dh: String(r.p256dh), auth: String(r.auth), created: Number(r.created) }));
|
|
38
|
+
}
|
|
39
|
+
remove(endpoint, user) {
|
|
40
|
+
const r = user === undefined
|
|
41
|
+
? this.#db.prepare(`DELETE FROM ${this.#t} WHERE endpoint = ? RETURNING endpoint`).all(endpoint)
|
|
42
|
+
: this.#db.prepare(`DELETE FROM ${this.#t} WHERE endpoint = ? AND user_id = ? RETURNING endpoint`).all(endpoint, user);
|
|
43
|
+
return r.length > 0;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const utf8 = new TextEncoder();
|
|
47
|
+
function b64url(b) {
|
|
48
|
+
let s = "";
|
|
49
|
+
for (const x of b)
|
|
50
|
+
s += String.fromCharCode(x);
|
|
51
|
+
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
52
|
+
}
|
|
53
|
+
function fromB64url(s) {
|
|
54
|
+
if (!/^[A-Za-z0-9_-]*$/.test(s))
|
|
55
|
+
throw new Error("not base64url");
|
|
56
|
+
const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4));
|
|
57
|
+
const out = new Uint8Array(bin.length);
|
|
58
|
+
for (let i = 0; i < bin.length; i++)
|
|
59
|
+
out[i] = bin.charCodeAt(i);
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
function concat(...parts) {
|
|
63
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
64
|
+
let at = 0;
|
|
65
|
+
for (const p of parts) {
|
|
66
|
+
out.set(p, at);
|
|
67
|
+
at += p.length;
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
const ZERO = String.fromCharCode(0);
|
|
72
|
+
async function hkdf(ikm, salt, info, bytes) {
|
|
73
|
+
const key = await crypto.subtle.importKey("raw", ikm, "HKDF", false, ["deriveBits"]);
|
|
74
|
+
return new Uint8Array(await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info }, key, bytes * 8));
|
|
75
|
+
}
|
|
76
|
+
export async function generateVapidKeys() {
|
|
77
|
+
const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]));
|
|
78
|
+
const raw = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
|
|
79
|
+
const jwk = await crypto.subtle.exportKey("jwk", pair.privateKey);
|
|
80
|
+
return { publicKey: b64url(raw), privateKey: jwk.d };
|
|
81
|
+
}
|
|
82
|
+
function pointJwk(publicKey) {
|
|
83
|
+
if (publicKey.length !== 65 || publicKey[0] !== 4)
|
|
84
|
+
throw new Error("not an uncompressed P-256 point");
|
|
85
|
+
return { x: b64url(publicKey.subarray(1, 33)), y: b64url(publicKey.subarray(33)) };
|
|
86
|
+
}
|
|
87
|
+
export async function encryptPushPayload(plaintext, to, test = {}) {
|
|
88
|
+
if (to.p256dh.length !== 65 || to.p256dh[0] !== 4)
|
|
89
|
+
throw new Error("p256dh is an uncompressed P-256 point");
|
|
90
|
+
if (to.auth.length !== 16)
|
|
91
|
+
throw new Error("auth is 16 bytes");
|
|
92
|
+
const local = test.local ?? (await crypto.subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]));
|
|
93
|
+
const salt = test.salt ?? crypto.getRandomValues(new Uint8Array(16));
|
|
94
|
+
const asPublic = new Uint8Array(await crypto.subtle.exportKey("raw", local.publicKey));
|
|
95
|
+
const uaKey = await crypto.subtle.importKey("raw", to.p256dh, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
96
|
+
const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "ECDH", public: uaKey }, local.privateKey, 256));
|
|
97
|
+
const ikm = await hkdf(shared, to.auth, concat(utf8.encode(`WebPush: info${ZERO}`), to.p256dh, asPublic), 32);
|
|
98
|
+
const cek = await hkdf(ikm, salt, utf8.encode(`Content-Encoding: aes128gcm${ZERO}`), 16);
|
|
99
|
+
const nonce = await hkdf(ikm, salt, utf8.encode(`Content-Encoding: nonce${ZERO}`), 12);
|
|
100
|
+
const key = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
|
|
101
|
+
const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, key, concat(plaintext, Uint8Array.of(2))));
|
|
102
|
+
const rs = 4096;
|
|
103
|
+
const header = concat(salt, Uint8Array.of(rs >>> 24, (rs >>> 16) & 255, (rs >>> 8) & 255, rs & 255), Uint8Array.of(65), asPublic);
|
|
104
|
+
return concat(header, sealed);
|
|
105
|
+
}
|
|
106
|
+
export const PUSH_SERVICES = [
|
|
107
|
+
"fcm.googleapis.com",
|
|
108
|
+
"android.googleapis.com",
|
|
109
|
+
"push.services.mozilla.com",
|
|
110
|
+
"notify.windows.com",
|
|
111
|
+
"push.apple.com",
|
|
112
|
+
];
|
|
113
|
+
export class PushError extends Error {
|
|
114
|
+
permanent;
|
|
115
|
+
constructor(message, permanent, cause) {
|
|
116
|
+
super(message, cause !== undefined ? { cause } : undefined);
|
|
117
|
+
this.name = "PushError";
|
|
118
|
+
this.permanent = permanent;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const CONTROL_RE = /[\x00-\x08\x0b-\x1f\x7f]/;
|
|
122
|
+
const HOST_RE = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
|
|
123
|
+
export class WebPush {
|
|
124
|
+
publicKey;
|
|
125
|
+
#o;
|
|
126
|
+
#privateKey;
|
|
127
|
+
#signing = null;
|
|
128
|
+
#lastCreated = 0;
|
|
129
|
+
constructor(o) {
|
|
130
|
+
let pub;
|
|
131
|
+
try {
|
|
132
|
+
pub = fromB64url(o.publicKey);
|
|
133
|
+
pointJwk(pub);
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
throw new Error("defineWebPush: publicKey is a base64url P-256 public key (generateVapidKeys)");
|
|
137
|
+
}
|
|
138
|
+
const priv = isSecret(o.privateKey) ? o.privateKey.reveal() : o.privateKey;
|
|
139
|
+
if (typeof priv !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(priv))
|
|
140
|
+
throw new Error("defineWebPush: privateKey is a base64url 32-byte key");
|
|
141
|
+
if (typeof o.subject !== "string" || !/^(mailto:[^\s@]+@[^\s@]+|https:\/\/\S+)$/.test(o.subject)) {
|
|
142
|
+
throw new Error("defineWebPush: subject is a mailto: address or an https URL");
|
|
143
|
+
}
|
|
144
|
+
const hosts = [...PUSH_SERVICES];
|
|
145
|
+
for (const h of o.allowHosts ?? []) {
|
|
146
|
+
if (typeof h !== "string" || !HOST_RE.test(h))
|
|
147
|
+
throw new Error(`defineWebPush: allowHosts takes host names: ${JSON.stringify(h)}`);
|
|
148
|
+
hosts.push(h);
|
|
149
|
+
}
|
|
150
|
+
const max = o.maxPerUser ?? 10;
|
|
151
|
+
if (!Number.isInteger(max) || max < 1 || max > 50)
|
|
152
|
+
throw new Error("defineWebPush: maxPerUser is 1-50");
|
|
153
|
+
const ttl = o.ttlSeconds ?? 86_400;
|
|
154
|
+
if (!Number.isInteger(ttl) || ttl < 0 || ttl > 28 * 86_400)
|
|
155
|
+
throw new Error("defineWebPush: ttlSeconds is 0-28 days");
|
|
156
|
+
this.publicKey = o.publicKey;
|
|
157
|
+
this.#privateKey = o.privateKey;
|
|
158
|
+
this.#o = {
|
|
159
|
+
subject: o.subject,
|
|
160
|
+
store: o.store ?? new MemoryPushStore(),
|
|
161
|
+
hosts,
|
|
162
|
+
max,
|
|
163
|
+
ttl,
|
|
164
|
+
fetch: o.fetch ?? ((i, init) => fetch(i, init)),
|
|
165
|
+
timeoutMs: o.timeoutMs ?? 15_000,
|
|
166
|
+
now: o.now ?? Date.now,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
allowedEndpoint(endpoint) {
|
|
170
|
+
if (typeof endpoint !== "string" || endpoint.length > 2048 || /[\x00-\x20\x7f]/.test(endpoint))
|
|
171
|
+
return false;
|
|
172
|
+
let u;
|
|
173
|
+
try {
|
|
174
|
+
u = new URL(endpoint);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
if (u.protocol !== "https:" || u.port !== "" || u.username || u.password || u.hash)
|
|
180
|
+
return false;
|
|
181
|
+
const host = u.hostname.toLowerCase();
|
|
182
|
+
if (!HOST_RE.test(host))
|
|
183
|
+
return false;
|
|
184
|
+
return this.#o.hosts.some((h) => host === h || host.endsWith(`.${h}`));
|
|
185
|
+
}
|
|
186
|
+
#parse(input) {
|
|
187
|
+
let v = input;
|
|
188
|
+
if (typeof v === "string") {
|
|
189
|
+
if (v.length > 4096)
|
|
190
|
+
throw new PushError("subscription too large", true);
|
|
191
|
+
try {
|
|
192
|
+
v = JSON.parse(v);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
throw new PushError("not a push subscription", true);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const s = v;
|
|
199
|
+
if (!s || typeof s !== "object" || !this.allowedEndpoint(s.endpoint))
|
|
200
|
+
throw new PushError("not an allowed push endpoint", true);
|
|
201
|
+
const p256dh = s.keys?.p256dh;
|
|
202
|
+
const auth = s.keys?.auth;
|
|
203
|
+
try {
|
|
204
|
+
if (typeof p256dh !== "string" || typeof auth !== "string")
|
|
205
|
+
throw new Error();
|
|
206
|
+
pointJwk(fromB64url(p256dh));
|
|
207
|
+
if (fromB64url(auth).length !== 16)
|
|
208
|
+
throw new Error();
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
throw new PushError("not a push subscription: keys.p256dh is a P-256 point, keys.auth 16 bytes", true);
|
|
212
|
+
}
|
|
213
|
+
return { endpoint: s.endpoint, p256dh, auth };
|
|
214
|
+
}
|
|
215
|
+
async subscribe(ctx, subscription) {
|
|
216
|
+
const s = await authState(ctx);
|
|
217
|
+
if (!s || s.pending)
|
|
218
|
+
throw new PushError("sign in to turn on notifications", true);
|
|
219
|
+
const sub = this.#parse(subscription);
|
|
220
|
+
const store = this.#o.store;
|
|
221
|
+
await store.remove(sub.endpoint);
|
|
222
|
+
this.#lastCreated = Math.max(this.#o.now(), this.#lastCreated + 1);
|
|
223
|
+
await store.add({ ...sub, user: s.user, created: this.#lastCreated });
|
|
224
|
+
const mine = await store.forUser(s.user);
|
|
225
|
+
for (const old of mine.sort((a, b) => a.created - b.created || (a.endpoint < b.endpoint ? -1 : 1)).slice(0, Math.max(0, mine.length - this.#o.max))) {
|
|
226
|
+
await store.remove(old.endpoint, s.user);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
async unsubscribe(ctx, endpoint) {
|
|
230
|
+
const s = await authState(ctx);
|
|
231
|
+
if (!s || s.pending || typeof endpoint !== "string")
|
|
232
|
+
return false;
|
|
233
|
+
return this.#o.store.remove(endpoint, s.user);
|
|
234
|
+
}
|
|
235
|
+
async forget(user) {
|
|
236
|
+
let n = 0;
|
|
237
|
+
for (const r of await this.#o.store.forUser(user))
|
|
238
|
+
if (await this.#o.store.remove(r.endpoint, user))
|
|
239
|
+
n++;
|
|
240
|
+
return n;
|
|
241
|
+
}
|
|
242
|
+
async #key() {
|
|
243
|
+
this.#signing ??= (async () => {
|
|
244
|
+
const d = isSecret(this.#privateKey) ? this.#privateKey.reveal() : this.#privateKey;
|
|
245
|
+
const { x, y } = pointJwk(fromB64url(this.publicKey));
|
|
246
|
+
return crypto.subtle.importKey("jwk", { kty: "EC", crv: "P-256", d, x, y, ext: false }, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
|
|
247
|
+
})();
|
|
248
|
+
return this.#signing;
|
|
249
|
+
}
|
|
250
|
+
async authorization(endpoint) {
|
|
251
|
+
const aud = new URL(endpoint).origin;
|
|
252
|
+
const enc = (o) => b64url(utf8.encode(JSON.stringify(o)));
|
|
253
|
+
const input = `${enc({ typ: "JWT", alg: "ES256" })}.${enc({ aud, exp: Math.floor(this.#o.now() / 1000) + 12 * 3600, sub: this.#o.subject })}`;
|
|
254
|
+
const sig = new Uint8Array(await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, await this.#key(), utf8.encode(input)));
|
|
255
|
+
return `vapid t=${input}.${b64url(sig)}, k=${this.publicKey}`;
|
|
256
|
+
}
|
|
257
|
+
async send(user, message) {
|
|
258
|
+
const payload = pushPayload(message);
|
|
259
|
+
const result = { sent: 0, removed: 0, failed: 0 };
|
|
260
|
+
let transient = null;
|
|
261
|
+
for (const sub of await this.#o.store.forUser(user)) {
|
|
262
|
+
if (!this.allowedEndpoint(sub.endpoint)) {
|
|
263
|
+
await this.#o.store.remove(sub.endpoint, user);
|
|
264
|
+
result.removed++;
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
const body = await encryptPushPayload(payload, { p256dh: fromB64url(sub.p256dh), auth: fromB64url(sub.auth) });
|
|
269
|
+
const res = await this.#o.fetch(sub.endpoint, {
|
|
270
|
+
method: "POST",
|
|
271
|
+
redirect: "error",
|
|
272
|
+
signal: AbortSignal.timeout(this.#o.timeoutMs),
|
|
273
|
+
headers: {
|
|
274
|
+
authorization: await this.authorization(sub.endpoint),
|
|
275
|
+
"content-encoding": "aes128gcm",
|
|
276
|
+
"content-type": "application/octet-stream",
|
|
277
|
+
ttl: String(this.#o.ttl),
|
|
278
|
+
urgency: message.urgency ?? "normal",
|
|
279
|
+
},
|
|
280
|
+
body,
|
|
281
|
+
});
|
|
282
|
+
await res.body?.cancel().catch(() => { });
|
|
283
|
+
if (res.status === 404 || res.status === 410) {
|
|
284
|
+
await this.#o.store.remove(sub.endpoint, user);
|
|
285
|
+
result.removed++;
|
|
286
|
+
}
|
|
287
|
+
else if (res.ok) {
|
|
288
|
+
result.sent++;
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
result.failed++;
|
|
292
|
+
if (res.status === 429 || res.status >= 500)
|
|
293
|
+
transient = new PushError(`push service: HTTP ${res.status}`, false);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
catch (err) {
|
|
297
|
+
result.failed++;
|
|
298
|
+
transient = new PushError(`push service: ${err instanceof Error ? err.message : String(err)}`, false, err);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (result.sent === 0 && transient)
|
|
302
|
+
throw transient;
|
|
303
|
+
return result;
|
|
304
|
+
}
|
|
305
|
+
channel(label = "Push") {
|
|
306
|
+
return {
|
|
307
|
+
label,
|
|
308
|
+
send: ({ user, notification: n }) => this.send(user, { title: n.title, body: n.body, ...(n.url && n.url.startsWith("/") ? { url: n.url } : {}), tag: n.type }),
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
worker() {
|
|
312
|
+
return new Response(PUSH_WORKER_JS, {
|
|
313
|
+
headers: {
|
|
314
|
+
"content-type": "text/javascript; charset=utf-8",
|
|
315
|
+
"cache-control": "no-cache",
|
|
316
|
+
"x-content-type-options": "nosniff",
|
|
317
|
+
},
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function pushPayload(m) {
|
|
322
|
+
if (!m || typeof m.title !== "string" || m.title === "" || m.title.length > 200 || CONTROL_RE.test(m.title) || /[\r\n]/.test(m.title)) {
|
|
323
|
+
throw new PushError("title is one line of 1-200 characters", true);
|
|
324
|
+
}
|
|
325
|
+
const body = m.body ?? "";
|
|
326
|
+
if (typeof body !== "string" || body.length > 1000 || CONTROL_RE.test(body))
|
|
327
|
+
throw new PushError("body is at most 1000 characters", true);
|
|
328
|
+
if (m.url !== undefined && (typeof m.url !== "string" || !m.url.startsWith("/") || m.url.startsWith("//") || /[\s\\]/.test(m.url) || m.url.length > 1000)) {
|
|
329
|
+
throw new PushError("url is a path on this site", true);
|
|
330
|
+
}
|
|
331
|
+
if (m.tag !== undefined && (typeof m.tag !== "string" || !/^[A-Za-z0-9._:-]{1,64}$/.test(m.tag)))
|
|
332
|
+
throw new PushError("tag is [A-Za-z0-9._:-]{1,64}", true);
|
|
333
|
+
if (m.urgency !== undefined && !["very-low", "low", "normal", "high"].includes(m.urgency))
|
|
334
|
+
throw new PushError("urgency is very-low, low, normal or high", true);
|
|
335
|
+
const bytes = utf8.encode(JSON.stringify({ title: m.title, body, url: m.url ?? "/", ...(m.tag ? { tag: m.tag } : {}) }));
|
|
336
|
+
if (bytes.length > 3072)
|
|
337
|
+
throw new PushError("the message is over 3 KiB", true);
|
|
338
|
+
return bytes;
|
|
339
|
+
}
|
|
340
|
+
export function defineWebPush(o) {
|
|
341
|
+
return new WebPush(o);
|
|
342
|
+
}
|
|
343
|
+
export const PUSH_WORKER_JS = `// Weft push worker (generated by @weft-framework/server).
|
|
344
|
+
self.addEventListener("push", (event) => {
|
|
345
|
+
let d = {};
|
|
346
|
+
try {
|
|
347
|
+
d = event.data ? event.data.json() : {};
|
|
348
|
+
} catch {
|
|
349
|
+
d = {};
|
|
350
|
+
}
|
|
351
|
+
const title = typeof d.title === "string" && d.title ? d.title : "Notification";
|
|
352
|
+
const options = { body: typeof d.body === "string" ? d.body : "", data: { url: typeof d.url === "string" ? d.url : "/" } };
|
|
353
|
+
if (typeof d.tag === "string") options.tag = d.tag;
|
|
354
|
+
event.waitUntil(self.registration.showNotification(title, options));
|
|
355
|
+
});
|
|
356
|
+
self.addEventListener("notificationclick", (event) => {
|
|
357
|
+
event.notification.close();
|
|
358
|
+
let url = new URL("/", self.location.origin).href;
|
|
359
|
+
try {
|
|
360
|
+
const u = new URL((event.notification.data && event.notification.data.url) || "/", self.location.origin);
|
|
361
|
+
if (u.origin === self.location.origin) url = u.href;
|
|
362
|
+
} catch {
|
|
363
|
+
// keep the site root
|
|
364
|
+
}
|
|
365
|
+
event.waitUntil(
|
|
366
|
+
self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((list) => {
|
|
367
|
+
for (const c of list) if (c.url === url && "focus" in c) return c.focus();
|
|
368
|
+
return self.clients.openWindow(url);
|
|
369
|
+
}),
|
|
370
|
+
);
|
|
371
|
+
});
|
|
372
|
+
`;
|
package/dist/wizard.d.ts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import type { SqlDatabase } from "@weft-framework/data";
|
|
2
|
+
import type { PageContext } from "./context.js";
|
|
3
|
+
interface FieldBase {
|
|
4
|
+
label?: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
required?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export type WizardField = (FieldBase & {
|
|
9
|
+
type: "text" | "textarea" | "email" | "url" | "tel";
|
|
10
|
+
maxLength?: number;
|
|
11
|
+
minLength?: number;
|
|
12
|
+
pattern?: RegExp;
|
|
13
|
+
placeholder?: string;
|
|
14
|
+
}) | (FieldBase & {
|
|
15
|
+
type: "number";
|
|
16
|
+
min?: number;
|
|
17
|
+
max?: number;
|
|
18
|
+
integer?: boolean;
|
|
19
|
+
}) | (FieldBase & {
|
|
20
|
+
type: "boolean";
|
|
21
|
+
}) | (FieldBase & {
|
|
22
|
+
type: "choice";
|
|
23
|
+
options: readonly string[];
|
|
24
|
+
}) | (FieldBase & {
|
|
25
|
+
type: "date";
|
|
26
|
+
min?: string;
|
|
27
|
+
max?: string;
|
|
28
|
+
});
|
|
29
|
+
export type WizardValue = string | number | boolean;
|
|
30
|
+
export type WizardValues = Record<string, WizardValue>;
|
|
31
|
+
export type WizardErrors = Record<string, string>;
|
|
32
|
+
export interface WizardStep {
|
|
33
|
+
id: string;
|
|
34
|
+
label?: string;
|
|
35
|
+
fields: Record<string, WizardField>;
|
|
36
|
+
check?(values: WizardValues, all: WizardValues, ctx: PageContext): WizardErrors | void | Promise<WizardErrors | void>;
|
|
37
|
+
when?(all: WizardValues): boolean;
|
|
38
|
+
}
|
|
39
|
+
export interface Draft {
|
|
40
|
+
step: string;
|
|
41
|
+
values: WizardValues;
|
|
42
|
+
done: string[];
|
|
43
|
+
updated: number;
|
|
44
|
+
}
|
|
45
|
+
export interface DraftStore {
|
|
46
|
+
get(wizard: string, owner: string): Draft | null | Promise<Draft | null>;
|
|
47
|
+
put(wizard: string, owner: string, draft: Draft): void | Promise<void>;
|
|
48
|
+
take(wizard: string, owner: string): Draft | null | Promise<Draft | null>;
|
|
49
|
+
sweep(before: number): number | Promise<number>;
|
|
50
|
+
}
|
|
51
|
+
export interface WizardOptions<R> {
|
|
52
|
+
name: string;
|
|
53
|
+
steps: readonly WizardStep[];
|
|
54
|
+
store: DraftStore;
|
|
55
|
+
complete(ctx: PageContext, values: WizardValues): R | Promise<R>;
|
|
56
|
+
anonymous?: boolean;
|
|
57
|
+
ttlDays?: number;
|
|
58
|
+
now?(): number;
|
|
59
|
+
}
|
|
60
|
+
export interface WizardFieldView {
|
|
61
|
+
name: string;
|
|
62
|
+
label: string;
|
|
63
|
+
description: string | null;
|
|
64
|
+
type: WizardField["type"];
|
|
65
|
+
required: boolean;
|
|
66
|
+
value: WizardValue | null;
|
|
67
|
+
options: readonly string[] | null;
|
|
68
|
+
min: number | string | null;
|
|
69
|
+
max: number | string | null;
|
|
70
|
+
maxLength: number | null;
|
|
71
|
+
}
|
|
72
|
+
export interface WizardView {
|
|
73
|
+
step: string;
|
|
74
|
+
label: string;
|
|
75
|
+
index: number;
|
|
76
|
+
total: number;
|
|
77
|
+
steps: {
|
|
78
|
+
id: string;
|
|
79
|
+
label: string;
|
|
80
|
+
done: boolean;
|
|
81
|
+
current: boolean;
|
|
82
|
+
reachable: boolean;
|
|
83
|
+
}[];
|
|
84
|
+
fields: WizardFieldView[];
|
|
85
|
+
back: string | null;
|
|
86
|
+
last: boolean;
|
|
87
|
+
saved: number | null;
|
|
88
|
+
}
|
|
89
|
+
export type WizardSave = {
|
|
90
|
+
ok: true;
|
|
91
|
+
step: string | null;
|
|
92
|
+
} | {
|
|
93
|
+
ok: false;
|
|
94
|
+
reason: "invalid";
|
|
95
|
+
errors: WizardErrors;
|
|
96
|
+
} | {
|
|
97
|
+
ok: false;
|
|
98
|
+
reason: "not-found" | "unreachable";
|
|
99
|
+
};
|
|
100
|
+
export type WizardFinish<R> = {
|
|
101
|
+
ok: true;
|
|
102
|
+
result: R;
|
|
103
|
+
} | {
|
|
104
|
+
ok: false;
|
|
105
|
+
reason: "invalid";
|
|
106
|
+
step: string;
|
|
107
|
+
errors: WizardErrors;
|
|
108
|
+
} | {
|
|
109
|
+
ok: false;
|
|
110
|
+
reason: "not-found" | "incomplete";
|
|
111
|
+
};
|
|
112
|
+
export interface Wizard<R> {
|
|
113
|
+
readonly name: string;
|
|
114
|
+
view(ctx: PageContext): Promise<WizardView | null>;
|
|
115
|
+
save(ctx: PageContext, step: string, input: unknown, o?: {
|
|
116
|
+
go?: "next" | "stay" | "back";
|
|
117
|
+
}): Promise<WizardSave>;
|
|
118
|
+
finish(ctx: PageContext): Promise<WizardFinish<R>>;
|
|
119
|
+
discard(ctx: PageContext): Promise<void>;
|
|
120
|
+
values(ctx: PageContext): Promise<WizardValues | null>;
|
|
121
|
+
sweep(): Promise<number>;
|
|
122
|
+
}
|
|
123
|
+
export declare function defineWizard<R>(o: WizardOptions<R>): Wizard<R>;
|
|
124
|
+
export declare class MemoryDraftStore implements DraftStore {
|
|
125
|
+
private readonly drafts;
|
|
126
|
+
get(wizard: string, owner: string): Draft | null;
|
|
127
|
+
put(wizard: string, owner: string, draft: Draft): void;
|
|
128
|
+
take(wizard: string, owner: string): Draft | null;
|
|
129
|
+
sweep(before: number): number;
|
|
130
|
+
}
|
|
131
|
+
export declare class SqlDraftStore implements DraftStore {
|
|
132
|
+
private readonly db;
|
|
133
|
+
private readonly table;
|
|
134
|
+
constructor(db: SqlDatabase, table?: string);
|
|
135
|
+
private decode;
|
|
136
|
+
get(wizard: string, owner: string): Draft | null;
|
|
137
|
+
put(wizard: string, owner: string, draft: Draft): void;
|
|
138
|
+
take(wizard: string, owner: string): Draft | null;
|
|
139
|
+
sweep(before: number): number;
|
|
140
|
+
}
|
|
141
|
+
export {};
|