@tylix/core 1.3.0 → 1.5.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": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "description": "The Tylix server core: HTTP server and router, logging, metrics and health checks, a shared store (memory, database, Redis), cache, rate limiting, queue, scheduler and channels.",
5
5
  "license": "MIT",
6
6
  "author": "Mbiyrukzz",
@@ -44,9 +44,9 @@
44
44
  "test": "node --test 'src/**/*.test.js'"
45
45
  },
46
46
  "dependencies": {
47
- "@tylix/auth": "^1.3.0",
48
- "@tylix/orm": "^1.3.0",
49
- "@tylix/shared": "^1.3.0",
47
+ "@tylix/auth": "^1.5.0",
48
+ "@tylix/orm": "^1.5.0",
49
+ "@tylix/shared": "^1.5.0",
50
50
  "ws": "^8.18.0"
51
51
  },
52
52
  "devDependencies": {
@@ -16,4 +16,10 @@ export declare function enhanceResponse<T extends import('node:http').ServerResp
16
16
  send(data?: unknown): T
17
17
  cookie(name: string, value: string, options?: CookieOptions): T
18
18
  clearCookie(name: string, options?: CookieOptions): T
19
+ /** Send bytes, a string or a document with toBuffer() (PDF, workbook) as a download. */
20
+ download(
21
+ data: Uint8Array | ArrayBuffer | string | { toBuffer(): Promise<Uint8Array> },
22
+ filename?: string,
23
+ options?: { inline?: boolean; type?: string },
24
+ ): Promise<T>
19
25
  }
@@ -49,6 +49,21 @@ function compress(res, text) {
49
49
  return null
50
50
  }
51
51
 
52
+ const DOWNLOAD_TYPES = {
53
+ pdf: 'application/pdf',
54
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
55
+ csv: 'text/csv; charset=utf-8',
56
+ json: 'application/json',
57
+ txt: 'text/plain; charset=utf-8',
58
+ zip: 'application/zip',
59
+ png: 'image/png',
60
+ jpg: 'image/jpeg',
61
+ jpeg: 'image/jpeg',
62
+ svg: 'image/svg+xml',
63
+ html: 'text/html; charset=utf-8',
64
+ ics: 'text/calendar; charset=utf-8',
65
+ }
66
+
52
67
  const helpers = {
53
68
  status(code) {
54
69
  this.statusCode = code
@@ -108,6 +123,33 @@ const helpers = {
108
123
  return this
109
124
  },
110
125
 
126
+ // Sends a file to download: bytes, a string, or anything with an
127
+ // async toBuffer() (a @tylix/pdf document, a @tylix/excel workbook).
128
+ // The content type comes from the filename unless given.
129
+ // await res.download(createPdf(def), 'invoice.pdf')
130
+ // await res.download(workbook, 'orders.xlsx')
131
+ // await res.download(pdf, 'invoice.pdf', { inline: true }) // view in the browser
132
+ async download(data, filename = 'download', options = {}) {
133
+ let body = data
134
+ if (body && typeof body.toBuffer === 'function') body = await body.toBuffer()
135
+ if (typeof body === 'string') body = Buffer.from(body)
136
+ else if (body instanceof ArrayBuffer) body = Buffer.from(body)
137
+ else if (ArrayBuffer.isView(body) && !Buffer.isBuffer(body)) body = Buffer.from(body.buffer, body.byteOffset, body.byteLength)
138
+ if (!Buffer.isBuffer(body)) throw new TypeError('res.download() needs bytes, a string or an object with toBuffer()')
139
+ const name = String(filename).replace(/["\\\r\n]/g, '_')
140
+ const ascii = name.replace(/[^\x20-\x7e]/g, '_')
141
+ const type = options.type ?? DOWNLOAD_TYPES[name.split('.').pop().toLowerCase()] ?? 'application/octet-stream'
142
+ this.setHeader('Content-Type', type)
143
+ this.setHeader('Content-Length', body.length)
144
+ this.setHeader(
145
+ 'Content-Disposition',
146
+ `${options.inline ? 'inline' : 'attachment'}; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`,
147
+ )
148
+ this.setHeader('X-Content-Type-Options', 'nosniff')
149
+ this.end(this.req?.method === 'HEAD' ? undefined : body)
150
+ return this
151
+ },
152
+
111
153
  clearCookie(name, options = {}) {
112
154
  this.cookie(name, '', { ...options, maxAge: 0, expires: new Date(0) })
113
155
  return this
@@ -1,4 +1,4 @@
1
- import { verifyToken, ACCESS_TOKEN_COOKIE } from "@tylix/auth";
1
+ import { verifyTylixAccessToken, ACCESS_TOKEN_COOKIE } from "@tylix/auth";
2
2
 
3
3
  // Shared across packages (Symbol.for), so `tylix dev` can print a lock next
4
4
  // to every guarded route without importing anything from here.
@@ -10,9 +10,14 @@ const AUTH_MARK = Symbol.for("tylix.requireAuth");
10
10
  * browser app now uses), then falls back to an
11
11
  * "Authorization: Bearer <token>" header (for non-browser API clients
12
12
  * that can't rely on cookies). On success, req.user is set to the
13
- * token's payload (e.g. { userId }); on failure, responds 401 and
13
+ * token's payload (e.g. { userId, sid }); on failure, responds 401 and
14
14
  * never calls the wrapped handler.
15
15
  *
16
+ * Only real access tokens pass: email-verification links and other
17
+ * purpose tokens are refused, and when the app's AuthController manages
18
+ * sessions, a token whose session was ended (logout, "sign out
19
+ * everywhere", password reset) is refused immediately.
20
+ *
16
21
  * options.hydrate(payload, req) is optional. It runs after the token is
17
22
  * verified and can add fields to req.user (for example a team id):
18
23
  * - return an object -> its fields are merged into req.user
@@ -27,7 +32,7 @@ export function requireAuth(handler, secret, options = {}) {
27
32
 
28
33
  const authHeader = req.headers?.authorization || "";
29
34
  const [scheme, headerToken] = authHeader.split(" ");
30
- const bearerToken = scheme === "Bearer" ? headerToken : null;
35
+ const bearerToken = /^bearer$/i.test(scheme ?? "") ? headerToken : null;
31
36
 
32
37
  const token = cookieToken || bearerToken;
33
38
 
@@ -35,7 +40,13 @@ export function requireAuth(handler, secret, options = {}) {
35
40
  return res.status(401).json({ error: "Not authenticated." });
36
41
  }
37
42
 
38
- const result = verifyToken(token, secret);
43
+ let result;
44
+ try {
45
+ result = await verifyTylixAccessToken(token, secret);
46
+ } catch (error) {
47
+ console.error("[auth] token check failed:", error);
48
+ return res.status(500).json({ error: "Couldn't check your session." });
49
+ }
39
50
  if (!result.valid) {
40
51
  return res.status(401).json({ error: result.error || "Invalid token." });
41
52
  }
@@ -56,18 +56,18 @@ export function renderStatusPage({
56
56
  <style>
57
57
  * { box-sizing: border-box; }
58
58
  :root {
59
- --bg:#f8fafc; --card:#ffffff; --border:#e2e8f0; --border-strong:#cbd5e1;
60
- --text:#0f172a; --muted:#64748b;
61
- --success:#059669; --success-soft:rgba(16,185,129,.12);
62
- --error:#e11d48; --error-soft:rgba(225,29,72,.10);
63
- --notfound:#d97706; --notfound-soft:rgba(245,158,11,.14);
59
+ --bg:#f3f2f6; --card:#ffffff; --border:#dedbe6; --border-strong:#c9c5d4;
60
+ --text:#17151c; --muted:#6b6878; --brand:#0034ca; --brand-hover:#1a4be0;
61
+ --success:#0d8c67; --success-soft:rgba(13,140,103,.12);
62
+ --error:#cd3c3c; --error-soft:rgba(205,60,60,.10);
63
+ --notfound:#bd6226; --notfound-soft:rgba(189,98,38,.12);
64
64
  }
65
65
  html.dark {
66
- --bg:#020617; --card:#0f172a; --border:#1e293b; --border-strong:#334155;
67
- --text:#e2e8f0; --muted:#94a3b8;
68
- --success:#34d399; --success-soft:rgba(52,211,153,.12);
69
- --error:#fb7185; --error-soft:rgba(251,113,133,.12);
70
- --notfound:#fbbf24; --notfound-soft:rgba(251,191,36,.12);
66
+ --bg:#17161c; --card:#211f27; --border:#34313d; --border-strong:#46424f;
67
+ --text:#ecebf1; --muted:#9592a3; --brand:#3563ff; --brand-hover:#547cff;
68
+ --success:#5fe3b5; --success-soft:rgba(95,227,181,.12);
69
+ --error:#ff7b7b; --error-soft:rgba(255,123,123,.12);
70
+ --notfound:#ffb38a; --notfound-soft:rgba(255,179,138,.12);
71
71
  }
72
72
  html { color-scheme: light; } html.dark { color-scheme: dark; }
73
73
  body {
@@ -77,12 +77,13 @@ export function renderStatusPage({
77
77
  }
78
78
  .card {
79
79
  width:100%; max-width:440px; text-align:center; padding:36px 32px 32px;
80
- background:var(--card); border:1px solid var(--border); border-radius:20px;
81
- box-shadow:0 1px 2px rgba(15,23,42,.05), 0 12px 32px rgba(15,23,42,.06);
80
+ border:1px solid transparent; border-radius:20px;
81
+ background:linear-gradient(var(--card),var(--card)) padding-box, linear-gradient(135deg,#6fe0ea,#c8f07a) border-box;
82
+ box-shadow:0 0 32px -8px rgba(111,224,234,.35), 0 12px 32px -16px rgba(0,0,0,.25);
82
83
  }
83
- html.dark .card { box-shadow:none; }
84
84
  .brand { display:inline-flex; align-items:center; gap:8px; margin-bottom:24px; font-weight:600; color:var(--text); text-decoration:none; }
85
- .brand img { width:26px; height:26px; }
85
+ .brand img { height:20px; width:auto; }
86
+ html.dark .brand img { filter:brightness(1.7) saturate(1.1); }
86
87
  .icon { width:60px; height:60px; margin:0 auto 18px; border-radius:50%; display:grid; place-items:center;
87
88
  color:var(--tone); background:var(--tone-soft); }
88
89
  .tone-success { --tone:var(--success); --tone-soft:var(--success-soft); }
@@ -93,12 +94,12 @@ export function renderStatusPage({
93
94
  p.msg { margin:0 0 24px; color:var(--muted); font-size:14px; line-height:1.6; }
94
95
  .actions { display:flex; gap:10px; justify-content:center; flex-wrap:wrap; }
95
96
  .btn {
96
- font-size:14px; font-weight:600; text-decoration:none; padding:9px 18px; border-radius:999px;
97
+ font-size:14px; font-weight:600; text-decoration:none; padding:9px 18px; border-radius:9px;
97
98
  color:var(--text); border:1px solid var(--border-strong); background:transparent; transition:all .15s;
98
99
  }
99
- .btn:hover { border-color:var(--success); color:var(--success); }
100
- .btn-primary { color:#fff; border-color:transparent; background:linear-gradient(90deg,#34d399,#059669); }
101
- .btn-primary:hover { color:#fff; transform:translateY(-1px); box-shadow:0 6px 16px rgba(5,150,105,.3); }
100
+ .btn:hover { border-color:var(--brand); color:var(--brand); }
101
+ .btn-primary { color:#fff; border-color:transparent; background:var(--brand); }
102
+ .btn-primary:hover { color:#fff; background:var(--brand-hover); box-shadow:0 6px 18px -8px var(--brand); }
102
103
  .ref { margin:22px 0 0; font-size:12px; color:var(--muted); }
103
104
  .ref code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size:11px; padding:2px 6px;
104
105
  border-radius:6px; background:var(--bg); border:1px solid var(--border); user-select:all; }
@@ -106,7 +107,7 @@ export function renderStatusPage({
106
107
  </head>
107
108
  <body>
108
109
  <div class="card tone-${esc(tone)}">
109
- <a class="brand" href="/"><img src="/logo-mark.png" alt="" onerror="this.remove()">Tylix</a>
110
+ <a class="brand" href="/"><img src="/logo-mark.svg" alt="" onerror="if(!this.dataset.png){this.dataset.png=1;this.src='/logo-mark.png'}else{this.remove()}">Tylix</a>
110
111
  <div class="icon">${ICONS[tone] ?? ICONS.error}</div>
111
112
  ${code ? `<p class="code">${esc(code)}</p>` : ''}
112
113
  <h1>${esc(title)}</h1>
@@ -16,4 +16,10 @@ export interface TylixResponse extends ServerResponse {
16
16
  send(data?: unknown): TylixResponse
17
17
  cookie(name: string, value: string, options?: CookieOptions): TylixResponse
18
18
  clearCookie(name: string, options?: CookieOptions): TylixResponse
19
+ /** Send bytes, a string or a document with toBuffer() (PDF, workbook) as a download. */
20
+ download(
21
+ data: Uint8Array | ArrayBuffer | string | { toBuffer(): Promise<Uint8Array> },
22
+ filename?: string,
23
+ options?: { inline?: boolean; type?: string },
24
+ ): Promise<TylixResponse>
19
25
  }
package/src/types.ts CHANGED
@@ -23,4 +23,5 @@ export interface TylixResponse extends ServerResponse {
23
23
  send(data?: unknown): TylixResponse;
24
24
  cookie(name: string, value: string, options?: Record<string, unknown>): TylixResponse;
25
25
  clearCookie(name: string, options?: Record<string, unknown>): TylixResponse;
26
+ download(data: Uint8Array | ArrayBuffer | string | { toBuffer(): Promise<Uint8Array> }, filename?: string, options?: { inline?: boolean; type?: string }): Promise<TylixResponse>;
26
27
  }