raiton 6.5.0-beta.13 → 6.7.0-beta.15

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.
Files changed (166) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +16 -9
  3. package/build/bin/index.mjs +10288 -6059
  4. package/deno.json +4 -1
  5. package/docs/contributors/framework/README.md +2 -0
  6. package/docs/contributors/framework/cache/README.md +55 -0
  7. package/docs/contributors/framework/cache/cache.md +86 -0
  8. package/docs/contributors/framework/cache/etag.md +82 -0
  9. package/docs/contributors/framework/decorators/README.md +1 -0
  10. package/docs/contributors/framework/plugins/csrf.md +277 -0
  11. package/docs/contributors/framework/plugins/security.md +40 -6
  12. package/docs/contributors/framework/runtime.md +13 -3
  13. package/docs/user-guide/README.md +8 -4
  14. package/docs/user-guide/best-practices.md +1 -0
  15. package/docs/user-guide/cache.md +79 -0
  16. package/docs/user-guide/cli.md +35 -3
  17. package/docs/user-guide/csrf.md +557 -0
  18. package/docs/user-guide/decorators/README.md +3 -0
  19. package/docs/user-guide/decorators/cache.md +79 -0
  20. package/docs/user-guide/decorators/health-check.md +125 -0
  21. package/docs/user-guide/health-check.md +117 -0
  22. package/docs/user-guide/runtime.md +2 -1
  23. package/docs/user-guide/security.md +8 -2
  24. package/package.json +8 -3
  25. package/source/bin/bootstrapper.ts +4 -4
  26. package/source/bin/cli-tools.ts +27 -3
  27. package/source/bin/cli.ts +2 -2
  28. package/source/bin/commands.registry.ts +17 -0
  29. package/source/bin/constants.ts +1 -0
  30. package/source/bin/index.ts +2 -2
  31. package/source/commands/artifact.command.ts +2 -2
  32. package/source/commands/build.command.ts +2 -2
  33. package/source/commands/develop.command.ts +4 -5
  34. package/source/commands/grafts.command.ts +1 -1
  35. package/source/commands/start.command.ts +2 -2
  36. package/source/core/application.ts +10 -10
  37. package/source/core/artifacts/artifact.ts +1 -1
  38. package/source/core/artifacts/index.ts +1 -1
  39. package/source/core/builder.ts +69 -15
  40. package/source/core/bytes.util.ts +1 -1
  41. package/source/core/commands.ts +24 -14
  42. package/source/core/config/config.ts +2 -2
  43. package/source/core/config/define.ts +2 -2
  44. package/source/core/config/index.ts +2 -2
  45. package/source/core/context.ts +1 -1
  46. package/source/core/controller/builder.ts +31 -8
  47. package/source/core/controller/compiler.ts +6 -6
  48. package/source/core/controller/index.ts +4 -4
  49. package/source/core/controller/metadata.ts +2 -2
  50. package/source/core/controller/tracker.ts +1 -1
  51. package/source/core/directories.ts +3 -2
  52. package/source/core/guards.ts +1 -1
  53. package/source/core/helpers/index.ts +1 -1
  54. package/source/core/hooks.ts +1 -1
  55. package/source/core/index.ts +16 -16
  56. package/source/core/injection/index.ts +1 -1
  57. package/source/core/injection/injection.ts +3 -3
  58. package/source/core/mcp/builder.ts +8 -8
  59. package/source/core/mcp/index.ts +3 -3
  60. package/source/core/mcp/metadata.ts +2 -2
  61. package/source/core/mcp/tracker.ts +1 -1
  62. package/source/core/middleware/compose.ts +2 -2
  63. package/source/core/middleware/index.ts +2 -2
  64. package/source/core/middleware/pipeline.ts +2 -2
  65. package/source/core/plugins/index.ts +2 -2
  66. package/source/core/plugins/plugin.ts +1 -1
  67. package/source/core/plugins/scope.ts +4 -4
  68. package/source/core/raiton.ts +1 -1
  69. package/source/core/router/handler.ts +30 -6
  70. package/source/core/router/handler.utils.ts +3 -3
  71. package/source/core/router/index.ts +4 -4
  72. package/source/core/router/matcher.ts +1 -1
  73. package/source/core/router/route.ts +1 -1
  74. package/source/core/router/router.ts +4 -4
  75. package/source/core/server.ts +1 -1
  76. package/source/core/socket/builder.ts +2 -2
  77. package/source/core/socket/index.ts +2 -2
  78. package/source/core/socket/metadata.ts +2 -2
  79. package/source/core/thread.ts +53 -20
  80. package/source/framework/artifacts.ts +8 -5
  81. package/source/framework/cache/cache.decorator.ts +35 -0
  82. package/source/framework/cache/cache.ts +197 -0
  83. package/source/framework/cache/etag.ts +174 -0
  84. package/source/framework/cache/index.ts +4 -0
  85. package/source/framework/cache/types.ts +111 -0
  86. package/source/framework/constants/decorators.constant.ts +4 -0
  87. package/source/framework/constants/index.ts +2 -2
  88. package/source/framework/decorators/access-guard.decorator.ts +2 -2
  89. package/source/framework/decorators/api-response.decorator.ts +1 -1
  90. package/source/framework/decorators/api.decorator.ts +1 -1
  91. package/source/framework/decorators/controllable.decorator.ts +3 -3
  92. package/source/framework/decorators/csrf-guard.decorator.ts +60 -0
  93. package/source/framework/decorators/csrf-token.decorator.ts +20 -0
  94. package/source/framework/decorators/guard.decorator.ts +4 -4
  95. package/source/framework/decorators/health-check.decorator.ts +50 -0
  96. package/source/framework/decorators/index.ts +14 -11
  97. package/source/framework/decorators/injection.decorator.ts +3 -3
  98. package/source/framework/decorators/mcp.decorator.ts +4 -4
  99. package/source/framework/decorators/middleware.decorator.ts +2 -2
  100. package/source/framework/decorators/parametrable.decorator.ts +2 -2
  101. package/source/framework/decorators/routable.decorator.ts +3 -3
  102. package/source/framework/decorators/route-interaction.decorator.ts +4 -4
  103. package/source/framework/decorators/socket.decorator.ts +3 -3
  104. package/source/framework/encryption.ts +2 -2
  105. package/source/framework/enums/csrf.enum.ts +4 -0
  106. package/source/framework/enums/index.ts +8 -7
  107. package/source/framework/enums/runtime.enum.ts +1 -2
  108. package/source/framework/env.ts +2 -2
  109. package/source/framework/exceptions/http-exception.ts +3 -3
  110. package/source/framework/exceptions/index.ts +2 -2
  111. package/source/framework/health-check.ts +137 -0
  112. package/source/framework/index.ts +18 -16
  113. package/source/framework/mcp/handler.ts +3 -3
  114. package/source/framework/mcp/index.ts +3 -3
  115. package/source/framework/mcp/protocol.ts +1 -1
  116. package/source/framework/mcp/streamable-http.ts +3 -3
  117. package/source/framework/parameter-bag.ts +2 -2
  118. package/source/framework/plugins/body-parser.plugin.ts +3 -3
  119. package/source/framework/plugins/index.ts +4 -4
  120. package/source/framework/plugins/mcp.plugin.ts +5 -5
  121. package/source/framework/plugins/openapi.plugin.ts +4 -4
  122. package/source/framework/plugins/security/body-limit.ts +3 -3
  123. package/source/framework/plugins/security/cors.ts +2 -2
  124. package/source/framework/plugins/security/csrf.ts +145 -0
  125. package/source/framework/plugins/security/headers.ts +2 -2
  126. package/source/framework/plugins/security/index.ts +7 -5
  127. package/source/framework/plugins/security/method-guard.ts +3 -3
  128. package/source/framework/plugins/security/rate-limit.ts +3 -3
  129. package/source/framework/repositories.ts +1 -1
  130. package/source/framework/responses/error.ts +2 -2
  131. package/source/framework/responses/helpers.ts +3 -3
  132. package/source/framework/responses/http-throwable.ts +3 -3
  133. package/source/framework/responses/http.ts +3 -3
  134. package/source/framework/responses/index.ts +4 -4
  135. package/source/framework/runtime/bun/server.ts +5 -5
  136. package/source/framework/runtime/deno/server.ts +156 -96
  137. package/source/framework/runtime/index.ts +11 -17
  138. package/source/framework/runtime/node/reply.ts +1 -1
  139. package/source/framework/runtime/node/request.ts +2 -2
  140. package/source/framework/runtime/node/server.ts +3 -3
  141. package/source/framework/runtime/web/server.ts +2 -2
  142. package/source/framework/services.ts +1 -1
  143. package/source/framework/utilities/artifact.util.ts +4 -0
  144. package/source/framework/utilities/csrf.util.ts +162 -0
  145. package/source/framework/utilities/index.ts +10 -9
  146. package/source/framework/utilities/openapi.utils.ts +7 -7
  147. package/source/framework/utilities/utilities.util.ts +1 -1
  148. package/source/types/application.ts +2 -2
  149. package/source/types/builder.ts +1 -1
  150. package/source/types/config.ts +1 -1
  151. package/source/types/controller.ts +3 -3
  152. package/source/types/core.ts +1 -1
  153. package/source/types/csrf.ts +38 -0
  154. package/source/types/guard.ts +1 -1
  155. package/source/types/http-responses.ts +1 -1
  156. package/source/types/index.ts +26 -25
  157. package/source/types/injection.ts +1 -1
  158. package/source/types/middleware.ts +1 -1
  159. package/source/types/plugin.ts +1 -1
  160. package/source/types/raiton.ts +1 -1
  161. package/source/types/responses.ts +2 -2
  162. package/source/types/router.ts +2 -2
  163. package/source/types/runtime.ts +3 -5
  164. package/source/types/thread.ts +4 -4
  165. /package/source/framework/utilities/{https.ts → https.util.ts} +0 -0
  166. /package/source/framework/utilities/{url.ts → url.util.ts} +0 -0
@@ -1,106 +1,166 @@
1
- import {RuntimeAdapterInterface, RuntimeRequestInterface, RuntimeReplyInterface} from '../../../types'
1
+ import {RuntimeAdapterInterface, RuntimeServerOptionsInterface} from '../../../types/index.ts'
2
2
  import {Logger} from "@protorians/logger";
3
- import {getRealIp} from "../../utilities";
4
-
5
- // class DenoRequest implements RuntimeRequestInterface {
6
- // constructor(private req: Request) {}
7
- // get method(): string { return this.req.method; }
8
- // get url(): string { return this.req.url; }
9
- // get headers(): Headers { return new Headers(this.req.headers); }
10
- // get body(): any { return this.req.body; }
11
- // get query(): Record<string, any> | undefined { return undefined; }
12
- // get params(): Record<string, any> | undefined { return undefined; }
13
- // get file(): any { return undefined; }
14
- // get files(): any { return undefined; }
15
- // get remoteAddress(): string | undefined { return undefined; }
16
- // get ip(): string | undefined { return getRealIp(this.headers, this.remoteAddress); }
17
- // }
18
-
19
- // class DenoReply implements RuntimeReplyInterface {
20
- // private statusCode: number = 200;
21
- // private headers: Headers = new Headers();
22
- // private body: BodyInit | null = null;
23
- //
24
- // status(code: number): void { this.statusCode = code; }
25
- // header(name: string, value: string): void { this.headers.set(name, value); }
26
- // send(body: any): void {
27
- // if (body === undefined) {
28
- // this.body = null;
29
- // } else if (typeof body === 'string' || body instanceof Uint8Array) {
30
- // this.body = body;
31
- // } else {
32
- // if (!this.headers.has('content-type')) {
33
- // this.headers.set('content-type', 'application/json');
34
- // }
35
- // this.body = JSON.stringify(body);
36
- // }
37
- // }
38
- // text(text: string | Buffer): void {
39
- // // Accept string, Uint8Array, or any other value (including Buffer-like)
40
- // if (typeof text === 'string' || text instanceof Uint8Array) {
41
- // this.body = text;
42
- // } else {
43
- // // Fallback: treat as JSON string
44
- // this.body = JSON.stringify(text);
45
- // }
46
- // }
47
- // json(json: any): void {
48
- // this.headers.set('content-type', 'application/json');
49
- // this.body = JSON.stringify(json);
50
- // }
51
- // type(contentType: string): void {
52
- // this.headers.set('content-type', contentType);
53
- // }
54
- // toResponse(): Response {
55
- // let bodyToSend: BodyInit = '';
56
- // if (this.body instanceof Uint8Array) {
57
- // bodyToSend = this.body;
58
- // } else if (typeof this.body === 'string') {
59
- // bodyToSend = this.body;
60
- // } else if (this.body === null) {
61
- // bodyToSend = '';
62
- // } else {
63
- // // fallback: treat as JSON
64
- // bodyToSend = JSON.stringify(this.body);
65
- // }
66
- // return new Response(bodyToSend, { status: this.statusCode, headers: this.headers });
67
- // }
68
- // }
69
-
70
- /**
71
- * @alpha Not ready
72
- */
3
+ import {getRealIp} from "../../utilities/index.ts";
4
+ import {findSocketForPath} from "../../../core/socket/index.ts";
5
+ import {Injection} from "../../../core/injection/index.ts";
6
+ import {RaitonResponses, HttpStatus} from "../../index.ts";
7
+
73
8
  export const denoRuntime: RuntimeAdapterInterface = {
74
- createServer(handler) {
75
- let controller: AbortController | null = null;
9
+ createServer(handler, options?: RuntimeServerOptionsInterface) {
10
+ if (typeof Deno === 'undefined') throw new Error(
11
+ 'Deno is not available, please run this script with the Deno runtime (`deno run --allow-net ...`)'
12
+ )
13
+
14
+ let server: Deno.HttpServer | null = null
15
+
16
+ const socketHandlers = {
17
+ open(socket: WebSocket, entry: any) {
18
+ try {
19
+ const instance: any = Injection.resolve(entry.construct)
20
+ if (!instance) return
21
+
22
+ socket.onmessage = async (event: MessageEvent) => {
23
+ try {
24
+ let payload: any = event.data
25
+ if (typeof payload === 'string') {
26
+ try { payload = JSON.parse(payload) } catch { /* keep raw string */ }
27
+ }
28
+
29
+ const eventName = payload && typeof payload === 'object' ? payload.event : undefined
30
+ const evt = eventName
31
+ ? entry.metadata.events.find((item: any) => item.name === eventName && (item.type === 'event' || item.type === 'message'))
32
+ : entry.metadata.events.find((item: any) => item.type === 'message')
33
+
34
+ if (!evt) {
35
+ socket.send(JSON.stringify(RaitonResponses(
36
+ `Socket event "${eventName ?? 'message'}" not found`,
37
+ null,
38
+ HttpStatus.NOT_FOUND
39
+ )))
40
+ return
41
+ }
42
+
43
+ const response = await instance[evt.propertyKey]?.(payload?.data ?? payload)
44
+ if (response !== undefined) {
45
+ socket.send(JSON.stringify(response))
46
+ }
47
+ } catch (e: any) {
48
+ Logger.error('Socket message failed', e.message ?? e)
49
+ socket.send(JSON.stringify(RaitonResponses(
50
+ 'Internal server error',
51
+ null,
52
+ HttpStatus.INTERNAL_SERVER_ERROR
53
+ )))
54
+ }
55
+ }
56
+
57
+ const connect = entry.metadata.events.find((event: any) => event.type === 'connect')
58
+ if (connect) instance[connect.propertyKey]?.()
59
+ } catch (e: any) {
60
+ Logger.error('Socket connect failed', e.message ?? e)
61
+ try { socket.close(1011, 'Internal error') } catch { /* noop */ }
62
+ }
63
+ },
64
+ close(socket: WebSocket, entry: any) {
65
+ try {
66
+ const instance = (socket as any)._instance
67
+ if (!instance) return
68
+
69
+ const disconnect = entry.metadata.events.find((event: any) => event.type === 'disconnect')
70
+ if (disconnect) instance[disconnect.propertyKey]?.()
71
+ } catch (e: any) {
72
+ Logger.error('Socket disconnect failed', e.message ?? e)
73
+ }
74
+ }
75
+ }
76
76
 
77
77
  return {
78
78
  async listen(port, hostname) {
79
- // controller = new AbortController();
80
- //
81
- // const server = Deno.serve({
82
- // port: Number(port),
83
- // hostname,
84
- // signal: controller.signal,
85
- // handler: async (reqEvent) => {
86
- // const denoReq = new DenoRequest(reqEvent.request);
87
- // const denoRes = new DenoReply();
88
- //
89
- // await handler(denoReq, denoRes);
90
- //
91
- // const resp = denoRes.toResponse();
92
- // await reqEvent.respondWith(resp);
93
- // }
94
- // });
95
-
96
- // Server will run until close() is called
79
+ server = Deno.serve(
80
+ {
81
+ port: Number(port),
82
+ hostname,
83
+ onListen() {
84
+ Logger.log('Deno server listening')
85
+ }
86
+ },
87
+ async (request, info) => {
88
+ const upgrade = request.headers.get('upgrade')?.toLowerCase()
89
+ const pathname = new URL(request.url).pathname
90
+
91
+ if (upgrade === 'websocket') {
92
+ const socketEntry = findSocketForPath(pathname, options?.prefix)
93
+ if (socketEntry) {
94
+ const {socket, response} = Deno.upgradeWebSocket(request)
95
+ const instance: any = Injection.resolve(socketEntry.construct)
96
+ ;(socket as any)._instance = instance
97
+ socket.onopen = () => socketHandlers.open(socket, socketEntry)
98
+ socket.onclose = () => socketHandlers.close(socket, socketEntry)
99
+ return response
100
+ }
101
+ }
102
+
103
+ let responseBody: any
104
+ let statusCode = 200
105
+ const headers = new Headers()
106
+
107
+ const remoteAddress = info.remoteAddr?.hostname
108
+
109
+ await handler(
110
+ {
111
+ method: request.method,
112
+ url: request.url,
113
+ headers: request.headers as any,
114
+ body: request.body ? request.body : null,
115
+ remoteAddress,
116
+ ip: getRealIp(request.headers, remoteAddress)
117
+ },
118
+ {
119
+ status(code) {
120
+ statusCode = code
121
+ },
122
+ header(name, value) {
123
+ headers.set(name, value)
124
+ },
125
+ send(body: any) {
126
+ if (body === undefined) {
127
+ responseBody = ''
128
+ } else if (typeof body === 'string' || body instanceof Uint8Array) {
129
+ responseBody = body;
130
+ } else {
131
+ headers.set('content-type', 'application/json');
132
+ responseBody = (JSON.stringify(body));
133
+ }
134
+ },
135
+ text(text: string | Uint8Array) {
136
+ responseBody = text
137
+ },
138
+ json(json: any) {
139
+ headers.set('content-type', 'application/json')
140
+ responseBody = JSON.stringify(json)
141
+ },
142
+ type(contentType: string) {
143
+ headers.set('content-type', contentType)
144
+ }
145
+ }
146
+ )
147
+
148
+ if (responseBody instanceof Response) {
149
+ return responseBody;
150
+ }
151
+
152
+ return new Response(
153
+ typeof responseBody === 'object' && !(responseBody instanceof Uint8Array)
154
+ ? JSON.stringify(responseBody)
155
+ : responseBody,
156
+ {status: statusCode, headers}
157
+ )
158
+ }
159
+ )
97
160
  },
98
161
  async close() {
99
- // if (controller) {
100
- // controller.abort();
101
- // }
102
- // Note: Deno.serve does not expose a direct stop; closing the signal aborts incoming connections.
162
+ await server?.shutdown()
103
163
  }
104
- };
164
+ }
105
165
  }
106
166
  }
@@ -4,12 +4,12 @@ import type {
4
4
  RuntimeInterface,
5
5
  RuntimeServerInterface,
6
6
  RuntimeServerOptionsInterface
7
- } from "../../types";
8
- import {RuntimeType} from "../enums/runtime.enum";
9
- import {nodeRuntime} from "./node/server";
10
- import {bunRuntime} from "./bun/server";
11
- import {denoRuntime} from "./deno/server";
12
- // import {webRuntime} from "./web/server";
7
+ } from "../../types/index.ts";
8
+ import {RuntimeType} from "../enums/runtime.enum.ts";
9
+ import {nodeRuntime} from "./node/server.ts";
10
+ import {bunRuntime} from "./bun/server.ts";
11
+ import {denoRuntime} from "./deno/server.ts";
12
+ // import {webRuntime} from "./web/server.ts";
13
13
 
14
14
 
15
15
  export class Runtime implements RuntimeInterface {
@@ -22,13 +22,9 @@ export class Runtime implements RuntimeInterface {
22
22
  return this.type === RuntimeType.Node;
23
23
  }
24
24
 
25
- // get isDeno(): boolean {
26
- // return this.type === RuntimeType.Deno;
27
- // }
28
- //
29
- // get isWeb(): boolean {
30
- // return this.type === RuntimeType.Web;
31
- // }
25
+ get isDeno(): boolean {
26
+ return this.type === RuntimeType.Deno;
27
+ }
32
28
 
33
29
  get isBun(): boolean {
34
30
  return this.type === RuntimeType.Bun;
@@ -40,10 +36,8 @@ export class Runtime implements RuntimeInterface {
40
36
  return nodeRuntime
41
37
  case RuntimeType.Bun:
42
38
  return bunRuntime
43
- // case RuntimeType.Deno:
44
- // return denoRuntime
45
- // case RuntimeType.Web:
46
- // return webRuntime
39
+ case RuntimeType.Deno:
40
+ return denoRuntime
47
41
  }
48
42
  }
49
43
 
@@ -1,5 +1,5 @@
1
1
  import { ServerResponse } from 'node:http'
2
- import type { RuntimeReplyInterface } from '../../../types'
2
+ import type { RuntimeReplyInterface } from '../../../types/index.ts'
3
3
 
4
4
  export class NodeReply implements RuntimeReplyInterface {
5
5
  constructor(public res: ServerResponse) {}
@@ -1,6 +1,6 @@
1
1
  import { IncomingMessage } from 'node:http'
2
- import type { RuntimeRequestInterface } from '../../../types'
3
- import {getRealIp} from "../../utilities";
2
+ import type { RuntimeRequestInterface } from '../../../types/index.ts'
3
+ import {getRealIp} from "../../utilities/index.ts";
4
4
 
5
5
  export class NodeRequest implements RuntimeRequestInterface {
6
6
  constructor(public req: IncomingMessage) {
@@ -5,9 +5,9 @@ import {
5
5
  RuntimeRequestInterface,
6
6
  RuntimeReplyInterface,
7
7
  RuntimeServerOptionsInterface
8
- } from '../../../types'
9
- import { NodeRequest } from './request'
10
- import { NodeReply } from './reply'
8
+ } from '../../../types/index.ts'
9
+ import { NodeRequest } from './request.ts'
10
+ import { NodeReply } from './reply.ts'
11
11
 
12
12
  export const nodeRuntime: RuntimeAdapterInterface = {
13
13
  createServer(handler, options?: RuntimeServerOptionsInterface) {
@@ -1,6 +1,6 @@
1
- // import {RuntimeAdapterInterface} from '../../../types'
1
+ // import {RuntimeAdapterInterface} from '../../../types/index.ts'
2
2
  // import {Logger} from "@protorians/logger";
3
- // import {getRealIp} from "../../utilities";
3
+ // import {getRealIp} from "../../utilities/index.ts";
4
4
  //
5
5
  // export const webRuntime: RuntimeAdapterInterface = {
6
6
  // createServer(handler) {
@@ -1,4 +1,4 @@
1
- import {DelegateRepository} from "./repositories";
1
+ import {DelegateRepository} from "./repositories.ts";
2
2
 
3
3
  export class DelegateService {
4
4
  protected repository!: DelegateRepository;
@@ -14,6 +14,10 @@ export function isMcpArtifact(filename: string) {
14
14
  return isArtifact(filename, 'mcp')
15
15
  }
16
16
 
17
+ export function isHealthCheckArtifact(filename: string) {
18
+ return isArtifact(filename, 'health-check')
19
+ }
20
+
17
21
  export function isArtifact(filename: string, artifact: string) {
18
22
  return [
19
23
  filename.endsWith(`.${artifact}.ts`),
@@ -0,0 +1,162 @@
1
+ import crypto from "node:crypto";
2
+ import {CsrfTokenPayload} from "../../types/index.ts";
3
+
4
+ const DEFAULT_TTL = 3600_000
5
+
6
+ export class CsrfUtil {
7
+
8
+ static generateDoubleSubmitToken(secret: string): string {
9
+ const timestamp = Date.now().toString(36)
10
+ const nonce = crypto.randomBytes(16).toString('hex')
11
+ const payload = `${timestamp}.${nonce}`
12
+ const signature = crypto
13
+ .createHmac('sha256', secret)
14
+ .update(payload)
15
+ .digest('hex')
16
+ return `${payload}.${signature}`
17
+ }
18
+
19
+ static validateDoubleSubmitToken(secret: string, token: string, maxAge?: number): boolean {
20
+ if (!token || typeof token !== 'string') return false
21
+
22
+ const parts = token.split('.')
23
+ if (parts.length !== 3) return false
24
+
25
+ const [timestampB36, nonce, signature] = parts
26
+ const payload = `${timestampB36}.${nonce}`
27
+
28
+ const expectedSignature = crypto
29
+ .createHmac('sha256', secret)
30
+ .update(payload)
31
+ .digest('hex')
32
+
33
+ if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature))) {
34
+ return false
35
+ }
36
+
37
+ if (maxAge !== undefined) {
38
+ const timestamp = parseInt(timestampB36, 36)
39
+ if (isNaN(timestamp)) return false
40
+ if (Date.now() - timestamp > maxAge) return false
41
+ }
42
+
43
+ return true
44
+ }
45
+
46
+ static generateSynchronizerToken(): string {
47
+ return crypto.randomBytes(32).toString('hex')
48
+ }
49
+
50
+ static createTokenStore(ttl: number = DEFAULT_TTL) {
51
+ const store = new Map<string, CsrfTokenPayload>()
52
+
53
+ const cleanup = () => {
54
+ const now = Date.now()
55
+ for (const [key, entry] of store) {
56
+ if (now > entry.expiresAt) {
57
+ store.delete(key)
58
+ }
59
+ }
60
+ }
61
+
62
+ const interval = setInterval(cleanup, Math.min(ttl, 60_000))
63
+ if (typeof interval === 'object' && 'unref' in interval) {
64
+ interval.unref()
65
+ }
66
+
67
+ return {
68
+ create(): string {
69
+ const token = CsrfUtil.generateSynchronizerToken()
70
+ store.set(token, {
71
+ token,
72
+ expiresAt: Date.now() + ttl
73
+ })
74
+ return token
75
+ },
76
+
77
+ validate(token: string): boolean {
78
+ if (!token || typeof token !== 'string') return false
79
+ const entry = store.get(token)
80
+ if (!entry) return false
81
+ if (Date.now() > entry.expiresAt) {
82
+ store.delete(token)
83
+ return false
84
+ }
85
+ return true
86
+ },
87
+
88
+ revoke(token: string): boolean {
89
+ return store.delete(token)
90
+ },
91
+
92
+ get size(): number {
93
+ return store.size
94
+ },
95
+
96
+ destroy(): void {
97
+ clearInterval(interval)
98
+ store.clear()
99
+ }
100
+ }
101
+ }
102
+
103
+ static isBrowserClient(headers: Headers, config?: {
104
+ headerName?: string
105
+ skipClients?: string[]
106
+ }): boolean {
107
+ const clientTypeHeader = config?.headerName ?? 'X-Client-Type'
108
+ const skipClients = config?.skipClients ?? ['mobile', 'desktop']
109
+
110
+ const clientType = headers.get(clientTypeHeader)
111
+ if (clientType && skipClients.includes(clientType.toLowerCase())) {
112
+ return false
113
+ }
114
+
115
+ const authorization = headers.get('authorization')
116
+ const hasCookie = headers.get('cookie')?.includes('_csrf') ?? false
117
+
118
+ if (authorization && !hasCookie) {
119
+ return false
120
+ }
121
+
122
+ return true
123
+ }
124
+
125
+ static serializeCookie(name: string, value: string, options?: {
126
+ httpOnly?: boolean
127
+ secure?: boolean
128
+ sameSite?: 'strict' | 'lax' | 'none'
129
+ path?: string
130
+ domain?: string
131
+ maxAge?: number
132
+ }): string {
133
+ let cookie = `${name}=${value}`
134
+
135
+ if (options?.httpOnly) cookie += '; HttpOnly'
136
+ if (options?.secure) cookie += '; Secure'
137
+ if (options?.sameSite) {
138
+ cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`
139
+ }
140
+ if (options?.path) cookie += `; Path=${options.path}`
141
+ if (options?.domain) cookie += `; Domain=${options.domain}`
142
+ if (options?.maxAge) cookie += `; Max-Age=${options.maxAge}`
143
+
144
+ return cookie
145
+ }
146
+
147
+ static extractCookieValue(cookieHeader: string, name: string): string | undefined {
148
+ const cookies = cookieHeader.split(';')
149
+ for (const cookie of cookies) {
150
+ const [key, ...valueParts] = cookie.trim().split('=')
151
+ if (key === name) {
152
+ return valueParts.join('=')
153
+ }
154
+ }
155
+ return undefined
156
+ }
157
+
158
+ static timingSafeEqual(a: string, b: string): boolean {
159
+ if (a.length !== b.length) return false
160
+ return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b))
161
+ }
162
+ }
@@ -1,9 +1,10 @@
1
- export * from "./callable.util"
2
- export * from "./utilities.util"
3
- export * from "./artifact.util"
4
- export * from "./json.util"
5
- export * from "./path.util"
6
- export * from "./cookie.util"
7
- export * from "./openapi.utils"
8
- export * from "./ip.util"
9
- export * from "./https"
1
+ export * from "./callable.util.ts"
2
+ export * from "./utilities.util.ts"
3
+ export * from "./artifact.util.ts"
4
+ export * from "./json.util.ts"
5
+ export * from "./path.util.ts"
6
+ export * from "./cookie.util.ts"
7
+ export * from "./openapi.utils.ts"
8
+ export * from "./ip.util.ts"
9
+ export * from "./https.util.ts"
10
+ export * from "./csrf.util.ts"
@@ -1,10 +1,10 @@
1
- import type {ParamMetaInterface} from "../../types";
2
- import {METADATA_KEYS, Parametrable} from "../index";
3
- import {PluginScope} from "../../core";
4
- import {RaitonConfig} from "../../core/config";
5
- import {getSocketRegistry} from "../../core/socket";
6
- import {getMcpServerRegistry} from "../../core/mcp";
7
- import {RaitonThread} from "../../core/thread";
1
+ import type {ParamMetaInterface} from "../../types/index.ts";
2
+ import {METADATA_KEYS, Parametrable} from "../index.ts";
3
+ import {PluginScope} from "../../core/index.ts";
4
+ import {RaitonConfig} from "../../core/config/index.ts";
5
+ import {getSocketRegistry} from "../../core/socket/index.ts";
6
+ import {getMcpServerRegistry} from "../../core/mcp/index.ts";
7
+ import {RaitonThread} from "../../core/thread.ts";
8
8
 
9
9
  /**
10
10
  * Generate the OpenAPI specification object
@@ -1,4 +1,4 @@
1
- import {GenericValuesType} from "../../types";
1
+ import {GenericValuesType} from "../../types/index.ts";
2
2
 
3
3
  export function getType(value: any): GenericValuesType {
4
4
  if (typeof value === "string") return "string";
@@ -1,5 +1,5 @@
1
- import {HttpMethod} from "../framework";
2
- import {HttpsConfigInput, HttpsConfigInterface} from "../framework/utilities/https";
1
+ import {HttpMethod} from "../framework/index.ts";
2
+ import {HttpsConfigInput, HttpsConfigInterface} from "../framework/utilities/https.util.ts";
3
3
 
4
4
  export interface ApplicationConfigInterface {
5
5
  workdir?: string;
@@ -1,5 +1,5 @@
1
1
  import {WatchEventType} from "node:fs";
2
- import type {HmrChannel} from "../framework/artifacts";
2
+ import type {HmrChannel} from "../framework/artifacts.ts";
3
3
 
4
4
  export interface StartCommandOptionsInterface {
5
5
  develop?: boolean;
@@ -1,4 +1,4 @@
1
- import type {ArtifactsConfigInterface} from "./artifact";
1
+ import type {ArtifactsConfigInterface} from "./artifact.ts";
2
2
 
3
3
  export interface ConfigurableInterface {
4
4
  rootDir: string;
@@ -1,6 +1,6 @@
1
- import {HttpMethod, Parametrable} from "../framework/enums";
2
- import {ContextInterface} from "./core";
3
- import {MiddlewareCallable, MiddlewareType} from "./middleware";
1
+ import {HttpMethod, Parametrable} from "../framework/enums/index.ts";
2
+ import {ContextInterface} from "./core.ts";
3
+ import {MiddlewareCallable, MiddlewareType} from "./middleware.ts";
4
4
 
5
5
  export interface ControllerMetaInterface {
6
6
  prefix?: string;
@@ -1,7 +1,7 @@
1
1
  import type {
2
2
  RuntimeRequestInterface,
3
3
  RuntimeReplyInterface
4
- } from './runtime'
4
+ } from './runtime.ts'
5
5
 
6
6
  export type HookNameType =
7
7
  | 'onRequest'
@@ -0,0 +1,38 @@
1
+ import {CSRFModeEnum} from "../framework/enums/index.ts";
2
+
3
+ export interface CsrfClientDetectionConfig {
4
+ headerName?: string
5
+ skipClients?: string[]
6
+ }
7
+
8
+ export interface CsrfOptions {
9
+ mode?: CSRFModeEnum
10
+ secret?: string
11
+ cookieName?: string
12
+ headerName?: string
13
+ ttl?: number
14
+ methods?: string[]
15
+ skip?: string[]
16
+ client?: CsrfClientDetectionConfig
17
+ cookieOptions?: CsrfCookieOptions
18
+ }
19
+
20
+ export interface CsrfCookieOptions {
21
+ httpOnly?: boolean
22
+ secure?: boolean
23
+ sameSite?: 'strict' | 'lax' | 'none'
24
+ path?: string
25
+ domain?: string
26
+ maxAge?: number
27
+ }
28
+
29
+ export interface CsrfTokenPayload {
30
+ token: string
31
+ expiresAt: number
32
+ }
33
+
34
+ export interface CsrfGuardOptions {
35
+ mode?: CSRFModeEnum
36
+ methods?: string[]
37
+ skipPaths?: string[]
38
+ }