@tylix/core 0.4.0 → 0.4.2

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.4.0",
3
+ "version": "0.4.2",
4
4
  "type": "module",
5
5
  "keywords": [
6
6
  "tylix",
@@ -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
+ }
@@ -22,9 +22,10 @@ async function collect(dir) {
22
22
  }
23
23
 
24
24
  // Mounts every app/routes/**/*.{js,ts} file exporting routes(router, { auth }).
25
- export async function registerRouteFiles(router, baseDir, { secret } = {}) {
25
+ // `hydrate` (optional) is passed to requireAuth: see http/requireAuth.js.
26
+ export async function registerRouteFiles(router, baseDir, { secret, hydrate } = {}) {
26
27
  const routesDir = path.join(baseDir, 'app', 'routes')
27
- const context = { auth: (handler) => requireAuth(handler, secret) }
28
+ const context = { auth: (handler) => requireAuth(handler, secret, { hydrate }) }
28
29
  const mounted = []
29
30
 
30
31
  for (const file of await collect(routesDir)) {
@@ -15,4 +15,6 @@ export declare class Server {
15
15
  constructor(router: Router, options?: ServerOptions)
16
16
  createHandler(): (req: any, res: any) => Promise<void>
17
17
  listen(port: number, callback?: () => void): import('node:http').Server
18
- }
18
+ }
19
+
20
+ export declare function readBody(req: any): Promise<{ raw: string; body: any }>
@@ -1,6 +1,6 @@
1
1
  import http from 'node:http'
2
2
  import { enhanceResponse } from './enhanceResponse.js'
3
- import { parseBody } from './parseBody.js'
3
+ import { readBody } from './parseBody.js'
4
4
  import { parseQuery } from './parseQuery.js'
5
5
  import { parseCookies } from './parseCookies.js'
6
6
 
@@ -82,7 +82,11 @@ export class Server {
82
82
  req.cookies = parseCookies(req)
83
83
 
84
84
  try {
85
- req.body = await parseBody(req)
85
+ const { raw, body } = await readBody(req)
86
+ // The exact text the client sent. Webhook signatures are computed
87
+ // over these bytes, so they must not be re-serialised from req.body.
88
+ req.rawBody = raw
89
+ req.body = body
86
90
  } catch (err) {
87
91
  res.status(400).json({ error: err.message })
88
92
  return
@@ -1,25 +1,36 @@
1
- export function parseBody(req) {
1
+ /**
2
+ * Reads the whole request body once.
3
+ * Returns { raw, body }: raw is the exact UTF-8 text the client sent,
4
+ * body is the parsed JSON (or {} for empty or non-JSON bodies).
5
+ *
6
+ * Chunks are collected as Buffers and decoded once at the end. Joining
7
+ * them as strings can split a multi-byte character across two chunks,
8
+ * which would change the text and break webhook signature checks.
9
+ */
10
+ export function readBody(req) {
2
11
  return new Promise((resolve, reject) => {
3
- let chunks = "";
12
+ const chunks = [];
4
13
 
5
14
  req.on("data", (chunk) => {
6
- chunks += chunk;
15
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
7
16
  });
8
17
 
9
18
  req.on("end", () => {
10
- if (!chunks) {
11
- resolve({});
19
+ const raw = Buffer.concat(chunks).toString("utf8");
20
+
21
+ if (!raw) {
22
+ resolve({ raw: "", body: {} });
12
23
  return;
13
24
  }
14
25
 
15
26
  const contentType = req.headers["content-type"] || "";
16
27
  if (!contentType.includes("application/json")) {
17
- resolve({});
28
+ resolve({ raw, body: {} });
18
29
  return;
19
30
  }
20
31
 
21
32
  try {
22
- resolve(JSON.parse(chunks));
33
+ resolve({ raw, body: JSON.parse(raw) });
23
34
  } catch (err) {
24
35
  reject(new Error("Invalid JSON body"));
25
36
  }
@@ -28,3 +39,8 @@ export function parseBody(req) {
28
39
  req.on("error", reject);
29
40
  });
30
41
  }
42
+
43
+ export async function parseBody(req) {
44
+ const { body } = await readBody(req);
45
+ return body;
46
+ }
@@ -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
+ }