@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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vakea
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @weft-framework/server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Weft server: live pages over WebSocket/SSE with signed sessions, CSRF, rate limiting and a strict CSP, on the Fetch API (Bun, Node, edge).
|
|
4
|
+
|
|
5
|
+
Part of Weft. MIT licensed.
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { SqlDatabase } from "@weft-framework/data";
|
|
2
|
+
import { type LoginResult } from "./auth.js";
|
|
3
|
+
import type { PageContext } from "./context.js";
|
|
4
|
+
type Maybe<T> = T | Promise<T>;
|
|
5
|
+
export type AccountTokenKind = "reset" | "email" | "signup" | "verify";
|
|
6
|
+
export interface AccountToken {
|
|
7
|
+
id: string;
|
|
8
|
+
kind: AccountTokenKind;
|
|
9
|
+
user: string;
|
|
10
|
+
email: string;
|
|
11
|
+
expires: number;
|
|
12
|
+
data?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface AccountTokenStore {
|
|
15
|
+
add(t: AccountToken): Maybe<void>;
|
|
16
|
+
get(id: string): Maybe<AccountToken | null | undefined>;
|
|
17
|
+
take(id: string): Maybe<AccountToken | null | undefined>;
|
|
18
|
+
clear(user: string, kind: AccountTokenKind): Maybe<void>;
|
|
19
|
+
sweep(now: number): Maybe<void>;
|
|
20
|
+
}
|
|
21
|
+
export declare class MemoryAccountTokenStore implements AccountTokenStore {
|
|
22
|
+
#private;
|
|
23
|
+
add(t: AccountToken): void;
|
|
24
|
+
get(id: string): AccountToken | null;
|
|
25
|
+
take(id: string): AccountToken | null;
|
|
26
|
+
clear(user: string, kind: AccountTokenKind): void;
|
|
27
|
+
sweep(now: number): void;
|
|
28
|
+
}
|
|
29
|
+
export declare class SqlAccountTokenStore implements AccountTokenStore {
|
|
30
|
+
#private;
|
|
31
|
+
constructor(db: SqlDatabase, table?: string);
|
|
32
|
+
add(t: AccountToken): void;
|
|
33
|
+
get(id: string): AccountToken | null;
|
|
34
|
+
take(id: string): AccountToken | null;
|
|
35
|
+
clear(user: string, kind: AccountTokenKind): void;
|
|
36
|
+
sweep(now: number): void;
|
|
37
|
+
}
|
|
38
|
+
export type AccountMessage = {
|
|
39
|
+
kind: "password-reset";
|
|
40
|
+
to: string;
|
|
41
|
+
link: string;
|
|
42
|
+
expires: number;
|
|
43
|
+
} | {
|
|
44
|
+
kind: "password-changed";
|
|
45
|
+
to: string;
|
|
46
|
+
} | {
|
|
47
|
+
kind: "email-change";
|
|
48
|
+
to: string;
|
|
49
|
+
link: string;
|
|
50
|
+
expires: number;
|
|
51
|
+
} | {
|
|
52
|
+
kind: "email-changed";
|
|
53
|
+
to: string;
|
|
54
|
+
newEmail: string;
|
|
55
|
+
} | {
|
|
56
|
+
kind: "sign-up";
|
|
57
|
+
to: string;
|
|
58
|
+
link: string;
|
|
59
|
+
expires: number;
|
|
60
|
+
} | {
|
|
61
|
+
kind: "account-exists";
|
|
62
|
+
to: string;
|
|
63
|
+
} | {
|
|
64
|
+
kind: "verify-email";
|
|
65
|
+
to: string;
|
|
66
|
+
link: string;
|
|
67
|
+
expires: number;
|
|
68
|
+
};
|
|
69
|
+
export type AccountErrorCode = "invalid" | "limit" | "signed-out" | "weak" | "refused" | "expired";
|
|
70
|
+
export declare class AccountError extends Error {
|
|
71
|
+
readonly code: AccountErrorCode;
|
|
72
|
+
constructor(code: AccountErrorCode, message: string);
|
|
73
|
+
}
|
|
74
|
+
export interface AccountOptions {
|
|
75
|
+
url: string;
|
|
76
|
+
send(message: AccountMessage): Maybe<void>;
|
|
77
|
+
findUser(email: string): Maybe<string | null | undefined>;
|
|
78
|
+
emailOf(user: string): Maybe<string | null | undefined>;
|
|
79
|
+
setPassword?(user: string, hash: string): Maybe<void>;
|
|
80
|
+
setEmail?(user: string, email: string): Maybe<void>;
|
|
81
|
+
resetPage?: string;
|
|
82
|
+
emailPage?: string;
|
|
83
|
+
resetTtlMs?: number;
|
|
84
|
+
emailTtlMs?: number;
|
|
85
|
+
minPasswordLength?: number;
|
|
86
|
+
checkPassword?(password: string, user: string): Maybe<string | null | undefined>;
|
|
87
|
+
perEmail?: number;
|
|
88
|
+
perSession?: number;
|
|
89
|
+
createUser?(email: string, passwordHash: string | null): Maybe<string>;
|
|
90
|
+
markVerified?(user: string, email: string): Maybe<void>;
|
|
91
|
+
allowSignUp?(email: string, ctx: PageContext): Maybe<boolean | string>;
|
|
92
|
+
clientKey?(ctx: PageContext): string | null | undefined;
|
|
93
|
+
perClient?: number;
|
|
94
|
+
minFormMs?: number;
|
|
95
|
+
signUpPage?: string;
|
|
96
|
+
verifyPage?: string;
|
|
97
|
+
signUpTtlMs?: number;
|
|
98
|
+
store?: AccountTokenStore;
|
|
99
|
+
now?: () => number;
|
|
100
|
+
}
|
|
101
|
+
export declare class Account {
|
|
102
|
+
#private;
|
|
103
|
+
constructor(o: AccountOptions);
|
|
104
|
+
requestPasswordReset(ctx: PageContext, email: string): Promise<void>;
|
|
105
|
+
checkResetToken(token: string): Promise<boolean>;
|
|
106
|
+
resetPassword(ctx: PageContext, token: string, password: string): Promise<boolean>;
|
|
107
|
+
requestEmailChange(ctx: PageContext, email: string): Promise<void>;
|
|
108
|
+
confirmEmailChange(ctx: PageContext, token: string): Promise<string | null>;
|
|
109
|
+
signUpForm(ctx: PageContext): Promise<string>;
|
|
110
|
+
signUp(ctx: PageContext, input: {
|
|
111
|
+
email: string;
|
|
112
|
+
password?: string | null;
|
|
113
|
+
form: string;
|
|
114
|
+
trap?: string | null;
|
|
115
|
+
}): Promise<void>;
|
|
116
|
+
completeSignUp(ctx: PageContext, token: string): Promise<{
|
|
117
|
+
user: string;
|
|
118
|
+
login: LoginResult;
|
|
119
|
+
} | null>;
|
|
120
|
+
requestVerification(ctx: PageContext): Promise<void>;
|
|
121
|
+
verifyEmail(token: string): Promise<boolean>;
|
|
122
|
+
}
|
|
123
|
+
export declare function defineAccount(o: AccountOptions): Account;
|
|
124
|
+
export {};
|
package/dist/account.js
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import { authState, login, signOutUser } from "./auth.js";
|
|
2
|
+
import { normalizeEmail } from "./email-signin.js";
|
|
3
|
+
import { seal, unseal } from "./seal.js";
|
|
4
|
+
import { base64url, RateLimiter } from "./security.js";
|
|
5
|
+
export class MemoryAccountTokenStore {
|
|
6
|
+
#tokens = new Map();
|
|
7
|
+
add(t) {
|
|
8
|
+
this.#tokens.set(t.id, { ...t });
|
|
9
|
+
}
|
|
10
|
+
get(id) {
|
|
11
|
+
const t = this.#tokens.get(id);
|
|
12
|
+
return t ? { ...t } : null;
|
|
13
|
+
}
|
|
14
|
+
take(id) {
|
|
15
|
+
const t = this.#tokens.get(id);
|
|
16
|
+
this.#tokens.delete(id);
|
|
17
|
+
return t ?? null;
|
|
18
|
+
}
|
|
19
|
+
clear(user, kind) {
|
|
20
|
+
for (const [id, t] of this.#tokens)
|
|
21
|
+
if (t.user === user && t.kind === kind)
|
|
22
|
+
this.#tokens.delete(id);
|
|
23
|
+
}
|
|
24
|
+
sweep(now) {
|
|
25
|
+
for (const [id, t] of this.#tokens)
|
|
26
|
+
if (t.expires <= now)
|
|
27
|
+
this.#tokens.delete(id);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export class SqlAccountTokenStore {
|
|
31
|
+
#db;
|
|
32
|
+
#t;
|
|
33
|
+
constructor(db, table = "weft_account_tokens") {
|
|
34
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table))
|
|
35
|
+
throw new Error(`@weft-framework/server: not a valid table name: ${table}`);
|
|
36
|
+
this.#db = db;
|
|
37
|
+
this.#t = `"${table}"`;
|
|
38
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${this.#t} (id TEXT PRIMARY KEY NOT NULL, kind TEXT NOT NULL, user_id TEXT NOT NULL, ` +
|
|
39
|
+
`email TEXT NOT NULL, expires INTEGER NOT NULL, data TEXT)`);
|
|
40
|
+
const cols = db.prepare(`SELECT name FROM pragma_table_info(?)`).all(table);
|
|
41
|
+
if (!cols.some((c) => c.name === "data"))
|
|
42
|
+
db.exec(`ALTER TABLE ${this.#t} ADD COLUMN data TEXT`);
|
|
43
|
+
db.exec(`CREATE INDEX IF NOT EXISTS "${table}_user" ON ${this.#t} (user_id, kind)`);
|
|
44
|
+
}
|
|
45
|
+
static #row(r) {
|
|
46
|
+
if (!r)
|
|
47
|
+
return null;
|
|
48
|
+
const t = { id: String(r.id), kind: String(r.kind), user: String(r.user_id), email: String(r.email), expires: Number(r.expires) };
|
|
49
|
+
if (r.data !== null && r.data !== undefined)
|
|
50
|
+
t.data = String(r.data);
|
|
51
|
+
return t;
|
|
52
|
+
}
|
|
53
|
+
add(t) {
|
|
54
|
+
this.#db
|
|
55
|
+
.prepare(`INSERT INTO ${this.#t} (id, kind, user_id, email, expires, data) VALUES (?, ?, ?, ?, ?, ?)`)
|
|
56
|
+
.run(t.id, t.kind, t.user, t.email, t.expires, t.data ?? null);
|
|
57
|
+
}
|
|
58
|
+
get(id) {
|
|
59
|
+
return SqlAccountTokenStore.#row(this.#db.prepare(`SELECT * FROM ${this.#t} WHERE id = ?`).all(id)[0]);
|
|
60
|
+
}
|
|
61
|
+
take(id) {
|
|
62
|
+
return SqlAccountTokenStore.#row(this.#db.prepare(`DELETE FROM ${this.#t} WHERE id = ? RETURNING id, kind, user_id, email, expires, data`).all(id)[0]);
|
|
63
|
+
}
|
|
64
|
+
clear(user, kind) {
|
|
65
|
+
this.#db.prepare(`DELETE FROM ${this.#t} WHERE user_id = ? AND kind = ?`).run(user, kind);
|
|
66
|
+
}
|
|
67
|
+
sweep(now) {
|
|
68
|
+
this.#db.prepare(`DELETE FROM ${this.#t} WHERE expires <= ?`).run(now);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export class AccountError extends Error {
|
|
72
|
+
code;
|
|
73
|
+
constructor(code, message) {
|
|
74
|
+
super(message);
|
|
75
|
+
this.name = "AccountError";
|
|
76
|
+
this.code = code;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const MAX_PASSWORD = 1024;
|
|
80
|
+
function safePath(p, name) {
|
|
81
|
+
if (typeof p !== "string" || !p.startsWith("/") || p.startsWith("//") || p.includes("\\")) {
|
|
82
|
+
throw new Error(`defineAccount: \`${name}\` is a same-origin path`);
|
|
83
|
+
}
|
|
84
|
+
return p;
|
|
85
|
+
}
|
|
86
|
+
async function tokenId(token) {
|
|
87
|
+
const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`account:${token}`));
|
|
88
|
+
return base64url(new Uint8Array(d));
|
|
89
|
+
}
|
|
90
|
+
export class Account {
|
|
91
|
+
#o;
|
|
92
|
+
#origin;
|
|
93
|
+
#store;
|
|
94
|
+
#now;
|
|
95
|
+
#resetPage;
|
|
96
|
+
#emailPage;
|
|
97
|
+
#resetTtl;
|
|
98
|
+
#emailTtl;
|
|
99
|
+
#minLength;
|
|
100
|
+
#byEmail;
|
|
101
|
+
#bySession;
|
|
102
|
+
#byClient;
|
|
103
|
+
#minForm;
|
|
104
|
+
#signUpPage;
|
|
105
|
+
#verifyPage;
|
|
106
|
+
#signUpTtl;
|
|
107
|
+
#swept = 0;
|
|
108
|
+
constructor(o) {
|
|
109
|
+
let u;
|
|
110
|
+
try {
|
|
111
|
+
u = new URL(o.url);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
throw new Error("defineAccount: `url` is the app's public origin, such as https://app.example");
|
|
115
|
+
}
|
|
116
|
+
const local = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
|
|
117
|
+
if (u.protocol !== "https:" && !(u.protocol === "http:" && local)) {
|
|
118
|
+
throw new Error("defineAccount: `url` must use https (http only for localhost)");
|
|
119
|
+
}
|
|
120
|
+
for (const k of ["send", "findUser", "emailOf"]) {
|
|
121
|
+
if (typeof o[k] !== "function")
|
|
122
|
+
throw new Error(`defineAccount: \`${k}\` is required`);
|
|
123
|
+
}
|
|
124
|
+
const range = (name, v, lo, hi) => {
|
|
125
|
+
if (!Number.isInteger(v) || v < lo || v > hi)
|
|
126
|
+
throw new Error(`defineAccount: ${name} is ${lo} to ${hi}`);
|
|
127
|
+
return v;
|
|
128
|
+
};
|
|
129
|
+
this.#o = o;
|
|
130
|
+
this.#origin = u.origin;
|
|
131
|
+
this.#store = o.store ?? new MemoryAccountTokenStore();
|
|
132
|
+
this.#now = o.now ?? Date.now;
|
|
133
|
+
this.#resetPage = safePath(o.resetPage ?? "/reset-password", "resetPage");
|
|
134
|
+
this.#emailPage = safePath(o.emailPage ?? "/confirm-email", "emailPage");
|
|
135
|
+
this.#resetTtl = range("resetTtlMs", o.resetTtlMs ?? 30 * 60_000, 5 * 60_000, 2 * 3600_000);
|
|
136
|
+
this.#emailTtl = range("emailTtlMs", o.emailTtlMs ?? 24 * 3600_000, 10 * 60_000, 7 * 24 * 3600_000);
|
|
137
|
+
this.#minLength = range("minPasswordLength", o.minPasswordLength ?? 10, 8, 128);
|
|
138
|
+
const perEmail = range("perEmail", o.perEmail ?? 3, 1, 100);
|
|
139
|
+
const perSession = range("perSession", o.perSession ?? 10, 1, 1000);
|
|
140
|
+
this.#byEmail = new RateLimiter({ capacity: perEmail, refillPerSecond: perEmail / 3600 });
|
|
141
|
+
this.#bySession = new RateLimiter({ capacity: perSession, refillPerSecond: perSession / 3600 });
|
|
142
|
+
const perClient = range("perClient", o.perClient ?? 20, 1, 10_000);
|
|
143
|
+
this.#byClient = new RateLimiter({ capacity: perClient, refillPerSecond: perClient / 3600 });
|
|
144
|
+
this.#minForm = range("minFormMs", o.minFormMs ?? 2000, 0, 60_000);
|
|
145
|
+
this.#signUpPage = safePath(o.signUpPage ?? "/sign-up/confirm", "signUpPage");
|
|
146
|
+
this.#verifyPage = safePath(o.verifyPage ?? "/verify-email", "verifyPage");
|
|
147
|
+
this.#signUpTtl = range("signUpTtlMs", o.signUpTtlMs ?? 24 * 3600_000, 10 * 60_000, 7 * 24 * 3600_000);
|
|
148
|
+
}
|
|
149
|
+
async requestPasswordReset(ctx, email) {
|
|
150
|
+
const address = this.#limit(ctx, email);
|
|
151
|
+
const user = await this.#o.findUser(address);
|
|
152
|
+
if (typeof user !== "string" || user === "")
|
|
153
|
+
return;
|
|
154
|
+
await this.#issue({ kind: "reset", user, email: address, ttl: this.#resetTtl, page: this.#resetPage, message: "password-reset" });
|
|
155
|
+
}
|
|
156
|
+
async checkResetToken(token) {
|
|
157
|
+
const t = await this.#find(token, "reset");
|
|
158
|
+
return t !== null;
|
|
159
|
+
}
|
|
160
|
+
async resetPassword(ctx, token, password) {
|
|
161
|
+
if (typeof this.#o.setPassword !== "function")
|
|
162
|
+
throw new Error("defineAccount: resetting passwords needs `setPassword`");
|
|
163
|
+
const peeked = await this.#find(token, "reset");
|
|
164
|
+
if (!peeked)
|
|
165
|
+
return false;
|
|
166
|
+
await this.#checkPassword(password, peeked.user);
|
|
167
|
+
const t = await this.#store.take(peeked.id);
|
|
168
|
+
if (!t || t.kind !== "reset" || t.expires <= this.#now())
|
|
169
|
+
return false;
|
|
170
|
+
if (normalizeEmail(await this.#o.emailOf(t.user)) !== t.email)
|
|
171
|
+
return false;
|
|
172
|
+
const { hashPassword } = await import("./password.js");
|
|
173
|
+
await this.#o.setPassword(t.user, await hashPassword(password));
|
|
174
|
+
await this.#store.clear(t.user, "reset");
|
|
175
|
+
await signOutUser(ctx, t.user);
|
|
176
|
+
await this.#o.send({ kind: "password-changed", to: t.email });
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
async requestEmailChange(ctx, email) {
|
|
180
|
+
const me = await this.#signedIn(ctx);
|
|
181
|
+
const address = this.#limit(ctx, email);
|
|
182
|
+
if (normalizeEmail(await this.#o.emailOf(me)) === address) {
|
|
183
|
+
throw new AccountError("invalid", "That is already the account's address");
|
|
184
|
+
}
|
|
185
|
+
if (await this.#taken(address))
|
|
186
|
+
return;
|
|
187
|
+
await this.#issue({ kind: "email", user: me, email: address, ttl: this.#emailTtl, page: this.#emailPage, message: "email-change" });
|
|
188
|
+
}
|
|
189
|
+
async confirmEmailChange(ctx, token) {
|
|
190
|
+
if (typeof this.#o.setEmail !== "function")
|
|
191
|
+
throw new Error("defineAccount: changing addresses needs `setEmail`");
|
|
192
|
+
const me = await this.#signedIn(ctx);
|
|
193
|
+
const peeked = await this.#find(token, "email");
|
|
194
|
+
if (!peeked || peeked.user !== me)
|
|
195
|
+
return null;
|
|
196
|
+
const t = await this.#store.take(peeked.id);
|
|
197
|
+
if (!t || t.kind !== "email" || t.user !== me || t.expires <= this.#now())
|
|
198
|
+
return null;
|
|
199
|
+
if (await this.#taken(t.email))
|
|
200
|
+
return null;
|
|
201
|
+
const old = normalizeEmail(await this.#o.emailOf(me));
|
|
202
|
+
await this.#o.setEmail(me, t.email);
|
|
203
|
+
await this.#store.clear(me, "email");
|
|
204
|
+
if (old)
|
|
205
|
+
await this.#o.send({ kind: "email-changed", to: old, newEmail: t.email });
|
|
206
|
+
return t.email;
|
|
207
|
+
}
|
|
208
|
+
async signUpForm(ctx) {
|
|
209
|
+
return seal(ctx, { t: this.#now() }, { purpose: "signup-form", ttlMs: 3600_000, session: true });
|
|
210
|
+
}
|
|
211
|
+
async signUp(ctx, input) {
|
|
212
|
+
if (typeof this.#o.createUser !== "function")
|
|
213
|
+
throw new Error("defineAccount: sign-up needs `createUser`");
|
|
214
|
+
const f = (await unseal(ctx, typeof input.form === "string" ? input.form : null, { purpose: "signup-form", session: true }));
|
|
215
|
+
if (!f || typeof f.t !== "number" || this.#now() - f.t > 3600_000)
|
|
216
|
+
throw new AccountError("expired", "Reload the page and try again");
|
|
217
|
+
if ((typeof input.trap === "string" && input.trap !== "") || this.#now() - f.t < this.#minForm)
|
|
218
|
+
return;
|
|
219
|
+
const password = input.password ?? null;
|
|
220
|
+
if (password !== null)
|
|
221
|
+
await this.#checkPassword(password, "");
|
|
222
|
+
const client = this.#o.clientKey?.(ctx);
|
|
223
|
+
if (typeof client === "string" && client !== "" && !this.#byClient.take(client, this.#now())) {
|
|
224
|
+
throw new AccountError("limit", "Too many requests; try again later");
|
|
225
|
+
}
|
|
226
|
+
const address = this.#limit(ctx, input.email);
|
|
227
|
+
if (this.#o.allowSignUp) {
|
|
228
|
+
const ok = await this.#o.allowSignUp(address, ctx);
|
|
229
|
+
if (ok !== true)
|
|
230
|
+
throw new AccountError("refused", typeof ok === "string" && ok !== "" ? ok : "This address cannot sign up");
|
|
231
|
+
}
|
|
232
|
+
if (await this.#taken(address)) {
|
|
233
|
+
await this.#o.send({ kind: "account-exists", to: address });
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
let data = "";
|
|
237
|
+
if (password !== null) {
|
|
238
|
+
const { hashPassword } = await import("./password.js");
|
|
239
|
+
data = await hashPassword(password);
|
|
240
|
+
}
|
|
241
|
+
await this.#issue({ kind: "signup", user: "", email: address, ttl: this.#signUpTtl, page: this.#signUpPage, message: "sign-up", data });
|
|
242
|
+
}
|
|
243
|
+
async completeSignUp(ctx, token) {
|
|
244
|
+
if (typeof this.#o.createUser !== "function")
|
|
245
|
+
throw new Error("defineAccount: sign-up needs `createUser`");
|
|
246
|
+
const peeked = await this.#find(token, "signup");
|
|
247
|
+
if (!peeked)
|
|
248
|
+
return null;
|
|
249
|
+
const t = await this.#store.take(peeked.id);
|
|
250
|
+
if (!t || t.kind !== "signup" || t.expires <= this.#now())
|
|
251
|
+
return null;
|
|
252
|
+
if (await this.#taken(t.email))
|
|
253
|
+
return null;
|
|
254
|
+
const user = await this.#o.createUser(t.email, t.data ? t.data : null);
|
|
255
|
+
if (typeof user !== "string" || user === "")
|
|
256
|
+
throw new Error("defineAccount: createUser must return the new user id");
|
|
257
|
+
await this.#o.markVerified?.(user, t.email);
|
|
258
|
+
return { user, login: await login(ctx, user) };
|
|
259
|
+
}
|
|
260
|
+
async requestVerification(ctx) {
|
|
261
|
+
if (typeof this.#o.markVerified !== "function")
|
|
262
|
+
throw new Error("defineAccount: verification needs `markVerified`");
|
|
263
|
+
const me = await this.#signedIn(ctx);
|
|
264
|
+
const address = this.#limit(ctx, (await this.#o.emailOf(me)) ?? "");
|
|
265
|
+
await this.#issue({ kind: "verify", user: me, email: address, ttl: this.#signUpTtl, page: this.#verifyPage, message: "verify-email" });
|
|
266
|
+
}
|
|
267
|
+
async verifyEmail(token) {
|
|
268
|
+
if (typeof this.#o.markVerified !== "function")
|
|
269
|
+
throw new Error("defineAccount: verification needs `markVerified`");
|
|
270
|
+
const peeked = await this.#find(token, "verify");
|
|
271
|
+
if (!peeked)
|
|
272
|
+
return false;
|
|
273
|
+
const t = await this.#store.take(peeked.id);
|
|
274
|
+
if (!t || t.kind !== "verify" || t.expires <= this.#now())
|
|
275
|
+
return false;
|
|
276
|
+
if (normalizeEmail(await this.#o.emailOf(t.user)) !== t.email)
|
|
277
|
+
return false;
|
|
278
|
+
await this.#o.markVerified(t.user, t.email);
|
|
279
|
+
return true;
|
|
280
|
+
}
|
|
281
|
+
#limit(ctx, email) {
|
|
282
|
+
const address = normalizeEmail(email);
|
|
283
|
+
if (!address)
|
|
284
|
+
throw new AccountError("invalid", "That is not an email address");
|
|
285
|
+
const now = this.#now();
|
|
286
|
+
if (!this.#bySession.take(ctx.session, now) || !this.#byEmail.take(address, now)) {
|
|
287
|
+
throw new AccountError("limit", "Too many requests; try again later");
|
|
288
|
+
}
|
|
289
|
+
return address;
|
|
290
|
+
}
|
|
291
|
+
async #signedIn(ctx) {
|
|
292
|
+
const s = await authState(ctx);
|
|
293
|
+
if (!s || s.pending)
|
|
294
|
+
throw new AccountError("signed-out", "Sign in first");
|
|
295
|
+
return s.user;
|
|
296
|
+
}
|
|
297
|
+
async #taken(address) {
|
|
298
|
+
const other = await this.#o.findUser(address);
|
|
299
|
+
return typeof other === "string" && other !== "";
|
|
300
|
+
}
|
|
301
|
+
async #find(token, kind) {
|
|
302
|
+
if (typeof token !== "string" || token.length < 20 || token.length > 128)
|
|
303
|
+
return null;
|
|
304
|
+
const t = await this.#store.get(await tokenId(token));
|
|
305
|
+
return t && t.kind === kind && t.expires > this.#now() ? t : null;
|
|
306
|
+
}
|
|
307
|
+
async #issue(o) {
|
|
308
|
+
const { kind, user, email, ttl, page, message } = o;
|
|
309
|
+
const now = this.#now();
|
|
310
|
+
if (now - this.#swept > 60_000) {
|
|
311
|
+
this.#swept = now;
|
|
312
|
+
await this.#store.sweep(now);
|
|
313
|
+
}
|
|
314
|
+
const token = base64url(crypto.getRandomValues(new Uint8Array(32)));
|
|
315
|
+
const id = await tokenId(token);
|
|
316
|
+
const expires = now + ttl;
|
|
317
|
+
if (user !== "")
|
|
318
|
+
await this.#store.clear(user, kind);
|
|
319
|
+
await this.#store.add({ id, kind, user, email, expires, ...(o.data !== undefined ? { data: o.data } : {}) });
|
|
320
|
+
const link = new URL(page, this.#origin);
|
|
321
|
+
link.searchParams.set("token", token);
|
|
322
|
+
try {
|
|
323
|
+
await this.#o.send({ kind: message, to: email, link: link.href, expires });
|
|
324
|
+
}
|
|
325
|
+
catch (err) {
|
|
326
|
+
await this.#store.take(id);
|
|
327
|
+
throw err;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
async #checkPassword(password, user) {
|
|
331
|
+
if (typeof password !== "string" || [...password].length < this.#minLength) {
|
|
332
|
+
throw new AccountError("weak", `Use at least ${this.#minLength} characters`);
|
|
333
|
+
}
|
|
334
|
+
if (new TextEncoder().encode(password).length > MAX_PASSWORD) {
|
|
335
|
+
throw new AccountError("weak", `Use at most ${MAX_PASSWORD} bytes`);
|
|
336
|
+
}
|
|
337
|
+
const reason = await this.#o.checkPassword?.(password, user);
|
|
338
|
+
if (typeof reason === "string" && reason !== "")
|
|
339
|
+
throw new AccountError("weak", reason);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
export function defineAccount(o) {
|
|
343
|
+
return new Account(o);
|
|
344
|
+
}
|
package/dist/action.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { PageContext } from "./context.js";
|
|
2
|
+
export { Redirect, redirect } from "./live.js";
|
|
3
|
+
export type { PageContext };
|
|
4
|
+
export type ParamType = "string" | "number" | "boolean";
|
|
5
|
+
export interface ParamSpec {
|
|
6
|
+
name: string;
|
|
7
|
+
type: ParamType;
|
|
8
|
+
list?: boolean;
|
|
9
|
+
optional?: boolean;
|
|
10
|
+
held?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export type ActionContext = PageContext;
|
|
13
|
+
declare const ACTION: unique symbol;
|
|
14
|
+
declare const BOUND: unique symbol;
|
|
15
|
+
export interface Action<A extends unknown[] = never[], R = unknown> {
|
|
16
|
+
readonly [ACTION]: true;
|
|
17
|
+
readonly name: string;
|
|
18
|
+
readonly params: readonly ParamSpec[];
|
|
19
|
+
run(ctx: ActionContext, ...args: A): R | Promise<R>;
|
|
20
|
+
with(...held: unknown[]): BoundAction;
|
|
21
|
+
}
|
|
22
|
+
export interface BoundAction {
|
|
23
|
+
readonly [BOUND]: true;
|
|
24
|
+
readonly name: string;
|
|
25
|
+
readonly args: readonly unknown[];
|
|
26
|
+
}
|
|
27
|
+
export declare function heldCount(params: readonly ParamSpec[]): number;
|
|
28
|
+
export declare function defineAction<A extends unknown[], R>(name: string, params: readonly ParamSpec[], run: (ctx: ActionContext, ...args: A) => R | Promise<R>): Action<A, R>;
|
|
29
|
+
export declare function isAction(v: unknown): v is Action<unknown[]>;
|
|
30
|
+
export declare class ActionError extends Error {
|
|
31
|
+
readonly status: number;
|
|
32
|
+
constructor(message: string, status?: number);
|
|
33
|
+
}
|
|
34
|
+
export declare function fail(message: string, status?: number): never;
|
|
35
|
+
export type Decoded = {
|
|
36
|
+
ok: true;
|
|
37
|
+
args: unknown[];
|
|
38
|
+
} | {
|
|
39
|
+
ok: false;
|
|
40
|
+
error: string;
|
|
41
|
+
};
|
|
42
|
+
export declare function decodeForm(params: readonly ParamSpec[], form: FormData | URLSearchParams): Decoded;
|
|
43
|
+
export declare function decodeJson(params: readonly ParamSpec[], body: unknown): Decoded;
|
package/dist/action.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
export { Redirect, redirect } from "./live.js";
|
|
2
|
+
const ACTION = Symbol.for("weft.action");
|
|
3
|
+
const BOUND = Symbol.for("weft.boundAction");
|
|
4
|
+
export function heldCount(params) {
|
|
5
|
+
let n = 0;
|
|
6
|
+
while (n < params.length && params[n].held)
|
|
7
|
+
n++;
|
|
8
|
+
return n;
|
|
9
|
+
}
|
|
10
|
+
export function defineAction(name, params, run) {
|
|
11
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name)) {
|
|
12
|
+
throw new Error(`@weft-framework/server: invalid action name: ${name}`);
|
|
13
|
+
}
|
|
14
|
+
const seen = new Set();
|
|
15
|
+
for (const p of params) {
|
|
16
|
+
if (seen.has(p.name) || p.name.startsWith("_weft")) {
|
|
17
|
+
throw new Error(`@weft-framework/server: action ${name}: bad parameter ${p.name}`);
|
|
18
|
+
}
|
|
19
|
+
seen.add(p.name);
|
|
20
|
+
}
|
|
21
|
+
const held = heldCount(params);
|
|
22
|
+
if (params.slice(held).some((p) => p.held) || params.slice(0, held).some((p) => p.optional)) {
|
|
23
|
+
throw new Error(`@weft-framework/server: action ${name}: held parameters come first and are never optional`);
|
|
24
|
+
}
|
|
25
|
+
const specs = Object.freeze(params.map((p) => Object.freeze({ ...p })));
|
|
26
|
+
const bind = (...args) => {
|
|
27
|
+
if (held === 0)
|
|
28
|
+
throw new Error(`@weft-framework/server: ${name}.with(..): the action has no Held<T> parameters`);
|
|
29
|
+
if (args.length !== held)
|
|
30
|
+
throw new Error(`@weft-framework/server: ${name}.with(..): expected ${held} held value(s), got ${args.length}`);
|
|
31
|
+
const checked = decodeJson(specs.slice(0, held), Object.fromEntries(specs.slice(0, held).map((p, i) => [p.name, args[i]])));
|
|
32
|
+
if (!checked.ok)
|
|
33
|
+
throw new Error(`@weft-framework/server: ${name}.with(..): ${checked.error}`);
|
|
34
|
+
return Object.freeze({ [BOUND]: true, name, args: Object.freeze(checked.args) });
|
|
35
|
+
};
|
|
36
|
+
return Object.freeze({ [ACTION]: true, name, params: specs, run, with: bind });
|
|
37
|
+
}
|
|
38
|
+
export function isAction(v) {
|
|
39
|
+
return typeof v === "object" && v !== null && v[ACTION] === true;
|
|
40
|
+
}
|
|
41
|
+
export class ActionError extends Error {
|
|
42
|
+
status;
|
|
43
|
+
constructor(message, status = 400) {
|
|
44
|
+
super(message);
|
|
45
|
+
this.status = status;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export function fail(message, status = 400) {
|
|
49
|
+
throw new ActionError(message, status);
|
|
50
|
+
}
|
|
51
|
+
export function decodeForm(params, form) {
|
|
52
|
+
const args = [];
|
|
53
|
+
for (const p of params) {
|
|
54
|
+
const raw = form.getAll(p.name);
|
|
55
|
+
if (raw.some((v) => typeof v !== "string")) {
|
|
56
|
+
return { ok: false, error: `${p.name}: files are not accepted` };
|
|
57
|
+
}
|
|
58
|
+
const values = raw;
|
|
59
|
+
if (p.type === "boolean" && !p.list) {
|
|
60
|
+
args.push(values.length > 0 && !["false", "0", "off"].includes(values[0]));
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (p.list) {
|
|
64
|
+
const out = [];
|
|
65
|
+
for (const v of values) {
|
|
66
|
+
const one = fromString(p, v);
|
|
67
|
+
if (one === INVALID) {
|
|
68
|
+
return { ok: false, error: `${p.name}: expected ${p.type} values` };
|
|
69
|
+
}
|
|
70
|
+
out.push(one);
|
|
71
|
+
}
|
|
72
|
+
args.push(out);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const v = values[0];
|
|
76
|
+
if (v === undefined || (v === "" && p.type !== "string")) {
|
|
77
|
+
if (!p.optional) {
|
|
78
|
+
return { ok: false, error: `${p.name} is required` };
|
|
79
|
+
}
|
|
80
|
+
args.push(undefined);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const one = fromString(p, v);
|
|
84
|
+
if (one === INVALID) {
|
|
85
|
+
return { ok: false, error: `${p.name}: expected a ${p.type}` };
|
|
86
|
+
}
|
|
87
|
+
args.push(one);
|
|
88
|
+
}
|
|
89
|
+
return { ok: true, args };
|
|
90
|
+
}
|
|
91
|
+
const INVALID = Symbol("invalid");
|
|
92
|
+
function fromString(p, v) {
|
|
93
|
+
switch (p.type) {
|
|
94
|
+
case "string":
|
|
95
|
+
return v;
|
|
96
|
+
case "number": {
|
|
97
|
+
const n = v.trim() === "" ? NaN : Number(v);
|
|
98
|
+
return Number.isFinite(n) ? n : INVALID;
|
|
99
|
+
}
|
|
100
|
+
case "boolean":
|
|
101
|
+
return v === "true" ? true : v === "false" ? false : INVALID;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
export function decodeJson(params, body) {
|
|
105
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
106
|
+
return { ok: false, error: "expected an object of arguments" };
|
|
107
|
+
}
|
|
108
|
+
const obj = body;
|
|
109
|
+
const known = new Set(params.map((p) => p.name));
|
|
110
|
+
for (const k of Object.keys(obj)) {
|
|
111
|
+
if (!known.has(k)) {
|
|
112
|
+
return { ok: false, error: `unknown argument ${k}` };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const args = [];
|
|
116
|
+
for (const p of params) {
|
|
117
|
+
const v = Object.hasOwn(obj, p.name) ? obj[p.name] : undefined;
|
|
118
|
+
if (v === undefined || v === null) {
|
|
119
|
+
if (!p.optional) {
|
|
120
|
+
return { ok: false, error: `${p.name} is required` };
|
|
121
|
+
}
|
|
122
|
+
args.push(undefined);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const ok = p.list ? Array.isArray(v) && v.every((x) => isType(p.type, x)) : isType(p.type, v);
|
|
126
|
+
if (!ok) {
|
|
127
|
+
return { ok: false, error: `${p.name}: expected ${p.list ? `${p.type}[]` : p.type}` };
|
|
128
|
+
}
|
|
129
|
+
args.push(p.list ? [...v] : v);
|
|
130
|
+
}
|
|
131
|
+
return { ok: true, args };
|
|
132
|
+
}
|
|
133
|
+
function isType(t, v) {
|
|
134
|
+
return t === "number" ? typeof v === "number" && Number.isFinite(v) : typeof v === t;
|
|
135
|
+
}
|