timetable-api-node 1.3.4 → 1.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/INTEGRATION.md CHANGED
@@ -67,9 +67,8 @@ All tools are read-only. Argument names are **exact** — pass them as shown.
67
67
  | `get_stops_around_location` | `latitude`, `longitude` (numbers), `radius_meters` (int 50–3000, optional) | Discover stops near a coordinate. |
68
68
  | `get_nearby_vehicles` | `latitude`, `longitude` (numbers) | Live vehicles within 1 km of a coordinate. |
69
69
  | `get_vehicle_info` | `vehicle_id` (string) | Position, route, plate, upcoming stops for one vehicle. |
70
- | `plan_trip` | `origin_stop_id`, `destination_stop_id` (numbers) | Direct and 1-transfer route options between two stops. |
71
70
 
72
- Every tool result is JSON with three keys — `view`, `data` (raw payload), and `ui_blocks` (ordered map/arrival-list rendering hints). Resolve a place name or address to a `stop_id` with `get_stops_around_location` before calling stop- or trip-based tools.
71
+ Every tool result is JSON with three keys — `view`, `data` (raw payload), and `ui_blocks` (ordered map/arrival-list rendering hints). Resolve a place name or address to a `stop_id` with `get_stops_around_location` before calling stop-based tools.
73
72
 
74
73
  ---
75
74
 
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Timetable API Node
2
2
 
3
3
  [![CI](https://img.shields.io/github/actions/workflow/status/vbhjckfd/timetable-api-node/ci.yml?branch=master&logo=github&label=CI)](https://github.com/vbhjckfd/timetable-api-node/actions/workflows/ci.yml)
4
- [![Node.js](https://img.shields.io/badge/node.js-24-43853d?logo=node.js&logoColor=white)](https://github.com/vbhjckfd/timetable-api-node/blob/master/.nvmrc)
4
+ [![Node.js](https://img.shields.io/badge/node.js-26-43853d?logo=node.js&logoColor=white)](https://github.com/vbhjckfd/timetable-api-node/blob/master/.nvmrc)
5
5
  [![License: WTFPL](https://img.shields.io/github/license/vbhjckfd/timetable-api-node?label=license)](https://github.com/vbhjckfd/timetable-api-node/blob/master/LICENSE)
6
6
  [![MCP Registry](https://img.shields.io/badge/MCP_Registry-listed-6366f1?style=flat-square)](https://registry.modelcontextprotocol.io/v0/servers/io.github.vbhjckfd%2Ftimetable-api-node/versions)
7
7
 
@@ -14,7 +14,7 @@ Express-based API for Lviv transport timetable data with a read-only MCP endpoin
14
14
 
15
15
  ## Requirements
16
16
 
17
- - Node.js 24 (see `.nvmrc`)
17
+ - Node.js 26 (see `.nvmrc`)
18
18
 
19
19
  ## Run locally
20
20
 
@@ -29,6 +29,36 @@ make start
29
29
  nvm use && make test
30
30
  ```
31
31
 
32
+ ## Monitoring
33
+
34
+ Two optional integrations, both off unless their environment variable is set:
35
+
36
+ | Variable | Effect |
37
+ | --- | --- |
38
+ | `SENTRY_DSN` | Error reporting via `instrument.js` |
39
+ | `NEW_RELIC_LICENSE_KEY` | New Relic APM via `newrelic.cjs` |
40
+
41
+ New Relic runs as a preloaded agent, so `npm start` carries the flags:
42
+
43
+ ```bash
44
+ node -r dotenv/config -r newrelic --import newrelic/esm-loader.mjs index.js
45
+ ```
46
+
47
+ `dotenv/config` is preloaded first so `.env` is populated before the agent
48
+ reads its configuration. The config file is `newrelic.cjs` (the agent is
49
+ CommonJS and this project is ESM) and holds no secrets — the key comes from the
50
+ environment. `/health` is excluded from transactions via `rules.ignore`.
51
+
52
+ The account is in the **EU** region; its license key starts with `eu01xx` and
53
+ the agent picks the collector from that prefix. Use the 40-character ingest
54
+ license key, not an `NRAK-...` user API key.
55
+
56
+ Cloud Run reads the key from Secret Manager:
57
+
58
+ ```bash
59
+ gcloud run services update timetable-api-node --region=us-central1 --project=timetable-252615 --set-secrets=NEW_RELIC_LICENSE_KEY=new-relic-license-key:latest
60
+ ```
61
+
32
62
  ## MCP Server
33
63
 
34
64
  This service exposes a public read-only MCP endpoint over Streamable HTTP.
@@ -112,7 +142,6 @@ Consistency rule: each vehicle rendered on map must either have a matching ETA i
112
142
  - `get_stops_around_location`
113
143
  - `get_nearby_vehicles`
114
144
  - `get_vehicle_info`
115
- - `plan_trip`
116
145
 
117
146
  <details>
118
147
  <summary><code>get_stop_realtime</code> — input &amp; example</summary>
@@ -453,65 +482,6 @@ Full details for one vehicle by its ID: position, route, license plate, directio
453
482
 
454
483
  </details>
455
484
 
456
- <details>
457
- <summary><code>plan_trip</code> — input &amp; example</summary>
458
-
459
- Plans a transit trip from an origin stop to a destination stop using the static route graph. Returns direct options (one route) and 1-transfer options sorted by fewest stops. Does **not** account for realtime disruptions — combine with `get_stop_realtime` for live ETAs after planning.
460
-
461
- **Arguments (JSON):**
462
-
463
- | Field | Type | Required |
464
- |-------|------|----------|
465
- | `origin_stop_id` | positive integer or digits-only string | yes |
466
- | `destination_stop_id` | positive integer or digits-only string | yes |
467
-
468
- **Example result** (direct trip):
469
-
470
- ```json
471
- {
472
- "view": "transit_realtime",
473
- "data": {
474
- "origin": { "id": "101", "name": "Головний вокзал" },
475
- "destination": { "id": "707", "name": "Стадіон Сільмаш" },
476
- "options": [
477
- {
478
- "type": "direct",
479
- "route": "T30",
480
- "direction": 0,
481
- "board_stop_code": 101,
482
- "board_stop_name": "Головний вокзал",
483
- "alight_stop_code": 707,
484
- "alight_stop_name": "Стадіон Сільмаш",
485
- "stops_count": 4
486
- }
487
- ],
488
- "updated_at": "2026-01-23T12:00:00Z"
489
- },
490
- "ui_blocks": []
491
- }
492
- ```
493
-
494
- **Transfer trip** option shape:
495
-
496
- ```json
497
- {
498
- "type": "transfer",
499
- "route1": "T01",
500
- "route2": "А05",
501
- "board_stop_code": 101,
502
- "board_stop_name": "Головний вокзал",
503
- "transfer_stop_code": 303,
504
- "transfer_stop_name": "Площа Ринок",
505
- "alight_stop_code": 707,
506
- "alight_stop_name": "Стадіон Сільмаш",
507
- "stops_count_1": 3,
508
- "stops_count_2": 2
509
- }
510
- ```
511
-
512
- Up to 5 direct and 3 transfer options are returned. Use `get_stops_around_location` to resolve addresses or coordinates to stop codes before calling this tool.
513
-
514
- </details>
515
485
 
516
486
  ### Resources and resource templates
517
487
 
@@ -546,6 +516,25 @@ All stops as a JSON array, sorted by code.
546
516
 
547
517
  (`GET /stops` returns an HTML table instead.)
548
518
 
519
+ #### Per-stop route overrides
520
+
521
+ The upstream route list for a stop is sometimes behind reality. `GET /stops`
522
+ applies a stored override to its `Маршрути` column — removed routes shown red and
523
+ struck through, added ones green — and hangs the matching `?add=`/`?remove=` on
524
+ that row's SVG and PDF links, which `offline.lad.lviv.ua` and `pdf.lad.lviv.ua`
525
+ both understand.
526
+
527
+ The route column is always clickable: click a route to drop or restore it, type
528
+ one into the `+` box to add it.
529
+
530
+ Overrides live in the browser's own `localStorage` (see
531
+ [`public/stopOverrides.js`](public/stopOverrides.js)), not on a server — no
532
+ account to edit through, no cache to purge, an edit applies at once. The trade
533
+ is scope: an override is visible only in the browser that made it, not to
534
+ anyone else who opens `/stops`.
535
+
536
+ `/stops.json` reports `sign` and `sign_pdf` without overrides applied.
537
+
549
538
  #### `GET /stops/:code`
550
539
 
551
540
  Single stop with live realtime timetable. Short-cached (5–10 s).
@@ -617,12 +606,3 @@ Look up a vehicle ID by its license plate. Short-cached (5 s).
617
606
  Vehicles within 1 km of a point. Short-cached (10 s).
618
607
 
619
608
  - **Response:** array of `{ id, route, routeId, direction, vehicle_type, color, location: [lat, lng], bearing, speed, lowfloor }`. `routeId` is usable as `:name` in `/routes/static/:name`; `direction` matches the index into `stops`/`shapes` (0 = outbound, 1 = return, null if unknown). `speed` is m/s or `null`.
620
-
621
- ### Trip planning
622
-
623
- #### `GET /trip-plan?origin={code}&destination={code}`
624
-
625
- Static trip planning between two stops using the route graph.
626
-
627
- - **Response:** `{ origin, destination, options }` where each option is either a `direct` trip (single route) or a `transfer` trip (two routes with a transfer stop). Up to 5 direct and 3 transfer options, sorted by fewest stops.
628
- - Cached for 60 s.
package/index.js CHANGED
@@ -10,8 +10,8 @@ const PORT = process.env.PORT || 8080;
10
10
  import { openDb } from "gtfs";
11
11
  import { readFile } from "fs/promises";
12
12
  import cors from "cors";
13
+ import rateLimit, { ipKeyGenerator } from "express-rate-limit";
13
14
  import express from "express";
14
- import bodyParser from "body-parser";
15
15
  import localDb from "./connections/timetableSqliteDb.js";
16
16
 
17
17
  import notFoundAction from "./actions/notFoundAction.js";
@@ -33,17 +33,30 @@ import {
33
33
  buildMcpServerCard,
34
34
  handleMcpPostRequest,
35
35
  } from "./mcp/timetableMcpServer.js";
36
- import planTripAction from "./actions/planTripAction.js";
36
+ import { renderMcpDocsPage, wantsHtmlDocs } from "./mcp/docsPage.js";
37
37
  import healthAction from "./actions/healthAction.js";
38
+ import errorHandler from "./utils/errorHandler.js";
38
39
 
39
40
  const app = express();
40
41
 
41
42
  app.set("trust proxy", true);
42
43
 
44
+ /**
45
+ * Cache headers for responses baked into the image: docs, manifests, icons.
46
+ * A GTFS data refresh never changes these, so they are tagged "long" and the
47
+ * daily refresh build leaves them alone; only code-push builds purge the tag
48
+ * (see the DropCache step in cloudbuild.yaml). GTFS-derived responses use
49
+ * "short" instead and are purged by every build.
50
+ */
51
+ const setStaticAssetCache = (res, maxAgeSeconds = 3600 * 24) =>
52
+ res
53
+ .set("Cache-Control", `public, max-age=0, s-maxage=${maxAgeSeconds}`)
54
+ .set("Cache-Tag", "long");
55
+
43
56
  app.use(cors());
44
57
 
45
58
  app.use((req, res, next) => {
46
- const baseUrl = `${req.protocol}://${req.hostname}`;
59
+ const baseUrl = `${req.protocol}://${req.host}`;
47
60
  res.set(
48
61
  "Link",
49
62
  [
@@ -56,28 +69,93 @@ app.use((req, res, next) => {
56
69
  next();
57
70
  });
58
71
 
59
- app.use(bodyParser.json({ limit: "100kb" }));
72
+ app.use(express.json({ limit: "100kb" }));
73
+
74
+ // `trust proxy` is true above, which makes req.ip the leftmost X-Forwarded-For
75
+ // entry — a value the caller writes, so keying a limiter on it would let one
76
+ // client mint a fresh bucket per request. Cloudflare sets CF-Connecting-IP at
77
+ // the edge and overwrites whatever the client sent, so prefer that and fall
78
+ // back to req.ip only for a request that did not arrive through the edge.
79
+ // ipKeyGenerator collapses IPv6 to a /56, so a single allocation cannot spread
80
+ // its hits across addresses either.
81
+ const clientIpKey = (req) =>
82
+ ipKeyGenerator(req.headers["cf-connecting-ip"] ?? req.ip ?? "");
83
+
84
+ // Limits are per client address and sit well above what a person browsing
85
+ // generates. They exist to bound the unattended callers: a scraper looping a
86
+ // fixed set of stop codes, or an app under development replaying deploy
87
+ // loops, both of which otherwise run against the origin with nothing to push
88
+ // back. Liveness paths are exempt so a probe never trips a limit some abusive
89
+ // neighbour filled, and /mcp is exempt because it carries its own limiter
90
+ // below: sharing this bucket meant the global one always emptied first (it
91
+ // counts every path) and answered MCP clients with a body that is not
92
+ // JSON-RPC.
93
+ const globalRateLimiter = rateLimit({
94
+ windowMs: 60_000,
95
+ limit: 60,
96
+ standardHeaders: true,
97
+ legacyHeaders: false,
98
+ keyGenerator: clientIpKey,
99
+ skip: (req) =>
100
+ req.path === "/health" || req.path === "/ping" || req.path === "/mcp",
101
+ message: { error: "Rate limit exceeded. Try again later." },
102
+ });
103
+
104
+ // /routes/dynamic/:name and /transport both fan out over the live vehicle
105
+ // feed, which makes them the most expensive responses here and the pair a
106
+ // single client can do the most damage with. Their bucket is drawn on top of
107
+ // the global one, so this only ever narrows what that already allows.
108
+ const liveDataRateLimiter = rateLimit({
109
+ windowMs: 60_000,
110
+ limit: 40,
111
+ standardHeaders: true,
112
+ legacyHeaders: false,
113
+ keyGenerator: clientIpKey,
114
+ message: { error: "Rate limit exceeded. Try again later." },
115
+ });
116
+
117
+ // Where the unattended traffic actually lands. The stop endpoints are what a
118
+ // scraper loops over, and it runs round the clock at a rate that sits under
119
+ // the global 60/minute ceiling by design, so that bucket never catches it —
120
+ // the giveaway is a request curve with no diurnal shape at all, roughly as
121
+ // busy at 04:00 as at midday. Neither stop view polls (unlike the route page,
122
+ // which refreshes every 10s), so a stop is one or two requests per
123
+ // navigation: 20/minute is around ten stop views a minute from one address,
124
+ // far above a person browsing and well under the observed scraping rate.
125
+ // /stops/:code/static is left out deliberately — it is cheap, cached, and
126
+ // loaded alongside a timetable, so counting it would halve the real budget.
127
+ // Drawn on top of the global bucket, so like the live-data one it only ever
128
+ // narrows what that already allows.
129
+ const stopDataRateLimiter = rateLimit({
130
+ windowMs: 60_000,
131
+ limit: 20,
132
+ standardHeaders: true,
133
+ legacyHeaders: false,
134
+ keyGenerator: clientIpKey,
135
+ message: { error: "Rate limit exceeded. Try again later." },
136
+ });
137
+
138
+ app.use(globalRateLimiter);
60
139
 
61
- app.get("/stops/:code/timetable", validateStopCode, getStopTimetableAction);
140
+ app.get("/stops/:code/timetable", stopDataRateLimiter, validateStopCode, getStopTimetableAction);
62
141
  app.get("/stops/:code/static", validateStopCode, getStopStaticDataAction);
63
- app.get("/stops/:code", validateStopCode, getSingleStopAction);
142
+ app.get("/stops/:code", stopDataRateLimiter, validateStopCode, getSingleStopAction);
64
143
  app.get("/stops.json", getAllStopsAction);
65
144
  app.get("/stops", getAllStopsAction);
66
145
  app.get("/closest", getClosestStopsAction);
67
146
 
68
147
  app.get("/routes.json", getAllRoutesAction);
69
148
  app.get("/routes", getAllRoutesAction);
70
- app.get("/routes/dynamic/:name", routeInfoDynamicAction);
149
+ app.get("/routes/dynamic/:name", liveDataRateLimiter, routeInfoDynamicAction);
71
150
  app.get("/routes/static/:name", routeInfoStaticAction);
72
151
  app.get("/vehicle/:vehicleId", vehicleInfoAction);
73
152
  app.get("/vehicle-by-plate/:plate", vehicleByPlateAction);
74
- app.get("/transport", closestTransportAction);
75
- app.get("/trip-plan", planTripAction);
153
+ app.get("/transport", liveDataRateLimiter, closestTransportAction);
76
154
 
77
155
  app.get("/sitemap.xml", sitemapAction);
78
156
 
79
157
  app.get("/openapi.yaml", (req, res) => {
80
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
158
+ setStaticAssetCache(res);
81
159
  res.type("application/yaml");
82
160
  res.sendFile(path.join(__dirname, "openapi.yaml"));
83
161
  });
@@ -87,8 +165,8 @@ app.get("/.well-known/openapi.yaml", (req, res) => {
87
165
  });
88
166
 
89
167
  app.get("/.well-known/ai-plugin.json", (req, res) => {
90
- const baseUrl = `${req.protocol}://${req.hostname}`;
91
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
168
+ const baseUrl = `${req.protocol}://${req.host}`;
169
+ setStaticAssetCache(res);
92
170
  res.json({
93
171
  schema_version: "v1",
94
172
  name_for_human: "Lviv Public Transport",
@@ -109,8 +187,8 @@ app.get("/.well-known/ai-plugin.json", (req, res) => {
109
187
  });
110
188
 
111
189
  app.get("/.well-known/agent.json", (req, res) => {
112
- const baseUrl = `${req.protocol}://${req.hostname}`;
113
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
190
+ const baseUrl = `${req.protocol}://${req.host}`;
191
+ setStaticAssetCache(res);
114
192
  res.json({
115
193
  name: "Lviv Public Transport",
116
194
  description:
@@ -195,16 +273,6 @@ app.get("/.well-known/agent.json", (req, res) => {
195
273
  outputModes: ["application/json"],
196
274
  examples: ["Track vehicle 12345", "Where is vehicle 12345 heading?"],
197
275
  },
198
- {
199
- id: "plan_trip",
200
- name: "Plan Trip",
201
- description:
202
- "Plan a transit trip between two stop codes; returns direct and 1-transfer route options.",
203
- tags: ["transit", "trip-planning", "routing", "lviv"],
204
- inputModes: ["text/plain", "application/json"],
205
- outputModes: ["application/json"],
206
- examples: ["How do I get from stop 707 to stop 808?", "Plan a trip from 707 to 1234"],
207
- },
208
276
  ],
209
277
  authentication: { schemes: [] },
210
278
  provider: {
@@ -218,13 +286,13 @@ app.get("/.well-known/agent.json", (req, res) => {
218
286
  });
219
287
 
220
288
  app.get("/llms.txt", (req, res) => {
221
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
289
+ setStaticAssetCache(res);
222
290
  res.type("text/plain");
223
291
  res.sendFile(path.join(__dirname, "llms.txt"));
224
292
  });
225
293
 
226
294
  app.get("/INTEGRATION.md", (req, res) => {
227
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
295
+ setStaticAssetCache(res);
228
296
  res.type("text/markdown");
229
297
  res.sendFile(path.join(__dirname, "INTEGRATION.md"));
230
298
  });
@@ -235,30 +303,22 @@ app.get("/ping", (req, res) => {
235
303
 
236
304
  app.get("/health", healthAction);
237
305
 
238
- // Simple in-memory rate limiter: 60 requests/min per IP
239
- const _mcpRateLimitMap = new Map();
240
- const MCP_RATE_LIMIT = 60;
241
- const MCP_RATE_WINDOW_MS = 60_000;
242
-
243
- function mcpRateLimiter(req, res, next) {
244
- const ip = req.ip ?? "unknown";
245
- const now = Date.now();
246
- const entry = _mcpRateLimitMap.get(ip) ?? { count: 0, windowStart: now };
247
- if (now - entry.windowStart > MCP_RATE_WINDOW_MS) {
248
- entry.count = 0;
249
- entry.windowStart = now;
250
- }
251
- entry.count++;
252
- _mcpRateLimitMap.set(ip, entry);
253
- if (entry.count > MCP_RATE_LIMIT) {
254
- return res.status(429).json({
306
+ // express-rate-limit rather than a hand-rolled counter map: its MemoryStore
307
+ // drops the whole hit table each window, so the key space cannot grow without
308
+ // bound across the instance's lifetime.
309
+ const mcpRateLimiter = rateLimit({
310
+ windowMs: 60_000,
311
+ limit: 60,
312
+ standardHeaders: true,
313
+ legacyHeaders: false,
314
+ keyGenerator: clientIpKey,
315
+ handler: (req, res) =>
316
+ res.status(429).json({
255
317
  jsonrpc: "2.0",
256
318
  error: { code: -32000, message: "Rate limit exceeded. Try again later." },
257
319
  id: null,
258
- });
259
- }
260
- next();
261
- }
320
+ }),
321
+ });
262
322
 
263
323
  app.post("/mcp", mcpRateLimiter, async (req, res) => {
264
324
  try {
@@ -278,7 +338,25 @@ app.post("/mcp", mcpRateLimiter, async (req, res) => {
278
338
  }
279
339
  });
280
340
 
341
+ // A browser opening /mcp gets a human-readable page. Everything else that
342
+ // GETs it — above all a Streamable HTTP client probing for an SSE stream —
343
+ // falls through to the 405 below, which that client knows how to handle.
344
+ // Neither answer is cacheable: Cloudflare ignores Vary: Accept, so a cached
345
+ // docs page would be handed to MCP clients probing the same URL. Vary stays
346
+ // for any cache that does honour it.
347
+ app.get("/mcp", mcpRateLimiter, async (req, res, next) => {
348
+ res.vary("Accept");
349
+ res.set("Cache-Control", "no-store");
350
+ if (!wantsHtmlDocs(req.get("Accept"))) return next();
351
+ const baseUrl = `${req.protocol}://${req.host}`;
352
+ res.type("html").send(await renderMcpDocsPage(baseUrl));
353
+ });
354
+
281
355
  app.all("/mcp", (req, res) => {
356
+ // RFC 9110: a 405 has to say which methods the resource does take. The
357
+ // transport is stateless, so there is no SSE stream for GET to open and
358
+ // no session for DELETE to end — POST is the whole surface.
359
+ res.set("Allow", "POST");
282
360
  res.status(405).json({
283
361
  jsonrpc: "2.0",
284
362
  error: {
@@ -290,8 +368,8 @@ app.all("/mcp", (req, res) => {
290
368
  });
291
369
 
292
370
  app.get("/.well-known/oauth-protected-resource", (req, res) => {
293
- const baseUrl = `${req.protocol}://${req.hostname}`;
294
- res.set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24}`);
371
+ const baseUrl = `${req.protocol}://${req.host}`;
372
+ setStaticAssetCache(res);
295
373
  res.json({
296
374
  resource: baseUrl,
297
375
  authorization_required: false,
@@ -306,18 +384,24 @@ app.get("/.well-known/oauth-protected-resource", (req, res) => {
306
384
  });
307
385
 
308
386
  app.get("/.well-known/mcp/server-card.json", (req, res) => {
309
- const baseUrl = `${req.protocol}://${req.hostname}`;
387
+ const baseUrl = `${req.protocol}://${req.host}`;
388
+ // The card carries pkg.version, so a code push has to be able to purge it;
389
+ // without the "long" tag the DropCache step in cloudbuild.yaml could not
390
+ // reach it and clients kept a stale version for a day.
391
+ setStaticAssetCache(res);
310
392
  res.json(buildMcpServerCard(baseUrl));
311
393
  });
312
394
 
313
395
  app.get("/mcp-icon.svg", (req, res) => {
314
396
  res.type("image/svg+xml");
315
- res.set("Cache-Control", "public, max-age=86400");
397
+ // Was a browser-side max-age=86400, which no purge can reach; moved to
398
+ // s-maxage so a code push actually invalidates it.
399
+ setStaticAssetCache(res);
316
400
  res.sendFile(path.join(__dirname, "mcp", "mcp-icon.svg"));
317
401
  });
318
402
 
319
403
  app.get("/robots.txt", (req, res) => {
320
- const baseUrl = `${req.protocol}://${req.hostname}`;
404
+ const baseUrl = `${req.protocol}://${req.host}`;
321
405
  const lines = [
322
406
  "User-agent: *",
323
407
  "Disallow: /private/",
@@ -334,23 +418,37 @@ app.get("/last-modified.txt", (req, res, next) => {
334
418
  });
335
419
 
336
420
  app.get("/favicon.ico", (req, res, next) => {
337
- res
338
- .set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24 * 31}`)
339
- .set("Cache-Tag", "long");
421
+ setStaticAssetCache(res, 3600 * 24 * 31);
340
422
  res.sendFile(path.join(__dirname, "favicon.ico"));
341
423
  });
342
424
 
425
+ // Applies the per-stop route overrides to the /stops listing in the browser.
426
+ // Tagged "long" like the other baked-in assets: it ships with the image, so a
427
+ // GTFS refresh leaves it alone and a code push purges it. Cloudflare caches it
428
+ // for a day on that tag, so an uncached request reaching this far is rare —
429
+ // the limiter is here so a cache-bypassing client can't turn the file read
430
+ // underneath sendFile into an amplifier.
431
+ const staticFileRateLimiter = rateLimit({
432
+ windowMs: 60_000,
433
+ limit: 60,
434
+ standardHeaders: true,
435
+ legacyHeaders: false,
436
+ keyGenerator: clientIpKey,
437
+ });
438
+
439
+ app.get("/stop-overrides.js", staticFileRateLimiter, (req, res) => {
440
+ setStaticAssetCache(res);
441
+ res.type("text/javascript");
442
+ res.sendFile(path.join(__dirname, "public", "stopOverrides.js"));
443
+ });
444
+
343
445
  app.get("/smithery.json", (req, res) => {
344
- res
345
- .set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24 * 7}`)
346
- .set("Cache-Tag", "long");
446
+ setStaticAssetCache(res, 3600 * 24 * 7);
347
447
  res.sendFile(path.join(__dirname, "smithery.json"));
348
448
  });
349
449
 
350
450
  app.get("/server.json", (req, res) => {
351
- res
352
- .set("Cache-Control", `public, max-age=0, s-maxage=${3600 * 24 * 7}`)
353
- .set("Cache-Tag", "long");
451
+ setStaticAssetCache(res, 3600 * 24 * 7);
354
452
  res.sendFile(path.join(__dirname, "server.json"));
355
453
  });
356
454
 
@@ -358,10 +456,7 @@ app.use(notFoundAction);
358
456
 
359
457
  Sentry.setupExpressErrorHandler(app);
360
458
 
361
- app.use(function (err, req, res, next) {
362
- console.error(err.stack);
363
- res.status(500).json({ error: "Internal server error" });
364
- });
459
+ app.use(errorHandler);
365
460
 
366
461
  app.on("ready", () => {
367
462
  app.listen(PORT, () => {
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "timetable-api-node",
3
- "version": "1.3.4",
3
+ "version": "1.4.1",
4
4
  "description": "Lviv (Ukraine) public transport REST API and read-only Model Context Protocol (MCP) server: stops, timetables, routes, live vehicle positions, GTFS/GTFS-RT. No API key required.",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
7
10
  "bin": {
8
11
  "timetable-mcp": "mcp/stdio.js"
9
12
  },
@@ -34,10 +37,11 @@
34
37
  "cors": "^2.8.5",
35
38
  "dotenv": "^17.4",
36
39
  "express": "^5.2.1",
40
+ "express-rate-limit": "^8.6.2",
37
41
  "gtfs": "^4.18.5",
38
42
  "gtfs-realtime-bindings": "^2.0.0",
39
43
  "lokijs": "^1.5.12",
40
- "npm-config": "^0.2.0",
44
+ "newrelic": "^14.3.4",
41
45
  "protobufjs": ">=8.2.0",
42
46
  "public-google-sheets-parser": "^1.3.2",
43
47
  "tar": ">=7.5.15",
@@ -46,13 +50,13 @@
46
50
  "scripts": {
47
51
  "import": "node gtfs-import.js",
48
52
  "import-slim": "node gtfs-import-slim.js",
49
- "start": "node index.js",
53
+ "start": "node -r dotenv/config -r newrelic --import newrelic/esm-loader.mjs index.js",
50
54
  "test": "vitest run",
51
55
  "test:watch": "vitest"
52
56
  },
53
57
  "author": "vbhjckfd@gmail.com",
54
58
  "license": "WTFPL",
55
59
  "devDependencies": {
56
- "vitest": "^4.1.5"
60
+ "vitest": "^5.0.0"
57
61
  }
58
62
  }