@weft-framework/server 0.0.3 → 0.0.5
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/dist/auth.d.ts +13 -1
- package/dist/auth.js +1 -0
- package/dist/config.js +2 -2
- package/dist/db-backup.js +3 -0
- package/dist/explain.js +13 -4
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/jobs.d.ts +2 -0
- package/dist/jobs.js +2 -1
- package/dist/migrate.d.ts +2 -0
- package/dist/migrate.js +35 -0
- package/dist/personal-data.js +2 -2
- package/dist/pg-stores.d.ts +109 -0
- package/dist/pg-stores.js +431 -0
- package/dist/project.js +7 -1
- package/dist/storage.d.ts +4 -0
- package/dist/storage.js +40 -5
- package/package.json +7 -3
package/dist/auth.d.ts
CHANGED
|
@@ -72,6 +72,17 @@ export declare class MemorySessionStore implements SessionStore {
|
|
|
72
72
|
}[];
|
|
73
73
|
get size(): number;
|
|
74
74
|
}
|
|
75
|
+
/** @internal */
|
|
76
|
+
export interface SessionRow {
|
|
77
|
+
user: string;
|
|
78
|
+
created: number | bigint;
|
|
79
|
+
seen: number | bigint;
|
|
80
|
+
tenant: string | null;
|
|
81
|
+
pending: number | bigint | null;
|
|
82
|
+
mfa: number | bigint | null;
|
|
83
|
+
agent: string | null;
|
|
84
|
+
view_as?: string | null;
|
|
85
|
+
}
|
|
75
86
|
export declare class SqlSessionStore implements SessionStore {
|
|
76
87
|
private readonly db;
|
|
77
88
|
private readonly table;
|
|
@@ -81,7 +92,8 @@ export declare class SqlSessionStore implements SessionStore {
|
|
|
81
92
|
sid: string;
|
|
82
93
|
record: SessionRecord;
|
|
83
94
|
}[];
|
|
84
|
-
|
|
95
|
+
/** @internal Shared with `PgSessionStore`. */
|
|
96
|
+
static record(row: SessionRow): SessionRecord;
|
|
85
97
|
set(sid: string, r: SessionRecord): void;
|
|
86
98
|
delete(sid: string): void;
|
|
87
99
|
sweep(before: number): void;
|
package/dist/auth.js
CHANGED
|
@@ -72,6 +72,7 @@ export class SqlSessionStore {
|
|
|
72
72
|
.all(user);
|
|
73
73
|
return rows.map((row) => ({ sid: String(row.sid), record: SqlSessionStore.record(row) }));
|
|
74
74
|
}
|
|
75
|
+
/** @internal Shared with `PgSessionStore`. */
|
|
75
76
|
static record(row) {
|
|
76
77
|
const rec = { user: String(row.user), created: Number(row.created), seen: Number(row.seen) };
|
|
77
78
|
if (row.tenant !== null) {
|
package/dist/config.js
CHANGED
|
@@ -82,8 +82,8 @@ export function parseConfig(raw) {
|
|
|
82
82
|
src.database.trim() === "" ||
|
|
83
83
|
src.database.length > 1024 ||
|
|
84
84
|
src.database.includes("\0") ||
|
|
85
|
-
/^[a-z][a-z0-9+.-]*:\/\//i.test(src.database)) {
|
|
86
|
-
fail('database must be a file path (relative to the project)
|
|
85
|
+
(/^[a-z][a-z0-9+.-]*:\/\//i.test(src.database) && !/^postgres(ql)?:\/\//i.test(src.database))) {
|
|
86
|
+
fail('database must be a SQLite file path (relative to the project), ":memory:", a postgres:// URL or pglite:<dir>');
|
|
87
87
|
}
|
|
88
88
|
out.database = src.database;
|
|
89
89
|
}
|
package/dist/db-backup.js
CHANGED
|
@@ -26,6 +26,9 @@ export async function backupProject(root, compiler, cmd) {
|
|
|
26
26
|
if (database === undefined || database === ":memory:") {
|
|
27
27
|
throw new BackupCommandError("no `database` file in weft.config.ts; there is nothing to back up");
|
|
28
28
|
}
|
|
29
|
+
if (/^postgres(ql)?:\/\//i.test(database) || database.startsWith("pglite:")) {
|
|
30
|
+
throw new BackupCommandError("`weft db` backs up SQLite files; for Postgres use definePgBackups (pg_dump) from @weft-framework/server/backup");
|
|
31
|
+
}
|
|
29
32
|
const file = ["backup.ts", "backup.js"].map((name) => join(outDir, name)).find((f) => existsSync(f));
|
|
30
33
|
if (!file) {
|
|
31
34
|
throw new BackupCommandError("no src/backup.ts; export `target` from it (dirBackups(...) or s3Backups(...))");
|
package/dist/explain.js
CHANGED
|
@@ -157,10 +157,19 @@ export async function explainProject(root, opts) {
|
|
|
157
157
|
if (project.database === undefined || project.database === ":memory:") {
|
|
158
158
|
throw new ExplainError("--tenant needs a `database` file in weft.config.ts");
|
|
159
159
|
}
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
160
|
+
const pg = await import("@weft-framework/data/postgres");
|
|
161
|
+
if (pg.isPostgresUrl(project.database)) {
|
|
162
|
+
const pool = await pg.openPostgres(project.database);
|
|
163
|
+
close = () => void pool.end();
|
|
164
|
+
// Access models are `replica: true`: their rows are loaded into memory for sync reads.
|
|
165
|
+
await pg.usePostgres(pool, models, { migrate: false, onWarning: () => { } });
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
const { openSqlite } = await import("@weft-framework/data/sqlite");
|
|
169
|
+
const db = openSqlite(project.database, { readOnly: true });
|
|
170
|
+
close = () => db.close();
|
|
171
|
+
useDatabase(db, models, { migrate: false, onWarning: () => { } });
|
|
172
|
+
}
|
|
164
173
|
}
|
|
165
174
|
try {
|
|
166
175
|
const parts = [];
|
package/dist/index.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export { LivePage, Redirect, redirect } from "./live.js";
|
|
|
11
11
|
export { ActionError, decodeForm, decodeJson, defineAction, fail, isAction } from "./action.js";
|
|
12
12
|
export type { Action, ActionContext, Decoded, ParamSpec, ParamType } from "./action.js";
|
|
13
13
|
export type { LivePageOptions } from "./live.js";
|
|
14
|
-
export { MIN_SECRET_LENGTH, RateLimiter, csrfToken, importSecret, parseCookies, randomId, sameOrigin, securityHeaders, checkCspSources, type CspSources, sessionCookie, signSession, timingSafeEqual, verifyCsrf, verifySession, } from "./security.js";
|
|
14
|
+
export { MIN_SECRET_LENGTH, RateLimiter, csrfToken, importSecret, parseCookies, randomId, sameOrigin, securityHeaders, checkCspSources, mergeCspSources, type CspSources, sessionCookie, signSession, timingSafeEqual, verifyCsrf, verifySession, } from "./security.js";
|
|
15
15
|
export type { RateLimitOptions, HeaderOptions, CookieOptions } from "./security.js";
|
|
16
16
|
export { external } from "./api.js";
|
|
17
17
|
export type { ApiHandler, ApiHandlers, ApiMethod } from "./api.js";
|
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ export { Router, parsePattern, patternForFile, splitPath } from "./router.js";
|
|
|
5
5
|
export { DEFAULT_SHELL, parseShell } from "./shell.js";
|
|
6
6
|
export { LivePage, Redirect, redirect } from "./live.js";
|
|
7
7
|
export { ActionError, decodeForm, decodeJson, defineAction, fail, isAction } from "./action.js";
|
|
8
|
-
export { MIN_SECRET_LENGTH, RateLimiter, csrfToken, importSecret, parseCookies, randomId, sameOrigin, securityHeaders, checkCspSources, sessionCookie, signSession, timingSafeEqual, verifyCsrf, verifySession, } from "./security.js";
|
|
8
|
+
export { MIN_SECRET_LENGTH, RateLimiter, csrfToken, importSecret, parseCookies, randomId, sameOrigin, securityHeaders, checkCspSources, mergeCspSources, sessionCookie, signSession, timingSafeEqual, verifyCsrf, verifySession, } from "./security.js";
|
|
9
9
|
export { external } from "./api.js";
|
|
10
10
|
export { MemorySessionStore, login, logout, switchTenant, viewAs, stopViewingAs, viewingAs, allowWhileViewing } from "./auth.js";
|
|
11
11
|
export { github, google, microsoft, oidc, SignInError } from "./oauth.js";
|
package/dist/jobs.d.ts
CHANGED
|
@@ -70,6 +70,8 @@ export declare class MemoryJobStore implements JobStore {
|
|
|
70
70
|
counts(): Record<JobStatus, number>;
|
|
71
71
|
sweep(before: number): void;
|
|
72
72
|
}
|
|
73
|
+
/** @internal Shared by `SqlJobStore` and `PgJobStore`. */
|
|
74
|
+
export declare function jobFromRow(r: Record<string, unknown> | undefined): JobRecord | null;
|
|
73
75
|
export declare class SqlJobStore implements JobStore {
|
|
74
76
|
#private;
|
|
75
77
|
constructor(db: SqlDatabase, table?: string);
|
package/dist/jobs.js
CHANGED
package/dist/migrate.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ export interface MigrateCommandOptions {
|
|
|
7
7
|
}
|
|
8
8
|
export declare class MigrateError extends Error {
|
|
9
9
|
}
|
|
10
|
+
/** Hide the password of a database URL before printing it. */
|
|
11
|
+
export declare function redactUrl(database: string): string;
|
|
10
12
|
export declare function migrateProject(root: string, opts: MigrateCommandOptions): Promise<MigrationPlan & {
|
|
11
13
|
database: string;
|
|
12
14
|
}>;
|
package/dist/migrate.js
CHANGED
|
@@ -9,6 +9,18 @@ import { ConfigError } from "./config.js";
|
|
|
9
9
|
import { ProjectError, loadProject } from "./project.js";
|
|
10
10
|
export class MigrateError extends Error {
|
|
11
11
|
}
|
|
12
|
+
/** Hide the password of a database URL before printing it. */
|
|
13
|
+
export function redactUrl(database) {
|
|
14
|
+
try {
|
|
15
|
+
const u = new URL(database);
|
|
16
|
+
if (u.password)
|
|
17
|
+
u.password = "***";
|
|
18
|
+
return u.toString();
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return database;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
12
24
|
export async function migrateProject(root, opts) {
|
|
13
25
|
root = resolve(root);
|
|
14
26
|
const outDir = join(root, ".weft", "migrate", randomUUID());
|
|
@@ -18,6 +30,29 @@ export async function migrateProject(root, opts) {
|
|
|
18
30
|
throw new MigrateError("no `database` in weft.config.ts; models are kept in memory");
|
|
19
31
|
}
|
|
20
32
|
const models = Object.values(project.models);
|
|
33
|
+
const pg = await import("@weft-framework/data/postgres");
|
|
34
|
+
if (pg.isPostgresUrl(project.database)) {
|
|
35
|
+
const pool = await pg.openPostgres(project.database);
|
|
36
|
+
try {
|
|
37
|
+
let plan;
|
|
38
|
+
if (opts.dryRun) {
|
|
39
|
+
const client = await pool.connect();
|
|
40
|
+
try {
|
|
41
|
+
plan = await pg.planPgMigrations(client, models, { destructive: opts.destructive });
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
client.release();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
plan = await pg.migratePg(pool, models, { destructive: opts.destructive });
|
|
49
|
+
}
|
|
50
|
+
return { ...plan, database: redactUrl(project.database) };
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
await pool.end();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
21
56
|
const { openSqlite } = await import("@weft-framework/data/sqlite");
|
|
22
57
|
if (project.database !== ":memory:") {
|
|
23
58
|
mkdirSync(dirname(project.database), { recursive: true });
|
package/dist/personal-data.js
CHANGED
|
@@ -44,7 +44,7 @@ export async function personalDataCommand(root, opts) {
|
|
|
44
44
|
const key = keyField && keyField.type === "number" && /^-?\d+$/.test(opts.key) ? Number(opts.key) : opts.key;
|
|
45
45
|
let data;
|
|
46
46
|
try {
|
|
47
|
-
data = personalData(models, subject, key, { plan: opts.plan ?? {} });
|
|
47
|
+
data = await personalData(models, subject, key, { plan: opts.plan ?? {} });
|
|
48
48
|
}
|
|
49
49
|
catch (err) {
|
|
50
50
|
throw new PersonalDataError(err instanceof Error ? err.message.replace(/^personalData: /, "") : String(err));
|
|
@@ -53,7 +53,7 @@ export async function personalDataCommand(root, opts) {
|
|
|
53
53
|
const { steps: _steps, ...visible } = data;
|
|
54
54
|
if (opts.command === "export" || opts.dryRun)
|
|
55
55
|
return { data: visible, summary };
|
|
56
|
-
return { data: visible, erased: eraseData(data), summary };
|
|
56
|
+
return { data: visible, erased: await eraseData(data), summary };
|
|
57
57
|
}
|
|
58
58
|
finally {
|
|
59
59
|
storage.close();
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { type PgPool } from "@weft-framework/data/postgres";
|
|
2
|
+
import type { AccountToken, AccountTokenKind, AccountTokenStore } from "./account.js";
|
|
3
|
+
import { type SessionRecord, type SessionStore } from "./auth.js";
|
|
4
|
+
import type { EmailToken, EmailTokenStore } from "./email-signin.js";
|
|
5
|
+
import { type JobFilter, type JobRecord, type JobStatus, type JobStore } from "./jobs.js";
|
|
6
|
+
import type { PasskeyCredential, PasskeyStore } from "./passkey.js";
|
|
7
|
+
import type { TwoFactorRecord, TwoFactorStore } from "./two-factor.js";
|
|
8
|
+
import type { FileRecord, FileStore } from "./uploads.js";
|
|
9
|
+
import type { WebhookKind, WebhookStore } from "./webhooks.js";
|
|
10
|
+
type Row = Record<string, unknown>;
|
|
11
|
+
declare abstract class PgStore {
|
|
12
|
+
#private;
|
|
13
|
+
/** The quoted table name. */
|
|
14
|
+
protected readonly t: string;
|
|
15
|
+
constructor(pool: PgPool, table: string, ddl: (t: string, name: string) => string[]);
|
|
16
|
+
protected q<R = Row>(sql: string, params?: unknown[]): Promise<R[]>;
|
|
17
|
+
protected atomically<R>(fn: () => Promise<R>): Promise<R>;
|
|
18
|
+
}
|
|
19
|
+
export declare class PgSessionStore extends PgStore implements SessionStore {
|
|
20
|
+
constructor(pool: PgPool, table?: string);
|
|
21
|
+
get(sid: string): Promise<SessionRecord | null>;
|
|
22
|
+
forUser(user: string): Promise<{
|
|
23
|
+
sid: string;
|
|
24
|
+
record: SessionRecord;
|
|
25
|
+
}[]>;
|
|
26
|
+
set(sid: string, r: SessionRecord): Promise<void>;
|
|
27
|
+
delete(sid: string): Promise<void>;
|
|
28
|
+
sweep(before: number): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export declare class PgJobStore extends PgStore implements JobStore {
|
|
31
|
+
constructor(pool: PgPool, table?: string);
|
|
32
|
+
add(r: JobRecord): Promise<boolean>;
|
|
33
|
+
get(id: string): Promise<JobRecord | null>;
|
|
34
|
+
claim(now: number, worker: string, leaseUntil: number): Promise<JobRecord | null>;
|
|
35
|
+
extend(id: string, worker: string, leaseUntil: number, progress: number | null): Promise<boolean>;
|
|
36
|
+
settle(id: string, worker: string, to: {
|
|
37
|
+
status: "queued" | "done" | "dead";
|
|
38
|
+
runAt?: number;
|
|
39
|
+
error?: string | null;
|
|
40
|
+
}, now: number): Promise<boolean>;
|
|
41
|
+
move(id: string, from: JobStatus[], to: {
|
|
42
|
+
status: "queued" | "cancelled";
|
|
43
|
+
runAt?: number;
|
|
44
|
+
attempts?: number;
|
|
45
|
+
}, now: number): Promise<boolean>;
|
|
46
|
+
list(f: JobFilter): Promise<JobRecord[]>;
|
|
47
|
+
counts(): Promise<Record<JobStatus, number>>;
|
|
48
|
+
sweep(before: number): Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
export declare class PgPasskeyStore extends PgStore implements PasskeyStore {
|
|
51
|
+
constructor(pool: PgPool, table?: string);
|
|
52
|
+
add(c: PasskeyCredential): Promise<void>;
|
|
53
|
+
get(id: string): Promise<PasskeyCredential | null>;
|
|
54
|
+
list(user: string): Promise<PasskeyCredential[]>;
|
|
55
|
+
update(id: string, patch: Partial<Pick<PasskeyCredential, "signCount" | "lastUsed" | "backedUp" | "name">>): Promise<void>;
|
|
56
|
+
remove(id: string): Promise<boolean>;
|
|
57
|
+
}
|
|
58
|
+
export declare class PgTwoFactorStore extends PgStore implements TwoFactorStore {
|
|
59
|
+
#private;
|
|
60
|
+
constructor(pool: PgPool, table?: string);
|
|
61
|
+
get(user: string): Promise<TwoFactorRecord | null>;
|
|
62
|
+
add(r: TwoFactorRecord): Promise<boolean>;
|
|
63
|
+
remove(user: string): Promise<boolean>;
|
|
64
|
+
advance(user: string, step: number): Promise<boolean>;
|
|
65
|
+
fail(user: string, max: number, until: number): Promise<boolean>;
|
|
66
|
+
succeed(user: string): Promise<void>;
|
|
67
|
+
setRecovery(user: string, hashes: string[]): Promise<void>;
|
|
68
|
+
useRecovery(user: string, hash: string): Promise<boolean>;
|
|
69
|
+
countRecovery(user: string): Promise<number>;
|
|
70
|
+
}
|
|
71
|
+
export declare class PgEmailTokenStore extends PgStore implements EmailTokenStore {
|
|
72
|
+
constructor(pool: PgPool, table?: string);
|
|
73
|
+
add(t: EmailToken): Promise<void>;
|
|
74
|
+
get(id: string): Promise<EmailToken | null>;
|
|
75
|
+
find(session: string, email: string): Promise<EmailToken | null>;
|
|
76
|
+
attempt(id: string): Promise<number>;
|
|
77
|
+
take(id: string): Promise<boolean>;
|
|
78
|
+
clear(session: string, email: string): Promise<void>;
|
|
79
|
+
sweep(now: number): Promise<void>;
|
|
80
|
+
}
|
|
81
|
+
export declare class PgAccountTokenStore extends PgStore implements AccountTokenStore {
|
|
82
|
+
constructor(pool: PgPool, table?: string);
|
|
83
|
+
add(t: AccountToken): Promise<void>;
|
|
84
|
+
get(id: string): Promise<AccountToken | null>;
|
|
85
|
+
take(id: string): Promise<AccountToken | null>;
|
|
86
|
+
clear(user: string, kind: AccountTokenKind): Promise<void>;
|
|
87
|
+
sweep(now: number): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
export declare class PgFileStore extends PgStore implements FileStore {
|
|
90
|
+
constructor(pool: PgPool, table?: string);
|
|
91
|
+
put(r: FileRecord): Promise<void>;
|
|
92
|
+
get(id: string): Promise<FileRecord | null>;
|
|
93
|
+
remove(id: string): Promise<void>;
|
|
94
|
+
pending(owner: string): Promise<number>;
|
|
95
|
+
stale(uploadingBefore: number, unclaimedBefore: number, limit: number): Promise<FileRecord[]>;
|
|
96
|
+
}
|
|
97
|
+
export declare class PgWebhookStore extends PgStore implements WebhookStore {
|
|
98
|
+
constructor(pool: PgPool, table?: string);
|
|
99
|
+
put(kind: WebhookKind, id: string, owner: string, ref: string | null, created: number, data: string): Promise<void>;
|
|
100
|
+
get(kind: WebhookKind, id: string): Promise<string | null>;
|
|
101
|
+
list(kind: WebhookKind, owner: string, o: {
|
|
102
|
+
ref?: string;
|
|
103
|
+
limit: number;
|
|
104
|
+
before?: number;
|
|
105
|
+
}): Promise<string[]>;
|
|
106
|
+
remove(kind: WebhookKind, id: string): Promise<void>;
|
|
107
|
+
sweep(kind: WebhookKind, before: number, owner?: string): Promise<number>;
|
|
108
|
+
}
|
|
109
|
+
export {};
|
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
import { asyncTransaction, enlistAsync } from "@weft-framework/data";
|
|
2
|
+
import { numbered } from "@weft-framework/data/postgres";
|
|
3
|
+
import { SqlSessionStore } from "./auth.js";
|
|
4
|
+
import { jobFromRow } from "./jobs.js";
|
|
5
|
+
const TABLE_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
6
|
+
const SETUP_LOCK = 0x77656674; // "weft"
|
|
7
|
+
class PgStore {
|
|
8
|
+
#pool;
|
|
9
|
+
#ddl;
|
|
10
|
+
#ready = null;
|
|
11
|
+
/** The quoted table name. */
|
|
12
|
+
t;
|
|
13
|
+
constructor(pool, table, ddl) {
|
|
14
|
+
if (!TABLE_RE.test(table))
|
|
15
|
+
throw new Error(`@weft-framework/server: not a valid table name: ${table}`);
|
|
16
|
+
this.#pool = pool;
|
|
17
|
+
this.t = `"${table}"`;
|
|
18
|
+
this.#ddl = ddl(this.t, table);
|
|
19
|
+
}
|
|
20
|
+
async #setup() {
|
|
21
|
+
const c = await this.#pool.connect();
|
|
22
|
+
try {
|
|
23
|
+
await c.query("BEGIN");
|
|
24
|
+
await c.query("SELECT pg_advisory_xact_lock($1)", [SETUP_LOCK]);
|
|
25
|
+
for (const sql of this.#ddl)
|
|
26
|
+
await c.query(sql);
|
|
27
|
+
await c.query("COMMIT");
|
|
28
|
+
}
|
|
29
|
+
catch (e) {
|
|
30
|
+
await c.query("ROLLBACK").catch(() => { });
|
|
31
|
+
throw e;
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
c.release?.();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async q(sql, params = []) {
|
|
38
|
+
if (!this.#ready) {
|
|
39
|
+
this.#ready = this.#setup();
|
|
40
|
+
this.#ready.catch(() => (this.#ready = null));
|
|
41
|
+
}
|
|
42
|
+
await this.#ready;
|
|
43
|
+
const text = numbered(sql);
|
|
44
|
+
const tx = enlistAsync(this.#pool);
|
|
45
|
+
const res = tx ? await (await tx).query(text, params) : await this.#pool.query(text, params);
|
|
46
|
+
return res.rows;
|
|
47
|
+
}
|
|
48
|
+
atomically(fn) {
|
|
49
|
+
return asyncTransaction(fn);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const num = (v) => Number(v);
|
|
53
|
+
export class PgSessionStore extends PgStore {
|
|
54
|
+
constructor(pool, table = "weft_sessions") {
|
|
55
|
+
super(pool, table, (t, name) => [
|
|
56
|
+
`CREATE TABLE IF NOT EXISTS ${t} (sid text PRIMARY KEY NOT NULL, "user" text NOT NULL, created bigint NOT NULL, ` +
|
|
57
|
+
`seen bigint NOT NULL, tenant text, pending integer, mfa integer, agent text, view_as text)`,
|
|
58
|
+
`CREATE INDEX IF NOT EXISTS "${name}_user" ON ${t} ("user")`,
|
|
59
|
+
]);
|
|
60
|
+
}
|
|
61
|
+
async get(sid) {
|
|
62
|
+
const [row] = await this.q(`SELECT "user", created, seen, tenant, pending, mfa, agent, view_as FROM ${this.t} WHERE sid = ?`, [sid]);
|
|
63
|
+
return row ? SqlSessionStore.record(row) : null;
|
|
64
|
+
}
|
|
65
|
+
async forUser(user) {
|
|
66
|
+
const rows = await this.q(`SELECT sid, "user", created, seen, tenant, pending, mfa, agent, view_as FROM ${this.t} WHERE "user" = ?`, [user]);
|
|
67
|
+
return rows.map((row) => ({ sid: String(row.sid), record: SqlSessionStore.record(row) }));
|
|
68
|
+
}
|
|
69
|
+
async set(sid, r) {
|
|
70
|
+
await this.q(`INSERT INTO ${this.t} (sid, "user", created, seen, tenant, pending, mfa, agent, view_as) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ` +
|
|
71
|
+
`ON CONFLICT (sid) DO UPDATE SET "user" = excluded."user", created = excluded.created, seen = excluded.seen, ` +
|
|
72
|
+
`tenant = excluded.tenant, pending = excluded.pending, mfa = excluded.mfa, agent = excluded.agent, view_as = excluded.view_as`, [sid, r.user, r.created, r.seen, r.tenant ?? null, r.pending ? 1 : null, r.mfa ? 1 : null, r.agent ?? null, r.viewAs ? JSON.stringify(r.viewAs) : null]);
|
|
73
|
+
}
|
|
74
|
+
async delete(sid) {
|
|
75
|
+
await this.q(`DELETE FROM ${this.t} WHERE sid = ?`, [sid]);
|
|
76
|
+
}
|
|
77
|
+
async sweep(before) {
|
|
78
|
+
await this.q(`DELETE FROM ${this.t} WHERE seen < ?`, [before]);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export class PgJobStore extends PgStore {
|
|
82
|
+
constructor(pool, table = "weft_jobs") {
|
|
83
|
+
super(pool, table, (t, name) => [
|
|
84
|
+
`CREATE TABLE IF NOT EXISTS ${t} (id text PRIMARY KEY NOT NULL, name text NOT NULL, args text NOT NULL, ` +
|
|
85
|
+
`actor text, status text NOT NULL, attempts integer NOT NULL, max_attempts integer NOT NULL, run_at bigint NOT NULL, ` +
|
|
86
|
+
`created bigint NOT NULL, updated bigint NOT NULL, worker text, lease_until bigint NOT NULL, error text, ` +
|
|
87
|
+
`job_key text UNIQUE, keep_key integer NOT NULL, progress double precision)`,
|
|
88
|
+
`CREATE INDEX IF NOT EXISTS "${name}_due" ON ${t} (status, run_at)`,
|
|
89
|
+
]);
|
|
90
|
+
}
|
|
91
|
+
async add(r) {
|
|
92
|
+
const rows = await this.q(`INSERT INTO ${this.t} (id, name, args, actor, status, attempts, max_attempts, run_at, created, updated, worker, ` +
|
|
93
|
+
`lease_until, error, job_key, keep_key, progress) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ` +
|
|
94
|
+
`ON CONFLICT DO NOTHING RETURNING id`, [
|
|
95
|
+
r.id, r.name, JSON.stringify(r.args), r.actor ? JSON.stringify(r.actor) : null, r.status, r.attempts, r.maxAttempts,
|
|
96
|
+
r.runAt, r.created, r.updated, r.worker, r.leaseUntil, r.error, r.key, r.keepKey ? 1 : 0, r.progress,
|
|
97
|
+
]);
|
|
98
|
+
return rows.length === 1;
|
|
99
|
+
}
|
|
100
|
+
async get(id) {
|
|
101
|
+
return jobFromRow((await this.q(`SELECT * FROM ${this.t} WHERE id = ?`, [id]))[0]);
|
|
102
|
+
}
|
|
103
|
+
async claim(now, worker, leaseUntil) {
|
|
104
|
+
const [row] = await this.q(`UPDATE ${this.t} SET status = 'running', attempts = attempts + 1, worker = ?, lease_until = ?, updated = ? ` +
|
|
105
|
+
`WHERE id = (SELECT id FROM ${this.t} WHERE (status = 'queued' AND run_at <= ?) OR (status = 'running' AND lease_until < ?) ` +
|
|
106
|
+
`ORDER BY run_at, id COLLATE "C" LIMIT 1 FOR UPDATE SKIP LOCKED) RETURNING *`, [worker, leaseUntil, now, now, now]);
|
|
107
|
+
return jobFromRow(row);
|
|
108
|
+
}
|
|
109
|
+
async extend(id, worker, leaseUntil, progress) {
|
|
110
|
+
const rows = await this.q(`UPDATE ${this.t} SET lease_until = ?, progress = COALESCE(?::double precision, progress) ` +
|
|
111
|
+
`WHERE id = ? AND status = 'running' AND worker = ? RETURNING id`, [leaseUntil, progress, id, worker]);
|
|
112
|
+
return rows.length === 1;
|
|
113
|
+
}
|
|
114
|
+
async settle(id, worker, to, now) {
|
|
115
|
+
const ended = to.status !== "queued";
|
|
116
|
+
const rows = await this.q(`UPDATE ${this.t} SET status = ?, worker = NULL, lease_until = 0, updated = ?, run_at = COALESCE(?::bigint, run_at), ` +
|
|
117
|
+
`error = CASE WHEN ?::int = 1 THEN ?::text ELSE error END, ` +
|
|
118
|
+
`job_key = CASE WHEN ?::int = 1 AND keep_key = 0 THEN NULL ELSE job_key END ` +
|
|
119
|
+
`WHERE id = ? AND status = 'running' AND worker = ? RETURNING id`, [to.status, now, to.runAt ?? null, to.error !== undefined ? 1 : 0, to.error ?? null, ended ? 1 : 0, id, worker]);
|
|
120
|
+
return rows.length === 1;
|
|
121
|
+
}
|
|
122
|
+
async move(id, from, to, now) {
|
|
123
|
+
if (from.length === 0)
|
|
124
|
+
return false;
|
|
125
|
+
const marks = from.map(() => "?").join(", ");
|
|
126
|
+
const rows = await this.q(`UPDATE ${this.t} SET status = ?, updated = ?, run_at = COALESCE(?::bigint, run_at), attempts = COALESCE(?::int, attempts), ` +
|
|
127
|
+
`job_key = CASE WHEN ?::int = 1 AND keep_key = 0 THEN NULL ELSE job_key END ` +
|
|
128
|
+
`WHERE id = ? AND status IN (${marks}) RETURNING id`, [to.status, now, to.runAt ?? null, to.attempts ?? null, to.status === "cancelled" ? 1 : 0, id, ...from]);
|
|
129
|
+
return rows.length === 1;
|
|
130
|
+
}
|
|
131
|
+
async list(f) {
|
|
132
|
+
const where = [];
|
|
133
|
+
const args = [];
|
|
134
|
+
if (f.status)
|
|
135
|
+
(where.push("status = ?"), args.push(f.status));
|
|
136
|
+
if (f.name)
|
|
137
|
+
(where.push("name = ?"), args.push(f.name));
|
|
138
|
+
const rows = await this.q(`SELECT * FROM ${this.t}${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY created DESC, id COLLATE "C" DESC LIMIT ?`, [...args, Math.min(Math.max(1, f.limit ?? 100), 1000)]);
|
|
139
|
+
return rows.map((r) => jobFromRow(r));
|
|
140
|
+
}
|
|
141
|
+
async counts() {
|
|
142
|
+
const c = { queued: 0, running: 0, done: 0, dead: 0, cancelled: 0 };
|
|
143
|
+
for (const r of await this.q(`SELECT status, count(*) AS n FROM ${this.t} GROUP BY status`)) {
|
|
144
|
+
if (r.status in c)
|
|
145
|
+
c[r.status] = num(r.n);
|
|
146
|
+
}
|
|
147
|
+
return c;
|
|
148
|
+
}
|
|
149
|
+
async sweep(before) {
|
|
150
|
+
await this.q(`DELETE FROM ${this.t} WHERE status IN ('done', 'cancelled') AND updated < ?`, [before]);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function passkeyRow(o) {
|
|
154
|
+
if (!o)
|
|
155
|
+
return null;
|
|
156
|
+
return {
|
|
157
|
+
id: String(o.id),
|
|
158
|
+
user: String(o.user_id),
|
|
159
|
+
handle: String(o.handle),
|
|
160
|
+
publicKey: JSON.parse(String(o.public_key)),
|
|
161
|
+
alg: num(o.alg),
|
|
162
|
+
signCount: num(o.sign_count),
|
|
163
|
+
transports: JSON.parse(String(o.transports)),
|
|
164
|
+
backedUp: num(o.backed_up) === 1,
|
|
165
|
+
name: String(o.name),
|
|
166
|
+
created: num(o.created),
|
|
167
|
+
lastUsed: o.last_used === null || o.last_used === undefined ? null : num(o.last_used),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
export class PgPasskeyStore extends PgStore {
|
|
171
|
+
constructor(pool, table = "weft_passkeys") {
|
|
172
|
+
super(pool, table, (t, name) => [
|
|
173
|
+
`CREATE TABLE IF NOT EXISTS ${t} (id text PRIMARY KEY, user_id text NOT NULL, handle text NOT NULL, ` +
|
|
174
|
+
`public_key text NOT NULL, alg integer NOT NULL, sign_count bigint NOT NULL, transports text NOT NULL, ` +
|
|
175
|
+
`backed_up integer NOT NULL, name text NOT NULL, created bigint NOT NULL, last_used bigint)`,
|
|
176
|
+
`CREATE INDEX IF NOT EXISTS "${name}_user" ON ${t} (user_id)`,
|
|
177
|
+
]);
|
|
178
|
+
}
|
|
179
|
+
async add(c) {
|
|
180
|
+
await this.q(`INSERT INTO ${this.t} (id, user_id, handle, public_key, alg, sign_count, transports, backed_up, name, created, last_used) ` +
|
|
181
|
+
`VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [c.id, c.user, c.handle, JSON.stringify(c.publicKey), c.alg, c.signCount, JSON.stringify(c.transports), c.backedUp ? 1 : 0, c.name, c.created, c.lastUsed]);
|
|
182
|
+
}
|
|
183
|
+
async get(id) {
|
|
184
|
+
return passkeyRow((await this.q(`SELECT * FROM ${this.t} WHERE id = ?`, [id]))[0]);
|
|
185
|
+
}
|
|
186
|
+
async list(user) {
|
|
187
|
+
return (await this.q(`SELECT * FROM ${this.t} WHERE user_id = ? ORDER BY created, id COLLATE "C"`, [user])).map((r) => passkeyRow(r));
|
|
188
|
+
}
|
|
189
|
+
async update(id, patch) {
|
|
190
|
+
const cols = { signCount: "sign_count", lastUsed: "last_used", backedUp: "backed_up", name: "name" };
|
|
191
|
+
const sets = [];
|
|
192
|
+
const args = [];
|
|
193
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
194
|
+
const col = cols[k];
|
|
195
|
+
if (!col)
|
|
196
|
+
continue;
|
|
197
|
+
sets.push(`${col} = ?`);
|
|
198
|
+
args.push(typeof v === "boolean" ? (v ? 1 : 0) : v);
|
|
199
|
+
}
|
|
200
|
+
if (sets.length)
|
|
201
|
+
await this.q(`UPDATE ${this.t} SET ${sets.join(", ")} WHERE id = ?`, [...args, id]);
|
|
202
|
+
}
|
|
203
|
+
async remove(id) {
|
|
204
|
+
return (await this.q(`DELETE FROM ${this.t} WHERE id = ? RETURNING id`, [id])).length > 0;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
export class PgTwoFactorStore extends PgStore {
|
|
208
|
+
#r;
|
|
209
|
+
constructor(pool, table = "weft_two_factor") {
|
|
210
|
+
super(pool, table, (t, name) => [
|
|
211
|
+
`CREATE TABLE IF NOT EXISTS ${t} (user_id text PRIMARY KEY NOT NULL, secret text NOT NULL, ` +
|
|
212
|
+
`last_step bigint NOT NULL, failures integer NOT NULL, locked_until bigint NOT NULL, created bigint NOT NULL)`,
|
|
213
|
+
`CREATE TABLE IF NOT EXISTS "${name}_recovery" (user_id text NOT NULL, hash text NOT NULL, PRIMARY KEY (user_id, hash))`,
|
|
214
|
+
]);
|
|
215
|
+
this.#r = `"${table}_recovery"`;
|
|
216
|
+
}
|
|
217
|
+
async get(user) {
|
|
218
|
+
const [row] = await this.q(`SELECT secret, last_step, failures, locked_until, created FROM ${this.t} WHERE user_id = ?`, [user]);
|
|
219
|
+
if (!row)
|
|
220
|
+
return null;
|
|
221
|
+
return {
|
|
222
|
+
user,
|
|
223
|
+
secret: String(row.secret),
|
|
224
|
+
lastStep: num(row.last_step),
|
|
225
|
+
failures: num(row.failures),
|
|
226
|
+
lockedUntil: num(row.locked_until),
|
|
227
|
+
created: num(row.created),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
async add(r) {
|
|
231
|
+
const rows = await this.q(`INSERT INTO ${this.t} (user_id, secret, last_step, failures, locked_until, created) VALUES (?, ?, ?, ?, ?, ?) ` +
|
|
232
|
+
`ON CONFLICT (user_id) DO NOTHING RETURNING user_id`, [r.user, r.secret, r.lastStep, r.failures, r.lockedUntil, r.created]);
|
|
233
|
+
return rows.length === 1;
|
|
234
|
+
}
|
|
235
|
+
remove(user) {
|
|
236
|
+
return this.atomically(async () => {
|
|
237
|
+
await this.q(`DELETE FROM ${this.#r} WHERE user_id = ?`, [user]);
|
|
238
|
+
return (await this.q(`DELETE FROM ${this.t} WHERE user_id = ? RETURNING user_id`, [user])).length === 1;
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
async advance(user, step) {
|
|
242
|
+
const rows = await this.q(`UPDATE ${this.t} SET last_step = ?, failures = 0 WHERE user_id = ? AND last_step < ? RETURNING user_id`, [step, user, step]);
|
|
243
|
+
return rows.length === 1;
|
|
244
|
+
}
|
|
245
|
+
async fail(user, max, until) {
|
|
246
|
+
const [row] = await this.q(`UPDATE ${this.t} SET failures = CASE WHEN failures + 1 >= ?::int THEN 0 ELSE failures + 1 END, ` +
|
|
247
|
+
`locked_until = CASE WHEN failures + 1 >= ?::int THEN ?::bigint ELSE locked_until END WHERE user_id = ? ` +
|
|
248
|
+
`RETURNING failures, locked_until`, [max, max, until, user]);
|
|
249
|
+
return row !== undefined && num(row.failures) === 0 && num(row.locked_until) === until;
|
|
250
|
+
}
|
|
251
|
+
async succeed(user) {
|
|
252
|
+
await this.q(`UPDATE ${this.t} SET failures = 0 WHERE user_id = ?`, [user]);
|
|
253
|
+
}
|
|
254
|
+
setRecovery(user, hashes) {
|
|
255
|
+
return this.atomically(async () => {
|
|
256
|
+
await this.q(`DELETE FROM ${this.#r} WHERE user_id = ?`, [user]);
|
|
257
|
+
for (const h of hashes)
|
|
258
|
+
await this.q(`INSERT INTO ${this.#r} (user_id, hash) VALUES (?, ?)`, [user, h]);
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
async useRecovery(user, hash) {
|
|
262
|
+
return (await this.q(`DELETE FROM ${this.#r} WHERE user_id = ? AND hash = ? RETURNING hash`, [user, hash])).length === 1;
|
|
263
|
+
}
|
|
264
|
+
async countRecovery(user) {
|
|
265
|
+
const [row] = await this.q(`SELECT count(*) AS n FROM ${this.#r} WHERE user_id = ?`, [user]);
|
|
266
|
+
return num(row?.n ?? 0);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function emailRow(o) {
|
|
270
|
+
if (!o)
|
|
271
|
+
return null;
|
|
272
|
+
return {
|
|
273
|
+
id: String(o.id),
|
|
274
|
+
email: String(o.email),
|
|
275
|
+
code: String(o.code),
|
|
276
|
+
session: String(o.session),
|
|
277
|
+
next: String(o.next),
|
|
278
|
+
expires: num(o.expires),
|
|
279
|
+
attempts: num(o.attempts),
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
export class PgEmailTokenStore extends PgStore {
|
|
283
|
+
constructor(pool, table = "weft_email_tokens") {
|
|
284
|
+
super(pool, table, (t, name) => [
|
|
285
|
+
`CREATE TABLE IF NOT EXISTS ${t} (id text PRIMARY KEY, email text NOT NULL, code text NOT NULL, ` +
|
|
286
|
+
`session text NOT NULL, next text NOT NULL, expires bigint NOT NULL, attempts integer NOT NULL)`,
|
|
287
|
+
`CREATE INDEX IF NOT EXISTS "${name}_session" ON ${t} (session, email)`,
|
|
288
|
+
]);
|
|
289
|
+
}
|
|
290
|
+
async add(t) {
|
|
291
|
+
await this.q(`INSERT INTO ${this.t} (id, email, code, session, next, expires, attempts) VALUES (?, ?, ?, ?, ?, ?, ?)`, [
|
|
292
|
+
t.id, t.email, t.code, t.session, t.next, t.expires, t.attempts,
|
|
293
|
+
]);
|
|
294
|
+
}
|
|
295
|
+
async get(id) {
|
|
296
|
+
return emailRow((await this.q(`SELECT * FROM ${this.t} WHERE id = ?`, [id]))[0]);
|
|
297
|
+
}
|
|
298
|
+
async find(session, email) {
|
|
299
|
+
return emailRow((await this.q(`SELECT * FROM ${this.t} WHERE session = ? AND email = ? ORDER BY expires DESC LIMIT 1`, [session, email]))[0]);
|
|
300
|
+
}
|
|
301
|
+
async attempt(id) {
|
|
302
|
+
const [r] = await this.q(`UPDATE ${this.t} SET attempts = attempts + 1 WHERE id = ? RETURNING attempts`, [id]);
|
|
303
|
+
return r ? num(r.attempts) : Number.POSITIVE_INFINITY;
|
|
304
|
+
}
|
|
305
|
+
async take(id) {
|
|
306
|
+
return (await this.q(`DELETE FROM ${this.t} WHERE id = ? RETURNING id`, [id])).length > 0;
|
|
307
|
+
}
|
|
308
|
+
async clear(session, email) {
|
|
309
|
+
await this.q(`DELETE FROM ${this.t} WHERE session = ? AND email = ?`, [session, email]);
|
|
310
|
+
}
|
|
311
|
+
async sweep(now) {
|
|
312
|
+
await this.q(`DELETE FROM ${this.t} WHERE expires <= ?`, [now]);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
function accountRow(r) {
|
|
316
|
+
if (!r)
|
|
317
|
+
return null;
|
|
318
|
+
const t = { id: String(r.id), kind: String(r.kind), user: String(r.user_id), email: String(r.email), expires: num(r.expires) };
|
|
319
|
+
if (r.data !== null && r.data !== undefined)
|
|
320
|
+
t.data = String(r.data);
|
|
321
|
+
return t;
|
|
322
|
+
}
|
|
323
|
+
export class PgAccountTokenStore extends PgStore {
|
|
324
|
+
constructor(pool, table = "weft_account_tokens") {
|
|
325
|
+
super(pool, table, (t, name) => [
|
|
326
|
+
`CREATE TABLE IF NOT EXISTS ${t} (id text PRIMARY KEY NOT NULL, kind text NOT NULL, user_id text NOT NULL, ` +
|
|
327
|
+
`email text NOT NULL, expires bigint NOT NULL, data text)`,
|
|
328
|
+
`CREATE INDEX IF NOT EXISTS "${name}_user" ON ${t} (user_id, kind)`,
|
|
329
|
+
]);
|
|
330
|
+
}
|
|
331
|
+
async add(t) {
|
|
332
|
+
await this.q(`INSERT INTO ${this.t} (id, kind, user_id, email, expires, data) VALUES (?, ?, ?, ?, ?, ?)`, [
|
|
333
|
+
t.id, t.kind, t.user, t.email, t.expires, t.data ?? null,
|
|
334
|
+
]);
|
|
335
|
+
}
|
|
336
|
+
async get(id) {
|
|
337
|
+
return accountRow((await this.q(`SELECT * FROM ${this.t} WHERE id = ?`, [id]))[0]);
|
|
338
|
+
}
|
|
339
|
+
async take(id) {
|
|
340
|
+
return accountRow((await this.q(`DELETE FROM ${this.t} WHERE id = ? RETURNING id, kind, user_id, email, expires, data`, [id]))[0]);
|
|
341
|
+
}
|
|
342
|
+
async clear(user, kind) {
|
|
343
|
+
await this.q(`DELETE FROM ${this.t} WHERE user_id = ? AND kind = ?`, [user, kind]);
|
|
344
|
+
}
|
|
345
|
+
async sweep(now) {
|
|
346
|
+
await this.q(`DELETE FROM ${this.t} WHERE expires <= ?`, [now]);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
function fileRow(x) {
|
|
350
|
+
return {
|
|
351
|
+
id: String(x.id),
|
|
352
|
+
kind: String(x.kind),
|
|
353
|
+
owner: String(x.owner),
|
|
354
|
+
name: String(x.name),
|
|
355
|
+
type: String(x.type),
|
|
356
|
+
size: num(x.size),
|
|
357
|
+
partBytes: num(x.part_bytes),
|
|
358
|
+
status: String(x.status),
|
|
359
|
+
upload: String(x.upload),
|
|
360
|
+
claimed: num(x.claimed) === 1,
|
|
361
|
+
created: num(x.created),
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
export class PgFileStore extends PgStore {
|
|
365
|
+
constructor(pool, table = "weft_files") {
|
|
366
|
+
super(pool, table, (t, name) => [
|
|
367
|
+
`CREATE TABLE IF NOT EXISTS ${t} (id text PRIMARY KEY NOT NULL, kind text NOT NULL, owner text NOT NULL, ` +
|
|
368
|
+
`name text NOT NULL, type text NOT NULL, size bigint NOT NULL, part_bytes bigint NOT NULL, status text NOT NULL, ` +
|
|
369
|
+
`upload text NOT NULL, claimed integer NOT NULL, created bigint NOT NULL)`,
|
|
370
|
+
`CREATE INDEX IF NOT EXISTS "${name}_owner" ON ${t} (owner, status)`,
|
|
371
|
+
`CREATE INDEX IF NOT EXISTS "${name}_created" ON ${t} (created)`,
|
|
372
|
+
]);
|
|
373
|
+
}
|
|
374
|
+
async put(r) {
|
|
375
|
+
await this.q(`INSERT INTO ${this.t} (id, kind, owner, name, type, size, part_bytes, status, upload, claimed, created) ` +
|
|
376
|
+
`VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET kind = excluded.kind, owner = excluded.owner, ` +
|
|
377
|
+
`name = excluded.name, type = excluded.type, size = excluded.size, part_bytes = excluded.part_bytes, ` +
|
|
378
|
+
`status = excluded.status, upload = excluded.upload, claimed = excluded.claimed, created = excluded.created`, [r.id, r.kind, r.owner, r.name, r.type, r.size, r.partBytes, r.status, r.upload, r.claimed ? 1 : 0, r.created]);
|
|
379
|
+
}
|
|
380
|
+
async get(id) {
|
|
381
|
+
const [r] = await this.q(`SELECT * FROM ${this.t} WHERE id = ?`, [id]);
|
|
382
|
+
return r ? fileRow(r) : null;
|
|
383
|
+
}
|
|
384
|
+
async remove(id) {
|
|
385
|
+
await this.q(`DELETE FROM ${this.t} WHERE id = ?`, [id]);
|
|
386
|
+
}
|
|
387
|
+
async pending(owner) {
|
|
388
|
+
const [r] = await this.q(`SELECT count(*) AS n FROM ${this.t} WHERE owner = ? AND status = 'uploading'`, [owner]);
|
|
389
|
+
return num(r?.n ?? 0);
|
|
390
|
+
}
|
|
391
|
+
async stale(uploadingBefore, unclaimedBefore, limit) {
|
|
392
|
+
const rows = await this.q(`SELECT * FROM ${this.t} WHERE (status = 'uploading' AND created < ?) OR (status = 'ready' AND claimed = 0 AND created < ?) LIMIT ?`, [uploadingBefore, unclaimedBefore, limit]);
|
|
393
|
+
return rows.map(fileRow);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
export class PgWebhookStore extends PgStore {
|
|
397
|
+
constructor(pool, table = "weft_webhooks") {
|
|
398
|
+
super(pool, table, (t, name) => [
|
|
399
|
+
`CREATE TABLE IF NOT EXISTS ${t} (kind text NOT NULL, id text NOT NULL, owner text NOT NULL, ref text, ` +
|
|
400
|
+
`created bigint NOT NULL, data text NOT NULL, seq bigserial, PRIMARY KEY (kind, id))`,
|
|
401
|
+
`CREATE INDEX IF NOT EXISTS "${name}_owner" ON ${t} (kind, owner, created)`,
|
|
402
|
+
]);
|
|
403
|
+
}
|
|
404
|
+
async put(kind, id, owner, ref, created, data) {
|
|
405
|
+
await this.q(`INSERT INTO ${this.t} (kind, id, owner, ref, created, data) VALUES (?, ?, ?, ?, ?, ?) ` +
|
|
406
|
+
`ON CONFLICT (kind, id) DO UPDATE SET data = excluded.data`, [kind, id, owner, ref, created, data]);
|
|
407
|
+
}
|
|
408
|
+
async get(kind, id) {
|
|
409
|
+
const [r] = await this.q(`SELECT data FROM ${this.t} WHERE kind = ? AND id = ?`, [kind, id]);
|
|
410
|
+
return r ? String(r.data) : null;
|
|
411
|
+
}
|
|
412
|
+
async list(kind, owner, o) {
|
|
413
|
+
const where = ["kind = ?", "owner = ?"];
|
|
414
|
+
const args = [kind, owner];
|
|
415
|
+
if (o.ref !== undefined)
|
|
416
|
+
(where.push("ref = ?"), args.push(o.ref));
|
|
417
|
+
if (o.before !== undefined)
|
|
418
|
+
(where.push("created < ?"), args.push(o.before));
|
|
419
|
+
const rows = await this.q(`SELECT data FROM ${this.t} WHERE ${where.join(" AND ")} ORDER BY created DESC, seq DESC LIMIT ?`, [...args, o.limit]);
|
|
420
|
+
return rows.map((r) => String(r.data));
|
|
421
|
+
}
|
|
422
|
+
async remove(kind, id) {
|
|
423
|
+
await this.q(`DELETE FROM ${this.t} WHERE kind = ? AND id = ?`, [kind, id]);
|
|
424
|
+
}
|
|
425
|
+
async sweep(kind, before, owner) {
|
|
426
|
+
const rows = owner === undefined
|
|
427
|
+
? await this.q(`DELETE FROM ${this.t} WHERE kind = ? AND created < ? RETURNING id`, [kind, before])
|
|
428
|
+
: await this.q(`DELETE FROM ${this.t} WHERE kind = ? AND created < ? AND owner = ? RETURNING id`, [kind, before, owner]);
|
|
429
|
+
return rows.length;
|
|
430
|
+
}
|
|
431
|
+
}
|
package/dist/project.js
CHANGED
|
@@ -488,7 +488,13 @@ export async function loadProject(root, opts) {
|
|
|
488
488
|
api,
|
|
489
489
|
models,
|
|
490
490
|
emails,
|
|
491
|
-
database: config.database === undefined || config.database === ":memory:"
|
|
491
|
+
database: config.database === undefined || config.database === ":memory:" || /^postgres(ql)?:\/\//i.test(config.database)
|
|
492
|
+
? config.database
|
|
493
|
+
: config.database.startsWith("pglite:")
|
|
494
|
+
? config.database === "pglite:" || config.database === "pglite:memory"
|
|
495
|
+
? config.database
|
|
496
|
+
: `pglite:${resolve(root, config.database.slice("pglite:".length))}`
|
|
497
|
+
: resolve(root, config.database),
|
|
492
498
|
middleware,
|
|
493
499
|
...(ready ? { ready } : {}),
|
|
494
500
|
...(sharedFields ? { sharedFields } : {}),
|
package/dist/storage.d.ts
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import type { Model } from "@weft-framework/data";
|
|
2
2
|
export interface StorageOptions {
|
|
3
|
+
/** SQLite file, ":memory:", `postgres://…` or `pglite:<dir>`. */
|
|
3
4
|
database?: string;
|
|
4
5
|
onWarning?(message: string): void;
|
|
5
6
|
}
|
|
6
7
|
export declare class ModelStorage {
|
|
7
8
|
private db;
|
|
9
|
+
private pool;
|
|
8
10
|
private dbPath;
|
|
11
|
+
/** Postgres: the global change feed is bridged across instances over LISTEN/NOTIFY. */
|
|
12
|
+
private unbridge;
|
|
9
13
|
private memory;
|
|
10
14
|
attach(models: readonly Model<unknown>[], opts?: StorageOptions): Promise<void>;
|
|
11
15
|
close(): void;
|
package/dist/storage.js
CHANGED
|
@@ -4,19 +4,46 @@ import { useDatabase } from "@weft-framework/data";
|
|
|
4
4
|
function signature(m) {
|
|
5
5
|
return JSON.stringify([m.key, m.fields]);
|
|
6
6
|
}
|
|
7
|
+
function isPg(database) {
|
|
8
|
+
return /^postgres(ql)?:\/\//i.test(database) || database.startsWith("pglite:");
|
|
9
|
+
}
|
|
7
10
|
export class ModelStorage {
|
|
8
11
|
db = null;
|
|
12
|
+
pool = null;
|
|
9
13
|
dbPath = null;
|
|
14
|
+
/** Postgres: the global change feed is bridged across instances over LISTEN/NOTIFY. */
|
|
15
|
+
unbridge = null;
|
|
10
16
|
memory = new Map();
|
|
11
17
|
async attach(models, opts = {}) {
|
|
18
|
+
if (opts.database !== undefined && isPg(opts.database)) {
|
|
19
|
+
const pg = await import("@weft-framework/data/postgres");
|
|
20
|
+
if (this.dbPath !== opts.database || this.pool === null) {
|
|
21
|
+
const next = await pg.openPostgres(opts.database);
|
|
22
|
+
await this.closeDb();
|
|
23
|
+
this.pool = next;
|
|
24
|
+
this.dbPath = opts.database;
|
|
25
|
+
if (!opts.database.startsWith("pglite:")) {
|
|
26
|
+
const { bridgeChanges, changes } = await import("@weft-framework/data");
|
|
27
|
+
const channel = pg.pgBroadcast(next);
|
|
28
|
+
const off = bridgeChanges(changes, channel);
|
|
29
|
+
this.unbridge = async () => {
|
|
30
|
+
off();
|
|
31
|
+
await channel.close();
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
this.memory.clear();
|
|
36
|
+
await pg.usePostgres(this.pool, models, { onWarning: opts.onWarning });
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
12
39
|
if (opts.database !== undefined) {
|
|
13
|
-
if (this.dbPath !== opts.database) {
|
|
40
|
+
if (this.dbPath !== opts.database || this.db === null) {
|
|
14
41
|
const { openSqlite } = await import("@weft-framework/data/sqlite");
|
|
15
42
|
if (opts.database !== ":memory:") {
|
|
16
43
|
mkdirSync(dirname(opts.database), { recursive: true });
|
|
17
44
|
}
|
|
18
45
|
const next = openSqlite(opts.database);
|
|
19
|
-
this.closeDb();
|
|
46
|
+
await this.closeDb();
|
|
20
47
|
this.db = next;
|
|
21
48
|
this.dbPath = opts.database;
|
|
22
49
|
}
|
|
@@ -24,7 +51,7 @@ export class ModelStorage {
|
|
|
24
51
|
useDatabase(this.db, models, { onWarning: opts.onWarning });
|
|
25
52
|
return;
|
|
26
53
|
}
|
|
27
|
-
this.closeDb();
|
|
54
|
+
await this.closeDb();
|
|
28
55
|
const seen = new Set();
|
|
29
56
|
for (const m of models) {
|
|
30
57
|
const sig = signature(m);
|
|
@@ -44,12 +71,20 @@ export class ModelStorage {
|
|
|
44
71
|
}
|
|
45
72
|
}
|
|
46
73
|
close() {
|
|
47
|
-
this.closeDb();
|
|
74
|
+
void this.closeDb();
|
|
48
75
|
this.memory.clear();
|
|
49
76
|
}
|
|
50
|
-
closeDb() {
|
|
77
|
+
async closeDb() {
|
|
51
78
|
this.db?.close();
|
|
52
79
|
this.db = null;
|
|
80
|
+
const pool = this.pool;
|
|
81
|
+
const unbridge = this.unbridge;
|
|
82
|
+
this.pool = null;
|
|
83
|
+
this.unbridge = null;
|
|
53
84
|
this.dbPath = null;
|
|
85
|
+
if (unbridge)
|
|
86
|
+
await unbridge();
|
|
87
|
+
if (pool)
|
|
88
|
+
await pool.end();
|
|
54
89
|
}
|
|
55
90
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weft-framework/server",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.5",
|
|
4
4
|
"description": "Weft server: live pages over WebSocket/SSE with signed sessions, CSRF, rate limiting and a strict CSP, on the Fetch API (Bun, Node, edge).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"weft",
|
|
@@ -170,11 +170,15 @@
|
|
|
170
170
|
"./production": {
|
|
171
171
|
"types": "./dist/production.d.ts",
|
|
172
172
|
"default": "./dist/production.js"
|
|
173
|
+
},
|
|
174
|
+
"./pg-stores": {
|
|
175
|
+
"types": "./dist/pg-stores.d.ts",
|
|
176
|
+
"default": "./dist/pg-stores.js"
|
|
173
177
|
}
|
|
174
178
|
},
|
|
175
179
|
"dependencies": {
|
|
176
|
-
"@weft-framework/data": "0.0.
|
|
177
|
-
"@weft-framework/runtime": "0.0.
|
|
180
|
+
"@weft-framework/data": "0.0.4",
|
|
181
|
+
"@weft-framework/runtime": "0.0.5",
|
|
178
182
|
"@xmldom/xmldom": "0.8.15",
|
|
179
183
|
"xml-crypto": "6.4.0"
|
|
180
184
|
},
|