@bejibun/core 0.1.51 → 0.1.53

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/CHANGELOG.md CHANGED
@@ -3,6 +3,55 @@ All notable changes to this project will be documented in this file.
3
3
 
4
4
  ---
5
5
 
6
+ ## [v0.1.53](https://github.com/crenata/bejibun-core/compare/v0.1.52...v0.1.53) - 2025-11-24
7
+
8
+ ### 🩹 Fixes
9
+
10
+ ### 📖 Changes
11
+ What's New :
12
+ - Adding `Rate Limiter` to limit any action in a certain time.
13
+
14
+ Available `Rate Limiter` functions :
15
+ - `.attempt(key, limit, callback, duration)` throw an error if limit reached.
16
+ - `.tooManyAttempts(key, limit, duration)` method to check if limit has reached.
17
+ - `.clear(key)` reset the counter.
18
+
19
+ ### ❤️Contributors
20
+ - Havea Crenata ([@crenata](https://github.com/crenata))
21
+ - Ghulje ([@ghulje](https://github.com/ghulje))
22
+
23
+ **Full Changelog**: https://github.com/crenata/bejibun-core/blob/master/CHANGELOG.md
24
+
25
+ ---
26
+
27
+ ## [v0.1.52](https://github.com/crenata/bejibun-core/compare/v0.1.51...v0.1.52) - 2025-11-17
28
+
29
+ ### 🩹 Fixes
30
+
31
+ ### 📖 Changes
32
+ What's New :
33
+
34
+ Adding support for x402 protocol. You can secure your paid endpoint by adding `.x402()` chaining on router.
35
+
36
+ How to use it :
37
+
38
+ First, you need to install the package by running `bun ace install @bejibun/x402`.
39
+
40
+ Customize your `config/x402.ts` with your own configuration.
41
+
42
+ Add `.x402()` chain into router you want to add for payment middleware.
43
+ ```ts
44
+ Router.x402()
45
+ ```
46
+
47
+ ### ❤️Contributors
48
+ - Havea Crenata ([@crenata](https://github.com/crenata))
49
+ - Ghulje ([@ghulje](https://github.com/ghulje))
50
+
51
+ **Full Changelog**: https://github.com/crenata/bejibun-core/blob/master/CHANGELOG.md
52
+
53
+ ---
54
+
6
55
  ## [v0.1.51](https://github.com/crenata/bejibun-core/compare/v0.1.49...v0.1.51) - 2025-11-04
7
56
 
8
57
  ### 🩹 Fixes
@@ -0,0 +1,12 @@
1
+ export default class RateLimiterBuilder {
2
+ protected key: string;
3
+ protected limit: number;
4
+ protected duration: number;
5
+ constructor();
6
+ setKey(key: string): RateLimiterBuilder;
7
+ setLimit(limit: number): RateLimiterBuilder;
8
+ setDuration(duration: number): RateLimiterBuilder;
9
+ attempt(callback: Function): Promise<any>;
10
+ tooManyAttempts(): Promise<boolean>;
11
+ clear(): Promise<void>;
12
+ }
@@ -0,0 +1,44 @@
1
+ import Cache from "@bejibun/cache";
2
+ import { isNotEmpty } from "@bejibun/utils";
3
+ import RateLimiterException from "../exceptions/RateLimiterException";
4
+ export default class RateLimiterBuilder {
5
+ key;
6
+ limit;
7
+ duration; // seconds
8
+ constructor() {
9
+ this.key = "";
10
+ this.limit = 60;
11
+ this.duration = 60;
12
+ }
13
+ setKey(key) {
14
+ this.key = key;
15
+ return this;
16
+ }
17
+ setLimit(limit) {
18
+ this.limit = limit;
19
+ return this;
20
+ }
21
+ setDuration(duration) {
22
+ this.duration = duration;
23
+ return this;
24
+ }
25
+ async attempt(callback) {
26
+ const count = Number(await Cache.increment(this.key, this.duration));
27
+ const canExecute = count <= this.limit;
28
+ if (isNotEmpty(callback) && typeof callback === "function") {
29
+ if (canExecute)
30
+ return callback();
31
+ }
32
+ else {
33
+ throw new RateLimiterException("Invalid callback.");
34
+ }
35
+ throw new RateLimiterException("Too many attempts.");
36
+ }
37
+ async tooManyAttempts() {
38
+ const count = Number(await Cache.get(this.key));
39
+ return count > this.limit;
40
+ }
41
+ async clear() {
42
+ return await Cache.forget(this.key);
43
+ }
44
+ }
@@ -1,6 +1,7 @@
1
- import HttpMethodEnum from "@bejibun/utils/enums/HttpMethodEnum";
1
+ import type { TFacilitator, TPaywall, TX402Config } from "@bejibun/x402";
2
2
  import type { IMiddleware } from "../types/middleware";
3
3
  import type { HandlerType, ResourceAction, RouterGroup } from "../types/router";
4
+ import HttpMethodEnum from "@bejibun/utils/enums/HttpMethodEnum";
4
5
  export interface ResourceOptions {
5
6
  only?: Array<ResourceAction>;
6
7
  except?: Array<ResourceAction>;
@@ -12,6 +13,7 @@ export default class RouterBuilder {
12
13
  prefix(basePath: string): RouterBuilder;
13
14
  middleware(...middlewares: Array<IMiddleware>): RouterBuilder;
14
15
  namespace(baseNamespace: string): RouterBuilder;
16
+ x402(config?: TX402Config, facilitatorConfig?: TFacilitator, paywallConfig?: TPaywall): RouterBuilder;
15
17
  group(routes: RouterGroup | Array<RouterGroup>): RouterGroup;
16
18
  resources(controller: Record<string, HandlerType>, options?: ResourceOptions): RouterGroup;
17
19
  buildSingle(method: HttpMethodEnum, path: string, handler: string | HandlerType): RouterGroup;
@@ -1,9 +1,10 @@
1
1
  import App from "@bejibun/app";
2
- import { isEmpty } from "@bejibun/utils";
2
+ import { isEmpty, isModuleExists } from "@bejibun/utils";
3
3
  import HttpMethodEnum from "@bejibun/utils/enums/HttpMethodEnum";
4
4
  import Enum from "@bejibun/utils/facades/Enum";
5
5
  import path from "path";
6
6
  import RouterInvalidException from "../exceptions/RouterInvalidException";
7
+ import X402Middleware from "../middlewares/X402Middleware";
7
8
  export default class RouterBuilder {
8
9
  basePath = "";
9
10
  middlewares = [];
@@ -20,6 +21,12 @@ export default class RouterBuilder {
20
21
  this.baseNamespace = baseNamespace;
21
22
  return this;
22
23
  }
24
+ x402(config, facilitatorConfig, paywallConfig) {
25
+ if (!isModuleExists("@bejibun/x402"))
26
+ throw new RouterInvalidException("@bejibun/x402 is not installed.");
27
+ this.middlewares.push(new X402Middleware(config, facilitatorConfig, paywallConfig));
28
+ return this;
29
+ }
23
30
  group(routes) {
24
31
  const routeList = Array.isArray(routes) ? routes : [routes];
25
32
  const newRoutes = {};
@@ -0,0 +1,2 @@
1
+ declare const config: Record<string, any>;
2
+ export default config;
@@ -0,0 +1,5 @@
1
+ const config = {
2
+ limit: 60,
3
+ duration: 60 // seconds
4
+ };
5
+ export default config;
@@ -1,7 +1,10 @@
1
1
  import { ValidationError } from "objection";
2
2
  import ModelNotFoundException from "../exceptions/ModelNotFoundException";
3
+ import RateLimiterException from "../exceptions/RateLimiterException";
4
+ import RouterInvalidException from "../exceptions/RouterInvalidException";
5
+ import RuntimeException from "../exceptions/RuntimeException";
3
6
  import ValidatorException from "../exceptions/ValidatorException";
4
7
  export default class ExceptionHandler {
5
- handle(error: Bun.ErrorLike | ModelNotFoundException | ValidatorException | ValidationError): globalThis.Response;
8
+ handle(error: Bun.ErrorLike | ModelNotFoundException | RateLimiterException | RouterInvalidException | RuntimeException | ValidatorException | ValidationError): globalThis.Response;
6
9
  route(request: Bun.BunRequest): globalThis.Response;
7
10
  }
@@ -3,12 +3,18 @@ import { defineValue } from "@bejibun/utils";
3
3
  import HttpMethodEnum from "@bejibun/utils/enums/HttpMethodEnum";
4
4
  import { ValidationError } from "objection";
5
5
  import ModelNotFoundException from "../exceptions/ModelNotFoundException";
6
+ import RateLimiterException from "../exceptions/RateLimiterException";
7
+ import RouterInvalidException from "../exceptions/RouterInvalidException";
8
+ import RuntimeException from "../exceptions/RuntimeException";
6
9
  import ValidatorException from "../exceptions/ValidatorException";
7
10
  import Response from "../facades/Response";
8
11
  export default class ExceptionHandler {
9
12
  handle(error) {
10
13
  Logger.setContext("APP").error(error.message).trace(error.stack);
11
14
  if (error instanceof ModelNotFoundException ||
15
+ error instanceof RateLimiterException ||
16
+ error instanceof RouterInvalidException ||
17
+ error instanceof RuntimeException ||
12
18
  error instanceof ValidatorException)
13
19
  return Response
14
20
  .setMessage(error.message)
@@ -0,0 +1,4 @@
1
+ export default class RateLimiterException extends Error {
2
+ code: number;
3
+ constructor(message?: string, code?: number);
4
+ }
@@ -0,0 +1,14 @@
1
+ import Logger from "@bejibun/logger";
2
+ import { defineValue } from "@bejibun/utils";
3
+ export default class RateLimiterException extends Error {
4
+ code;
5
+ constructor(message, code) {
6
+ super(message);
7
+ this.name = "RateLimiterException";
8
+ this.code = defineValue(code, 429);
9
+ Logger.setContext(this.name).error(this.message).trace(this.stack);
10
+ if (Error.captureStackTrace) {
11
+ Error.captureStackTrace(this, RateLimiterException);
12
+ }
13
+ }
14
+ }
@@ -0,0 +1,5 @@
1
+ export default class RateLimiter {
2
+ static attempt(key: string, limit: number, callback: Function, duration?: number): Promise<any>;
3
+ static tooManyAttempts(key: string, limit: number, duration?: number): Promise<boolean>;
4
+ static clear(key: string): Promise<void>;
5
+ }
@@ -0,0 +1,23 @@
1
+ import { defineValue } from "@bejibun/utils";
2
+ import RateLimiterBuilder from "../builders/RateLimiterBuilder";
3
+ export default class RateLimiter {
4
+ static async attempt(key, limit, callback, duration) {
5
+ return await new RateLimiterBuilder()
6
+ .setKey(key)
7
+ .setLimit(defineValue(limit, 60))
8
+ .setDuration(defineValue(duration, 60))
9
+ .attempt(callback);
10
+ }
11
+ static async tooManyAttempts(key, limit, duration) {
12
+ return await new RateLimiterBuilder()
13
+ .setKey(key)
14
+ .setLimit(defineValue(limit, 60))
15
+ .setDuration(defineValue(duration, 60))
16
+ .tooManyAttempts();
17
+ }
18
+ static async clear(key) {
19
+ return await new RateLimiterBuilder()
20
+ .setKey(key)
21
+ .clear();
22
+ }
23
+ }
@@ -6,6 +6,7 @@ export default class Router {
6
6
  static prefix(basePath: string): RouterBuilder;
7
7
  static middleware(...middlewares: Array<IMiddleware>): RouterBuilder;
8
8
  static namespace(baseNamespace: string): RouterBuilder;
9
+ static x402(): RouterBuilder;
9
10
  static resources(controller: Record<string, HandlerType>, options?: ResourceOptions): RouterGroup;
10
11
  static group(routes: RouterGroup, prefix?: string, middlewares?: Array<IMiddleware>): RouterGroup;
11
12
  static connect(path: string, handler: string | HandlerType): RouterGroup;
package/facades/Router.js CHANGED
@@ -10,6 +10,9 @@ export default class Router {
10
10
  static namespace(baseNamespace) {
11
11
  return new RouterBuilder().namespace(baseNamespace);
12
12
  }
13
+ static x402() {
14
+ return new RouterBuilder().x402();
15
+ }
13
16
  static resources(controller, options) {
14
17
  return new RouterBuilder().resources(controller, options);
15
18
  }
package/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from "./bases/index";
2
2
  export * from "./exceptions/index";
3
3
  export * from "./facades/index";
4
+ export * from "./middlewares/index";
package/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from "./bases/index";
2
2
  export * from "./exceptions/index";
3
3
  export * from "./facades/index";
4
+ export * from "./middlewares/index";
@@ -2,7 +2,7 @@ import App from "@bejibun/app";
2
2
  import Response from "../facades/Response";
3
3
  export default class MaintenanceMiddleware {
4
4
  handle(handler) {
5
- return async (request) => {
5
+ return async (request, server) => {
6
6
  if (await App.Maintenance.isMaintenanceMode()) {
7
7
  const maintenance = await App.Maintenance.getData();
8
8
  return Response
@@ -10,7 +10,7 @@ export default class MaintenanceMiddleware {
10
10
  .setStatus(maintenance.status)
11
11
  .send();
12
12
  }
13
- return handler(request);
13
+ return handler(request, server);
14
14
  };
15
15
  }
16
16
  }
@@ -0,0 +1,4 @@
1
+ import type { HandlerType } from "../types/router";
2
+ export default class RateLimiterMiddleware {
3
+ handle(handler: HandlerType): HandlerType;
4
+ }
@@ -0,0 +1,20 @@
1
+ import App from "@bejibun/app";
2
+ import { defineValue } from "@bejibun/utils";
3
+ import LimiterConfig from "../config/limiter";
4
+ import RateLimiter from "../facades/RateLimiter";
5
+ export default class RateLimiterMiddleware {
6
+ handle(handler) {
7
+ return async (request, server) => {
8
+ const configPath = App.Path.configPath("limiter.ts");
9
+ let config;
10
+ if (await Bun.file(configPath).exists())
11
+ config = require(configPath).default;
12
+ else
13
+ config = LimiterConfig;
14
+ return await RateLimiter
15
+ .attempt(`rate-limiter/${defineValue(server.requestIP(request)?.address, "")}`, defineValue(config?.limit, 60), () => {
16
+ return handler(request, server);
17
+ });
18
+ };
19
+ }
20
+ }
@@ -0,0 +1,9 @@
1
+ import type { TFacilitator, TPaywall, TX402Config } from "@bejibun/x402";
2
+ import type { HandlerType } from "../types/router";
3
+ export default class X402Middleware {
4
+ protected config?: TX402Config;
5
+ protected facilitatorConfig?: TFacilitator;
6
+ protected paywallConfig?: TPaywall;
7
+ constructor(config?: TX402Config, facilitatorConfig?: TFacilitator, paywallConfig?: TPaywall);
8
+ handle(handler: HandlerType): HandlerType;
9
+ }
@@ -0,0 +1,23 @@
1
+ import X402 from "@bejibun/x402";
2
+ export default class X402Middleware {
3
+ config;
4
+ facilitatorConfig;
5
+ paywallConfig;
6
+ constructor(config, facilitatorConfig, paywallConfig) {
7
+ this.config = config;
8
+ this.facilitatorConfig = facilitatorConfig;
9
+ this.paywallConfig = paywallConfig;
10
+ }
11
+ handle(handler) {
12
+ return async (request, server) => {
13
+ return X402
14
+ .setConfig(this.config)
15
+ .setFacilitator(this.facilitatorConfig)
16
+ .setPaywall(this.paywallConfig)
17
+ .setRequest(request)
18
+ .middleware(() => {
19
+ return handler(request, server);
20
+ });
21
+ };
22
+ }
23
+ }
@@ -0,0 +1,2 @@
1
+ export * from "../middlewares/MaintenanceMiddleware";
2
+ export * from "../middlewares/X402Middleware";
@@ -0,0 +1,2 @@
1
+ export * from "../middlewares/MaintenanceMiddleware";
2
+ export * from "../middlewares/X402Middleware";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bejibun/core",
3
- "version": "0.1.51",
3
+ "version": "0.1.53",
4
4
  "author": "Havea Crenata <havea.crenata@gmail.com>",
5
5
  "repository": {
6
6
  "type": "git",
@@ -10,16 +10,18 @@
10
10
  "module": "index.js",
11
11
  "dependencies": {
12
12
  "@bejibun/app": "^0.1.22",
13
+ "@bejibun/cache": "^0.1.11",
13
14
  "@bejibun/cors": "^0.1.16",
14
15
  "@bejibun/database": "^0.1.19",
15
16
  "@bejibun/logger": "^0.1.22",
16
- "@bejibun/utils": "^0.1.20",
17
+ "@bejibun/utils": "^0.1.21",
17
18
  "@vinejs/vine": "^3.0.1",
18
19
  "commander": "^14.0.2",
19
20
  "luxon": "^3.7.2",
20
21
  "objection": "^3.1.5"
21
22
  },
22
23
  "devDependencies": {
24
+ "@bejibun/x402": "^0.1.1",
23
25
  "@types/bun": "latest",
24
26
  "@types/luxon": "^3.7.1",
25
27
  "tsc-alias": "^1.8.16"
package/server.js CHANGED
@@ -3,6 +3,7 @@ import Logger from "@bejibun/logger";
3
3
  import RuntimeException from "./exceptions/RuntimeException";
4
4
  import Router from "./facades/Router";
5
5
  import MaintenanceMiddleware from "./middlewares/MaintenanceMiddleware";
6
+ import RateLimiterMiddleware from "./middlewares/RateLimiterMiddleware";
6
7
  import(App.Path.rootPath("bootstrap.ts"));
7
8
  const exceptionHandlerPath = App.Path.appPath("exceptions/handler.ts");
8
9
  let ExceptionHandler;
@@ -39,7 +40,7 @@ const server = Bun.serve({
39
40
  port: Bun.env.APP_PORT,
40
41
  routes: {
41
42
  "/": require(App.Path.publicPath("index.html")),
42
- ...Router.middleware(new MaintenanceMiddleware()).group([
43
+ ...Router.middleware(new MaintenanceMiddleware(), new RateLimiterMiddleware()).group([
43
44
  Router.namespace("app/exceptions").any("/*", "Handler@route"),
44
45
  ApiRoutes,
45
46
  WebRoutes
package/types/router.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export type HandlerType = (request: Bun.BunRequest) => Promise<Response>;
1
+ export type HandlerType = (request: Bun.BunRequest, server: Bun.Server) => Promise<Response>;
2
2
  export type RouterGroup = Record<string, Record<string, HandlerType>>;
3
3
  export type ResourceAction = "index" | "store" | "show" | "update" | "destroy";