@snagset/server 0.1.54 → 0.1.56

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 (116) hide show
  1. package/dist/app.js +8 -0
  2. package/dist/app.js.map +1 -1
  3. package/dist/config.generated.js +3 -1
  4. package/dist/config.generated.js.map +1 -1
  5. package/dist/db/migrations/0018_integration_inbound.sql +24 -0
  6. package/dist/db/migrations/0019_trello_provider.no-txn.sql +11 -0
  7. package/dist/integrations/github.js +17 -0
  8. package/dist/integrations/github.js.map +1 -1
  9. package/dist/integrations/inbound.js +2 -0
  10. package/dist/integrations/inbound.js.map +1 -1
  11. package/dist/integrations/jira.js +17 -1
  12. package/dist/integrations/jira.js.map +1 -1
  13. package/dist/integrations/linear.js +10 -0
  14. package/dist/integrations/linear.js.map +1 -1
  15. package/dist/integrations/outbox.js +24 -5
  16. package/dist/integrations/outbox.js.map +1 -1
  17. package/dist/integrations/store.js +53 -4
  18. package/dist/integrations/store.js.map +1 -1
  19. package/dist/integrations/trello.js +147 -0
  20. package/dist/integrations/trello.js.map +1 -0
  21. package/dist/jobs/set.js +3 -0
  22. package/dist/jobs/set.js.map +1 -1
  23. package/dist/net/publicFetch.js +144 -5
  24. package/dist/net/publicFetch.js.map +1 -1
  25. package/dist/routes/integrations.js +327 -41
  26. package/dist/routes/integrations.js.map +1 -1
  27. package/dist/routes/threads.js.map +1 -1
  28. package/package.json +1 -1
  29. package/static/dashboard/assets/{CompositeItem-D7Q5QVvi.js → CompositeItem-B0Gv-UGy.js} +1 -1
  30. package/static/dashboard/assets/{CompositeList-w7YcjHbo.js → CompositeList-DJzkqbsI.js} +1 -1
  31. package/static/dashboard/assets/{ConfirmDialog-CHiXSDkR.js → ConfirmDialog-DrJjmykZ.js} +1 -1
  32. package/static/dashboard/assets/{CopyButton-DkXHOvAs.js → CopyButton-N4ZGq5sM.js} +1 -1
  33. package/static/dashboard/assets/{FieldItemContext-BWEjbC5Z.js → FieldItemContext-Btlb65DI.js} +1 -1
  34. package/static/dashboard/assets/{InstallTag-DlqXIhqI.js → InstallTag-ErmrqxJG.js} +1 -1
  35. package/static/dashboard/assets/{InstanceRows-DwXLnXU2.js → InstanceRows-qItZIB6E.js} +1 -1
  36. package/static/dashboard/assets/McpTokens-BANlGby-.js +1 -0
  37. package/static/dashboard/assets/Picker-BGDXZjRG.js +6 -0
  38. package/static/dashboard/assets/{SaveState-DzX_pKjo.js → SaveState-C5sUD5wu.js} +1 -1
  39. package/static/dashboard/assets/{_app-DW5KDMy_.js → _app-Bskz-yjz.js} +2 -2
  40. package/static/dashboard/assets/{_app-B-X6wLWA.js → _app-QhVaTUQt.js} +1 -1
  41. package/static/dashboard/assets/activity-RabDpuwi.js +1 -0
  42. package/static/dashboard/assets/{arrow-left-DbWDuhAv.js → arrow-left-DJWxyBo6.js} +1 -1
  43. package/static/dashboard/assets/{avatar-BL6yPDkc.js → avatar-CN3-8DpI.js} +1 -1
  44. package/static/dashboard/assets/{badge-Dybw0_bq.js → badge-C54dE8rx.js} +1 -1
  45. package/static/dashboard/assets/{card-DwOk-mSd.js → card-Dxk95cVf.js} +1 -1
  46. package/static/dashboard/assets/{check-Dfkv0gma.js → check-CK4ao5He.js} +1 -1
  47. package/static/dashboard/assets/{chevron-down-BFQamcZy.js → chevron-down-OtEbsKDP.js} +1 -1
  48. package/static/dashboard/assets/{chevron-right-v0My-Qwf.js → chevron-right-DsIeYYan.js} +1 -1
  49. package/static/dashboard/assets/{copy-Bnl05Zl3.js → copy-oQJtUs23.js} +1 -1
  50. package/static/dashboard/assets/{createBaseUIEventDetails-DviWdj-N.js → createBaseUIEventDetails-CtitjO53.js} +1 -1
  51. package/static/dashboard/assets/{dialog-B1TvUOp8.js → dialog-PoGeAS0T.js} +2 -2
  52. package/static/dashboard/assets/{dropdown-menu-DQDS-MXM.js → dropdown-menu-CnT2RuY9.js} +2 -2
  53. package/static/dashboard/assets/{forgot-B13MZpbf.js → forgot-C2yLPZRe.js} +1 -1
  54. package/static/dashboard/assets/getPseudoElementBounds-1HRS6at-.js +1 -0
  55. package/static/dashboard/assets/{image-off-4dn7EbeZ.js → image-off-DUeMoP3X.js} +1 -1
  56. package/static/dashboard/assets/index-BQBdFBZG.css +1 -0
  57. package/static/dashboard/assets/{index-_7kIe8FW.js → index-DCtWnS4U.js} +3 -3
  58. package/static/dashboard/assets/{inertValue-BSe8K39O.js → inertValue-DvQ1EW5I.js} +1 -1
  59. package/static/dashboard/assets/{invite-nV6ykkp0.js → invite-CGRft1Wf.js} +1 -1
  60. package/static/dashboard/assets/{label-BkHFb2_L.js → label-Br7CuW71.js} +1 -1
  61. package/static/dashboard/assets/{layout-grid-Dt1Q4YQ_.js → layout-grid-D8FSCXx_.js} +1 -1
  62. package/static/dashboard/assets/me-Bz7e5FMG.js +1 -0
  63. package/static/dashboard/assets/{parts-DGVjMHe8.js → parts-BE9o8mAH.js} +1 -1
  64. package/static/dashboard/assets/{plus-hkwBCzos.js → plus-CZbLvWG1.js} +1 -1
  65. package/static/dashboard/assets/{reset-BNNJmqWL.js → reset-ZYeb2Axs.js} +1 -1
  66. package/static/dashboard/assets/{s._site-MSdo-oKn.js → s._site-DT0FXe9C.js} +1 -1
  67. package/static/dashboard/assets/s._site.comments-Ci3k9e5e.js +49 -0
  68. package/static/dashboard/assets/s._site.reviewers-CMYsq2DL.js +1 -0
  69. package/static/dashboard/assets/{s._site.settings-_fxdLl8T.js → s._site.settings-CWNTmj8T.js} +1 -1
  70. package/static/dashboard/assets/{setup-Ccth7CNk.js → setup-C7sY4SXb.js} +1 -1
  71. package/static/dashboard/assets/{sign-in-BeNKRQ7N.js → sign-in-DzeEwdj0.js} +1 -1
  72. package/static/dashboard/assets/{sign-up-B8239y6x.js → sign-up-iJvFq_R3.js} +1 -1
  73. package/static/dashboard/assets/{sites-CekL50U1.js → sites-DiBJvBBN.js} +1 -1
  74. package/static/dashboard/assets/studio-CK_HRLS5.js +1 -0
  75. package/static/dashboard/assets/{studio-pysRGF6Z.js → studio-QR3vjisG.js} +1 -1
  76. package/static/dashboard/assets/{studio.index-D1Utbxqz.js → studio.index-B2WSVF56.js} +1 -1
  77. package/static/dashboard/assets/studio.integrations-BYz4cDCb.js +16 -0
  78. package/static/dashboard/assets/studio.members-DPqoth_D.js +6 -0
  79. package/static/dashboard/assets/{studio.plan-CVZcQmU2.js → studio.plan-C3t2S9GZ.js} +1 -1
  80. package/static/dashboard/assets/{sun-Ciy3ROc0.js → sun-ChMFVIDA.js} +1 -1
  81. package/static/dashboard/assets/{switch-wRlAfGsi.js → switch-D0flLg1r.js} +1 -1
  82. package/static/dashboard/assets/{table-Bd53YpCs.js → table-PCTyuzaU.js} +1 -1
  83. package/static/dashboard/assets/{useAriaLabelledBy-Dt1pmXDF.js → useAriaLabelledBy-Bu-GFL0B.js} +1 -1
  84. package/static/dashboard/assets/{useBaseQuery-DVrotnH-.js → useBaseQuery-Cw1dAAOb.js} +1 -1
  85. package/static/dashboard/assets/useCompositeItem-CHXWc-fj.js +1 -0
  86. package/static/dashboard/assets/useQuery-B9Vos2vJ.js +1 -0
  87. package/static/dashboard/assets/useRender-BJibc2kV.js +1 -0
  88. package/static/dashboard/assets/{useScrollLock-DdWilGdG.js → useScrollLock-d8peZTpK.js} +1 -1
  89. package/static/dashboard/assets/{useValueChanged-Cm4_pRNG.js → useValueChanged-CEhqkcjS.js} +1 -1
  90. package/static/dashboard/assets/{users-BDCRp6bm.js → users-DGXcs62X.js} +1 -1
  91. package/static/dashboard/assets/{welcome-CcxTkiVu.js → welcome-FVEqWF-E.js} +1 -1
  92. package/static/dashboard/assets/{widget-signin-CpAmvjAU.js → widget-signin-CDnZ1WcR.js} +1 -1
  93. package/static/dashboard/assets/you-DaUXbySS.js +1 -0
  94. package/static/dashboard/assets/zod-Cs-QZqu7.js +1 -0
  95. package/static/dashboard/index.html +2 -2
  96. package/static/widget/build.json +2 -2
  97. package/static/widget/snag.capture.js +3 -3
  98. package/static/widget/snag.js +1 -1
  99. package/static/widget/snag.runtime.js +1 -1
  100. package/static/dashboard/assets/McpTokens-BvQnjHcP.js +0 -1
  101. package/static/dashboard/assets/Picker-CtjWzkpT.js +0 -1
  102. package/static/dashboard/assets/activity-C8vHHVVs.js +0 -1
  103. package/static/dashboard/assets/getPseudoElementBounds-Bv3Ra6Wj.js +0 -1
  104. package/static/dashboard/assets/index-PP-fkxl1.css +0 -1
  105. package/static/dashboard/assets/me-BDpKAhA-.js +0 -1
  106. package/static/dashboard/assets/s._site.comments-0jkl72Ja.js +0 -49
  107. package/static/dashboard/assets/s._site.reviewers-BWi4M9dg.js +0 -1
  108. package/static/dashboard/assets/select-DjpYopV7.js +0 -6
  109. package/static/dashboard/assets/studio-5pj2ZjeU.js +0 -1
  110. package/static/dashboard/assets/studio.integrations-M2aLKrz5.js +0 -1
  111. package/static/dashboard/assets/studio.members-C9Gigy9Y.js +0 -6
  112. package/static/dashboard/assets/useCompositeItem-fDEe_Juq.js +0 -1
  113. package/static/dashboard/assets/useQuery-ClGlUO36.js +0 -1
  114. package/static/dashboard/assets/useRender-BO4-nlty.js +0 -1
  115. package/static/dashboard/assets/you-guotGi3r.js +0 -1
  116. package/static/dashboard/assets/zod-Q9KJcyiZ.js +0 -1
@@ -5,8 +5,9 @@ import { githubClient } from "../integrations/github.js";
5
5
  import { linearClient, statusForLinearState, verifyLinearSignature } from "../integrations/linear.js";
6
6
  import { jiraClient, statusForJiraCategory, verifyJiraSignature } from "../integrations/jira.js";
7
7
  import { slackClient, slackManifest } from "../integrations/slack.js";
8
+ import { statusForTrelloList, trelloClient, verifyTrelloSignature } from "../integrations/trello.js";
8
9
  import { LimitReached, planLimitReached } from "../plan.js";
9
- import { getIntegration, isTracker, listIntegrations, markIntegration, mintWebhookSecret, putIntegration, removeIntegration, trackerSecrets, REF_KIND, } from "../integrations/store.js";
10
+ import { getIntegration, isTracker, listIntegrations, markDelivered, replaceCredentials, markRefused, markIntegration, mintWebhookSecret, putIntegration, removeIntegration, trackerSecrets, REF_KIND, } from "../integrations/store.js";
10
11
  import { applyGitHubIssueEvent, applyIssueState, verifyGitHubSignature } from "../integrations/inbound.js";
11
12
  import { queueResolvedNotice } from "../mail/notify.js";
12
13
  import { drainNow, queueIntegrationEvent } from "../integrations/outbox.js";
@@ -17,12 +18,22 @@ function fail(c, status, code, message, details) {
17
18
  return c.json({ error: { code, message, ...(details ? { details } : {}), requestId: c.get("requestId") } }, status);
18
19
  }
19
20
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
20
- const NAME = { github: "GitHub", linear: "Linear", jira: "Jira", slack: "Slack" };
21
+ const NAME = { github: "GitHub", linear: "Linear", jira: "Jira", trello: "Trello", slack: "Slack" };
22
+ /** Access checks a studio may make in a minute. */
23
+ const DISCOVER_PER_MINUTE = 20;
24
+ /** What the card says when a delivery arrived but its signature did not match: the fix, in words. */
25
+ const SIGNATURE_REFUSED = {
26
+ github: "GitHub's delivery was signed with a different secret. Make a new secret here and give it to the repository's webhook.",
27
+ linear: "Linear's delivery was signed with a different secret. Copy the signing secret from Linear's webhook and paste it here.",
28
+ jira: "Jira's delivery was signed with a different secret. Give Jira's webhook the secret Snagset shows, or make a new one here.",
29
+ trello: "Trello's delivery was signed with a different secret. Copy the secret from your Power-Up's API key page in Trello and paste it here.",
30
+ };
21
31
  export function integrationRoutes(deps) {
22
32
  const { sql, keys, projects } = deps;
23
33
  const app = new Hono();
24
34
  const webhookUrl = async (provider) => `${(await deps.baseUrl()).replace(/\/+$/, "")}/api/v1/integrations/${provider}/inbound`;
25
35
  const ghOpts = () => ({ ...(deps.push.githubApiBase ? { apiBase: deps.push.githubApiBase } : {}), ...(deps.push.fetch ? { fetch: deps.push.fetch } : {}) });
36
+ const trOpts = () => ({ ...(deps.push.trelloApiBase ? { apiBase: deps.push.trelloApiBase } : {}), ...(deps.push.fetch ? { fetch: deps.push.fetch } : {}) });
26
37
  const lnOpts = () => ({ ...(deps.push.linearApiBase ? { apiBase: deps.push.linearApiBase } : {}), ...(deps.push.fetch ? { fetch: deps.push.fetch } : {}) });
27
38
  const mustBeOwner = (c) => {
28
39
  const owner = c.get("owner");
@@ -46,7 +57,7 @@ export function integrationRoutes(deps) {
46
57
  };
47
58
  const provider = (c) => {
48
59
  const v = c.req.param("provider") ?? "";
49
- return isTracker(v) ? v : fail(c, 404, "integration_not_configured", `No tracker called ${JSON.stringify(v)}. This build speaks: github, linear, jira, slack.`);
60
+ return isTracker(v) ? v : fail(c, 404, "integration_not_configured", `No tracker called ${JSON.stringify(v)}. This build speaks: github, linear, jira, trello, slack.`);
50
61
  };
51
62
  /** The card's view of a connection — never a token. */
52
63
  const shape = (i, projectUid) => {
@@ -57,6 +68,11 @@ export function integrationRoutes(deps) {
57
68
  lastError: i.lastError,
58
69
  updatedAt: i.updatedAt.toISOString(),
59
70
  hasWebhookSecret: !!trackerSecrets(i.secret).webhookSecret,
71
+ // The way back's record: the last delivery the tracker sent this
72
+ // connection, and the refusal in words if there was one.
73
+ lastDeliveryAt: i.lastDeliveryAt ? i.lastDeliveryAt.toISOString() : null,
74
+ lastRefusedAt: i.lastRefusedAt ? i.lastRefusedAt.toISOString() : null,
75
+ lastRefusedError: i.lastRefusedError,
60
76
  };
61
77
  if (i.provider === "linear") {
62
78
  const cfg = i.config;
@@ -66,6 +82,10 @@ export function integrationRoutes(deps) {
66
82
  const cfg = i.config;
67
83
  return { provider: "jira", ...base, siteUrl: cfg.siteUrl, projectKey: cfg.projectKey, projectName: cfg.projectName, issueType: cfg.issueTypeName, email: cfg.email };
68
84
  }
85
+ if (i.provider === "trello") {
86
+ const cfg = i.config;
87
+ return { provider: "trello", ...base, boardName: cfg.boardName, boardUrl: cfg.boardUrl, listNames: cfg.listNames, webhookRegistered: !!cfg.webhookId };
88
+ }
69
89
  if (i.provider === "slack") {
70
90
  const cfg = i.config;
71
91
  return { provider: "slack", ...base, teamName: cfg.teamName, teamUrl: cfg.teamUrl, channelId: cfg.channelId, channelName: cfg.channelName };
@@ -105,6 +125,91 @@ export function integrationRoutes(deps) {
105
125
  return c.json({ data: rows.map((r) => shape(r, p.uid)) });
106
126
  });
107
127
  /** The manifest the operator creates the Slack app from — one link, scopes pre-filled. */
128
+ /**
129
+ * What a connect dialog offers to pick from (0.1.55): the credentials are
130
+ * tried, and the answer is who they belong to and the repositories, teams
131
+ * or projects they can see — so nobody types a key that turns out to be the
132
+ * wrong one. Nothing is stored; the connect call checks again.
133
+ */
134
+ const countDiscover = async (orgId) => {
135
+ const now = new Date();
136
+ const windowStart = new Date(now.getTime() - 60_000);
137
+ const expires = new Date(now.getTime() + 60_000);
138
+ const [row] = await sql.begin(async (tx) => {
139
+ await tx `SELECT set_config('app.org_id', ${orgId}, true)`;
140
+ return tx `
141
+ INSERT INTO rate_counters (org_id, bucket_key, window_start, count, expires_at)
142
+ VALUES (${orgId}::uuid, 'integrations:discover', ${now}, 1, ${expires})
143
+ ON CONFLICT (org_id, bucket_key) DO UPDATE
144
+ SET count = CASE WHEN rate_counters.window_start < ${windowStart} THEN 1 ELSE rate_counters.count + 1 END,
145
+ window_start = CASE WHEN rate_counters.window_start < ${windowStart} THEN ${now} ELSE rate_counters.window_start END,
146
+ expires_at = CASE WHEN rate_counters.window_start < ${windowStart} THEN ${expires} ELSE rate_counters.expires_at END
147
+ RETURNING count::text`;
148
+ });
149
+ return Number(row?.count ?? 0);
150
+ };
151
+ app.post("/api/v1/integrations/:provider/discover", async (c) => {
152
+ const owner = mustBeOwner(c);
153
+ if (owner instanceof Response)
154
+ return owner;
155
+ const pv = provider(c);
156
+ if (pv instanceof Response)
157
+ return pv;
158
+ if (pv === "slack")
159
+ return fail(c, 409, "integration_not_configured", "Slack's channel is typed; there is nothing to list.");
160
+ // The same plan gate as connecting: this call reaches out to the tracker
161
+ // with what it is given, and a studio that cannot connect has no reason to.
162
+ if (!(await deps.limits(owner.orgId)).integrations)
163
+ return planLimitReached(c, new LimitReached("integrations", 0, 0));
164
+ // Each check is a request this server makes to an address the caller
165
+ // chose, so a studio gets a handful a minute — plenty for a person trying
166
+ // tokens, too few to use the server as a prober (0.1.55 review).
167
+ if ((await countDiscover(owner.orgId)) > DISCOVER_PER_MINUTE) {
168
+ return fail(c, 429, "rate_limited", "Too many access checks in a minute. Wait a minute and try again.");
169
+ }
170
+ const body = (await c.req.json().catch(() => null));
171
+ const str = (k) => (typeof body?.[k] === "string" ? body[k].trim() : "");
172
+ if (pv === "github") {
173
+ const token = str("token");
174
+ if (!token)
175
+ return fail(c, 422, "validation_failed", "Paste a token first.", { field: "token" });
176
+ const r = await githubClient({ token, ...ghOpts() }).discover();
177
+ return r.ok ? c.json({ who: r.who, options: r.options }) : fail(c, 422, "validation_failed", r.detail, { field: "token" });
178
+ }
179
+ if (pv === "linear") {
180
+ const apiKey = str("apiKey");
181
+ if (!apiKey)
182
+ return fail(c, 422, "validation_failed", "Paste an API key first.", { field: "apiKey" });
183
+ const r = await linearClient({ apiKey, ...lnOpts() }).discover();
184
+ return r.ok ? c.json({ who: r.who, options: r.options }) : fail(c, 422, "validation_failed", r.detail, { field: "apiKey" });
185
+ }
186
+ if (pv === "trello") {
187
+ const apiKey = str("apiKey");
188
+ if (!apiKey)
189
+ return fail(c, 422, "validation_failed", "Paste your Power-Up's API key first.", { field: "apiKey" });
190
+ const token = str("token");
191
+ if (!token)
192
+ return fail(c, 422, "validation_failed", "Paste a token first — the Generate a token link makes one.", { field: "token" });
193
+ // A board id narrows the answer to that board's lists: the second
194
+ // half of the Connect step, asked once a board is picked.
195
+ const boardId = str("boardId");
196
+ if (boardId && !/^[0-9a-f]{24}$/i.test(boardId))
197
+ return fail(c, 422, "validation_failed", "That is not a Trello board id.", { field: "boardId" });
198
+ const r = await trelloClient({ apiKey, token, ...trOpts() }).discover(boardId || undefined);
199
+ return r.ok ? c.json({ who: r.who, options: r.options }) : fail(c, 422, "validation_failed", r.detail, { field: "token" });
200
+ }
201
+ const siteUrl = str("siteUrl").replace(/\/+$/, "");
202
+ if (!/^https?:\/\/[^\s/]+$/.test(siteUrl))
203
+ return fail(c, 422, "validation_failed", "Give the site's address, like https://kilnwork.atlassian.net.", { field: "siteUrl" });
204
+ const email = str("email").toLowerCase();
205
+ if (!looksLikeEmail(email))
206
+ return fail(c, 422, "validation_failed", "Give the Atlassian account's email — the token belongs to it.", { field: "email" });
207
+ const apiToken = str("apiToken");
208
+ if (!apiToken)
209
+ return fail(c, 422, "validation_failed", "Paste an API token first.", { field: "apiToken" });
210
+ const r = await jiraClient({ siteUrl, email, apiToken, allowPrivate: !!deps.push.jiraPrivate, ...(deps.push.fetch ? { fetch: deps.push.fetch } : {}) }).discover();
211
+ return r.ok ? c.json({ who: r.who, options: r.options }) : fail(c, 422, "validation_failed", r.detail, { field: "apiToken" });
212
+ });
108
213
  app.get("/api/v1/integrations/slack/manifest", async (c) => {
109
214
  const owner = mustBeOwner(c);
110
215
  if (owner instanceof Response)
@@ -145,6 +250,72 @@ export function integrationRoutes(deps) {
145
250
  const createOn = body?.["createOn"] === "thread.created" ? "thread.created" : body?.["createOn"] === "manual" ? "manual" : pv === "slack" ? "thread.created" : "manual";
146
251
  const existing = await getIntegration(sql, keys, p.org_id, p.id, pv);
147
252
  const had = trackerSecrets(existing?.secret ?? null);
253
+ if (pv === "trello") {
254
+ // Trello (0.1.56): an API key and a token, a board, and three of its
255
+ // lists for open, in progress and resolved — probed before anything
256
+ // is stored. The way back is a webhook we register on the board
257
+ // ourselves; Trello signs deliveries with the Power-Up's secret, which
258
+ // the owner pastes on the next step (or here).
259
+ const prev = existing?.config;
260
+ const apiKey = str("apiKey") || prev?.apiKey || "";
261
+ if (!apiKey)
262
+ return fail(c, 422, "validation_failed", "Paste your Power-Up's API key.", { field: "apiKey" });
263
+ const token = str("token") || had.token || "";
264
+ if (!token)
265
+ return fail(c, 422, "validation_failed", "Paste a token — the Generate a token link makes one.", { field: "token" });
266
+ const boardId = str("boardId");
267
+ if (!/^[0-9a-f]{24}$/i.test(boardId))
268
+ return fail(c, 422, "validation_failed", "Pick a board.", { field: "boardId" });
269
+ const lists = { open: str("openList"), progress: str("progressList"), resolved: str("resolvedList") };
270
+ for (const [k, v] of Object.entries(lists)) {
271
+ if (!/^[0-9a-f]{24}$/i.test(v))
272
+ return fail(c, 422, "validation_failed", "Pick a list for open, in progress and resolved.", { field: `${k}List` });
273
+ }
274
+ const tc = trelloClient({ apiKey, token, ...trOpts() });
275
+ const probe = await tc.probe(boardId, lists);
276
+ if (!probe.ok)
277
+ return fail(c, 422, "validation_failed", `Trello: ${probe.detail}.`, { field: "boardId" });
278
+ const url = await webhookUrl("trello");
279
+ let webhookId = null;
280
+ let webhookError = null;
281
+ try {
282
+ webhookId = (await tc.registerWebhook(boardId, url)).id;
283
+ }
284
+ catch (e) {
285
+ // Trello checks the address with a HEAD before it registers, so a
286
+ // server it cannot reach (a laptop, a private network) lands here.
287
+ // The connection still works one way; the dialog says why the way
288
+ // back does not.
289
+ webhookError = e instanceof Error ? e.message : String(e);
290
+ }
291
+ // Re-registering on the same board failed: the webhook that was working
292
+ // stays, rather than being taken down with nothing in its place.
293
+ if (!webhookId && prev?.webhookId && prev.boardId === boardId)
294
+ webhookId = prev.webhookId;
295
+ // A board change leaves the old board's webhook behind: take it down,
296
+ // unless another connection holds the same webhook (one token, one
297
+ // board, one callback is one webhook at Trello).
298
+ if (prev?.webhookId && prev.webhookId !== webhookId && !(await webhookShared(prev.webhookId, p.id)))
299
+ await tc.removeWebhook(prev.webhookId).catch(() => { });
300
+ await putIntegration(sql, keys, {
301
+ orgId: p.org_id,
302
+ projectId: p.id,
303
+ provider: "trello",
304
+ config: {
305
+ apiKey,
306
+ boardId: probe.board.id,
307
+ boardName: probe.board.name,
308
+ boardUrl: probe.board.url,
309
+ lists,
310
+ listNames: probe.names,
311
+ webhookId,
312
+ createOn,
313
+ },
314
+ secret: JSON.stringify({ token, webhookSecret: str("webhookSecret") || had.webhookSecret }),
315
+ });
316
+ const i = await getIntegration(sql, keys, p.org_id, p.id, "trello");
317
+ return c.json({ integration: i ? shape(i, p.uid) : null, webhook: { url, registered: !!webhookId, ...(webhookError ? { error: webhookError } : {}) } });
318
+ }
148
319
  if (pv === "slack") {
149
320
  // Slack: a bot token from the app the operator created from our
150
321
  // manifest, and a channel by #name or id. Probed — the token, then the
@@ -241,8 +412,13 @@ export function integrationRoutes(deps) {
241
412
  const apiToken = str("apiToken") || had.token || "";
242
413
  if (!apiToken)
243
414
  return fail(c, 422, "validation_failed", "Paste an API token from id.atlassian.com › Security › API tokens.", { field: "apiToken" });
244
- const webhookSecret = str("webhookSecret") || had.webhookSecret || null;
245
- const probe = await jiraClient({ siteUrl, email, apiToken, ...(deps.push.fetch ? { fetch: deps.push.fetch } : {}) }).probe(projectKey);
415
+ // Jira takes any secret typed into its webhook form, so we mint one, as
416
+ // for GitHub, and show it once — nobody has to invent a secret. One
417
+ // typed here (a webhook made before connecting) is kept instead.
418
+ const typed = str("webhookSecret");
419
+ const minted = typed || had.webhookSecret ? null : mintWebhookSecret();
420
+ const webhookSecret = typed || had.webhookSecret || minted;
421
+ const probe = await jiraClient({ siteUrl, email, apiToken, allowPrivate: !!deps.push.jiraPrivate, ...(deps.push.fetch ? { fetch: deps.push.fetch } : {}) }).probe(projectKey);
246
422
  if (!probe.ok)
247
423
  return fail(c, 422, "validation_failed", probe.detail, { field: "apiToken" });
248
424
  await putIntegration(sql, keys, {
@@ -262,7 +438,7 @@ export function integrationRoutes(deps) {
262
438
  secret: JSON.stringify({ token: apiToken, webhookSecret }),
263
439
  });
264
440
  const i = await getIntegration(sql, keys, p.org_id, p.id, "jira");
265
- return c.json({ integration: i ? shape(i, p.uid) : null, webhook: { url: await webhookUrl("jira") } });
441
+ return c.json({ integration: i ? shape(i, p.uid) : null, webhook: { url: await webhookUrl("jira"), ...(minted ? { secret: minted } : {}) } });
266
442
  }
267
443
  // Linear: an API key belonging to a member of the team, the team's
268
444
  // key, and — for the way back — the signing secret Linear shows when the
@@ -297,6 +473,15 @@ export function integrationRoutes(deps) {
297
473
  const p = await site(c, owner);
298
474
  if (!p)
299
475
  return fail(c, 404, "project_not_found", "No project with that uid.");
476
+ if (pv === "trello") {
477
+ // The board's webhook is ours to take down; best effort, since a
478
+ // revoked token cannot, and Trello drops a webhook whose token goes.
479
+ const i = await getIntegration(sql, keys, p.org_id, p.id, "trello");
480
+ const cfg = i?.config;
481
+ const token = trackerSecrets(i?.secret ?? null).token;
482
+ if (cfg?.webhookId && token && !(await webhookShared(cfg.webhookId, p.id)))
483
+ await trelloClient({ apiKey: cfg.apiKey, token, ...trOpts() }).removeWebhook(cfg.webhookId).catch(() => { });
484
+ }
300
485
  await removeIntegration(sql, p.org_id, p.id, pv);
301
486
  return c.json({ integration: null });
302
487
  });
@@ -322,9 +507,14 @@ export function integrationRoutes(deps) {
322
507
  }
323
508
  else if (pv === "jira") {
324
509
  const cfg = i.config;
325
- const r = await jiraClient({ siteUrl: cfg.siteUrl, email: cfg.email, apiToken: token, ...(deps.push.fetch ? { fetch: deps.push.fetch } : {}) }).probe(cfg.projectKey);
510
+ const r = await jiraClient({ siteUrl: cfg.siteUrl, email: cfg.email, apiToken: token, allowPrivate: !!deps.push.jiraPrivate, ...(deps.push.fetch ? { fetch: deps.push.fetch } : {}) }).probe(cfg.projectKey);
326
511
  ok = r.ok ? { ok: true, target: `${r.project.key} · ${r.project.name}` } : r;
327
512
  }
513
+ else if (pv === "trello") {
514
+ const cfg = i.config;
515
+ const r = await trelloClient({ apiKey: cfg.apiKey, token, ...trOpts() }).probe(cfg.boardId, cfg.lists);
516
+ ok = r.ok ? { ok: true, target: r.board.name } : r;
517
+ }
328
518
  else if (pv === "slack") {
329
519
  const cfg = i.config;
330
520
  try {
@@ -345,7 +535,12 @@ export function integrationRoutes(deps) {
345
535
  await markIntegration(sql, p.org_id, i.id, ok.ok ? "ok" : "needs_reauth", ok.ok ? null : ok.detail);
346
536
  return c.json(ok.ok ? { ok: true, repository: ok.target, target: ok.target } : { ok: false, detail: ok.detail });
347
537
  });
348
- /** GitHub only: a new minted webhook secret, shown once; the old one stops working the moment this answers. */
538
+ /**
539
+ * The webhook's secret, after connecting. GitHub and Jira: a new one minted
540
+ * here and shown once; the old one stops working the moment this answers.
541
+ * Linear makes its own: the body carries the one Linear shows, and it
542
+ * replaces the stored one — no disconnecting to fix a wrong paste.
543
+ */
349
544
  app.post("/api/v1/projects/:uid/integrations/:provider/webhook-secret", async (c) => {
350
545
  const owner = mustBeOwner(c);
351
546
  if (owner instanceof Response)
@@ -358,22 +553,33 @@ export function integrationRoutes(deps) {
358
553
  return fail(c, 404, "project_not_found", "No project with that uid.");
359
554
  if (pv === "slack")
360
555
  return fail(c, 409, "integration_not_configured", "Slack sends nothing back in this version; there is no webhook to secure.");
361
- if (pv !== "github") {
362
- return fail(c, 409, "integration_not_configured", `${NAME[pv]}'s webhook secret is typed into ${NAME[pv]}'s own webhook form: paste the same secret when connecting.`);
363
- }
364
- const i = await getIntegration(sql, keys, p.org_id, p.id, "github");
556
+ const i = await getIntegration(sql, keys, p.org_id, p.id, pv);
365
557
  const had = trackerSecrets(i?.secret ?? null);
366
558
  if (!i || !had.token)
367
- return fail(c, 409, "integration_not_configured", "GitHub is not connected on this site.");
368
- const secret = mintWebhookSecret();
369
- await putIntegration(sql, keys, {
559
+ return fail(c, 409, "integration_not_configured", `${NAME[pv]} is not connected on this site.`);
560
+ let secret;
561
+ let show = true;
562
+ if (pv === "linear" || pv === "trello") {
563
+ // Theirs, not ours: Linear's webhook shows its signing secret, and
564
+ // Trello signs with the Power-Up's secret. Pasted, and never echoed.
565
+ const body = (await c.req.json().catch(() => null));
566
+ secret = typeof body?.["secret"] === "string" ? body["secret"].trim() : "";
567
+ if (!secret) {
568
+ const how = pv === "linear" ? "Paste the signing secret Linear shows on the webhook." : "Paste the secret from your Power-Up's API key page in Trello.";
569
+ return fail(c, 422, "validation_failed", how, { field: "secret" });
570
+ }
571
+ show = false;
572
+ }
573
+ else {
574
+ secret = mintWebhookSecret();
575
+ }
576
+ await replaceCredentials(sql, keys, {
370
577
  orgId: p.org_id,
371
578
  projectId: p.id,
372
- provider: "github",
373
- config: i.config,
579
+ provider: pv,
374
580
  secret: JSON.stringify({ token: had.token, webhookSecret: secret }),
375
581
  });
376
- return c.json({ webhook: { url: await webhookUrl("github"), secret } });
582
+ return c.json({ webhook: { url: await webhookUrl(pv), ...(show ? { secret } : {}) } });
377
583
  });
378
584
  /** After an inbound resolve, the same mail a dashboard resolve sends, signed by the tracker. */
379
585
  const noticeIfResolved = async (applied, orgId, projectId, actorName) => {
@@ -393,6 +599,14 @@ export function integrationRoutes(deps) {
393
599
  });
394
600
  });
395
601
  };
602
+ const hostOf = (u) => {
603
+ try {
604
+ return new URL(String(u ?? "")).host.toLowerCase();
605
+ }
606
+ catch {
607
+ return "";
608
+ }
609
+ };
396
610
  const candidatesFor = (pv, where) => sql.begin(async (tx) => {
397
611
  // Read under the maintenance claim: the tracker holds no org, and the
398
612
  // org is what the row tells us.
@@ -400,6 +614,11 @@ export function integrationRoutes(deps) {
400
614
  return where(tx);
401
615
  });
402
616
  const secretOf = (r) => trackerSecrets(r.credentials && r.credentials_iv ? open(keys, { ciphertext: r.credentials, iv: r.credentials_iv }) : null).webhookSecret;
617
+ /** Whether a live Trello connection on another site holds this webhook (Trello hands one token the same webhook for the same board and callback). */
618
+ const webhookShared = async (webhookId, exceptProjectId) => (await candidatesFor("trello", (tx) => tx `
619
+ SELECT id, org_id, project_id, credentials, credentials_iv FROM integrations
620
+ WHERE provider = 'trello' AND deleted_at IS NULL AND config->>'webhookId' = ${webhookId} AND project_id <> ${exceptProjectId}::uuid
621
+ `)).length > 0;
403
622
  /**
404
623
  * The tracker → us (05 endpoint 25c). Unauthenticated in the session
405
624
  * sense; authenticated by the provider's signature over the RAW body with
@@ -407,6 +626,10 @@ export function integrationRoutes(deps) {
407
626
  * pasted from Linear's form for Linear. The target named in the
408
627
  * payload picks the candidate connections; the signature picks the one.
409
628
  */
629
+ // Trello checks the address with a HEAD before it will register a webhook
630
+ // (and again from time to time). Nothing is read or written. Hono answers a
631
+ // HEAD from the GET route, so the route is a GET.
632
+ app.get("/api/v1/integrations/trello/inbound", (c) => c.body(null, 200));
410
633
  app.post("/api/v1/integrations/:provider/inbound", async (c) => {
411
634
  const pv = provider(c);
412
635
  if (pv instanceof Response)
@@ -425,8 +648,6 @@ export function integrationRoutes(deps) {
425
648
  const signature = c.req.header("x-hub-signature-256");
426
649
  const event = c.req.header("x-github-event") ?? "";
427
650
  const delivery = c.req.header("x-github-delivery") ?? "";
428
- if (event === "ping")
429
- return c.json({ ok: true, pong: true });
430
651
  const fullName = String(payload?.repository?.full_name ?? "").toLowerCase();
431
652
  if (!fullName.includes("/"))
432
653
  return fail(c, 400, "validation_failed", "The payload names no repository.");
@@ -441,10 +662,15 @@ export function integrationRoutes(deps) {
441
662
  return !!s && verifyGitHubSignature(raw, signature, s);
442
663
  });
443
664
  if (!match) {
444
- return candidates.length
445
- ? fail(c, 401, "provider_signature_invalid", "The signature does not match this repository's webhook secret.")
446
- : fail(c, 409, "integration_not_configured", `No site here is connected to ${fullName}.`);
665
+ if (candidates.length === 1)
666
+ await markRefused(sql, candidates[0].id, SIGNATURE_REFUSED.github);
667
+ return fail(c, 401, "provider_signature_invalid", "The signature does not match this repository's webhook secret.");
447
668
  }
669
+ // GitHub pings a webhook the moment it is made: a signed ping is the
670
+ // first proof the way back works, so it is recorded like any delivery.
671
+ await markDelivered(sql, match.id);
672
+ if (event === "ping")
673
+ return c.json({ ok: true, pong: true });
448
674
  if (event !== "issues")
449
675
  return c.json({ ok: true, ignored: event });
450
676
  const number = Number(payload?.issue?.number);
@@ -472,27 +698,26 @@ export function integrationRoutes(deps) {
472
698
  const issueKey = String(issue?.key ?? "");
473
699
  if (!projectId || !issueKey)
474
700
  return fail(c, 400, "validation_failed", "The payload names no issue in a project.");
475
- let host = "";
476
- try {
477
- host = new URL(String(issue?.self ?? "")).host.toLowerCase();
478
- }
479
- catch {
480
- /* no self link — the project id alone will have to do */
481
- }
482
- const candidates = await candidatesFor("jira", (tx) => tx `
483
- SELECT id, org_id, project_id, credentials, credentials_iv FROM integrations
484
- WHERE provider = 'jira' AND deleted_at IS NULL AND enabled AND config->>'projectId' = ${projectId}
485
- AND (${host} = '' OR lower(config->>'siteUrl') LIKE ${"%//" + host + "%"})
486
- `);
701
+ // The site is the issue's own `self` link, and it must be there: a
702
+ // project id alone is a small number many Jira sites share, so a
703
+ // delivery without its site could name every one of them.
704
+ const host = hostOf(issue?.self);
705
+ if (!host)
706
+ return fail(c, 400, "validation_failed", "The payload names no Jira site.");
707
+ const candidates = (await candidatesFor("jira", (tx) => tx `
708
+ SELECT id, org_id, project_id, credentials, credentials_iv, config->>'siteUrl' AS site_url FROM integrations
709
+ WHERE provider = 'jira' AND deleted_at IS NULL AND enabled AND config->>'projectId' = ${projectId}
710
+ `)).filter((r) => hostOf(r.site_url) === host);
487
711
  const match = candidates.find((r) => {
488
712
  const s = secretOf(r);
489
713
  return !!s && verifyJiraSignature(raw, signature, s);
490
714
  });
491
715
  if (!match) {
492
- return candidates.length
493
- ? fail(c, 401, "provider_signature_invalid", "The signature does not match this project's webhook secret — type the same secret into Jira's webhook and when connecting.")
494
- : fail(c, 409, "integration_not_configured", "No site here is connected to that Jira project.");
716
+ if (candidates.length === 1)
717
+ await markRefused(sql, candidates[0].id, SIGNATURE_REFUSED.jira);
718
+ return fail(c, 401, "provider_signature_invalid", "The signature does not match this project's webhook secret — give Jira's webhook the secret Snagset shows.");
495
719
  }
720
+ await markDelivered(sql, match.id);
496
721
  let status = null;
497
722
  if (event === "jira:issue_deleted")
498
723
  status = "detach";
@@ -514,6 +739,66 @@ export function integrationRoutes(deps) {
514
739
  await noticeIfResolved(applied, match.org_id, match.project_id, "Jira");
515
740
  return c.json({ ok: true, applied: applied.kind, ...("why" in applied ? { why: applied.why } : {}) });
516
741
  }
742
+ if (pv === "trello") {
743
+ // Trello (0.1.56): X-Trello-Webhook is the base64 HMAC-SHA1 of the raw
744
+ // body followed by the callback URL, keyed with the Power-Up's secret;
745
+ // the action's id is the replay key. The board picks the candidates.
746
+ const signature = c.req.header("x-trello-webhook");
747
+ const action = payload?.action;
748
+ const boardId = String(payload?.model?.id ?? action?.data?.board?.id ?? "");
749
+ if (!/^[0-9a-f]{24}$/i.test(boardId))
750
+ return fail(c, 400, "validation_failed", "The payload names no board.");
751
+ const callbackURL = await webhookUrl("trello");
752
+ const candidates = await candidatesFor("trello", (tx) => tx `
753
+ SELECT id, org_id, project_id, credentials, credentials_iv, config FROM integrations
754
+ WHERE provider = 'trello' AND deleted_at IS NULL AND enabled AND config->>'boardId' = ${boardId}
755
+ `);
756
+ // Several connections can share one board, and one Power-Up's secret
757
+ // (a studio's staging and live sites; one token's single webhook). The
758
+ // delivery is applied to EVERY connection it verifies for, each with
759
+ // its own ledger key: Trello's action id is the same in every
760
+ // webhook's delivery of that action, so a bare id would let one
761
+ // connection's delivery spend another's.
762
+ const matches = candidates.filter((r) => {
763
+ const s = secretOf(r);
764
+ return !!s && verifyTrelloSignature(raw, callbackURL, signature, s);
765
+ });
766
+ if (!matches.length) {
767
+ if (candidates.length === 1)
768
+ await markRefused(sql, candidates[0].id, SIGNATURE_REFUSED.trello);
769
+ return fail(c, 401, "provider_signature_invalid", "The signature does not match this board's secret — paste the Power-Up's secret from Trello into Snagset.");
770
+ }
771
+ const type = String(action?.type ?? "");
772
+ const cardId = String(action?.data?.card?.id ?? "");
773
+ const actionId = String(action?.id ?? "") || `${cardId}:${type}:${Date.now()}`;
774
+ let shown = null;
775
+ for (const match of matches) {
776
+ await markDelivered(sql, match.id);
777
+ const cfg = match.config;
778
+ let status = null;
779
+ if (type === "deleteCard")
780
+ status = "detach";
781
+ else if (type === "updateCard" && action?.data?.listAfter?.id)
782
+ status = statusForTrelloList(String(action.data.listAfter.id), cfg.lists);
783
+ if (!status || !cardId)
784
+ continue;
785
+ const applied = await applyIssueState(sql, {
786
+ provider: "trello",
787
+ orgId: match.org_id,
788
+ projectId: match.project_id,
789
+ deliveryId: `${match.id}:${actionId}`,
790
+ externalId: cardId,
791
+ status,
792
+ progressHoldsReview: true,
793
+ });
794
+ await noticeIfResolved(applied, match.org_id, match.project_id, "Trello");
795
+ if (!shown || (shown.kind === "ignored" && shown.why === "no-thread"))
796
+ shown = applied;
797
+ }
798
+ if (!shown)
799
+ return c.json({ ok: true, applied: "ignored", why: "action" });
800
+ return c.json({ ok: true, applied: shown.kind, ...("why" in shown ? { why: shown.why } : {}) });
801
+ }
517
802
  // Linear: Linear-Signature is the hex HMAC over the raw body
518
803
  // with the webhook's signing secret; Linear-Delivery is the replay key;
519
804
  // webhookTimestamp guards a captured body replayed much later.
@@ -535,10 +820,11 @@ export function integrationRoutes(deps) {
535
820
  return !!s && verifyLinearSignature(raw, signature, s);
536
821
  });
537
822
  if (!match) {
538
- return candidates.length
539
- ? fail(c, 401, "provider_signature_invalid", "The signature does not match this team's webhook secret — paste the signing secret from Linear's webhook when connecting.")
540
- : fail(c, 409, "integration_not_configured", "No site here is connected to that Linear team.");
823
+ if (candidates.length === 1)
824
+ await markRefused(sql, candidates[0].id, SIGNATURE_REFUSED.linear);
825
+ return fail(c, 401, "provider_signature_invalid", "The signature does not match this team's webhook secret — paste the signing secret from Linear's webhook into Snagset.");
541
826
  }
827
+ await markDelivered(sql, match.id);
542
828
  if (payload?.type !== "Issue")
543
829
  return c.json({ ok: true, ignored: String(payload?.type ?? "") });
544
830
  const issueId = String(payload?.data?.id ?? "");