@pollium/readable 0.0.0-stage → 0.2.0
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/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorate.js +8 -0
- package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorateMetadata.js +5 -0
- package/dist/app/Application.d.ts +34 -0
- package/dist/app/Application.js +136 -0
- package/dist/app/abort.d.ts +8 -0
- package/dist/app/abort.js +16 -0
- package/dist/app/compression.d.ts +2 -0
- package/dist/app/compression.js +35 -0
- package/dist/app/config.d.ts +45 -0
- package/dist/app/config.js +55 -0
- package/dist/app/discovery.d.ts +27 -0
- package/dist/app/discovery.js +75 -0
- package/dist/app/errors.d.ts +22 -0
- package/dist/app/errors.js +58 -0
- package/dist/app/logger.d.ts +20 -0
- package/dist/app/logger.js +40 -0
- package/dist/app/metadata.d.ts +5 -0
- package/dist/app/metadata.js +16 -0
- package/dist/app/redis.d.ts +4 -0
- package/dist/app/redis.js +24 -0
- package/dist/auth/credentials.d.ts +6 -0
- package/dist/auth/credentials.js +24 -0
- package/dist/auth/guards.d.ts +11 -0
- package/dist/auth/guards.js +44 -0
- package/dist/auth/params.d.ts +8 -0
- package/dist/auth/params.js +19 -0
- package/dist/auth/secrets.d.ts +6 -0
- package/dist/auth/secrets.js +38 -0
- package/dist/auth/sessions.d.ts +32 -0
- package/dist/auth/sessions.js +49 -0
- package/dist/database/data-source.d.ts +7 -0
- package/dist/database/data-source.js +22 -0
- package/dist/database/models.d.ts +16 -0
- package/dist/database/models.js +72 -0
- package/dist/database/queries.d.ts +26 -0
- package/dist/database/queries.js +56 -0
- package/dist/events/Broadcast.d.ts +8 -0
- package/dist/events/Broadcast.js +42 -0
- package/dist/events/EventBus.d.ts +23 -0
- package/dist/events/EventBus.js +115 -0
- package/dist/gateway/ConnectionRegistry.d.ts +25 -0
- package/dist/gateway/ConnectionRegistry.js +68 -0
- package/dist/gateway/Gateway.d.ts +15 -0
- package/dist/gateway/Gateway.js +135 -0
- package/dist/http/Controller.d.ts +29 -0
- package/dist/http/Controller.js +97 -0
- package/dist/http/auto-validate-body.d.ts +8 -0
- package/dist/http/auto-validate-body.js +16 -0
- package/dist/http/call.d.ts +24 -0
- package/dist/http/call.js +66 -0
- package/dist/http/middleware.d.ts +21 -0
- package/dist/http/middleware.js +39 -0
- package/dist/http/org-context.d.ts +6 -0
- package/dist/http/org-context.js +23 -0
- package/dist/http/params.d.ts +40 -0
- package/dist/http/params.js +95 -0
- package/dist/http/responses.d.ts +20 -0
- package/dist/http/responses.js +29 -0
- package/dist/queues/BaseQueue.d.ts +15 -0
- package/dist/queues/BaseQueue.js +69 -0
- package/dist/queues/QueueProducer.d.ts +9 -0
- package/dist/queues/QueueProducer.js +21 -0
- package/dist/storage/ObjectStorage.d.ts +37 -0
- package/dist/storage/ObjectStorage.js +170 -0
- package/dist/testing/harness.d.ts +25 -0
- package/dist/testing/harness.js +46 -0
- package/dist/testing/rate-limit.d.ts +2 -0
- package/dist/testing/rate-limit.js +4 -0
- package/dist/testing/request.d.ts +21 -0
- package/dist/testing/request.js +41 -0
- package/dist/tools/ToolGroup.d.ts +33 -0
- package/dist/tools/ToolGroup.js +30 -0
- package/package.json +62 -3
- package/README.md +0 -3
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { promisify } from "node:util";
|
|
2
|
+
import { createHash, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
|
3
|
+
// lib/auth/credentials.ts
|
|
4
|
+
var PasswordService = class {
|
|
5
|
+
#scrypt = promisify(scrypt);
|
|
6
|
+
#keyLength = 64;
|
|
7
|
+
async hash(password) {
|
|
8
|
+
const salt = randomBytes(16).toString("hex");
|
|
9
|
+
return `${salt}:${(await this.#scrypt(password, salt, this.#keyLength)).toString("hex")}`;
|
|
10
|
+
}
|
|
11
|
+
async verify(password, stored) {
|
|
12
|
+
const [salt, hash] = stored.split(":");
|
|
13
|
+
if (!salt || !hash) return false;
|
|
14
|
+
const derived = await this.#scrypt(password, salt, this.#keyLength);
|
|
15
|
+
const expected = Buffer.from(hash, "hex");
|
|
16
|
+
return derived.length === expected.length && timingSafeEqual(derived, expected);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const answersChallenge = (challenge, verifier) => {
|
|
20
|
+
const expected = Buffer.from(challenge);
|
|
21
|
+
const actual = Buffer.from(createHash("sha256").update(verifier).digest("base64url"));
|
|
22
|
+
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
23
|
+
};
|
|
24
|
+
export { PasswordService, answersChallenge };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import BaseController from "../http/Controller.js";
|
|
2
|
+
import { Principal, TokenPayload } from "./sessions.js";
|
|
3
|
+
import { MiddlewareFn } from "../http/middleware.js";
|
|
4
|
+
import { FastifyRequest } from "fastify";
|
|
5
|
+
export type MembershipAssertion = (scopeId: string, userId: string) => Promise<unknown>;
|
|
6
|
+
export declare const bearerSession: (req: FastifyRequest) => Promise<TokenPayload | null>;
|
|
7
|
+
export declare const bearerPrincipal: (req: FastifyRequest) => Promise<Principal | null>;
|
|
8
|
+
export declare const AuthenticatedRoute: MiddlewareFn;
|
|
9
|
+
export declare abstract class AuthenticatedController extends BaseController {}
|
|
10
|
+
export declare const ParamGuardRoute: (param: string, assert: MembershipAssertion) => MiddlewareFn;
|
|
11
|
+
export declare const SocketAuthenticatedRoute: MiddlewareFn;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import BaseController from "../http/Controller.js";
|
|
2
|
+
import { verifiedSession } from "./sessions.js";
|
|
3
|
+
import { Middleware } from "../http/middleware.js";
|
|
4
|
+
import { AuthError } from "../app/errors.js";
|
|
5
|
+
import { principalId } from "./params.js";
|
|
6
|
+
import { parseId } from "../http/params.js";
|
|
7
|
+
import __decorate from "../_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorate.js";
|
|
8
|
+
// lib/auth/guards.ts
|
|
9
|
+
const bearerSession = async (req) => {
|
|
10
|
+
const scheme = "Bearer ";
|
|
11
|
+
const header = req.headers.authorization;
|
|
12
|
+
if (!header?.startsWith(scheme)) return null;
|
|
13
|
+
return verifiedSession(header.slice(7).trim());
|
|
14
|
+
};
|
|
15
|
+
const bearerPrincipal = async (req) => {
|
|
16
|
+
const session = await bearerSession(req);
|
|
17
|
+
return session === null ? null : { userId: session.sub };
|
|
18
|
+
};
|
|
19
|
+
const AuthenticatedRoute = async (req) => {
|
|
20
|
+
const session = await bearerSession(req);
|
|
21
|
+
if (session === null) throw AuthError.Unauthorized();
|
|
22
|
+
req.principal = { userId: session.sub };
|
|
23
|
+
req.sessionExpiresAt = session.exp;
|
|
24
|
+
};
|
|
25
|
+
let AuthenticatedController = class AuthenticatedController extends BaseController {};
|
|
26
|
+
AuthenticatedController = __decorate([Middleware(AuthenticatedRoute)], AuthenticatedController);
|
|
27
|
+
const ParamGuardRoute = (param, assert) => async (req, reply) => {
|
|
28
|
+
await AuthenticatedRoute(req, reply);
|
|
29
|
+
await assert(parseId(req.params[param]), principalId(req));
|
|
30
|
+
};
|
|
31
|
+
const SocketAuthenticatedRoute = async (req) => {
|
|
32
|
+
const token = tokenFromSubprotocol(req.headers["sec-websocket-protocol"]) ?? tokenFromQuery(req.query);
|
|
33
|
+
if (!token) throw AuthError.Unauthorized();
|
|
34
|
+
const session = await verifiedSession(token);
|
|
35
|
+
req.principal = { userId: session.sub };
|
|
36
|
+
req.sessionExpiresAt = session.exp;
|
|
37
|
+
};
|
|
38
|
+
const tokenFromSubprotocol = (header) => {
|
|
39
|
+
return header?.split(",")[0]?.trim() || void 0;
|
|
40
|
+
};
|
|
41
|
+
const tokenFromQuery = (query) => {
|
|
42
|
+
return query.token?.trim() || void 0;
|
|
43
|
+
};
|
|
44
|
+
export { AuthenticatedController, AuthenticatedRoute, ParamGuardRoute, SocketAuthenticatedRoute, bearerPrincipal, bearerSession };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { FastifyRequest } from "fastify";
|
|
2
|
+
export interface OwnedResolver<T> {
|
|
3
|
+
getOwned(userId: string, id: string): Promise<T>;
|
|
4
|
+
}
|
|
5
|
+
export declare const principalId: (req: FastifyRequest) => string;
|
|
6
|
+
export declare const CurrentUser: () => ParameterDecorator;
|
|
7
|
+
export declare const SessionExpiresAt: () => ParameterDecorator;
|
|
8
|
+
export declare const Owned: <T>(Service: new () => OwnedResolver<T>, param?: string) => ParameterDecorator;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { AuthError } from "../app/errors.js";
|
|
2
|
+
import { createParamDecorator, parseId } from "../http/params.js";
|
|
3
|
+
// lib/auth/params.ts
|
|
4
|
+
const principalId = (req) => {
|
|
5
|
+
if (!req.principal) throw AuthError.Unauthorized();
|
|
6
|
+
return req.principal.userId;
|
|
7
|
+
};
|
|
8
|
+
const CurrentUser = () => createParamDecorator(principalId);
|
|
9
|
+
const sessionExpiresAt = (req) => {
|
|
10
|
+
if (req.sessionExpiresAt === void 0) throw AuthError.Unauthorized();
|
|
11
|
+
return req.sessionExpiresAt;
|
|
12
|
+
};
|
|
13
|
+
const SessionExpiresAt = () => createParamDecorator(sessionExpiresAt);
|
|
14
|
+
const Owned = (Service, param = "id") => createParamDecorator((req) => {
|
|
15
|
+
const userId = principalId(req);
|
|
16
|
+
const id = parseId(req.params[param]);
|
|
17
|
+
return new Service().getOwned(userId, id);
|
|
18
|
+
});
|
|
19
|
+
export { CurrentUser, Owned, SessionExpiresAt, principalId };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { ConfigError, CryptoError } from "../app/errors.js";
|
|
2
|
+
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
|
|
3
|
+
// lib/auth/secrets.ts
|
|
4
|
+
var SecretCipher = class SecretCipher {
|
|
5
|
+
static #ALGORITHM = "aes-256-gcm";
|
|
6
|
+
static #IV_BYTES = 12;
|
|
7
|
+
static #KEY_BYTES = 32;
|
|
8
|
+
#key;
|
|
9
|
+
constructor(encryptionKey) {
|
|
10
|
+
this.#key = SecretCipher.#decodeKey(encryptionKey);
|
|
11
|
+
}
|
|
12
|
+
static #decodeKey(raw) {
|
|
13
|
+
const key = /^[0-9a-f]{64}$/i.test(raw) ? Buffer.from(raw, "hex") : Buffer.from(raw, "base64");
|
|
14
|
+
if (key.length !== SecretCipher.#KEY_BYTES) throw ConfigError.InvalidEncryptionKey();
|
|
15
|
+
return key;
|
|
16
|
+
}
|
|
17
|
+
encrypt(plaintext) {
|
|
18
|
+
if (typeof plaintext !== "string" || plaintext === "") throw CryptoError.EncryptFailed();
|
|
19
|
+
const iv = randomBytes(SecretCipher.#IV_BYTES);
|
|
20
|
+
const cipher = createCipheriv(SecretCipher.#ALGORITHM, this.#key, iv);
|
|
21
|
+
const enc = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
22
|
+
const tag = cipher.getAuthTag();
|
|
23
|
+
return `${iv.toString("hex")}:${tag.toString("hex")}:${enc.toString("hex")}`;
|
|
24
|
+
}
|
|
25
|
+
decrypt(payload) {
|
|
26
|
+
const parts = payload.split(":");
|
|
27
|
+
if (parts.length !== 3) throw CryptoError.DecryptFailed();
|
|
28
|
+
try {
|
|
29
|
+
const [ivHex, tagHex, dataHex] = parts;
|
|
30
|
+
const decipher = createDecipheriv(SecretCipher.#ALGORITHM, this.#key, Buffer.from(ivHex, "hex"));
|
|
31
|
+
decipher.setAuthTag(Buffer.from(tagHex, "hex"));
|
|
32
|
+
return Buffer.concat([decipher.update(Buffer.from(dataHex, "hex")), decipher.final()]).toString("utf8");
|
|
33
|
+
} catch {
|
|
34
|
+
throw CryptoError.DecryptFailed();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
export { SecretCipher };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface Principal {
|
|
2
|
+
userId: string;
|
|
3
|
+
}
|
|
4
|
+
export interface TokenPayload {
|
|
5
|
+
sub: string;
|
|
6
|
+
iat: number;
|
|
7
|
+
exp: number;
|
|
8
|
+
}
|
|
9
|
+
declare module 'fastify' {
|
|
10
|
+
interface FastifyRequest {
|
|
11
|
+
principal?: Principal;
|
|
12
|
+
sessionExpiresAt?: number;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export interface SessionCutoffStore {
|
|
16
|
+
cutoffOf(userId: string): Promise<number | null>;
|
|
17
|
+
cut(userId: string, at?: number): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
export declare const SESSION_TTL_SECONDS: number;
|
|
20
|
+
export declare class JWTService {
|
|
21
|
+
#private;
|
|
22
|
+
sign(userId: string): string;
|
|
23
|
+
signUntil(userId: string, expiresAt: number): string;
|
|
24
|
+
verify(token: string): TokenPayload;
|
|
25
|
+
}
|
|
26
|
+
export declare class RedisSessionCutoffStore implements SessionCutoffStore {
|
|
27
|
+
#private;
|
|
28
|
+
cutoffOf(userId: string): Promise<number | null>;
|
|
29
|
+
cut(userId: string, at?: number): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
export declare const sessionCutoffs: SessionCutoffStore;
|
|
32
|
+
export declare const verifiedSession: (token: string) => Promise<TokenPayload>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { jwtSecret } from "../app/config.js";
|
|
2
|
+
import { redis } from "../app/redis.js";
|
|
3
|
+
import { AuthError } from "../app/errors.js";
|
|
4
|
+
import jwt from "jsonwebtoken";
|
|
5
|
+
// lib/auth/sessions.ts
|
|
6
|
+
const SESSION_TTL_SECONDS = 604800;
|
|
7
|
+
var JWTService = class {
|
|
8
|
+
#algorithm = "HS256";
|
|
9
|
+
sign(userId) {
|
|
10
|
+
return jwt.sign({ sub: String(userId) }, jwtSecret(), {
|
|
11
|
+
algorithm: this.#algorithm,
|
|
12
|
+
expiresIn: SESSION_TTL_SECONDS
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
signUntil(userId, expiresAt) {
|
|
16
|
+
return jwt.sign({
|
|
17
|
+
sub: String(userId),
|
|
18
|
+
exp: expiresAt
|
|
19
|
+
}, jwtSecret(), { algorithm: this.#algorithm });
|
|
20
|
+
}
|
|
21
|
+
verify(token) {
|
|
22
|
+
return jwt.verify(token, jwtSecret(), { algorithms: [this.#algorithm] });
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
var RedisSessionCutoffStore = class {
|
|
26
|
+
#prefix = "session:cutoff:";
|
|
27
|
+
async cutoffOf(userId) {
|
|
28
|
+
const value = await redis.get(`${this.#prefix}${userId}`);
|
|
29
|
+
return value === null ? null : Number(value);
|
|
30
|
+
}
|
|
31
|
+
async cut(userId, at = Math.floor(Date.now() / 1e3)) {
|
|
32
|
+
await redis.set(`${this.#prefix}${userId}`, String(at), "EX", SESSION_TTL_SECONDS);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
const sessionCutoffs = new RedisSessionCutoffStore();
|
|
36
|
+
const decoded = (token) => {
|
|
37
|
+
try {
|
|
38
|
+
return new JWTService().verify(token);
|
|
39
|
+
} catch {
|
|
40
|
+
throw AuthError.InvalidToken();
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
const verifiedSession = async (token) => {
|
|
44
|
+
const session = decoded(token);
|
|
45
|
+
const cutoff = await sessionCutoffs.cutoffOf(session.sub);
|
|
46
|
+
if (cutoff !== null && session.iat < cutoff) throw AuthError.InvalidToken();
|
|
47
|
+
return session;
|
|
48
|
+
};
|
|
49
|
+
export { JWTService, RedisSessionCutoffStore, SESSION_TTL_SECONDS, sessionCutoffs, verifiedSession };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { ReadableDatabaseConfig } from "../app/config.js";
|
|
2
|
+
import { DataSource } from "typeorm";
|
|
3
|
+
export interface MigrationSource {
|
|
4
|
+
migrations: Function[];
|
|
5
|
+
tableName: string;
|
|
6
|
+
}
|
|
7
|
+
export declare const createDataSource: (database: ReadableDatabaseConfig, entities: Function[], migrations?: MigrationSource) => DataSource;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { DataSource } from "typeorm";
|
|
2
|
+
// lib/database/data-source.ts
|
|
3
|
+
const createDataSource = (database, entities, migrations) => {
|
|
4
|
+
const dataSource = new DataSource({
|
|
5
|
+
type: "postgres",
|
|
6
|
+
url: database.url,
|
|
7
|
+
schema: database.schema,
|
|
8
|
+
synchronize: database.synchronize,
|
|
9
|
+
entities,
|
|
10
|
+
migrations: migrations?.migrations ?? [],
|
|
11
|
+
...migrations === void 0 ? {} : {
|
|
12
|
+
migrationsTableName: migrations.tableName,
|
|
13
|
+
migrationsTransactionMode: "all"
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
if (database.timestamptz) Object.assign(dataSource.driver.mappedDataTypes, {
|
|
17
|
+
createDate: "timestamptz",
|
|
18
|
+
updateDate: "timestamptz"
|
|
19
|
+
});
|
|
20
|
+
return dataSource;
|
|
21
|
+
};
|
|
22
|
+
export { createDataSource };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { BaseEntity } from "typeorm";
|
|
2
|
+
import { NIL as NIL_UUID, v7 as uuidv7 } from "uuid";
|
|
3
|
+
export interface FkOptions {
|
|
4
|
+
onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
|
|
5
|
+
nullable?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export declare const Hidden: () => PropertyDecorator;
|
|
8
|
+
export declare const getHiddenFields: (ctor: object) => Set<string>;
|
|
9
|
+
export declare const Fk: (entity: string, options?: FkOptions) => PropertyDecorator;
|
|
10
|
+
export declare abstract class BaseModel extends BaseEntity {
|
|
11
|
+
id: string;
|
|
12
|
+
createdAt: Date;
|
|
13
|
+
updatedAt: Date;
|
|
14
|
+
toJSON(): Record<string, unknown>;
|
|
15
|
+
}
|
|
16
|
+
export { NIL_UUID, uuidv7 };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import __decorateMetadata from "../_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorateMetadata.js";
|
|
2
|
+
import __decorate from "../_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/decorate.js";
|
|
3
|
+
import { BaseEntity, Column, CreateDateColumn, PrimaryColumn, UpdateDateColumn, getMetadataArgsStorage } from "typeorm";
|
|
4
|
+
import { NIL as NIL_UUID, v7 as uuidv7 } from "uuid";
|
|
5
|
+
// lib/database/models.ts
|
|
6
|
+
const hiddenFields = /* @__PURE__ */ new WeakMap();
|
|
7
|
+
const Hidden = () => {
|
|
8
|
+
return (target, propertyKey) => {
|
|
9
|
+
const ctor = target.constructor;
|
|
10
|
+
let fields = hiddenFields.get(ctor);
|
|
11
|
+
if (!fields) {
|
|
12
|
+
fields = /* @__PURE__ */ new Set();
|
|
13
|
+
hiddenFields.set(ctor, fields);
|
|
14
|
+
}
|
|
15
|
+
fields.add(String(propertyKey));
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
const getHiddenFields = (ctor) => {
|
|
19
|
+
const collected = /* @__PURE__ */ new Set();
|
|
20
|
+
let current = ctor;
|
|
21
|
+
while (typeof current === "function" && current !== Function.prototype) {
|
|
22
|
+
const own = hiddenFields.get(current);
|
|
23
|
+
if (own) for (const field of own) collected.add(field);
|
|
24
|
+
current = Object.getPrototypeOf(current);
|
|
25
|
+
}
|
|
26
|
+
return collected;
|
|
27
|
+
};
|
|
28
|
+
const Fk = (entity, options = {}) => (target, propertyKey) => {
|
|
29
|
+
const column = String(propertyKey);
|
|
30
|
+
const relation = column.endsWith("Id") ? column.slice(0, -2) : `_${column}`;
|
|
31
|
+
const nullable = options.nullable === true;
|
|
32
|
+
Column({
|
|
33
|
+
type: "uuid",
|
|
34
|
+
...nullable ? { nullable: true } : {}
|
|
35
|
+
})(target, column);
|
|
36
|
+
getMetadataArgsStorage().relations.push({
|
|
37
|
+
target: target.constructor,
|
|
38
|
+
propertyName: relation,
|
|
39
|
+
relationType: "many-to-one",
|
|
40
|
+
isLazy: false,
|
|
41
|
+
type: entity,
|
|
42
|
+
options: {
|
|
43
|
+
...options.onDelete === void 0 ? {} : { onDelete: options.onDelete },
|
|
44
|
+
nullable
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
getMetadataArgsStorage().joinColumns.push({
|
|
48
|
+
target: target.constructor,
|
|
49
|
+
propertyName: relation,
|
|
50
|
+
name: column,
|
|
51
|
+
referencedColumnName: "id"
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
var BaseModel = class extends BaseEntity {
|
|
55
|
+
constructor(..._args) {
|
|
56
|
+
super(..._args);
|
|
57
|
+
this.id = uuidv7();
|
|
58
|
+
}
|
|
59
|
+
toJSON() {
|
|
60
|
+
const hidden = getHiddenFields(this.constructor);
|
|
61
|
+
const output = {};
|
|
62
|
+
for (const [key, value] of Object.entries(this)) if (!hidden.has(key)) output[key] = value;
|
|
63
|
+
return output;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
__decorate([PrimaryColumn({
|
|
67
|
+
type: "uuid",
|
|
68
|
+
default: () => "uuidv7()"
|
|
69
|
+
}), __decorateMetadata("design:type", String)], BaseModel.prototype, "id", void 0);
|
|
70
|
+
__decorate([CreateDateColumn(), __decorateMetadata("design:type", typeof Date === "undefined" ? Object : Date)], BaseModel.prototype, "createdAt", void 0);
|
|
71
|
+
__decorate([UpdateDateColumn(), __decorateMetadata("design:type", typeof Date === "undefined" ? Object : Date)], BaseModel.prototype, "updatedAt", void 0);
|
|
72
|
+
export { BaseModel, Fk, Hidden, NIL_UUID, getHiddenFields, uuidv7 };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { RuntimeError } from "../app/errors.js";
|
|
2
|
+
import { BaseEntity, EntityManager, EntityTarget, FindOptionsWhere, ObjectLiteral, QueryFailedError } from "typeorm";
|
|
3
|
+
export interface TableRef {
|
|
4
|
+
table: string;
|
|
5
|
+
primaryKey: string;
|
|
6
|
+
column(property: string): string;
|
|
7
|
+
}
|
|
8
|
+
export interface DayCount {
|
|
9
|
+
date: string;
|
|
10
|
+
count: number;
|
|
11
|
+
}
|
|
12
|
+
type Positioned = BaseEntity & {
|
|
13
|
+
position: number;
|
|
14
|
+
};
|
|
15
|
+
export declare const tableRef: (manager: EntityManager, target: EntityTarget<ObjectLiteral>) => TableRef;
|
|
16
|
+
export declare const findOrThrow: <T extends BaseEntity>(model: {
|
|
17
|
+
new (): T;
|
|
18
|
+
} & typeof BaseEntity, where: FindOptionsWhere<T>, missing: () => RuntimeError) => Promise<T>;
|
|
19
|
+
export declare const isUniqueViolation: (error: unknown) => error is QueryFailedError;
|
|
20
|
+
export declare const nextPosition: <T extends Positioned>(model: {
|
|
21
|
+
new (): T;
|
|
22
|
+
} & typeof BaseEntity, scope: FindOptionsWhere<T>) => Promise<number>;
|
|
23
|
+
export declare const advisoryLock: (manager: EntityManager, namespace: number, key: string) => Promise<void>;
|
|
24
|
+
export declare const recentDates: (manager: EntityManager, days: number) => Promise<string[]>;
|
|
25
|
+
export declare const countPerDay: (target: typeof BaseEntity & EntityTarget<ObjectLiteral>, property: string, days: number) => Promise<DayCount[]>;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { QueryFailedError } from "typeorm";
|
|
2
|
+
// lib/database/queries.ts
|
|
3
|
+
const tableRef = (manager, target) => {
|
|
4
|
+
const metadata = manager.connection.getMetadata(target);
|
|
5
|
+
return {
|
|
6
|
+
table: metadata.tablePath.split(".").map((part) => `"${part}"`).join("."),
|
|
7
|
+
primaryKey: metadata.primaryColumns[0].databaseName,
|
|
8
|
+
column: (property) => metadata.findColumnWithPropertyPathStrict(property).databaseName
|
|
9
|
+
};
|
|
10
|
+
};
|
|
11
|
+
const findOrThrow = async (model, where, missing) => {
|
|
12
|
+
const found = await model.getRepository().findOneBy(where);
|
|
13
|
+
if (!found) throw missing();
|
|
14
|
+
return found;
|
|
15
|
+
};
|
|
16
|
+
const isUniqueViolation = (error) => {
|
|
17
|
+
return error instanceof QueryFailedError && error.driverError.code === "23505";
|
|
18
|
+
};
|
|
19
|
+
const nextPosition = async (model, scope) => {
|
|
20
|
+
const last = await model.getRepository().createQueryBuilder("entity").where(scope).orderBy("entity.position", "DESC").limit(1).getOne();
|
|
21
|
+
return last ? last.position + 1 : 0;
|
|
22
|
+
};
|
|
23
|
+
const advisoryLock = async (manager, namespace, key) => {
|
|
24
|
+
await manager.query("SELECT pg_advisory_xact_lock(hashtextextended($1, $2))", [key, namespace]);
|
|
25
|
+
};
|
|
26
|
+
const SERIES = `
|
|
27
|
+
generate_series(
|
|
28
|
+
CURRENT_DATE - make_interval(days => $1::int),
|
|
29
|
+
CURRENT_DATE,
|
|
30
|
+
INTERVAL '1 day'
|
|
31
|
+
) AS series(day)`;
|
|
32
|
+
const recentDates = async (manager, days) => {
|
|
33
|
+
return (await manager.query(`
|
|
34
|
+
SELECT to_char(series.day, 'YYYY-MM-DD') AS date
|
|
35
|
+
FROM ${SERIES}
|
|
36
|
+
ORDER BY series.day ASC
|
|
37
|
+
`, [days - 1])).map((row) => row.date);
|
|
38
|
+
};
|
|
39
|
+
const countPerDay = async (target, property, days) => {
|
|
40
|
+
const manager = target.getRepository().manager;
|
|
41
|
+
const ref = tableRef(manager, target);
|
|
42
|
+
const stamp = ref.column(property);
|
|
43
|
+
return (await manager.query(`
|
|
44
|
+
SELECT to_char(series.day, 'YYYY-MM-DD') AS date, COUNT(entry."${ref.primaryKey}") AS count
|
|
45
|
+
FROM ${SERIES}
|
|
46
|
+
LEFT JOIN ${ref.table} AS entry
|
|
47
|
+
ON entry."${stamp}" >= series.day
|
|
48
|
+
AND entry."${stamp}" < series.day + INTERVAL '1 day'
|
|
49
|
+
GROUP BY series.day
|
|
50
|
+
ORDER BY series.day ASC
|
|
51
|
+
`, [days - 1])).map((row) => ({
|
|
52
|
+
date: row.date,
|
|
53
|
+
count: Number(row.count)
|
|
54
|
+
}));
|
|
55
|
+
};
|
|
56
|
+
export { advisoryLock, countPerDay, findOrThrow, isUniqueViolation, nextPosition, recentDates, tableRef };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
declare class Broadcast {
|
|
2
|
+
#private;
|
|
3
|
+
publish(channel: string, payload: unknown): Promise<void>;
|
|
4
|
+
subscribe<T>(channel: string, handler: (payload: T) => void | Promise<void>): void;
|
|
5
|
+
close(): Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export declare const broadcast: Broadcast;
|
|
8
|
+
export {};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createRedis } from "../app/redis.js";
|
|
2
|
+
import { logger } from "../app/logger.js";
|
|
3
|
+
// lib/events/Broadcast.ts
|
|
4
|
+
var Broadcast = class {
|
|
5
|
+
#publisher;
|
|
6
|
+
#subscriber;
|
|
7
|
+
#handlers = /* @__PURE__ */ new Map();
|
|
8
|
+
async publish(channel, payload) {
|
|
9
|
+
this.#publisher ??= this.#connect();
|
|
10
|
+
await this.#publisher.publish(channel, JSON.stringify(payload));
|
|
11
|
+
}
|
|
12
|
+
subscribe(channel, handler) {
|
|
13
|
+
const handlers = this.#handlers.get(channel) ?? [];
|
|
14
|
+
handlers.push(handler);
|
|
15
|
+
this.#handlers.set(channel, handlers);
|
|
16
|
+
this.#subscriber ??= this.#listen();
|
|
17
|
+
this.#subscriber.subscribe(channel);
|
|
18
|
+
}
|
|
19
|
+
async close() {
|
|
20
|
+
await this.#publisher?.quit();
|
|
21
|
+
await this.#subscriber?.quit();
|
|
22
|
+
this.#publisher = void 0;
|
|
23
|
+
this.#subscriber = void 0;
|
|
24
|
+
this.#handlers.clear();
|
|
25
|
+
}
|
|
26
|
+
#connect() {
|
|
27
|
+
return createRedis();
|
|
28
|
+
}
|
|
29
|
+
#listen() {
|
|
30
|
+
const subscriber = this.#connect();
|
|
31
|
+
subscriber.on("message", (channel, message) => {
|
|
32
|
+
for (const handler of this.#handlers.get(channel) ?? []) try {
|
|
33
|
+
handler(JSON.parse(message));
|
|
34
|
+
} catch (error) {
|
|
35
|
+
logger.error(`Broadcast::HandlerFailed:${channel}`, error);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
return subscriber;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const broadcast = new Broadcast();
|
|
42
|
+
export { broadcast };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export interface EventBinding {
|
|
2
|
+
event: string;
|
|
3
|
+
handlerName: string | symbol;
|
|
4
|
+
}
|
|
5
|
+
declare global {
|
|
6
|
+
interface EventMap {}
|
|
7
|
+
}
|
|
8
|
+
type Handler = (payload: unknown) => unknown;
|
|
9
|
+
declare class EventBus {
|
|
10
|
+
#private;
|
|
11
|
+
subscribe(event: string, handler: Handler): void;
|
|
12
|
+
on<K extends keyof EventMap & string>(event: K, handler: (payload: EventMap[K]) => unknown): void;
|
|
13
|
+
emit<K extends keyof EventMap>(event: K, payload: EventMap[K]): void;
|
|
14
|
+
settled(): Promise<void>;
|
|
15
|
+
close(): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export declare const eventBus: EventBus;
|
|
18
|
+
export declare const DefineEventGroup: (group: string) => ClassDecorator;
|
|
19
|
+
export declare const getEventGroup: (ctor: object) => string | undefined;
|
|
20
|
+
export declare const Event: (event: string) => MethodDecorator;
|
|
21
|
+
export declare const getEvents: (ctor: object) => EventBinding[];
|
|
22
|
+
export declare const registerEventGroup: (GroupClass: new () => object) => void;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { ClassMetadata } from "../app/metadata.js";
|
|
2
|
+
import { createRedis } from "../app/redis.js";
|
|
3
|
+
import { readableConfig } from "../app/config.js";
|
|
4
|
+
import { logger } from "../app/logger.js";
|
|
5
|
+
import { EventError } from "../app/errors.js";
|
|
6
|
+
import { randomBytes } from "node:crypto";
|
|
7
|
+
// lib/events/EventBus.ts
|
|
8
|
+
const origin = randomBytes(8).toString("hex");
|
|
9
|
+
const groupByClass = /* @__PURE__ */ new WeakMap();
|
|
10
|
+
const eventsByClass = new ClassMetadata();
|
|
11
|
+
var EventBus = class {
|
|
12
|
+
#handlers = /* @__PURE__ */ new Map();
|
|
13
|
+
#inFlight = /* @__PURE__ */ new Set();
|
|
14
|
+
#publisher;
|
|
15
|
+
#subscriber;
|
|
16
|
+
#remote = process.env.VITEST === void 0;
|
|
17
|
+
subscribe(event, handler) {
|
|
18
|
+
const handlers = this.#handlers.get(event) ?? [];
|
|
19
|
+
handlers.push(handler);
|
|
20
|
+
this.#handlers.set(event, handlers);
|
|
21
|
+
if (this.#remote) this.#listen();
|
|
22
|
+
}
|
|
23
|
+
on(event, handler) {
|
|
24
|
+
this.subscribe(event, (payload) => handler(payload));
|
|
25
|
+
}
|
|
26
|
+
emit(event, payload) {
|
|
27
|
+
this.#dispatch(event, payload);
|
|
28
|
+
if (!this.#remote) return;
|
|
29
|
+
this.#publish(event, payload);
|
|
30
|
+
}
|
|
31
|
+
async settled() {
|
|
32
|
+
while (this.#inFlight.size > 0) await Promise.all(this.#inFlight);
|
|
33
|
+
}
|
|
34
|
+
async close() {
|
|
35
|
+
await this.#publisher?.quit();
|
|
36
|
+
await this.#subscriber?.quit();
|
|
37
|
+
this.#publisher = void 0;
|
|
38
|
+
this.#subscriber = void 0;
|
|
39
|
+
}
|
|
40
|
+
#dispatch(event, payload) {
|
|
41
|
+
for (const handler of this.#handlers.get(event) ?? []) {
|
|
42
|
+
const work = Promise.resolve().then(() => handler(payload)).catch((error) => {
|
|
43
|
+
logger.error(`EventBus::HandlerFailed:${event}`, error);
|
|
44
|
+
});
|
|
45
|
+
this.#inFlight.add(work);
|
|
46
|
+
work.finally(() => this.#inFlight.delete(work));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async #publish(event, payload) {
|
|
50
|
+
try {
|
|
51
|
+
this.#publisher ??= this.#connect();
|
|
52
|
+
const envelope = {
|
|
53
|
+
origin,
|
|
54
|
+
event,
|
|
55
|
+
payload
|
|
56
|
+
};
|
|
57
|
+
await this.#publisher.publish(this.#channel, JSON.stringify(envelope));
|
|
58
|
+
} catch (error) {
|
|
59
|
+
logger.error("EventBus::PublishFailed", error);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
#listen() {
|
|
63
|
+
if (this.#subscriber) return;
|
|
64
|
+
try {
|
|
65
|
+
this.#subscriber = this.#connect();
|
|
66
|
+
} catch {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
this.#subscriber.subscribe(this.#channel);
|
|
70
|
+
this.#subscriber.on("message", (_channel, message) => {
|
|
71
|
+
let envelope;
|
|
72
|
+
try {
|
|
73
|
+
envelope = JSON.parse(message);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
logger.error("EventBus::InvalidEnvelope", error);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (envelope.origin === origin) return;
|
|
79
|
+
this.#dispatch(envelope.event, envelope.payload);
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
get #channel() {
|
|
83
|
+
return `${readableConfig().name}:events`;
|
|
84
|
+
}
|
|
85
|
+
#connect() {
|
|
86
|
+
return createRedis();
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
const eventBus = new EventBus();
|
|
90
|
+
const DefineEventGroup = (group) => {
|
|
91
|
+
return (target) => {
|
|
92
|
+
groupByClass.set(target, group);
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
const getEventGroup = (ctor) => {
|
|
96
|
+
return groupByClass.get(ctor);
|
|
97
|
+
};
|
|
98
|
+
const Event = (event) => {
|
|
99
|
+
return (target, handlerName) => {
|
|
100
|
+
eventsByClass.append(target.constructor, {
|
|
101
|
+
event,
|
|
102
|
+
handlerName
|
|
103
|
+
});
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
const getEvents = (ctor) => {
|
|
107
|
+
return eventsByClass.get(ctor);
|
|
108
|
+
};
|
|
109
|
+
const registerEventGroup = (GroupClass) => {
|
|
110
|
+
const group = getEventGroup(GroupClass);
|
|
111
|
+
if (!group) throw EventError.UndefinedGroup();
|
|
112
|
+
const instance = new GroupClass();
|
|
113
|
+
for (const { event, handlerName } of getEvents(GroupClass)) eventBus.subscribe(`${group}.${event}`, instance[handlerName].bind(instance));
|
|
114
|
+
};
|
|
115
|
+
export { DefineEventGroup, Event, eventBus, getEventGroup, getEvents, registerEventGroup };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { WebSocket } from "@fastify/websocket";
|
|
2
|
+
export interface OutboundMessage<T> {
|
|
3
|
+
type: string;
|
|
4
|
+
data: T;
|
|
5
|
+
}
|
|
6
|
+
export interface RoomGrant {
|
|
7
|
+
room: string;
|
|
8
|
+
access: RoomAccess;
|
|
9
|
+
}
|
|
10
|
+
export type RoomAccess = () => Promise<unknown>;
|
|
11
|
+
export default class ConnectionsRegistry {
|
|
12
|
+
#private;
|
|
13
|
+
add(socket: WebSocket): void;
|
|
14
|
+
remove(socket: WebSocket): void;
|
|
15
|
+
join(socket: WebSocket, room: string, access?: RoomAccess): void;
|
|
16
|
+
leave(socket: WebSocket, room: string): void;
|
|
17
|
+
leaveAll(socket: WebSocket): void;
|
|
18
|
+
reauthorize(socket: WebSocket): Promise<void>;
|
|
19
|
+
has(room: string): boolean;
|
|
20
|
+
broadcast(message: OutboundMessage<unknown>): void;
|
|
21
|
+
sendTo(socket: WebSocket, message: OutboundMessage<unknown>): void;
|
|
22
|
+
sendToRoom(room: string, message: OutboundMessage<unknown>): void;
|
|
23
|
+
sendToRooms(rooms: string[], message: OutboundMessage<unknown>): void;
|
|
24
|
+
get size(): number;
|
|
25
|
+
}
|