lastlight-core 0.16.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.
Files changed (345) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +10 -0
  3. package/agent-context/rules.md +80 -0
  4. package/agent-context/security.md +69 -0
  5. package/agent-context/soul.md +21 -0
  6. package/config/default.yaml +119 -0
  7. package/deploy/.env.production.example +100 -0
  8. package/deploy/entrypoint.sh +82 -0
  9. package/deploy/native/README.md +160 -0
  10. package/deploy/native/install.sh +110 -0
  11. package/deploy/native/lastlight.env.example +95 -0
  12. package/deploy/native/lastlight.service +50 -0
  13. package/deploy/sandbox-entrypoint.sh +93 -0
  14. package/deploy/slack/README.md +92 -0
  15. package/deploy/slack/slack-manifest.json +55 -0
  16. package/dist/admin/auth.d.ts +51 -0
  17. package/dist/admin/auth.js +121 -0
  18. package/dist/admin/auth.js.map +1 -0
  19. package/dist/admin/chat-session-reader.d.ts +39 -0
  20. package/dist/admin/chat-session-reader.js +84 -0
  21. package/dist/admin/chat-session-reader.js.map +1 -0
  22. package/dist/admin/docker.d.ts +61 -0
  23. package/dist/admin/docker.js +187 -0
  24. package/dist/admin/docker.js.map +1 -0
  25. package/dist/admin/index.d.ts +9 -0
  26. package/dist/admin/index.js +59 -0
  27. package/dist/admin/index.js.map +1 -0
  28. package/dist/admin/routes.d.ts +81 -0
  29. package/dist/admin/routes.js +1381 -0
  30. package/dist/admin/routes.js.map +1 -0
  31. package/dist/admin/sessions.d.ts +89 -0
  32. package/dist/admin/sessions.js +204 -0
  33. package/dist/admin/sessions.js.map +1 -0
  34. package/dist/admin/tail.d.ts +12 -0
  35. package/dist/admin/tail.js +145 -0
  36. package/dist/admin/tail.js.map +1 -0
  37. package/dist/admin/version.d.ts +22 -0
  38. package/dist/admin/version.js +92 -0
  39. package/dist/admin/version.js.map +1 -0
  40. package/dist/config/config-resolve.d.ts +28 -0
  41. package/dist/config/config-resolve.js +47 -0
  42. package/dist/config/config-resolve.js.map +1 -0
  43. package/dist/config/config.d.ts +140 -0
  44. package/dist/config/config.js +581 -0
  45. package/dist/config/config.js.map +1 -0
  46. package/dist/connectors/github-webhook.d.ts +45 -0
  47. package/dist/connectors/github-webhook.js +321 -0
  48. package/dist/connectors/github-webhook.js.map +1 -0
  49. package/dist/connectors/index.d.ts +18 -0
  50. package/dist/connectors/index.js +41 -0
  51. package/dist/connectors/index.js.map +1 -0
  52. package/dist/connectors/messaging/base.d.ts +42 -0
  53. package/dist/connectors/messaging/base.js +139 -0
  54. package/dist/connectors/messaging/base.js.map +1 -0
  55. package/dist/connectors/messaging/delivery.d.ts +14 -0
  56. package/dist/connectors/messaging/delivery.js +38 -0
  57. package/dist/connectors/messaging/delivery.js.map +1 -0
  58. package/dist/connectors/messaging/index.d.ts +4 -0
  59. package/dist/connectors/messaging/index.js +4 -0
  60. package/dist/connectors/messaging/index.js.map +1 -0
  61. package/dist/connectors/messaging/session-manager.d.ts +53 -0
  62. package/dist/connectors/messaging/session-manager.js +255 -0
  63. package/dist/connectors/messaging/session-manager.js.map +1 -0
  64. package/dist/connectors/messaging/types.d.ts +58 -0
  65. package/dist/connectors/messaging/types.js +7 -0
  66. package/dist/connectors/messaging/types.js.map +1 -0
  67. package/dist/connectors/slack/connector.d.ts +142 -0
  68. package/dist/connectors/slack/connector.js +494 -0
  69. package/dist/connectors/slack/connector.js.map +1 -0
  70. package/dist/connectors/slack/index.d.ts +2 -0
  71. package/dist/connectors/slack/index.js +3 -0
  72. package/dist/connectors/slack/index.js.map +1 -0
  73. package/dist/connectors/slack/mrkdwn.d.ts +19 -0
  74. package/dist/connectors/slack/mrkdwn.js +240 -0
  75. package/dist/connectors/slack/mrkdwn.js.map +1 -0
  76. package/dist/connectors/types.d.ts +61 -0
  77. package/dist/connectors/types.js +2 -0
  78. package/dist/connectors/types.js.map +1 -0
  79. package/dist/cron/fanout.d.ts +33 -0
  80. package/dist/cron/fanout.js +55 -0
  81. package/dist/cron/fanout.js.map +1 -0
  82. package/dist/cron/jobs.d.ts +18 -0
  83. package/dist/cron/jobs.js +37 -0
  84. package/dist/cron/jobs.js.map +1 -0
  85. package/dist/cron/scheduler.d.ts +45 -0
  86. package/dist/cron/scheduler.js +105 -0
  87. package/dist/cron/scheduler.js.map +1 -0
  88. package/dist/engine/agent-executor.d.ts +34 -0
  89. package/dist/engine/agent-executor.js +246 -0
  90. package/dist/engine/agent-executor.js.map +1 -0
  91. package/dist/engine/chat/chat-runner.d.ts +132 -0
  92. package/dist/engine/chat/chat-runner.js +424 -0
  93. package/dist/engine/chat/chat-runner.js.map +1 -0
  94. package/dist/engine/chat/chat-skills.d.ts +45 -0
  95. package/dist/engine/chat/chat-skills.js +184 -0
  96. package/dist/engine/chat/chat-skills.js.map +1 -0
  97. package/dist/engine/chat/chat.d.ts +54 -0
  98. package/dist/engine/chat/chat.js +316 -0
  99. package/dist/engine/chat/chat.js.map +1 -0
  100. package/dist/engine/chat/message-batcher.d.ts +32 -0
  101. package/dist/engine/chat/message-batcher.js +109 -0
  102. package/dist/engine/chat/message-batcher.js.map +1 -0
  103. package/dist/engine/dispatcher.d.ts +73 -0
  104. package/dist/engine/dispatcher.js +663 -0
  105. package/dist/engine/dispatcher.js.map +1 -0
  106. package/dist/engine/event-shim.d.ts +117 -0
  107. package/dist/engine/event-shim.js +435 -0
  108. package/dist/engine/event-shim.js.map +1 -0
  109. package/dist/engine/executors/orchestrator.d.ts +74 -0
  110. package/dist/engine/executors/orchestrator.js +365 -0
  111. package/dist/engine/executors/orchestrator.js.map +1 -0
  112. package/dist/engine/executors/shared.d.ts +189 -0
  113. package/dist/engine/executors/shared.js +616 -0
  114. package/dist/engine/executors/shared.js.map +1 -0
  115. package/dist/engine/github/git-auth.d.ts +62 -0
  116. package/dist/engine/github/git-auth.js +161 -0
  117. package/dist/engine/github/git-auth.js.map +1 -0
  118. package/dist/engine/github/github-app-client.d.ts +23 -0
  119. package/dist/engine/github/github-app-client.js +33 -0
  120. package/dist/engine/github/github-app-client.js.map +1 -0
  121. package/dist/engine/github/github-tools.d.ts +18 -0
  122. package/dist/engine/github/github-tools.js +263 -0
  123. package/dist/engine/github/github-tools.js.map +1 -0
  124. package/dist/engine/github/github.d.ts +1193 -0
  125. package/dist/engine/github/github.js +357 -0
  126. package/dist/engine/github/github.js.map +1 -0
  127. package/dist/engine/github/profiles.d.ts +11 -0
  128. package/dist/engine/github/profiles.js +42 -0
  129. package/dist/engine/github/profiles.js.map +1 -0
  130. package/dist/engine/github/review-poster.d.ts +98 -0
  131. package/dist/engine/github/review-poster.js +177 -0
  132. package/dist/engine/github/review-poster.js.map +1 -0
  133. package/dist/engine/llm.d.ts +79 -0
  134. package/dist/engine/llm.js +269 -0
  135. package/dist/engine/llm.js.map +1 -0
  136. package/dist/engine/oauth.d.ts +8 -0
  137. package/dist/engine/oauth.js +9 -0
  138. package/dist/engine/oauth.js.map +1 -0
  139. package/dist/engine/router.d.ts +29 -0
  140. package/dist/engine/router.js +680 -0
  141. package/dist/engine/router.js.map +1 -0
  142. package/dist/engine/screen/classifier.d.ts +93 -0
  143. package/dist/engine/screen/classifier.js +215 -0
  144. package/dist/engine/screen/classifier.js.map +1 -0
  145. package/dist/engine/screen/screen.d.ts +41 -0
  146. package/dist/engine/screen/screen.js +93 -0
  147. package/dist/engine/screen/screen.js.map +1 -0
  148. package/dist/evals-api.d.ts +24 -0
  149. package/dist/evals-api.js +22 -0
  150. package/dist/evals-api.js.map +1 -0
  151. package/dist/index.d.ts +1 -0
  152. package/dist/index.js +940 -0
  153. package/dist/index.js.map +1 -0
  154. package/dist/managed-repos.d.ts +30 -0
  155. package/dist/managed-repos.js +72 -0
  156. package/dist/managed-repos.js.map +1 -0
  157. package/dist/notify/blocks.d.ts +23 -0
  158. package/dist/notify/blocks.js +118 -0
  159. package/dist/notify/blocks.js.map +1 -0
  160. package/dist/notify/index.d.ts +17 -0
  161. package/dist/notify/index.js +7 -0
  162. package/dist/notify/index.js.map +1 -0
  163. package/dist/notify/model.d.ts +57 -0
  164. package/dist/notify/model.js +89 -0
  165. package/dist/notify/model.js.map +1 -0
  166. package/dist/notify/notifier.d.ts +18 -0
  167. package/dist/notify/notifier.js +100 -0
  168. package/dist/notify/notifier.js.map +1 -0
  169. package/dist/notify/render.d.ts +21 -0
  170. package/dist/notify/render.js +59 -0
  171. package/dist/notify/render.js.map +1 -0
  172. package/dist/notify/transports/github.d.ts +26 -0
  173. package/dist/notify/transports/github.js +27 -0
  174. package/dist/notify/transports/github.js.map +1 -0
  175. package/dist/notify/transports/slack.d.ts +27 -0
  176. package/dist/notify/transports/slack.js +37 -0
  177. package/dist/notify/transports/slack.js.map +1 -0
  178. package/dist/notify/types.d.ts +111 -0
  179. package/dist/notify/types.js +16 -0
  180. package/dist/notify/types.js.map +1 -0
  181. package/dist/sandbox/docker.d.ts +180 -0
  182. package/dist/sandbox/docker.js +517 -0
  183. package/dist/sandbox/docker.js.map +1 -0
  184. package/dist/sandbox/egress-allowlist.d.ts +74 -0
  185. package/dist/sandbox/egress-allowlist.js +164 -0
  186. package/dist/sandbox/egress-allowlist.js.map +1 -0
  187. package/dist/sandbox/egress-firewall-config.d.ts +127 -0
  188. package/dist/sandbox/egress-firewall-config.js +434 -0
  189. package/dist/sandbox/egress-firewall-config.js.map +1 -0
  190. package/dist/sandbox/images.d.ts +23 -0
  191. package/dist/sandbox/images.js +55 -0
  192. package/dist/sandbox/images.js.map +1 -0
  193. package/dist/sandbox/index.d.ts +112 -0
  194. package/dist/sandbox/index.js +332 -0
  195. package/dist/sandbox/index.js.map +1 -0
  196. package/dist/sandbox/sandbox.d.ts +214 -0
  197. package/dist/sandbox/sandbox.js +453 -0
  198. package/dist/sandbox/sandbox.js.map +1 -0
  199. package/dist/sandbox/smol.d.ts +162 -0
  200. package/dist/sandbox/smol.js +485 -0
  201. package/dist/sandbox/smol.js.map +1 -0
  202. package/dist/session-log.d.ts +63 -0
  203. package/dist/session-log.js +290 -0
  204. package/dist/session-log.js.map +1 -0
  205. package/dist/state/approval-store.d.ts +88 -0
  206. package/dist/state/approval-store.js +149 -0
  207. package/dist/state/approval-store.js.map +1 -0
  208. package/dist/state/build-assets.d.ts +50 -0
  209. package/dist/state/build-assets.js +154 -0
  210. package/dist/state/build-assets.js.map +1 -0
  211. package/dist/state/db.d.ts +81 -0
  212. package/dist/state/db.js +155 -0
  213. package/dist/state/db.js.map +1 -0
  214. package/dist/state/execution-store.d.ts +257 -0
  215. package/dist/state/execution-store.js +527 -0
  216. package/dist/state/execution-store.js.map +1 -0
  217. package/dist/state/migrate.d.ts +15 -0
  218. package/dist/state/migrate.js +175 -0
  219. package/dist/state/migrate.js.map +1 -0
  220. package/dist/state/workflow-run-store.d.ts +216 -0
  221. package/dist/state/workflow-run-store.js +403 -0
  222. package/dist/state/workflow-run-store.js.map +1 -0
  223. package/dist/telemetry/index.d.ts +38 -0
  224. package/dist/telemetry/index.js +253 -0
  225. package/dist/telemetry/index.js.map +1 -0
  226. package/dist/telemetry/pi-events.d.ts +12 -0
  227. package/dist/telemetry/pi-events.js +134 -0
  228. package/dist/telemetry/pi-events.js.map +1 -0
  229. package/dist/workflows/dag.d.ts +1 -0
  230. package/dist/workflows/dag.js +2 -0
  231. package/dist/workflows/dag.js.map +1 -0
  232. package/dist/workflows/handlers/post-review.d.ts +45 -0
  233. package/dist/workflows/handlers/post-review.js +220 -0
  234. package/dist/workflows/handlers/post-review.js.map +1 -0
  235. package/dist/workflows/handlers/verdict-reader.d.ts +14 -0
  236. package/dist/workflows/handlers/verdict-reader.js +55 -0
  237. package/dist/workflows/handlers/verdict-reader.js.map +1 -0
  238. package/dist/workflows/loader.d.ts +9 -0
  239. package/dist/workflows/loader.js +10 -0
  240. package/dist/workflows/loader.js.map +1 -0
  241. package/dist/workflows/loop-eval.d.ts +1 -0
  242. package/dist/workflows/loop-eval.js +2 -0
  243. package/dist/workflows/loop-eval.js.map +1 -0
  244. package/dist/workflows/phase-executor.d.ts +1 -0
  245. package/dist/workflows/phase-executor.js +6 -0
  246. package/dist/workflows/phase-executor.js.map +1 -0
  247. package/dist/workflows/phase-ref.d.ts +1 -0
  248. package/dist/workflows/phase-ref.js +2 -0
  249. package/dist/workflows/phase-ref.js.map +1 -0
  250. package/dist/workflows/resume.d.ts +58 -0
  251. package/dist/workflows/resume.js +313 -0
  252. package/dist/workflows/resume.js.map +1 -0
  253. package/dist/workflows/runner.d.ts +47 -0
  254. package/dist/workflows/runner.js +278 -0
  255. package/dist/workflows/runner.js.map +1 -0
  256. package/dist/workflows/schema.d.ts +1 -0
  257. package/dist/workflows/schema.js +2 -0
  258. package/dist/workflows/schema.js.map +1 -0
  259. package/dist/workflows/simple.d.ts +90 -0
  260. package/dist/workflows/simple.js +393 -0
  261. package/dist/workflows/simple.js.map +1 -0
  262. package/dist/workflows/target-policy.d.ts +74 -0
  263. package/dist/workflows/target-policy.js +80 -0
  264. package/dist/workflows/target-policy.js.map +1 -0
  265. package/dist/workflows/templates.d.ts +1 -0
  266. package/dist/workflows/templates.js +2 -0
  267. package/dist/workflows/templates.js.map +1 -0
  268. package/dist/workflows/triggers.d.ts +21 -0
  269. package/dist/workflows/triggers.js +45 -0
  270. package/dist/workflows/triggers.js.map +1 -0
  271. package/dist/workflows/verdict.d.ts +1 -0
  272. package/dist/workflows/verdict.js +2 -0
  273. package/dist/workflows/verdict.js.map +1 -0
  274. package/dist/worktree/manager.d.ts +43 -0
  275. package/dist/worktree/manager.js +127 -0
  276. package/dist/worktree/manager.js.map +1 -0
  277. package/docker-compose.yml +280 -0
  278. package/package.json +93 -0
  279. package/sandbox.Dockerfile +68 -0
  280. package/skills/README.md +42 -0
  281. package/skills/browser-qa/SKILL.md +208 -0
  282. package/skills/browser-qa/scripts/agent-browser.mjs +531 -0
  283. package/skills/building/SKILL.md +95 -0
  284. package/skills/chat/SKILL.md +36 -0
  285. package/skills/code-review/SKILL.md +82 -0
  286. package/skills/debug-production/SKILL.md +108 -0
  287. package/skills/demo/SKILL.md +228 -0
  288. package/skills/demo/scripts/compose-demo.sh +243 -0
  289. package/skills/issue-answer/SKILL.md +91 -0
  290. package/skills/issue-comment/SKILL.md +49 -0
  291. package/skills/issue-triage/SKILL.md +149 -0
  292. package/skills/issue-triage/references/AGENT-BRIEF.md +65 -0
  293. package/skills/pr-comment/SKILL.md +64 -0
  294. package/skills/pr-review/SKILL.md +148 -0
  295. package/skills/pr-review/references/findings-schema.md +89 -0
  296. package/skills/qa-test/SKILL.md +97 -0
  297. package/skills/repo-health/SKILL.md +67 -0
  298. package/skills/security-feedback/SKILL.md +173 -0
  299. package/skills/security-feedback/references/templates.md +77 -0
  300. package/skills/security-review/SKILL.md +215 -0
  301. package/skills/security-review/references/issue-format.md +302 -0
  302. package/skills/verify/SKILL.md +118 -0
  303. package/workflows/answer.yaml +44 -0
  304. package/workflows/build.yaml +129 -0
  305. package/workflows/cron-health.yaml +6 -0
  306. package/workflows/cron-review.yaml +8 -0
  307. package/workflows/cron-security.yaml +6 -0
  308. package/workflows/cron-triage.yaml +8 -0
  309. package/workflows/demo.yaml +62 -0
  310. package/workflows/examples/bash-smoke.yaml +41 -0
  311. package/workflows/examples/parallel-review.yaml +36 -0
  312. package/workflows/examples/tdd-loop.yaml +17 -0
  313. package/workflows/explore.yaml +80 -0
  314. package/workflows/issue-comment.yaml +15 -0
  315. package/workflows/issue-triage.yaml +22 -0
  316. package/workflows/pr-comment.yaml +16 -0
  317. package/workflows/pr-fix.yaml +17 -0
  318. package/workflows/pr-review.yaml +50 -0
  319. package/workflows/prompts/answer.md +68 -0
  320. package/workflows/prompts/architect.md +44 -0
  321. package/workflows/prompts/classifier.md +60 -0
  322. package/workflows/prompts/classify-adds-info.md +17 -0
  323. package/workflows/prompts/demo.md +125 -0
  324. package/workflows/prompts/executor.md +42 -0
  325. package/workflows/prompts/explore-ask.md +99 -0
  326. package/workflows/prompts/explore-publish.md +31 -0
  327. package/workflows/prompts/explore-read.md +120 -0
  328. package/workflows/prompts/explore-synthesize.md +88 -0
  329. package/workflows/prompts/fix.md +18 -0
  330. package/workflows/prompts/guardrails.md +96 -0
  331. package/workflows/prompts/pr-fix.md +26 -0
  332. package/workflows/prompts/pr.md +39 -0
  333. package/workflows/prompts/qa-browser.md +95 -0
  334. package/workflows/prompts/qa-synth.md +44 -0
  335. package/workflows/prompts/qa-test.md +60 -0
  336. package/workflows/prompts/re-reviewer.md +33 -0
  337. package/workflows/prompts/reviewer.md +60 -0
  338. package/workflows/prompts/verify-browser.md +93 -0
  339. package/workflows/prompts/verify-synth.md +44 -0
  340. package/workflows/prompts/verify.md +63 -0
  341. package/workflows/qa-test.yaml +94 -0
  342. package/workflows/repo-health.yaml +15 -0
  343. package/workflows/security-feedback.yaml +25 -0
  344. package/workflows/security-review.yaml +37 -0
  345. package/workflows/verify.yaml +93 -0
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env bash
2
+ # Idempotent provision + (re)deploy of lastlight as a systemd service on a
3
+ # KVM-capable Linux host. Run as root from the repo root:
4
+ #
5
+ # sudo bash deploy/native/install.sh
6
+ #
7
+ # On first run: installs system deps, creates the lastlight user, scaffolds
8
+ # /etc/lastlight/lastlight.env from the example, installs and starts the
9
+ # systemd unit. On subsequent runs: re-installs the deps that changed,
10
+ # rebuilds, restarts the service.
11
+
12
+ set -euo pipefail
13
+
14
+ REPO_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
15
+ SERVICE_NAME=lastlight
16
+ LASTLIGHT_USER=lastlight
17
+ LASTLIGHT_HOME=/var/lib/lastlight
18
+ ENV_DIR=/etc/lastlight
19
+ ENV_FILE="${ENV_DIR}/lastlight.env"
20
+ PEM_FILE="${ENV_DIR}/app.pem"
21
+
22
+ if [ "$(id -u)" -ne 0 ]; then
23
+ echo "install.sh must run as root (try: sudo $0)" >&2
24
+ exit 1
25
+ fi
26
+
27
+ # ── 1. KVM check — gondolin silently hangs without it ──────────────────────
28
+ if [ ! -e /dev/kvm ]; then
29
+ echo "ERROR: /dev/kvm not present on this host." >&2
30
+ echo " gondolin (lastlight's default sandbox) requires KVM. The host must" >&2
31
+ echo " be bare-metal Linux or a VM with nested virtualization enabled." >&2
32
+ echo " See agentic-pi/SPIKE-gondolin.md for the full constraint." >&2
33
+ exit 1
34
+ fi
35
+
36
+ # ── 2. System dependencies (Debian/Ubuntu) ─────────────────────────────────
37
+ export DEBIAN_FRONTEND=noninteractive
38
+ apt-get update
39
+ apt-get install -y --no-install-recommends \
40
+ curl ca-certificates git \
41
+ qemu-system-x86 qemu-utils \
42
+ python3 build-essential
43
+ # Use NodeSource for a current Node 22 LTS (Debian's nodejs is too old).
44
+ if ! command -v node >/dev/null 2>&1 || ! node -e 'process.exit(process.versions.node.split(".")[0] >= 20 ? 0 : 1)'; then
45
+ curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
46
+ apt-get install -y --no-install-recommends nodejs
47
+ fi
48
+
49
+ # ── 3. User + group ────────────────────────────────────────────────────────
50
+ if ! id "$LASTLIGHT_USER" >/dev/null 2>&1; then
51
+ useradd --system --create-home --home-dir "$LASTLIGHT_HOME" \
52
+ --shell /usr/sbin/nologin "$LASTLIGHT_USER"
53
+ fi
54
+ # `kvm` group exists once qemu is installed; gate the membership add to
55
+ # avoid a usermod warning on hosts where it doesn't.
56
+ if getent group kvm >/dev/null 2>&1; then
57
+ usermod -aG kvm "$LASTLIGHT_USER"
58
+ fi
59
+
60
+ # ── 4. Repo install + build (as the lastlight user) ────────────────────────
61
+ chown -R "$LASTLIGHT_USER:$LASTLIGHT_USER" "$REPO_DIR"
62
+ sudo -u "$LASTLIGHT_USER" -H bash -c "cd '$REPO_DIR' && npm ci --no-audit --no-fund"
63
+ sudo -u "$LASTLIGHT_USER" -H bash -c "cd '$REPO_DIR' && npm run build && npm run build:dashboard"
64
+ # Prune dev deps to shrink the on-disk footprint of the deployed checkout.
65
+ sudo -u "$LASTLIGHT_USER" -H bash -c "cd '$REPO_DIR' && npm prune --omit=dev"
66
+
67
+ # ── 5. Env file scaffold (don't overwrite an existing config) ──────────────
68
+ mkdir -p "$ENV_DIR"
69
+ chmod 0750 "$ENV_DIR"
70
+ chgrp "$LASTLIGHT_USER" "$ENV_DIR"
71
+ if [ ! -f "$ENV_FILE" ]; then
72
+ install -m 0640 -o root -g "$LASTLIGHT_USER" \
73
+ "$REPO_DIR/deploy/native/lastlight.env.example" "$ENV_FILE"
74
+ echo "" >&2
75
+ echo " NOTE: $ENV_FILE was just created from the example template." >&2
76
+ echo " Edit it to fill in your GitHub App, model API keys, Slack tokens, etc." >&2
77
+ echo " Then re-run this script to start the service." >&2
78
+ echo "" >&2
79
+ fi
80
+
81
+ # ── 6. App PEM — referenced by GITHUB_APP_PRIVATE_KEY_PATH in the env file ─
82
+ # If you placed the PEM at /etc/lastlight/app.pem before running install.sh,
83
+ # this section locks down its permissions; otherwise it's a no-op.
84
+ if [ -f "$PEM_FILE" ]; then
85
+ chown root:"$LASTLIGHT_USER" "$PEM_FILE"
86
+ chmod 0640 "$PEM_FILE"
87
+ fi
88
+
89
+ # ── 7. systemd unit ────────────────────────────────────────────────────────
90
+ install -m 0644 \
91
+ "$REPO_DIR/deploy/native/lastlight.service" \
92
+ "/etc/systemd/system/${SERVICE_NAME}.service"
93
+ systemctl daemon-reload
94
+
95
+ # ── 8. Enable + start ──────────────────────────────────────────────────────
96
+ systemctl enable "${SERVICE_NAME}"
97
+ # Only start/restart if the env file looks configured (the example has the
98
+ # string CHANGE_ME everywhere a value is required).
99
+ if grep -q '^[A-Z].*=CHANGE_ME' "$ENV_FILE"; then
100
+ echo " $ENV_FILE still has CHANGE_ME placeholders — not (re)starting the service." >&2
101
+ echo " Fill in the values and re-run install.sh." >&2
102
+ exit 0
103
+ fi
104
+ systemctl restart "${SERVICE_NAME}"
105
+
106
+ # Brief status read-out so the operator sees if it started cleanly.
107
+ sleep 2
108
+ systemctl status "${SERVICE_NAME}" --no-pager -l | head -20 || true
109
+ echo ""
110
+ echo " Live logs: journalctl -u ${SERVICE_NAME} -f"
@@ -0,0 +1,95 @@
1
+ # ── Last Light — Native deploy env (systemd EnvironmentFile) ────────────
2
+ # Path on the host: /etc/lastlight/lastlight.env
3
+ # Mode 0640, owned by root:lastlight.
4
+ #
5
+ # Anything marked CHANGE_ME must be replaced before the service will start
6
+ # (install.sh refuses to start the unit while placeholders are present).
7
+
8
+ # ── GitHub App (required) ─────────────────────────────────────────────────
9
+ GITHUB_APP_ID=CHANGE_ME
10
+ GITHUB_APP_INSTALLATION_ID=CHANGE_ME
11
+ # PEM is read by the harness at boot. install.sh locks down permissions if
12
+ # you place it at /etc/lastlight/app.pem before running.
13
+ GITHUB_APP_PRIVATE_KEY_PATH=/etc/lastlight/app.pem
14
+
15
+ # Webhook receiver
16
+ WEBHOOK_SECRET=CHANGE_ME
17
+ # Listener port — Caddy/Nginx should reverse-proxy 443 → 127.0.0.1:PORT.
18
+ PORT=8644
19
+
20
+ # ── Model + provider API key ─────────────────────────────────────────────
21
+ # pi-ai supports anthropic/…, openai/…, openrouter/<vendor>/<model>.
22
+ LASTLIGHT_MODEL=anthropic/claude-sonnet-4-6
23
+ # Set whichever matches LASTLIGHT_MODEL (or several if LASTLIGHT_MODELS
24
+ # routes different phases to different providers).
25
+ ANTHROPIC_API_KEY=CHANGE_ME
26
+ # OPENAI_API_KEY=
27
+ # OPENROUTER_API_KEY=
28
+
29
+ # ── OpenTelemetry (optional, disabled by default) ────────────────────────
30
+ # LASTLIGHT_OTEL_ENABLED=false
31
+ # LASTLIGHT_OTEL_SERVICE_NAME=lastlight
32
+ # LASTLIGHT_OTEL_INCLUDE_CONTENT=false
33
+ # LASTLIGHT_OTEL_FORWARD_TO_SANDBOX=true
34
+ # LASTLIGHT_OTEL_STRICT=false
35
+ # OTEL_EXPORTER_OTLP_ENDPOINT=https://CHANGE_ME
36
+ # OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer CHANGE_ME
37
+ # docker backend routes sandbox telemetry through an in-network otel-collector
38
+ # (re-exports to the endpoint above; headers stay host-side, any port works).
39
+ # LASTLIGHT_OTEL_COLLECTOR_HOSTS is only used by the gondolin egress allowlist.
40
+ # LASTLIGHT_OTEL_COLLECTOR_HOSTS=CHANGE_ME
41
+
42
+ # Per-task model overrides (optional). JSON keyed by phase/skill name.
43
+ # LASTLIGHT_MODELS={"architect":"openai/gpt-5.5","triage":"anthropic/claude-haiku-4-5-20251001"}
44
+
45
+ # ── Web search (optional, explore workflow only) ─────────────────────────
46
+ # Set any one to enable agentic-pi's `web_search` / `web_fetch` tools for
47
+ # the explore workflow. Provider auto-detected from whichever key is set
48
+ # (Tavily > Exa > Brave). Other workflows ignore these keys.
49
+ # TAVILY_API_KEY=tvly-...
50
+ # BRAVE_SEARCH_API_KEY=BSA...
51
+ # EXA_API_KEY=...
52
+
53
+ # Reasoning-effort default + per-task overrides (optional).
54
+ # Values: off | minimal | low | medium | high | xhigh
55
+ # LASTLIGHT_THINKING=medium
56
+ # LASTLIGHT_THINKINGS={"architect":"high","reviewer":"high"}
57
+
58
+ # ── Sandbox backend ───────────────────────────────────────────────────────
59
+ # gondolin = agentic-pi's QEMU micro-VM (default, requires /dev/kvm).
60
+ # docker = sibling docker containers (requires docker socket access).
61
+ # none = unsandboxed in-process (dev only — agent reads/writes host fs).
62
+ LASTLIGHT_SANDBOX=gondolin
63
+
64
+ # ── State paths ───────────────────────────────────────────────────────────
65
+ # systemd's StateDirectory= grants /var/lib/lastlight with the right mode.
66
+ STATE_DIR=/var/lib/lastlight
67
+ DB_PATH=/var/lib/lastlight/lastlight.db
68
+ LASTLIGHT_SESSIONS_DIR=/var/lib/lastlight/agent-sessions
69
+
70
+ # ── Admin dashboard ───────────────────────────────────────────────────────
71
+ # HMAC secret for session tokens. Generate with: openssl rand -hex 32
72
+ ADMIN_SECRET=CHANGE_ME
73
+ # Optional: require a password for the dashboard. Leave unset to allow
74
+ # anyone who can reach the listener (i.e. anyone past Caddy).
75
+ # ADMIN_PASSWORD=
76
+
77
+ # ── Slack (optional) ──────────────────────────────────────────────────────
78
+ # Setting SLACK_BOT_TOKEN enables the chat skill and the Slack connector.
79
+ # SLACK_BOT_TOKEN=xoxb-…
80
+ # SLACK_APP_TOKEN=xapp-…
81
+ # SLACK_DELIVERY_CHANNEL=C0123456789
82
+ # SLACK_ALLOWED_USERS=U0123,U0456
83
+
84
+ # Slack OAuth for dashboard login (optional)
85
+ # SLACK_OAUTH_CLIENT_ID=
86
+ # SLACK_OAUTH_CLIENT_SECRET=
87
+ # SLACK_OAUTH_REDIRECT_URI=https://your-domain/admin/auth/slack/callback
88
+ # SLACK_ALLOWED_WORKSPACE=
89
+
90
+ # ── Approval gates (optional) ─────────────────────────────────────────────
91
+ # Comma-separated list of gate names that should pause the runner.
92
+ # APPROVAL_GATES=post_architect,post_reviewer
93
+
94
+ # ── Bootstrap label (optional) ────────────────────────────────────────────
95
+ # BOOTSTRAP_LABEL=lastlight:bootstrap
@@ -0,0 +1,50 @@
1
+ [Unit]
2
+ Description=Last Light — GitHub repository maintenance agent
3
+ Documentation=https://github.com/nearform/lastlight
4
+ After=network-online.target
5
+ Wants=network-online.target
6
+
7
+ [Service]
8
+ Type=simple
9
+ User=lastlight
10
+ Group=lastlight
11
+ # gondolin needs /dev/kvm — group `kvm` is the standard accessor on Debian/Ubuntu.
12
+ SupplementaryGroups=kvm
13
+
14
+ WorkingDirectory=/opt/lastlight
15
+ ExecStart=/usr/bin/node /opt/lastlight/dist/index.js
16
+ EnvironmentFile=/etc/lastlight/lastlight.env
17
+
18
+ # HOME drives where agentic-pi caches the gondolin guest image
19
+ # (~/.cache/agentic-pi/images/). Pin it to the StateDirectory so the cache
20
+ # survives redeploys and isn't recomputed on every restart.
21
+ Environment=HOME=/var/lib/lastlight
22
+ Environment=NODE_ENV=production
23
+
24
+ Restart=on-failure
25
+ RestartSec=5s
26
+ LimitNOFILE=65536
27
+ # 2 GB matches the docker-compose limit. Bursts during webhook fan-out +
28
+ # in-process pi-ai chat; per-task gondolin VMs have their own memory budget.
29
+ MemoryMax=2G
30
+
31
+ # /var/lib/lastlight created with mode 0750, owned by lastlight:lastlight
32
+ StateDirectory=lastlight
33
+ StateDirectoryMode=0750
34
+ LogsDirectory=lastlight
35
+ LogsDirectoryMode=0750
36
+
37
+ # Security hardening — the harness only writes to its state dir and logs.
38
+ NoNewPrivileges=true
39
+ PrivateTmp=true
40
+ ProtectSystem=strict
41
+ ProtectHome=true
42
+ ProtectKernelTunables=true
43
+ ProtectKernelModules=true
44
+ ProtectControlGroups=true
45
+ ReadWritePaths=/var/lib/lastlight /var/log/lastlight
46
+ # Explicit /dev/kvm rule — ProtectSystem=strict alone doesn't gate /dev.
47
+ DeviceAllow=/dev/kvm rw
48
+
49
+ [Install]
50
+ WantedBy=multi-user.target
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env bash
2
+ # Sandbox container entrypoint — runs as root after volumes are mounted.
3
+ # Used only when LASTLIGHT_SANDBOX=docker (the gondolin sandbox runs in
4
+ # process and doesn't go through this script). Fixes permissions, writes
5
+ # AGENTS.md, sets up git identity, then drops to the agent user via gosu.
6
+ set -euo pipefail
7
+
8
+ AGENT_HOME="/home/agent"
9
+ WORKSPACE="$AGENT_HOME/workspace"
10
+ # LASTLIGHT_WORKSPACE and LASTLIGHT_GIT_CREDENTIALS are set as image-level
11
+ # ENV in sandbox.Dockerfile so they're visible to every `docker exec` call
12
+ # the harness makes (not just the entrypoint's PID-1 tree). They show up in
13
+ # this shell's env via that mechanism; no export needed here.
14
+
15
+ # ── Fix workspace ownership (bind-mounts may be root-owned on macOS) ──
16
+ chown -R agent:agent "$WORKSPACE" 2>/dev/null || true
17
+ chown agent:agent "$AGENT_HOME"
18
+
19
+ # Ensure ~/.config exists and is agent-owned before any root-side mkdir
20
+ # below claims it (some tools write here at startup).
21
+ mkdir -p "$AGENT_HOME/.config"
22
+ chown agent:agent "$AGENT_HOME/.config"
23
+
24
+ # ── Shared package-manager cache (issue #107) ──
25
+ # /cache is a Docker named volume shared across every sandbox so npm / pnpm /
26
+ # yarn reuse already-downloaded tarballs. A freshly-created volume is root-owned,
27
+ # and a cache seeded by an older image (when `agent` had a different UID) leaves
28
+ # children owned by the wrong UID — which blocks npm/pnpm/yarn writes (e.g.
29
+ # /cache/npm/_logs). Self-heal: if the subdir OR any immediate child isn't
30
+ # agent-owned, chown -R it. The recursive pass runs only when something is
31
+ # actually wrong, so a warm, correctly-owned cache stays cheap.
32
+ if [ -d /cache ]; then
33
+ for sub in npm pnpm yarn uv; do
34
+ mkdir -p "/cache/$sub"
35
+ if [ -n "$(find "/cache/$sub" -maxdepth 1 ! -user agent -print -quit 2>/dev/null)" ]; then
36
+ chown -R agent:agent "/cache/$sub" 2>/dev/null || true
37
+ fi
38
+ done
39
+ fi
40
+
41
+ # ── App PEM: keep shared copy unreadable by the agent by default ──
42
+ if [ -f /data/secrets/app.pem ]; then
43
+ chmod 600 /data/secrets/app.pem 2>/dev/null || true
44
+ fi
45
+
46
+ # Optionally materialize an agent-readable PEM for high-trust runs only.
47
+ # The harness forwards GITHUB_APP_PRIVATE_KEY_PATH into the sandbox env so
48
+ # any tool inside that needs the App key can find it.
49
+ if [ "${ALLOW_APP_PEM:-0}" = "1" ] && [ -f /data/secrets/app.pem ]; then
50
+ cp /data/secrets/app.pem "$AGENT_HOME/.config/app.pem"
51
+ chown agent:agent "$AGENT_HOME/.config/app.pem"
52
+ chmod 600 "$AGENT_HOME/.config/app.pem"
53
+ export GITHUB_APP_PRIVATE_KEY_PATH="$AGENT_HOME/.config/app.pem"
54
+ else
55
+ export GITHUB_APP_PRIVATE_KEY_PATH=""
56
+ fi
57
+
58
+ # ── AGENTS.md — agentic-pi auto-loads this from cwd as the agent's
59
+ # system context (same convention as CLAUDE.md). ──
60
+ if [ ! -f "$WORKSPACE/AGENTS.md" ]; then
61
+ cat /app/agent-context/*.md > "$WORKSPACE/AGENTS.md" 2>/dev/null || true
62
+ fi
63
+ chown agent:agent "$WORKSPACE/AGENTS.md" 2>/dev/null || true
64
+
65
+ # ── Git identity and auth (system-wide so it applies regardless of exec user) ──
66
+ git config --system user.name "last-light[bot]"
67
+ git config --system user.email "last-light[bot]@users.noreply.github.com"
68
+
69
+ if [ -n "${GIT_TOKEN:-}" ]; then
70
+ # Reject tokens containing characters that would break the URL line in
71
+ # the credentials file (newline, '@', ':', '/', whitespace). Real GitHub
72
+ # tokens are alphanumeric + underscore — the wider charset here is
73
+ # defensive against future format changes.
74
+ if ! printf %s "$GIT_TOKEN" | grep -Eq '^[A-Za-z0-9_-]+$'; then
75
+ echo "ERROR: GIT_TOKEN contains characters outside [A-Za-z0-9_-]; refusing to write credentials file" >&2
76
+ exit 1
77
+ fi
78
+ # Write the file as the agent user (mode 600) so the helper can read it
79
+ # after the entrypoint drops privileges. Path is set by us above; the
80
+ # `store --file=<path>` value goes into git's config as argv-split (no
81
+ # shell), so the only constraint is no-whitespace in the path.
82
+ install -m 600 -o agent -g agent /dev/null "$LASTLIGHT_GIT_CREDENTIALS"
83
+ printf 'https://x-access-token:%s@github.com\n' "$GIT_TOKEN" > "$LASTLIGHT_GIT_CREDENTIALS"
84
+ chown agent:agent "$LASTLIGHT_GIT_CREDENTIALS"
85
+ git config --system credential.helper "store --file=$LASTLIGHT_GIT_CREDENTIALS"
86
+ fi
87
+
88
+ # ── Sentinel for harness waitForReady() ──
89
+ touch "$WORKSPACE/.ready"
90
+ chown agent:agent "$WORKSPACE/.ready"
91
+
92
+ # ── Drop to agent user ──
93
+ exec gosu agent "$@"
@@ -0,0 +1,92 @@
1
+ # Slack app manifest
2
+
3
+ `slack-manifest.json` is a reference Slack app manifest for a Last Light
4
+ deployment, trimmed to **only the scopes the code actually exercises**. Import
5
+ it at <https://api.slack.com/apps> → *Create New App* → *From a manifest*, or
6
+ paste it into an existing app's *App Manifest* editor.
7
+
8
+ ## Before importing — replace the placeholders
9
+
10
+ - `YOUR_INSTANCE_DOMAIN` (two occurrences) → your instance host, e.g.
11
+ `myinstance.example.com`. Used for:
12
+ - the "Sign in with Slack" OAuth callback
13
+ (`/admin/api/oauth/slack/callback`), and
14
+ - the Events API request URL (`/webhooks/slack`).
15
+ - `name` / `bot_user.display_name` — default to `last-light` (the repo's
16
+ default `botName`). If you set a custom `botName` in your overlay
17
+ `config.yaml`, match it here so `@mention` autocomplete lines up.
18
+
19
+ ## Scopes and why (each maps to real code)
20
+
21
+ ### Bot token scopes (`xoxb-…`)
22
+
23
+ | Scope | Why | Code |
24
+ | --- | --- | --- |
25
+ | `chat:write` | Post replies + cron reports; edit the in-place status message (`chat.postMessage` / `chat.update`) | `src/connectors/slack/connector.ts` |
26
+ | `app_mentions:read` | Respond when `@mention`ed in a channel (`app_mention` event) | `connector.ts` |
27
+ | `im:history` | Read + respond to DMs (`message.im` event) | `connector.ts` |
28
+ | `users:read` | Resolve a user ID → username for display (`users.info`) | `connector.ts` |
29
+ | `assistant:write` | The "Thinking…" thread status indicator (`assistant.threads.setStatus`) | `connector.ts` |
30
+ | `reactions:write` | Fallback 👀 ack reaction when the assistant status API isn't available (`reactions.add`) | `connector.ts` |
31
+
32
+ ### Event subscriptions
33
+
34
+ - `app_mention` — needs `app_mentions:read`.
35
+ - `message.im` — needs `im:history`.
36
+
37
+ ### User token scopes ("Sign in with Slack", dashboard login only)
38
+
39
+ - `openid`, `profile` — mint a dashboard session and read
40
+ `team_id` / `team_domain` / `user_id` to enforce the workspace allowlist
41
+ (`arctic`, `src/admin/routes.ts`). `email` is **not** requested.
42
+
43
+ ### Non-scope secret
44
+
45
+ - **Signing secret** (`SLACK_SIGNING_SECRET`) — verifies Events API requests
46
+ (HMAC over `v0:{ts}:{body}`). Not an OAuth scope; set it in your secrets
47
+ `.env`, not in this manifest.
48
+
49
+ ## Extra setup outside the manifest
50
+
51
+ - **`assistant:write` requires the "Agents & AI Apps" (Assistant) feature** to
52
+ be enabled on the app in the Slack dashboard. The scope alone isn't enough —
53
+ enable the feature, or the status indicator silently no-ops (the bot falls
54
+ back to the `reactions.add` ack).
55
+
56
+ ## Socket Mode (dev only)
57
+
58
+ This manifest is for **webhook / production mode** (`SLACK_MODE=webhook`, the
59
+ default). For Socket Mode local dev (`SLACK_MODE=socket`) instead:
60
+
61
+ - set `settings.socket_mode_enabled: true`,
62
+ - add an **app-level token** (`xapp-…`, `SLACK_APP_TOKEN`) with the
63
+ `connections:write` scope, and
64
+ - add `channels:history` + `groups:history` bot scopes **only if** you want the
65
+ bot to see non-mention messages in channels/private channels — Bolt's
66
+ `message()` listener is a catch-all in Socket Mode. The default handlers act
67
+ on DMs + mentions only, so you usually don't need them.
68
+
69
+ ## What was dropped from the original manifest (and why)
70
+
71
+ Relative to an earlier over-provisioned manifest, this reference removes scopes
72
+ no code path uses:
73
+
74
+ - **User scopes dropped:** `emoji:read`, `files:read`, `im:history`, `im:write`,
75
+ `mpim:read`, `mpim:write`, `mpim:history`, `reactions:read`, `reactions:write`,
76
+ `search:read.*` (files/im/mpim/private/public/users), `users:read`,
77
+ `users:read.email`. Nothing uses a Slack **user** token except the OIDC login
78
+ (`openid`/`profile`). The `search:read.*` set mirrors Slack's MCP scope
79
+ bundle, but `is_mcp_enabled` is `false` and there's no MCP integration. User
80
+ scopes also require per-user consent and grant access to that user's private
81
+ channels, DMs, and files — a needless privacy/blast-radius liability.
82
+ - **Bot scopes dropped:** `channels:read`, `files:write`, `im:read`, `im:write`,
83
+ `channels:history`, `groups:history` — none are called by the connector, and
84
+ the two `*:history` channel scopes only matter for Socket Mode (see above).
85
+ - **Bot scopes ADDED (were missing but required):** `assistant:write` and
86
+ `reactions:write`. The code calls both on the **bot** token; the original
87
+ granted `reactions:write` only as a *user* scope and omitted `assistant:write`
88
+ entirely, so those features were failing with `missing_scope`.
89
+ - **Events dropped:** `message.channels`, `message.groups` — the handlers act on
90
+ DMs (`message.im`) and mentions (`app_mention`); the code ignores plain
91
+ channel/group messages, so subscribing to them just delivers events nothing
92
+ consumes.
@@ -0,0 +1,55 @@
1
+ {
2
+ "display_information": {
3
+ "name": "last-light",
4
+ "description": "A helpful bot to work on our repos",
5
+ "background_color": "#010d38",
6
+ "long_description": "A coding harness that helps us do work on our repositories, and only able to work on repositories that have been configured for use. Ask it questions, or ask it to build features."
7
+ },
8
+ "features": {
9
+ "app_home": {
10
+ "home_tab_enabled": false,
11
+ "messages_tab_enabled": true,
12
+ "messages_tab_read_only_enabled": false
13
+ },
14
+ "assistant_view": {
15
+ "assistant_description": "Work on your repositories"
16
+ },
17
+ "bot_user": {
18
+ "display_name": "last-light",
19
+ "always_online": true
20
+ }
21
+ },
22
+ "oauth_config": {
23
+ "redirect_urls": [
24
+ "https://YOUR_INSTANCE_DOMAIN/admin/api/oauth/slack/callback"
25
+ ],
26
+ "scopes": {
27
+ "user": [
28
+ "openid",
29
+ "profile"
30
+ ],
31
+ "bot": [
32
+ "app_mentions:read",
33
+ "assistant:write",
34
+ "chat:write",
35
+ "im:history",
36
+ "reactions:write",
37
+ "users:read"
38
+ ]
39
+ },
40
+ "pkce_enabled": false
41
+ },
42
+ "settings": {
43
+ "event_subscriptions": {
44
+ "request_url": "https://YOUR_INSTANCE_DOMAIN/webhooks/slack",
45
+ "bot_events": [
46
+ "app_mention",
47
+ "message.im"
48
+ ]
49
+ },
50
+ "org_deploy_enabled": true,
51
+ "socket_mode_enabled": false,
52
+ "token_rotation_enabled": false,
53
+ "is_mcp_enabled": false
54
+ }
55
+ }
@@ -0,0 +1,51 @@
1
+ import type { Context, Next } from "hono";
2
+ /**
3
+ * Grace window past `exp` in which a token can still be *refreshed* (but not
4
+ * used to authenticate a normal request). Lets an active user whose token
5
+ * lapsed briefly slide their session forward via the refresh route instead of
6
+ * being bounced back through a full login. Beyond this, they must re-login.
7
+ */
8
+ export declare const REFRESH_GRACE_SECONDS: number;
9
+ export declare function createToken(secret: string, method?: "password" | "slack" | "github"): string;
10
+ export declare function verifyToken(token: string, secret: string): boolean;
11
+ /**
12
+ * Like `verifyToken`, but also accepts a token that expired within the last
13
+ * `REFRESH_GRACE_SECONDS`. Used ONLY by the refresh route so a briefly-lapsed
14
+ * session can be renewed. The signature must still be valid (we minted it), so
15
+ * this can't be forged.
16
+ */
17
+ export declare function verifyTokenForRefresh(token: string, secret: string): boolean;
18
+ export interface TokenPayload {
19
+ exp: number;
20
+ method?: "password" | "slack" | "github";
21
+ }
22
+ /**
23
+ * Decode a token's payload WITHOUT verifying its signature or expiry — used to
24
+ * carry the login `method` across a refresh. Callers that need authenticity
25
+ * must still gate on `verifyToken` (the refresh route runs behind
26
+ * `authMiddleware`, which does exactly that). Returns null if unparseable.
27
+ */
28
+ export declare function decodeToken(token: string): TokenPayload | null;
29
+ /**
30
+ * Whether any login method is configured — an admin password OR a working OAuth
31
+ * provider. The single source of truth for "is auth on", shared by the admin
32
+ * dashboard and the `/api/*` trigger routes so they can't drift. The GitHub
33
+ * gate, like the OAuth route, also requires an allowed-org to be set.
34
+ */
35
+ export declare function authIsEnabled(opts: {
36
+ adminPassword?: string;
37
+ slackOAuthClientId?: string;
38
+ slackOAuthClientSecret?: string;
39
+ githubOAuthClientId?: string;
40
+ githubOAuthClientSecret?: string;
41
+ githubAllowedOrg?: string;
42
+ }): boolean;
43
+ /**
44
+ * Gate the admin API. `enabled` should be true when ANY login method is
45
+ * configured — an admin password OR a working OAuth provider. Gating only on
46
+ * the password (the old behaviour) left the dashboard fully open whenever the
47
+ * password was cleared, even with Slack/GitHub OAuth set up.
48
+ */
49
+ export declare function authMiddleware(enabled: boolean, secret: string): (c: Context, next: Next) => Promise<void | (Response & import("hono").TypedResponse<{
50
+ error: string;
51
+ }, 401, "json">)>;
@@ -0,0 +1,121 @@
1
+ import crypto from "node:crypto";
2
+ const TOKEN_TTL_SECONDS = 60 * 60 * 24 * 30; // 30 days
3
+ /**
4
+ * Grace window past `exp` in which a token can still be *refreshed* (but not
5
+ * used to authenticate a normal request). Lets an active user whose token
6
+ * lapsed briefly slide their session forward via the refresh route instead of
7
+ * being bounced back through a full login. Beyond this, they must re-login.
8
+ */
9
+ export const REFRESH_GRACE_SECONDS = 60 * 60 * 24 * 7; // 7 days
10
+ export function createToken(secret, method) {
11
+ const payload = { exp: Math.floor(Date.now() / 1000) + TOKEN_TTL_SECONDS };
12
+ if (method)
13
+ payload.method = method;
14
+ const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url");
15
+ const sig = crypto.createHmac("sha256", secret).update(payloadB64).digest("base64url");
16
+ return `${payloadB64}.${sig}`;
17
+ }
18
+ /**
19
+ * Verify the HMAC signature and return the decoded payload, or null if the
20
+ * signature is invalid / the payload is unparseable. Does NOT check expiry —
21
+ * that's the caller's job (strict for auth, lenient for refresh).
22
+ */
23
+ function verifySignature(token, secret) {
24
+ const parts = token.split(".");
25
+ if (parts.length !== 2)
26
+ return null;
27
+ const [payloadB64, sig] = parts;
28
+ const expectedSig = crypto.createHmac("sha256", secret).update(payloadB64).digest("base64url");
29
+ if (expectedSig.length !== sig.length ||
30
+ !crypto.timingSafeEqual(Buffer.from(expectedSig), Buffer.from(sig))) {
31
+ return null;
32
+ }
33
+ return decodeToken(token);
34
+ }
35
+ export function verifyToken(token, secret) {
36
+ const payload = verifySignature(token, secret);
37
+ if (!payload)
38
+ return false;
39
+ return Math.floor(Date.now() / 1000) < payload.exp;
40
+ }
41
+ /**
42
+ * Like `verifyToken`, but also accepts a token that expired within the last
43
+ * `REFRESH_GRACE_SECONDS`. Used ONLY by the refresh route so a briefly-lapsed
44
+ * session can be renewed. The signature must still be valid (we minted it), so
45
+ * this can't be forged.
46
+ */
47
+ export function verifyTokenForRefresh(token, secret) {
48
+ const payload = verifySignature(token, secret);
49
+ if (!payload)
50
+ return false;
51
+ return Math.floor(Date.now() / 1000) < payload.exp + REFRESH_GRACE_SECONDS;
52
+ }
53
+ /**
54
+ * Decode a token's payload WITHOUT verifying its signature or expiry — used to
55
+ * carry the login `method` across a refresh. Callers that need authenticity
56
+ * must still gate on `verifyToken` (the refresh route runs behind
57
+ * `authMiddleware`, which does exactly that). Returns null if unparseable.
58
+ */
59
+ export function decodeToken(token) {
60
+ const parts = token.split(".");
61
+ if (parts.length !== 2)
62
+ return null;
63
+ try {
64
+ const payload = JSON.parse(Buffer.from(parts[0], "base64url").toString("utf8"));
65
+ if (typeof payload.exp !== "number")
66
+ return null;
67
+ const method = payload.method;
68
+ return {
69
+ exp: payload.exp,
70
+ method: method === "password" || method === "slack" || method === "github" ? method : undefined,
71
+ };
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ }
77
+ /**
78
+ * Whether any login method is configured — an admin password OR a working OAuth
79
+ * provider. The single source of truth for "is auth on", shared by the admin
80
+ * dashboard and the `/api/*` trigger routes so they can't drift. The GitHub
81
+ * gate, like the OAuth route, also requires an allowed-org to be set.
82
+ */
83
+ export function authIsEnabled(opts) {
84
+ const slack = Boolean(opts.slackOAuthClientId && opts.slackOAuthClientSecret);
85
+ const github = Boolean(opts.githubOAuthClientId && opts.githubOAuthClientSecret && opts.githubAllowedOrg);
86
+ return Boolean(opts.adminPassword) || slack || github;
87
+ }
88
+ /**
89
+ * Gate the admin API. `enabled` should be true when ANY login method is
90
+ * configured — an admin password OR a working OAuth provider. Gating only on
91
+ * the password (the old behaviour) left the dashboard fully open whenever the
92
+ * password was cleared, even with Slack/GitHub OAuth set up.
93
+ */
94
+ export function authMiddleware(enabled, secret) {
95
+ return async (c, next) => {
96
+ if (!enabled)
97
+ return next();
98
+ const path = new URL(c.req.url).pathname;
99
+ // Let login + health + OAuth routes through
100
+ if (path.endsWith("/login") ||
101
+ path.endsWith("/token/refresh") ||
102
+ path.endsWith("/health") ||
103
+ path.endsWith("/auth-required") ||
104
+ path.endsWith("/oauth/slack/authorize") ||
105
+ path.endsWith("/oauth/slack/callback") ||
106
+ path.endsWith("/oauth/github/authorize") ||
107
+ path.endsWith("/oauth/github/callback")) {
108
+ return next();
109
+ }
110
+ const header = c.req.header("Authorization");
111
+ let token = header?.startsWith("Bearer ") ? header.slice(7) : undefined;
112
+ // EventSource can't set headers — allow token via query param
113
+ if (!token)
114
+ token = c.req.query("token") ?? undefined;
115
+ if (!token || !verifyToken(token, secret)) {
116
+ return c.json({ error: "unauthorized" }, 401);
117
+ }
118
+ return next();
119
+ };
120
+ }
121
+ //# sourceMappingURL=auth.js.map