@forwardimpact/libbridge 0.1.0 → 0.1.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": "@forwardimpact/libbridge",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Threaded-channel bridge primitives — relay messages between human channels (GitHub Discussions, Microsoft Teams) and the Kata agent team.",
5
5
  "keywords": [
6
6
  "bridge",
@@ -50,7 +50,7 @@
50
50
  },
51
51
  "engines": {
52
52
  "bun": ">=1.2.0",
53
- "node": ">=18.0.0"
53
+ "node": ">=22.0.0"
54
54
  },
55
55
  "publishConfig": {
56
56
  "access": "public"
@@ -134,6 +134,19 @@ async function resolveContext(
134
134
  return { token, ctx, meta, payload };
135
135
  }
136
136
 
137
+ const STATUS_MESSAGES = {
138
+ 400: "Bad request",
139
+ 404: "Not found",
140
+ 410: "Gone",
141
+ 429: "Too many requests",
142
+ 500: "Internal error",
143
+ };
144
+
145
+ /** Map a CallbackHandlerError status to a safe generic message. */
146
+ function sanitizeErrorMessage(status) {
147
+ return STATUS_MESSAGES[status] ?? `Error ${status}`;
148
+ }
149
+
137
150
  async function runHandleReply(
138
151
  c,
139
152
  { ctx, meta, payload, handleReply, store, logger, tracer, spanName },
@@ -154,7 +167,7 @@ async function runHandleReply(
154
167
  if (err instanceof CallbackHandlerError) {
155
168
  span.addEvent("short_circuit", { status: err.status });
156
169
  span.setOk();
157
- return c.json({ error: err.message }, err.status);
170
+ return c.json({ error: sanitizeErrorMessage(err.status) }, err.status);
158
171
  }
159
172
  logger.error?.("callback", err, {
160
173
  correlation_id: meta.correlationId,
@@ -1,4 +1,5 @@
1
1
  export const MAX_FIELD_LENGTH = 2000;
2
+ export const MAX_REPLY_COUNT = 50;
2
3
 
3
4
  /**
4
5
  * Validate and sanitize the kata-dispatch callback payload. Lenient by
@@ -23,11 +24,17 @@ export function validateCallbackPayload(body) {
23
24
  typeof body.summary === "string"
24
25
  ? body.summary.slice(0, MAX_FIELD_LENGTH)
25
26
  : "";
26
- const replies = Array.isArray(body.replies) ? body.replies : [];
27
+ const rawReplies = Array.isArray(body.replies) ? body.replies : [];
28
+ const replies = rawReplies.slice(0, MAX_REPLY_COUNT).map((r) => {
29
+ if (!r || typeof r !== "object") return r;
30
+ if (typeof r.body === "string") {
31
+ return { ...r, body: r.body.slice(0, MAX_FIELD_LENGTH) };
32
+ }
33
+ return r;
34
+ });
27
35
  const discussionId =
28
36
  typeof body.discussion_id === "string" ? body.discussion_id : undefined;
29
- const trigger =
30
- body.trigger && typeof body.trigger === "object" ? body.trigger : undefined;
37
+ const trigger = validateTrigger(body.trigger);
31
38
  const runUrl = typeof body.run_url === "string" ? body.run_url : undefined;
32
39
 
33
40
  return {
@@ -41,6 +48,33 @@ export function validateCallbackPayload(body) {
41
48
  };
42
49
  }
43
50
 
51
+ const ALLOWED_TRIGGER_KINDS = new Set(["responses", "elapsed", "any"]);
52
+
53
+ /**
54
+ * Validate and sanitize a trigger object at the payload boundary.
55
+ * Rejects triggers with unknown `kind` values or invalid field types.
56
+ *
57
+ * @param {unknown} raw
58
+ * @returns {object | undefined}
59
+ */
60
+ function validateTrigger(raw) {
61
+ if (!raw || typeof raw !== "object") return undefined;
62
+ if (typeof raw.kind !== "string" || !ALLOWED_TRIGGER_KINDS.has(raw.kind)) {
63
+ return undefined;
64
+ }
65
+ const trigger = { kind: raw.kind };
66
+ if (raw.responses !== undefined) {
67
+ const n = Number(raw.responses);
68
+ if (!Number.isFinite(n) || n < 0) return undefined;
69
+ trigger.responses = n;
70
+ }
71
+ if (raw.elapsed !== undefined) {
72
+ if (typeof raw.elapsed !== "string") return undefined;
73
+ trigger.elapsed = raw.elapsed;
74
+ }
75
+ return trigger;
76
+ }
77
+
44
78
  /**
45
79
  * Strip trailing slashes from a base URL so callback URL composition is
46
80
  * deterministic regardless of operator input.
package/src/index.js CHANGED
@@ -17,6 +17,7 @@ export { appendHistory } from "./history.js";
17
17
  export { RateLimiter } from "./rate-limit.js";
18
18
  export { dispatchWorkflow } from "./dispatch.js";
19
19
  export { DiscussionContextStore } from "./discussion-context.js";
20
+ export { OriginIndex } from "./origin-index.js";
20
21
  export { ProgressTicker } from "./progress-ticker.js";
21
22
  export {
22
23
  Acknowledgement,
@@ -31,6 +32,7 @@ export { ElapsedScheduler } from "./elapsed-scheduler.js";
31
32
  export { ResumeScheduler } from "./resume-scheduler.js";
32
33
  export {
33
34
  MAX_FIELD_LENGTH,
35
+ MAX_REPLY_COUNT,
34
36
  newDiscussionContext,
35
37
  normalizeBaseUrl,
36
38
  validateCallbackPayload,
@@ -0,0 +1,49 @@
1
+ import { BufferedIndex } from "@forwardimpact/libindex";
2
+
3
+ const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
4
+
5
+ /**
6
+ * Tracks comment IDs posted by the bridge so webhook handlers can skip
7
+ * dispatching for self-originated events. Wraps `BufferedIndex` with
8
+ * caller-injected `StorageInterface` per the libbridge invariant.
9
+ *
10
+ * Record shape: `{ id: "<comment_node_id>", discussion_id, posted_at }`
11
+ *
12
+ * @augments BufferedIndex
13
+ */
14
+ export class OriginIndex extends BufferedIndex {
15
+ #ttlMs;
16
+
17
+ /**
18
+ * @param {import("@forwardimpact/libstorage").StorageInterface} storage
19
+ * @param {object} [options]
20
+ * @param {string} [options.indexKey]
21
+ * @param {number} [options.ttlMs] - Eviction window (default 24h)
22
+ */
23
+ constructor(
24
+ storage,
25
+ { indexKey = "origins.jsonl", ttlMs = DEFAULT_TTL_MS } = {},
26
+ ) {
27
+ super(storage, indexKey, {
28
+ flush_interval: 1_000,
29
+ max_buffer_size: 100,
30
+ });
31
+ this.#ttlMs = ttlMs;
32
+ }
33
+
34
+ /**
35
+ * Evict records older than `ttlMs`.
36
+ * @param {number} now
37
+ * @returns {number} count evicted
38
+ */
39
+ sweep(now) {
40
+ let evicted = 0;
41
+ for (const [id, record] of this.index) {
42
+ if (now - (record?.posted_at ?? 0) > this.#ttlMs) {
43
+ this.index.delete(id);
44
+ evicted++;
45
+ }
46
+ }
47
+ return evicted;
48
+ }
49
+ }
package/src/server.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Hono } from "hono";
2
+ import { bodyLimit } from "hono/body-limit";
2
3
  import { serve } from "@hono/node-server";
3
4
 
4
5
  /**
@@ -44,6 +45,17 @@ export function createBridgeServer({
44
45
 
45
46
  const app = new Hono();
46
47
 
48
+ // Security headers — standard hardening for a backend service.
49
+ app.use("*", async (c, next) => {
50
+ await next();
51
+ c.header("X-Content-Type-Options", "nosniff");
52
+ c.header("X-Frame-Options", "DENY");
53
+ c.header("Cache-Control", "no-store");
54
+ });
55
+
56
+ // Request body size limit — 1 MB is generous for JSON callback payloads.
57
+ app.use("*", bodyLimit({ maxSize: 1024 * 1024 }));
58
+
47
59
  // Capture the raw POST body once, before downstream handlers parse it.
48
60
  // Channel adapters use this buffer to verify HMAC signatures.
49
61
  app.use("*", async (c, next) => {