@tylix/core 0.5.3 → 0.6.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tylix/core",
3
- "version": "0.5.3",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "keywords": [
6
6
  "tylix",
@@ -12,10 +12,10 @@
12
12
  "test": "node --test src/**/*.test.js"
13
13
  },
14
14
  "dependencies": {
15
- "@tylix/auth": "^0.5.1",
16
- "@tylix/compiler": "^0.5.1",
17
- "@tylix/orm": "^0.5.1",
18
- "@tylix/shared": "^0.5.1",
15
+ "@tylix/auth": "^0.6.0",
16
+ "@tylix/compiler": "^0.6.0",
17
+ "@tylix/orm": "^0.6.0",
18
+ "@tylix/shared": "^0.6.0",
19
19
  "ws": "^8.18.0"
20
20
  },
21
21
  "devDependencies": {
@@ -1,3 +1,7 @@
1
1
  import type { Router } from '../router/Router.js'
2
2
 
3
- export declare function loadCustomRoutes(router: Router, baseDir: string): Promise<boolean>
3
+ export declare function loadCustomRoutes(
4
+ router: Router,
5
+ baseDir: string,
6
+ options?: { secret?: string; hydrate?: unknown },
7
+ ): Promise<boolean>
@@ -2,8 +2,56 @@ import fs from 'node:fs/promises'
2
2
  import path from 'node:path'
3
3
  import { pathToFileURL } from 'node:url'
4
4
  import { detectLanguage } from '@tylix/shared'
5
+ import { requireAuth } from '../http/requireAuth.js'
5
6
 
6
- export async function loadCustomRoutes(router, baseDir) {
7
+ const VERBS = new Set(['get', 'post', 'put', 'patch', 'delete'])
8
+
9
+ // Same symbol requireAuth sets on its handlers. authGuard below is not a
10
+ // requireAuth result, so it is marked here by hand.
11
+ const AUTH_MARK = Symbol.for('tylix.requireAuth')
12
+
13
+ // A view of the router where every route registered through it gets the
14
+ // `guards` middleware placed ahead of its own middleware and handler.
15
+ // Every method returns the scoped view, so chaining stays guarded.
16
+ function scopedRouter(router, guards) {
17
+ const register = (method, pattern, ...handlers) => {
18
+ if (handlers.length === 0) {
19
+ throw new Error(
20
+ `Router.${method.toLowerCase()}("${pattern}") needs a handler`,
21
+ )
22
+ }
23
+ router.register(method, pattern, ...guards, ...handlers)
24
+ return scoped
25
+ }
26
+
27
+ const scoped = new Proxy(router, {
28
+ get(target, prop) {
29
+ if (prop === 'register') return register
30
+ if (typeof prop === 'string' && VERBS.has(prop)) {
31
+ return (pattern, ...handlers) =>
32
+ register(prop.toUpperCase(), pattern, ...handlers)
33
+ }
34
+ if (prop === 'use') {
35
+ return () => {
36
+ throw new Error(
37
+ 'router.use() is global middleware and cannot be called inside protectedRoutes(); call it in publicRoutes() or a plain routes() export instead.',
38
+ )
39
+ }
40
+ }
41
+ const value = Reflect.get(target, prop, target)
42
+ return typeof value === 'function' ? value.bind(target) : value
43
+ },
44
+ })
45
+
46
+ return scoped
47
+ }
48
+
49
+ // Loads app/routes/web.{ts,js}. It may export:
50
+ // publicRoutes(router) reachable by anyone
51
+ // protectedRoutes(router) every route requires a logged-in user
52
+ // routes(router, { auth }) legacy: you wrap handlers yourself
53
+ // Returns true when the web file exists.
54
+ export async function loadCustomRoutes(router, baseDir, { secret, hydrate } = {}) {
7
55
  const language = await detectLanguage(baseDir)
8
56
  const ext = language === 'typescript' ? 'ts' : 'js'
9
57
  const routesPath = path.join(baseDir, 'app', 'routes', `web.${ext}`)
@@ -15,8 +63,41 @@ export async function loadCustomRoutes(router, baseDir) {
15
63
  if (!exists) return false
16
64
 
17
65
  const mod = await import(pathToFileURL(routesPath).href)
66
+ const auth = (handler) => requireAuth(handler, secret, { hydrate })
67
+
68
+ // Middleware form of requireAuth: runs first, and only calls next()
69
+ // when the token is valid (requireAuth answers 401/500 itself otherwise).
70
+ const authGuard = (req, res, next) =>
71
+ requireAuth(() => next(), secret, { hydrate })(req, res)
72
+ authGuard[AUTH_MARK] = true
73
+
74
+ let loaded = false
75
+
76
+ if (typeof mod.publicRoutes === 'function') {
77
+ await mod.publicRoutes(router)
78
+ loaded = true
79
+ }
80
+
81
+ if (typeof mod.protectedRoutes === 'function') {
82
+ if (!secret) {
83
+ throw new Error(
84
+ 'protectedRoutes() needs auth.secret, but none is configured. Set AUTH_SECRET.',
85
+ )
86
+ }
87
+ await mod.protectedRoutes(scopedRouter(router, [authGuard]))
88
+ loaded = true
89
+ }
90
+
18
91
  if (typeof mod.routes === 'function') {
19
- await mod.routes(router)
92
+ await mod.routes(router, { auth })
93
+ loaded = true
20
94
  }
95
+
96
+ if (!loaded) {
97
+ console.warn(
98
+ `⚠ app/routes/web.${ext} exports none of publicRoutes, protectedRoutes or routes, skipped`,
99
+ )
100
+ }
101
+
21
102
  return true
22
- }
103
+ }
@@ -6,6 +6,8 @@ import { requireAuth } from '../http/requireAuth.js'
6
6
  const ROUTE_FILE = /\.(js|ts)$/
7
7
  // .d.ts files, _private files, dotfiles, and web.* (already loaded by loadCustomRoutes)
8
8
  const SKIP = /(\.d\.ts$|^_|^\.|^web\.(js|ts)$)/
9
+ // Handler files written by make:api. web.* imports them; they export no routes().
10
+ const SKIP_DIRS = new Set(['handlers'])
9
11
 
10
12
  async function collect(dir) {
11
13
  const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => [])
@@ -14,8 +16,10 @@ async function collect(dir) {
14
16
  for (const entry of entries) {
15
17
  if (SKIP.test(entry.name)) continue
16
18
  const full = path.join(dir, entry.name)
17
- if (entry.isDirectory()) files.push(...(await collect(full)))
18
- else if (entry.isFile() && ROUTE_FILE.test(entry.name)) files.push(full)
19
+ if (entry.isDirectory()) {
20
+ if (SKIP_DIRS.has(entry.name)) continue
21
+ files.push(...(await collect(full)))
22
+ } else if (entry.isFile() && ROUTE_FILE.test(entry.name)) files.push(full)
19
23
  }
20
24
 
21
25
  return files.sort()
@@ -1,20 +1,61 @@
1
1
  import type { Router } from '../router/Router.js'
2
+ import type { Server as HttpServer } from 'node:http'
2
3
 
3
- export type NotFoundHandler = (req: any, res: any) => boolean | void | Promise<boolean | void>
4
+ export type NotFoundHandler = (
5
+ req: any,
6
+ res: any,
7
+ ) => boolean | void | Promise<boolean | void>
4
8
 
5
9
  export interface ServerOptions {
10
+ /**
11
+ * Called when no route matches, before the default 404 JSON response.
12
+ * `tylix dev` uses it to serve static files from public/. Return true
13
+ * if it handled the request; false/undefined falls through to the 404.
14
+ */
6
15
  notFoundHandler?: NotFoundHandler | null
16
+
7
17
  /**
8
- * Believe X-Forwarded-For and X-Forwarded-Proto. Enable only behind a
9
- * proxy you control (nginx). Defaults to the TRUST_PROXY=true env var.
18
+ * Believe X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto.
19
+ * Enable only behind a proxy you control (nginx).
20
+ * Defaults to the TRUST_PROXY=true env var.
10
21
  */
11
22
  trustProxy?: boolean
23
+
24
+ /**
25
+ * Show real error details (debug page, SQL, stack) instead of a generic
26
+ * 500. Defaults to the APP_DEBUG=true env var.
27
+ */
28
+ debug?: boolean
29
+
30
+ /**
31
+ * Largest request body accepted, in bytes. Bigger bodies get a 413.
32
+ * Defaults to the MAX_BODY_BYTES env var, then 1 MB.
33
+ */
34
+ maxBodyBytes?: number
12
35
  }
13
36
 
14
37
  export declare class Server {
38
+ router: Router
39
+ notFoundHandler: NotFoundHandler | null
40
+ trustProxy: boolean
41
+ production: boolean
42
+ debug: boolean
43
+ maxBodyBytes: number
44
+ /** Origins allowed to make cross-site browser writes (TRUSTED_ORIGINS + APP_URL). */
45
+ trustedOrigins: Set<string>
46
+ /** CSP_MODE: 'off' | 'report-only' | 'enforce' (lowercased, not validated). */
47
+ cspMode: string
48
+ csp: string
49
+
15
50
  constructor(router: Router, options?: ServerOptions)
51
+
16
52
  createHandler(): (req: any, res: any) => Promise<void>
17
- listen(port: number, callback?: () => void): import('node:http').Server
18
- }
53
+ listen(port: number, callback?: () => void): HttpServer
19
54
 
20
- export declare function readBody(req: any): Promise<{ raw: string; body: any }>
55
+ applySecurityHeaders(req: any, res: any): void
56
+ isCrossSiteWrite(req: any): boolean
57
+ handle(req: any, res: any): Promise<void>
58
+ logFailure(req: any, err: any): void
59
+ sendDebug(req: any, res: any, err: any): void
60
+ fail(req: any, res: any, err: any): void
61
+ }
@@ -7,6 +7,7 @@ import { buildDebugPayload } from './debug/buildDebugPayload.js'
7
7
  import { renderDebugPage } from './debug/renderDebugPage.js'
8
8
 
9
9
  const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
10
+ const DEFAULT_MAX_BODY_BYTES = 1024 * 1024 // 1 MB
10
11
 
11
12
  // Pages inline their scripts, so script-src needs 'unsafe-inline'. The rest
12
13
  // still blocks framing, base-tag and form hijacking, plugins, and data being
@@ -90,7 +91,10 @@ function wantsHtml(req) {
90
91
  }
91
92
 
92
93
  export class Server {
93
- constructor(router, { notFoundHandler = null, trustProxy, debug } = {}) {
94
+ constructor(
95
+ router,
96
+ { notFoundHandler = null, trustProxy, debug, maxBodyBytes } = {},
97
+ ) {
94
98
  this.router = router
95
99
  // Optional fallback called when no route matches, before the
96
100
  // default 404 JSON response -- e.g. tylix dev uses this to serve
@@ -105,6 +109,11 @@ export class Server {
105
109
  // Show real error details (debug page, SQL, stack) instead of a
106
110
  // generic 500. Defaults to the APP_DEBUG=true env var.
107
111
  this.debug = debug ?? process.env.APP_DEBUG === 'true'
112
+ // Largest request body accepted, in bytes. Bigger bodies get a 413.
113
+ // Defaults to the MAX_BODY_BYTES env var, then 1 MB.
114
+ this.maxBodyBytes =
115
+ maxBodyBytes ??
116
+ (Number(process.env.MAX_BODY_BYTES) || DEFAULT_MAX_BODY_BYTES)
108
117
 
109
118
  // Origins allowed to make browser write requests from elsewhere
110
119
  // (TRUSTED_ORIGINS=https://a.example,https://b.example). APP_URL counts too.
@@ -216,13 +225,17 @@ export class Server {
216
225
  req.cookies = parseCookies(req)
217
226
 
218
227
  try {
219
- const { raw, body } = await readBody(req)
228
+ const { raw, body } = await readBody(req, { maxBytes: this.maxBodyBytes })
220
229
  // The exact text the client sent. Webhook signatures are computed
221
230
  // over these bytes, so they must not be re-serialised from req.body.
222
231
  req.rawBody = raw
223
232
  req.body = body
224
233
  } catch (err) {
225
- res.status(400).json({ error: err.message })
234
+ const status = err.status ?? 400
235
+ // After an oversized upload, don't reuse the connection: the rest of
236
+ // the body may still be on the wire.
237
+ if (status === 413) res.setHeader('Connection', 'close')
238
+ res.status(status).json({ error: err.message })
226
239
  return
227
240
  }
228
241
 
@@ -1 +1,22 @@
1
- export declare function parseBody(req: import('node:http').IncomingMessage): Promise<Record<string, unknown>>
1
+ import type { IncomingMessage } from 'node:http'
2
+
3
+ export interface ReadBodyOptions {
4
+ /** Maximum body size in bytes. Defaults to 1 MB. Larger bodies reject with status 413. */
5
+ maxBytes?: number
6
+ }
7
+
8
+ /**
9
+ * Reads the whole request body once. `raw` is the exact UTF-8 text the
10
+ * client sent (use it for webhook signatures). `body` is the parsed JSON,
11
+ * or {} for empty and non-JSON bodies. Rejects with an Error carrying
12
+ * `status` (413 too large, 400 invalid JSON).
13
+ */
14
+ export declare function readBody(
15
+ req: IncomingMessage,
16
+ options?: ReadBodyOptions,
17
+ ): Promise<{ raw: string; body: any }>
18
+
19
+ export declare function parseBody(
20
+ req: IncomingMessage,
21
+ options?: ReadBodyOptions,
22
+ ): Promise<any>
@@ -1,3 +1,16 @@
1
+ const DEFAULT_MAX_BYTES = 1024 * 1024 // 1 MB
2
+
3
+ function isJson(contentType) {
4
+ const type = String(contentType).split(';')[0].trim().toLowerCase()
5
+ return type === 'application/json' || type.endsWith('+json')
6
+ }
7
+
8
+ function httpError(message, status) {
9
+ const err = new Error(message)
10
+ err.status = status
11
+ return err
12
+ }
13
+
1
14
  /**
2
15
  * Reads the whole request body once.
3
16
  * Returns { raw, body }: raw is the exact UTF-8 text the client sent,
@@ -6,41 +19,58 @@
6
19
  * Chunks are collected as Buffers and decoded once at the end. Joining
7
20
  * them as strings can split a multi-byte character across two chunks,
8
21
  * which would change the text and break webhook signature checks.
22
+ *
23
+ * Bodies larger than `maxBytes` (default 1 MB) are rejected with an error
24
+ * whose `status` is 413. Invalid JSON is rejected with status 400.
9
25
  */
10
- export function readBody(req) {
26
+ export function readBody(req, { maxBytes = DEFAULT_MAX_BYTES } = {}) {
11
27
  return new Promise((resolve, reject) => {
12
- const chunks = [];
13
-
14
- req.on("data", (chunk) => {
15
- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
16
- });
28
+ const chunks = []
29
+ let size = 0
30
+ let tooLarge = false
17
31
 
18
- req.on("end", () => {
19
- const raw = Buffer.concat(chunks).toString("utf8");
32
+ // Reject early when the client announces a size that is already too big.
33
+ const declared = Number(req.headers['content-length'])
34
+ if (declared > maxBytes) {
35
+ req.resume() // drain so the response can still be sent
36
+ return reject(httpError('Request body too large', 413))
37
+ }
20
38
 
21
- if (!raw) {
22
- resolve({ raw: "", body: {} });
23
- return;
39
+ req.on('data', (chunk) => {
40
+ if (tooLarge) return // keep draining, stop buffering
41
+ const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk
42
+ size += buf.length
43
+ if (size > maxBytes) {
44
+ tooLarge = true
45
+ chunks.length = 0
46
+ reject(httpError('Request body too large', 413))
47
+ return
24
48
  }
49
+ chunks.push(buf)
50
+ })
51
+
52
+ req.on('end', () => {
53
+ if (tooLarge) return
54
+ const raw = Buffer.concat(chunks).toString('utf8')
55
+
56
+ if (!raw) return resolve({ raw: '', body: {} })
25
57
 
26
- const contentType = req.headers["content-type"] || "";
27
- if (!contentType.includes("application/json")) {
28
- resolve({ raw, body: {} });
29
- return;
58
+ if (!isJson(req.headers['content-type'] || '')) {
59
+ return resolve({ raw, body: {} })
30
60
  }
31
61
 
32
62
  try {
33
- resolve({ raw, body: JSON.parse(raw) });
34
- } catch (err) {
35
- reject(new Error("Invalid JSON body"));
63
+ resolve({ raw, body: JSON.parse(raw) })
64
+ } catch {
65
+ reject(httpError('Invalid JSON body', 400))
36
66
  }
37
- });
67
+ })
38
68
 
39
- req.on("error", reject);
40
- });
69
+ req.on('error', reject)
70
+ })
41
71
  }
42
72
 
43
- export async function parseBody(req) {
44
- const { body } = await readBody(req);
45
- return body;
73
+ export async function parseBody(req, options) {
74
+ const { body } = await readBody(req, options)
75
+ return body
46
76
  }
@@ -1,3 +1,15 @@
1
1
  import type { Handler } from '../router/Router.js'
2
2
 
3
- export declare function requireAuth(handler: Handler, secret: string): Handler
3
+ export interface RequireAuthOptions {
4
+ /**
5
+ * Runs after the token is verified. Return an object to merge into
6
+ * req.user, return null/false to reject with 401, or throw for a 500.
7
+ */
8
+ hydrate?: (payload: any, req: any) => unknown | Promise<unknown>
9
+ }
10
+
11
+ export declare function requireAuth(
12
+ handler: Handler,
13
+ secret: string,
14
+ options?: RequireAuthOptions,
15
+ ): Handler
@@ -1,5 +1,9 @@
1
1
  import { verifyToken, ACCESS_TOKEN_COOKIE } from "@tylix/auth";
2
2
 
3
+ // Shared across packages (Symbol.for), so `tylix dev` can print a lock next
4
+ // to every guarded route without importing anything from here.
5
+ const AUTH_MARK = Symbol.for("tylix.requireAuth");
6
+
3
7
  /**
4
8
  * Wraps a route handler so it only runs if the request carries a valid
5
9
  * session. Checks the httpOnly access-token cookie first (what the
@@ -18,7 +22,7 @@ import { verifyToken, ACCESS_TOKEN_COOKIE } from "@tylix/auth";
18
22
  export function requireAuth(handler, secret, options = {}) {
19
23
  const { hydrate } = options;
20
24
 
21
- return async (req, res) => {
25
+ const guarded = async (req, res) => {
22
26
  const cookieToken = req.cookies?.[ACCESS_TOKEN_COOKIE];
23
27
 
24
28
  const authHeader = req.headers?.authorization || "";
@@ -57,4 +61,7 @@ export function requireAuth(handler, secret, options = {}) {
57
61
 
58
62
  return handler(req, res);
59
63
  };
64
+
65
+ guarded[AUTH_MARK] = true;
66
+ return guarded;
60
67
  }
@@ -2,7 +2,7 @@ export type Handler = (
2
2
  req: any,
3
3
  res: any,
4
4
  next: () => Promise<void>,
5
- ) => void | Promise<void>
5
+ ) => unknown
6
6
 
7
7
  interface Route {
8
8
  method: string
@@ -21,6 +21,7 @@ export declare class Router {
21
21
  get(pattern: string, ...handlers: Handler[]): this
22
22
  post(pattern: string, ...handlers: Handler[]): this
23
23
  put(pattern: string, ...handlers: Handler[]): this
24
+ patch(pattern: string, ...handlers: Handler[]): this
24
25
  delete(pattern: string, ...handlers: Handler[]): this
25
26
  match(
26
27
  method: string,
@@ -72,6 +72,10 @@ export class Router {
72
72
  return this.register('PUT', pattern, ...handlers)
73
73
  }
74
74
 
75
+ patch(pattern, ...handlers) {
76
+ return this.register('PATCH', pattern, ...handlers)
77
+ }
78
+
75
79
  delete(pattern, ...handlers) {
76
80
  return this.register('DELETE', pattern, ...handlers)
77
81
  }
@@ -100,4 +104,4 @@ export class Router {
100
104
 
101
105
  return null
102
106
  }
103
- }
107
+ }