@tylix/core 0.3.5 → 0.4.1

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.3.5",
3
+ "version": "0.4.1",
4
4
  "type": "module",
5
5
  "keywords": [
6
6
  "tylix",
@@ -12,14 +12,14 @@
12
12
  "test": "node --test src/**/*.test.js"
13
13
  },
14
14
  "dependencies": {
15
- "@tylix/auth": "^0.3.5",
16
- "@tylix/compiler": "^0.3.5",
17
- "@tylix/orm": "^0.3.5",
18
- "@tylix/shared": "^0.3.5",
15
+ "@tylix/auth": "^0.4.0",
16
+ "@tylix/compiler": "^0.4.0",
17
+ "@tylix/orm": "^0.4.0",
18
+ "@tylix/shared": "^0.4.0",
19
19
  "ws": "^8.18.0"
20
20
  },
21
21
  "devDependencies": {
22
22
  "@types/node": "^26.1.2",
23
23
  "@types/ws": "^8.18.1"
24
24
  }
25
- }
25
+ }
@@ -1,9 +1,9 @@
1
1
  import { requireAuth } from "../http/requireAuth.js";
2
2
 
3
- export function registerFeatureRoutes(router, features, { secret } = {}) {
3
+ export function registerFeatureRoutes(router, features, { secret, hydrate } = {}) {
4
4
  for (const { manifest, controller } of features) {
5
5
  const base = `/api/${manifest.table}`;
6
- const wrap = (fn) => (manifest.auth ? requireAuth(fn, secret) : fn);
6
+ const wrap = (fn) => (manifest.auth ? requireAuth(fn, secret, { hydrate }) : fn);
7
7
 
8
8
  router.get(base, wrap((req, res) => controller.index(req, res)));
9
9
  router.get(`${base}/:id`, wrap((req, res) => controller.show(req, res)));
@@ -11,4 +11,4 @@ export function registerFeatureRoutes(router, features, { secret } = {}) {
11
11
  router.put(`${base}/:id`, wrap((req, res) => controller.update(req, res)));
12
12
  router.delete(`${base}/:id`, wrap((req, res) => controller.destroy(req, res)));
13
13
  }
14
- }
14
+ }
@@ -0,0 +1,7 @@
1
+ import type { Router } from '../router/Router.js'
2
+
3
+ export declare function registerRouteFiles(
4
+ router: Router,
5
+ baseDir: string,
6
+ options?: { secret?: string },
7
+ ): Promise<string[]>
@@ -0,0 +1,44 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { pathToFileURL } from 'node:url'
4
+ import { requireAuth } from '../http/requireAuth.js'
5
+
6
+ const ROUTE_FILE = /\.(js|ts)$/
7
+ // .d.ts files, _private files, dotfiles, and web.* (already loaded by loadCustomRoutes)
8
+ const SKIP = /(\.d\.ts$|^_|^\.|^web\.(js|ts)$)/
9
+
10
+ async function collect(dir) {
11
+ const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => [])
12
+ const files = []
13
+
14
+ for (const entry of entries) {
15
+ if (SKIP.test(entry.name)) continue
16
+ 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
+ }
20
+
21
+ return files.sort()
22
+ }
23
+
24
+ // Mounts every app/routes/**/*.{js,ts} file exporting routes(router, { auth }).
25
+ // `hydrate` (optional) is passed to requireAuth: see http/requireAuth.js.
26
+ export async function registerRouteFiles(router, baseDir, { secret, hydrate } = {}) {
27
+ const routesDir = path.join(baseDir, 'app', 'routes')
28
+ const context = { auth: (handler) => requireAuth(handler, secret, { hydrate }) }
29
+ const mounted = []
30
+
31
+ for (const file of await collect(routesDir)) {
32
+ const mod = await import(pathToFileURL(file).href)
33
+
34
+ if (typeof mod.routes !== 'function') {
35
+ console.warn(`⚠ ${path.relative(baseDir, file)} has no routes() export, skipped`)
36
+ continue
37
+ }
38
+
39
+ await mod.routes(router, context)
40
+ mounted.push(path.relative(baseDir, file))
41
+ }
42
+
43
+ return mounted
44
+ }
@@ -4,6 +4,11 @@ export type NotFoundHandler = (req: any, res: any) => boolean | void | Promise<b
4
4
 
5
5
  export interface ServerOptions {
6
6
  notFoundHandler?: NotFoundHandler | null
7
+ /**
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.
10
+ */
11
+ trustProxy?: boolean
7
12
  }
8
13
 
9
14
  export declare class Server {
@@ -4,8 +4,33 @@ import { parseBody } from './parseBody.js'
4
4
  import { parseQuery } from './parseQuery.js'
5
5
  import { parseCookies } from './parseCookies.js'
6
6
 
7
+ // Forwarding headers are only believed when the app is told it sits behind
8
+ // a proxy it controls, because any client can send X-Forwarded-For. The LAST
9
+ // hop is the one our own proxy appended, so a forged leading entry is ignored.
10
+ function clientIp(req, trustProxy) {
11
+ if (trustProxy) {
12
+ const hops = String(req.headers['x-forwarded-for'] || '')
13
+ .split(',')
14
+ .map((hop) => hop.trim())
15
+ .filter(Boolean)
16
+ if (hops.length > 0) return hops[hops.length - 1]
17
+ }
18
+ return req.socket.remoteAddress || 'unknown'
19
+ }
20
+
21
+ function isSecure(req, trustProxy) {
22
+ if (req.socket.encrypted) return true
23
+ if (!trustProxy) return false
24
+ const proto = String(req.headers['x-forwarded-proto'] || '')
25
+ .split(',')
26
+ .pop()
27
+ .trim()
28
+ .toLowerCase()
29
+ return proto === 'https'
30
+ }
31
+
7
32
  export class Server {
8
- constructor(router, { notFoundHandler = null } = {}) {
33
+ constructor(router, { notFoundHandler = null, trustProxy } = {}) {
9
34
  this.router = router
10
35
  // Optional fallback called when no route matches, before the
11
36
  // default 404 JSON response -- e.g. tylix dev uses this to serve
@@ -13,43 +38,85 @@ export class Server {
13
38
  // request (already wrote a response); false/undefined falls
14
39
  // through to the default 404.
15
40
  this.notFoundHandler = notFoundHandler
41
+ // Believe X-Forwarded-For / X-Forwarded-Proto. Enable only behind a
42
+ // proxy you control (nginx). Defaults to the TRUST_PROXY=true env var.
43
+ this.trustProxy = trustProxy ?? process.env.TRUST_PROXY === 'true'
44
+ this.production = process.env.NODE_ENV === 'production'
16
45
  }
17
46
 
18
47
  createHandler() {
19
48
  return async (req, res) => {
20
49
  enhanceResponse(res)
21
-
22
- const match = this.router.match(req.method, req.url)
23
- if (!match) {
24
- if (this.notFoundHandler) {
25
- const handled = await this.notFoundHandler(req, res)
26
- if (handled) return
27
- }
28
- res.status(404).json({ error: 'Not found' })
29
- return
30
- }
31
-
32
- req.params = match.params
33
- req.query = parseQuery(req.url)
34
- req.cookies = parseCookies(req)
35
-
36
50
  try {
37
- req.body = await parseBody(req)
51
+ await this.handle(req, res)
38
52
  } catch (err) {
39
- res.status(400).json({ error: err.message })
40
- return
53
+ this.fail(req, res, err)
41
54
  }
55
+ }
56
+ }
42
57
 
43
- try {
44
- await match.handler(req, res)
45
- } catch (err) {
46
- res.status(500).json({ error: err.message })
58
+ async handle(req, res) {
59
+ res.setHeader('X-Content-Type-Options', 'nosniff')
60
+ res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin')
61
+
62
+ req.ip = clientIp(req, this.trustProxy)
63
+ req.secure = isSecure(req, this.trustProxy)
64
+
65
+ let match = this.router.match(req.method, req.url)
66
+ // HEAD is GET without a body; Node drops the body for us.
67
+ if (!match && req.method === 'HEAD') {
68
+ match = this.router.match('GET', req.url)
69
+ }
70
+
71
+ if (!match) {
72
+ if (this.notFoundHandler) {
73
+ const handled = await this.notFoundHandler(req, res)
74
+ if (handled) return
47
75
  }
76
+ res.status(404).json({ error: 'Not found' })
77
+ return
78
+ }
79
+
80
+ req.params = match.params
81
+ req.query = parseQuery(req.url)
82
+ req.cookies = parseCookies(req)
83
+
84
+ try {
85
+ req.body = await parseBody(req)
86
+ } catch (err) {
87
+ res.status(400).json({ error: err.message })
88
+ return
48
89
  }
90
+
91
+ await match.handler(req, res)
92
+ }
93
+
94
+ fail(req, res, err) {
95
+ // A malformed %-escape in the URL is the client's fault, not a crash.
96
+ const badRequest = err instanceof URIError
97
+
98
+ if (!badRequest) {
99
+ // Log the path only: query strings can carry tokens.
100
+ console.error(`[tylix] ${req.method} ${String(req.url).split('?')[0]} failed:`, err)
101
+ }
102
+
103
+ if (res.headersSent) {
104
+ if (!res.writableEnded) res.end()
105
+ return
106
+ }
107
+
108
+ if (badRequest) {
109
+ res.status(400).json({ error: 'Bad request' })
110
+ return
111
+ }
112
+
113
+ res.status(500).json({
114
+ error: this.production ? 'Internal server error' : err.message,
115
+ })
49
116
  }
50
117
 
51
118
  listen(port, callback) {
52
119
  const server = http.createServer(this.createHandler())
53
120
  return server.listen(port, callback)
54
121
  }
55
- }
122
+ }
@@ -39,14 +39,28 @@ export function enhanceResponse(res) {
39
39
  res.end()
40
40
  return res
41
41
  }
42
- res.end(typeof data === 'string' ? data : JSON.stringify(data))
43
- return res
42
+ if (typeof data === 'string' || Buffer.isBuffer(data)) {
43
+ res.end(data)
44
+ return res
45
+ }
46
+ // Objects, numbers, booleans: send as JSON with the right Content-Type.
47
+ return res.json(data)
44
48
  }
45
49
 
46
50
  // Set-Cookie can legitimately appear more than once (access + refresh
47
51
  // tokens in the same response), so this appends rather than overwrites.
52
+ // Secure defaults to on for HTTPS requests and in production, and is
53
+ // forced on for SameSite=None (browsers reject it otherwise). Pass
54
+ // secure: false explicitly to opt out.
48
55
  res.cookie = function (name, value, options = {}) {
49
- const serialized = serializeCookie(name, value, options)
56
+ const secureByDefault =
57
+ Boolean(res.req && res.req.secure) ||
58
+ process.env.NODE_ENV === 'production' ||
59
+ options.sameSite === 'None'
60
+ const serialized = serializeCookie(name, value, {
61
+ ...options,
62
+ secure: options.secure ?? secureByDefault,
63
+ })
50
64
  const existing = res.getHeader('Set-Cookie')
51
65
  const cookies = existing
52
66
  ? Array.isArray(existing)
@@ -64,4 +78,4 @@ export function enhanceResponse(res) {
64
78
  }
65
79
 
66
80
  return res
67
- }
81
+ }
@@ -0,0 +1,9 @@
1
+ export interface RateLimitResult {
2
+ allowed: boolean
3
+ retryAfterSeconds: number
4
+ }
5
+
6
+ export declare function createRateLimiter(options: {
7
+ max: number
8
+ windowMs: number
9
+ }): (key: string) => RateLimitResult
@@ -0,0 +1,33 @@
1
+ // In-memory sliding-window limiter. Fine for a single server process;
2
+ // with several processes each one keeps its own counts.
3
+ export function createRateLimiter({ max, windowMs }) {
4
+ const hits = new Map()
5
+ let lastSweep = Date.now()
6
+
7
+ return function check(key) {
8
+ const now = Date.now()
9
+
10
+ // Drop keys that have gone quiet so the map can't grow without bound.
11
+ if (now - lastSweep > windowMs) {
12
+ for (const [k, times] of hits) {
13
+ if (times.every((t) => now - t >= windowMs)) hits.delete(k)
14
+ }
15
+ lastSweep = now
16
+ }
17
+
18
+ const recent = (hits.get(key) ?? []).filter((t) => now - t < windowMs)
19
+
20
+ if (recent.length >= max) {
21
+ hits.set(key, recent)
22
+ const retryAfterSeconds = Math.max(
23
+ 1,
24
+ Math.ceil((recent[0] + windowMs - now) / 1000),
25
+ )
26
+ return { allowed: false, retryAfterSeconds }
27
+ }
28
+
29
+ recent.push(now)
30
+ hits.set(key, recent)
31
+ return { allowed: true, retryAfterSeconds: 0 }
32
+ }
33
+ }
@@ -8,8 +8,16 @@ import { verifyToken, ACCESS_TOKEN_COOKIE } from "@tylix/auth";
8
8
  * that can't rely on cookies). On success, req.user is set to the
9
9
  * token's payload (e.g. { userId }); on failure, responds 401 and
10
10
  * never calls the wrapped handler.
11
+ *
12
+ * options.hydrate(payload, req) is optional. It runs after the token is
13
+ * verified and can add fields to req.user (for example a team id):
14
+ * - return an object -> its fields are merged into req.user
15
+ * - return null/false -> the request is rejected with 401
16
+ * - throw -> the request is rejected with 500
11
17
  */
12
- export function requireAuth(handler, secret) {
18
+ export function requireAuth(handler, secret, options = {}) {
19
+ const { hydrate } = options;
20
+
13
21
  return async (req, res) => {
14
22
  const cookieToken = req.cookies?.[ACCESS_TOKEN_COOKIE];
15
23
 
@@ -29,6 +37,24 @@ export function requireAuth(handler, secret) {
29
37
  }
30
38
 
31
39
  req.user = result.payload;
40
+
41
+ if (typeof hydrate === "function") {
42
+ let extra;
43
+ try {
44
+ extra = await hydrate(result.payload, req);
45
+ } catch (error) {
46
+ console.error("[auth] hydrate failed:", error);
47
+ return res.status(500).json({ error: "Couldn't load your account." });
48
+ }
49
+
50
+ if (extra === null || extra === false) {
51
+ return res.status(401).json({ error: "Not authenticated." });
52
+ }
53
+ if (extra && typeof extra === "object") {
54
+ req.user = { ...result.payload, ...extra };
55
+ }
56
+ }
57
+
32
58
  return handler(req, res);
33
59
  };
34
- }
60
+ }
package/src/index.d.ts CHANGED
@@ -5,8 +5,10 @@ export * from './http/parseBody.js'
5
5
  export * from './http/parseQuery.js'
6
6
  export * from './http/parseCookies.js'
7
7
  export * from './http/requireAuth.js'
8
+ export * from './http/rateLimit.js'
8
9
  export * from './discovery/discoverFeatures.js'
9
10
  export * from './discovery/registerFeatureRoutes.js'
11
+ export * from './discovery/registerRouteFiles.js'
10
12
  export * from './discovery/loadCustomRoutes.js'
11
13
  export * from './queue/JobRecord.js'
12
14
  export * from './queue/dispatch.js'
package/src/index.js CHANGED
@@ -5,12 +5,14 @@ export * from './http/parseBody.js'
5
5
  export * from './http/parseQuery.js'
6
6
  export * from './http/parseCookies.js'
7
7
  export * from './http/requireAuth.js'
8
+ export * from './http/rateLimit.js'
8
9
  export * from './discovery/discoverFeatures.js'
9
10
  export * from './discovery/registerFeatureRoutes.js'
11
+ export * from './discovery/registerRouteFiles.js'
10
12
  export * from './discovery/loadCustomRoutes.js'
11
13
  export * from './queue/JobRecord.js'
12
14
  export * from './queue/dispatch.js'
13
15
  export * from './scheduling/Scheduler.js'
14
16
  export * from './channels/ChannelServer.js'
15
17
  export * from './cache/CacheRecord.js'
16
- export * from './cache/Cache.js'
18
+ export * from './cache/Cache.js'
@@ -2,35 +2,56 @@ import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { Router } from "./Router.js";
4
4
 
5
- test("matches an exact static route", () => {
5
+ // match() returns a composed chain (global middleware, route
6
+ // middleware, then the final handler), so tests run the chain and
7
+ // check what the original handler saw.
8
+ async function run(match) {
9
+ const req = {};
10
+ const res = {};
11
+ await match.handler(req, res);
12
+ return { req, res };
13
+ }
14
+
15
+ test("matches an exact static route", async () => {
6
16
  const router = new Router();
7
- const handler = () => {};
8
- router.get("/api/posts", handler);
17
+ let calls = 0;
18
+ router.get("/api/posts", () => {
19
+ calls++;
20
+ });
9
21
 
10
22
  const match = router.match("GET", "/api/posts");
11
- assert.equal(match.handler, handler);
23
+ assert.ok(match);
12
24
  assert.deepEqual(match.params, {});
25
+
26
+ await run(match);
27
+ assert.equal(calls, 1);
13
28
  });
14
29
 
15
- test("matches a dynamic route and extracts params", () => {
30
+ test("matches a dynamic route and extracts params", async () => {
16
31
  const router = new Router();
17
- const handler = () => {};
18
- router.get("/api/posts/:id", handler);
32
+ let calls = 0;
33
+ router.get("/api/posts/:id", () => {
34
+ calls++;
35
+ });
19
36
 
20
37
  const match = router.match("GET", "/api/posts/42");
21
- assert.equal(match.handler, handler);
38
+ assert.ok(match);
22
39
  assert.deepEqual(match.params, { id: "42" });
40
+
41
+ await run(match);
42
+ assert.equal(calls, 1);
23
43
  });
24
44
 
25
- test("differentiates by HTTP method", () => {
45
+ test("differentiates by HTTP method", async () => {
26
46
  const router = new Router();
27
- const getHandler = () => {};
28
- const postHandler = () => {};
29
- router.get("/api/posts", getHandler);
30
- router.post("/api/posts", postHandler);
47
+ const seen = [];
48
+ router.get("/api/posts", () => seen.push("get"));
49
+ router.post("/api/posts", () => seen.push("post"));
31
50
 
32
- assert.equal(router.match("GET", "/api/posts").handler, getHandler);
33
- assert.equal(router.match("POST", "/api/posts").handler, postHandler);
51
+ await run(router.match("GET", "/api/posts"));
52
+ await run(router.match("POST", "/api/posts"));
53
+
54
+ assert.deepEqual(seen, ["get", "post"]);
34
55
  });
35
56
 
36
57
  test("returns null when no route matches", () => {
@@ -39,11 +60,69 @@ test("returns null when no route matches", () => {
39
60
  assert.equal(router.match("GET", "/api/nonexistent"), null);
40
61
  });
41
62
 
42
- test("ignores query string when matching", () => {
63
+ test("ignores query string when matching", async () => {
43
64
  const router = new Router();
44
- const handler = () => {};
45
- router.get("/api/posts", handler);
65
+ let calls = 0;
66
+ router.get("/api/posts", () => {
67
+ calls++;
68
+ });
46
69
 
47
70
  const match = router.match("GET", "/api/posts?page=2");
48
- assert.equal(match.handler, handler);
71
+ assert.ok(match);
72
+
73
+ await run(match);
74
+ assert.equal(calls, 1);
75
+ });
76
+
77
+ test("runs global middleware, then route middleware, then the handler, in order", async () => {
78
+ const router = new Router();
79
+ const order = [];
80
+
81
+ router.use(async (req, res, next) => {
82
+ order.push("global");
83
+ await next();
84
+ });
85
+ router.get(
86
+ "/api/posts",
87
+ async (req, res, next) => {
88
+ order.push("route");
89
+ await next();
90
+ },
91
+ () => {
92
+ order.push("handler");
93
+ },
94
+ );
95
+
96
+ await run(router.match("GET", "/api/posts"));
97
+ assert.deepEqual(order, ["global", "route", "handler"]);
49
98
  });
99
+
100
+ test("a middleware that does not call next() stops the chain", async () => {
101
+ const router = new Router();
102
+ let handlerCalled = false;
103
+
104
+ router.use(() => {
105
+ // deliberately never calls next()
106
+ });
107
+ router.get("/api/posts", () => {
108
+ handlerCalled = true;
109
+ });
110
+
111
+ await run(router.match("GET", "/api/posts"));
112
+ assert.equal(handlerCalled, false);
113
+ });
114
+
115
+ test("calling next() twice in one middleware rejects", async () => {
116
+ const router = new Router();
117
+
118
+ router.use(async (req, res, next) => {
119
+ await next();
120
+ await next();
121
+ });
122
+ router.get("/api/posts", () => {});
123
+
124
+ await assert.rejects(
125
+ () => run(router.match("GET", "/api/posts")),
126
+ /next\(\) called multiple times/,
127
+ );
128
+ });