ccdeck 3.46.0 → 3.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +99 -46
- package/bin/cli/commands.js +17 -9
- package/bin/cli/help.js +9 -4
- package/bin/cli/second-start.js +4 -2
- package/bin/cli/startup.js +26 -2
- package/bin/cli/tui.js +544 -0
- package/bin/deck.js +32 -1
- package/dist/web/assets/{BrowserWatchModal-CoX9FIUE.js → BrowserWatchModal-DuopT2Oa.js} +1 -1
- package/dist/web/assets/IntegrationModal-CszT-tts.js +7 -0
- package/dist/web/assets/{RadioPanel-biw_BbZq.js → RadioPanel-Cn3WvPUG.js} +1 -1
- package/dist/web/assets/TrafficRadar-DZA8XSi7.js +8 -0
- package/dist/web/assets/UsageHistoryModal-MgZJLXbF.js +1 -0
- package/dist/web/assets/app-DjlHxWHg.css +1 -0
- package/dist/web/assets/app-F1xryJpn.js +321 -0
- package/dist/web/assets/claude-settings-index-1Qg1AUda.js +1 -0
- package/dist/web/assets/{index-DmENqVdt.js → index-BK9avF1k.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/release-notes.json +58 -2
- package/src/server/args.mjs +1 -0
- package/src/server/ccusage-install.mjs +58 -1
- package/src/server/ccusage-registry.mjs +289 -0
- package/src/server/ccusage-runner.mjs +9 -2
- package/src/server/claude-accounts.mjs +21 -0
- package/src/server/claude-login.mjs +21 -3
- package/src/server/claude-settings-catalog.d.mts +37 -0
- package/src/server/claude-settings-catalog.mjs +169 -0
- package/src/server/claude-settings-docs.mjs +109 -0
- package/src/server/claude-settings-index.json +251 -0
- package/src/server/claude-settings-routes.mjs +46 -0
- package/src/server/claude-settings.mjs +406 -0
- package/src/server/cli-arrival.mjs +64 -0
- package/src/server/cli-lines.mjs +46 -0
- package/src/server/gpu-metrics.mjs +78 -0
- package/src/server/index.mjs +18 -2
- package/src/server/integrations/jira-move.mjs +239 -0
- package/src/server/integrations/jira.mjs +30 -8
- package/src/server/integrations/proxy.mjs +14 -6
- package/src/server/integrations/routes.mjs +25 -9
- package/src/server/quota-close-watch.mjs +81 -0
- package/src/server/quota-closes.mjs +181 -0
- package/src/server/quota-history.mjs +8 -1
- package/src/server/quota-shape.mjs +12 -0
- package/src/server/quota.mjs +28 -1
- package/src/server/request-gates.mjs +3 -1
- package/src/server/system-metrics.mjs +4 -0
- package/src/server/term.mjs +14 -5
- package/src/server/tool-audit-operations.mjs +30 -10
- package/src/server/tool-audit-report.mjs +79 -7
- package/src/server/tool-audit-routes.mjs +1 -1
- package/src/server/tool-audit-skills.mjs +8 -3
- package/src/server/tool-audit.mjs +55 -5
- package/src/server/traffic-radar-capture.mjs +3 -3
- package/src/server/traffic-radar-config.mjs +10 -3
- package/src/server/traffic-radar-monitor.mjs +8 -5
- package/src/server/traffic-radar-permission.mjs +162 -0
- package/src/server/traffic-radar-platform.mjs +9 -3
- package/src/server/traffic-radar-routes.mjs +8 -18
- package/src/server/traffic-radar-service.mjs +76 -92
- package/src/server/tui-screen.mjs +110 -0
- package/src/server/tui-view.mjs +1072 -0
- package/src/server/usage-routes.mjs +14 -2
- package/src/server/way-back.mjs +27 -0
- package/dist/web/assets/IntegrationModal-B1ypkK-E.js +0 -5
- package/dist/web/assets/TrafficRadar-nhtFoYVv.js +0 -8
- package/dist/web/assets/UsageHistoryModal-Bd-JRAa4.js +0 -1
- package/dist/web/assets/app-BlRY6EME.css +0 -1
- package/dist/web/assets/app-DhGvSH7o.js +0 -319
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// One bounded Jira write: up to 50 top-level issues' sprint/backlog membership and
|
|
2
|
+
// rank. No URL, method, field id or arbitrary Jira body comes from the caller.
|
|
3
|
+
// Both Cloud and Server/DC support these Agile endpoints. Use assignment then
|
|
4
|
+
// rank separately: older Server schemas accept only `issues` on assignment.
|
|
5
|
+
// https://docs.atlassian.com/jira-software/REST/9.12.0/
|
|
6
|
+
// https://developer.atlassian.com/cloud/jira/software/rest/api-group-issue/
|
|
7
|
+
import { errorFromFetchFailure, errorFromStatus, errorResponse, integrationError } from "./errors.mjs";
|
|
8
|
+
import { isSafeTarget, originOf } from "./proxy.mjs";
|
|
9
|
+
|
|
10
|
+
const KEY = /^[A-Z][A-Z0-9_]{0,40}-[1-9]\d{0,11}$/;
|
|
11
|
+
const positiveId = n => Number.isSafeInteger(n) && n > 0 && n <= 999_999_999_999;
|
|
12
|
+
const object = v => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
13
|
+
const only = (v, keys) => object(v) && Object.keys(v).every(k => keys.includes(k));
|
|
14
|
+
const invalid = message => integrationError("invalid", message);
|
|
15
|
+
|
|
16
|
+
export function parseJiraMove(body) {
|
|
17
|
+
if (!only(body, ["issueKey", "issueKeys", "target", "beforeIssue", "afterIssue"]) || Object.hasOwn(body, "issueKey") === Object.hasOwn(body, "issueKeys")) {
|
|
18
|
+
throw invalid("Supply either one issueKey or 2–50 ordered issueKeys and a sprint or backlog target.");
|
|
19
|
+
}
|
|
20
|
+
const key = value => typeof value === "string" && value === value.trim() && KEY.test(value) ? value : null;
|
|
21
|
+
const batch = Object.hasOwn(body, "issueKeys");
|
|
22
|
+
const issueKeys = batch ? body.issueKeys : [body.issueKey];
|
|
23
|
+
if (!Array.isArray(issueKeys) || issueKeys.length < (batch ? 2 : 1) || issueKeys.length > 50 ||
|
|
24
|
+
issueKeys.some(value => !key(value)) || new Set(issueKeys).size !== issueKeys.length) throw invalid("Supply unique, valid issue keys (2–50 for a batch).");
|
|
25
|
+
const t = body.target;
|
|
26
|
+
if (!only(t, t?.kind === "sprint" ? ["kind", "sprintId"] : ["kind"]) ||
|
|
27
|
+
!(t.kind === "backlog" || (t.kind === "sprint" && positiveId(t.sprintId)))) throw invalid("Not a valid issue key or move target.");
|
|
28
|
+
const beforeIssue = Object.hasOwn(body, "beforeIssue") ? key(body.beforeIssue) : undefined;
|
|
29
|
+
const afterIssue = Object.hasOwn(body, "afterIssue") ? key(body.afterIssue) : undefined;
|
|
30
|
+
if (beforeIssue === null || afterIssue === null || (beforeIssue && afterIssue) || issueKeys.includes(beforeIssue) || issueKeys.includes(afterIssue)) {
|
|
31
|
+
throw invalid("Use at most one other issue as the rank anchor.");
|
|
32
|
+
}
|
|
33
|
+
return { issueKeys: issueKeys.slice(), batch, target: t.kind === "sprint" ? { kind: "sprint", sprintId: t.sprintId } : { kind: "backlog" }, beforeIssue, afterIssue };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Conservative support, not a claim about the token's write permissions. */
|
|
37
|
+
export function jiraMoveCapability(config, filter) {
|
|
38
|
+
const rank = config?.ranking?.rankCustomFieldId;
|
|
39
|
+
if (config?.type !== "scrum" || !positiveId(rank)) return { enabled: false, reason: "Moving requires a Scrum board with a configured rank field." };
|
|
40
|
+
// Rank order must be the only ordering. An extra sort can make a successful
|
|
41
|
+
// rank invisible. Accept Jira's Rank alias or the configured field's JQL id.
|
|
42
|
+
const order = /\border\s+by\s+(.+)$/i.exec(String(filter?.jql ?? ""))?.[1]?.trim();
|
|
43
|
+
const field = order && /^(?:Rank|"Rank"|cf\[(\d+)\])\s+ASC$/i.exec(order);
|
|
44
|
+
if (!field || (field[1] && Number(field[1]) !== rank)) return { enabled: false, reason: "Moving requires the board filter to end with ORDER BY Rank ASC." };
|
|
45
|
+
return { enabled: true, rankCustomFieldId: rank };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function readJiraMoveCapability(read, agile, rest, boardId, config) {
|
|
49
|
+
const cfg = config ?? await read.json(`${agile}/board/${boardId}/configuration`);
|
|
50
|
+
if (cfg?.type !== "scrum" || !positiveId(cfg?.ranking?.rankCustomFieldId) || !/^\d{1,12}$/.test(String(cfg?.filter?.id ?? ""))) return jiraMoveCapability(cfg, null);
|
|
51
|
+
const filter = await read.json(`${rest}/filter/${cfg.filter.id}`);
|
|
52
|
+
return jiraMoveCapability(cfg, filter);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Only this closure can sign a write. The returned API takes a validated
|
|
56
|
+
* move, never an upstream address or HTTP method. */
|
|
57
|
+
export function createJiraMover({ secret, origins, sign, authCheck, fetchImpl = globalThis.fetch, reader, agile, rest, invalidate }) {
|
|
58
|
+
async function write(suffix, method, body, issueKeys, signal) {
|
|
59
|
+
const url = `${agile}/${suffix}`;
|
|
60
|
+
if (!isSafeTarget(url) || !origins().includes(originOf(url))) throw integrationError("permission", "This Jira write is outside the connection's token origins.");
|
|
61
|
+
const controller = new AbortController();
|
|
62
|
+
const stop = () => controller.abort(signal?.reason);
|
|
63
|
+
if (signal?.aborted) stop(); else signal?.addEventListener("abort", stop, { once: true });
|
|
64
|
+
const timer = setTimeout(() => controller.abort(), 15_000);
|
|
65
|
+
timer.unref?.();
|
|
66
|
+
let res;
|
|
67
|
+
try {
|
|
68
|
+
try {
|
|
69
|
+
res = await fetchImpl(url, { method, redirect: "manual", headers: { Accept: "application/json", "Content-Type": "application/json", "User-Agent": "ccdeck", ...sign(secret) }, body: JSON.stringify(body), signal: controller.signal });
|
|
70
|
+
} catch (err) { throw errorFromFetchFailure(err, "Jira"); }
|
|
71
|
+
// Never follow even a same-origin redirect: replaying a write is unsafe.
|
|
72
|
+
if (res.status >= 300 && res.status < 400) throw integrationError("upstream", "Jira redirected the write. It was not replayed; refresh the board before trying again.", { status: res.status });
|
|
73
|
+
const refused = authCheck(res.headers, secret);
|
|
74
|
+
if (refused) throw integrationError("expired", refused, { status: 401 });
|
|
75
|
+
if (res.status === 204) return;
|
|
76
|
+
if (res.status === 207) {
|
|
77
|
+
// Every requested key needs exactly one explicit success. A missing,
|
|
78
|
+
// duplicate or unrecognized entry is uncertainty, never success.
|
|
79
|
+
let size = 0;
|
|
80
|
+
const chunks = [];
|
|
81
|
+
if (res.body) for await (const chunk of res.body) {
|
|
82
|
+
size += chunk.byteLength;
|
|
83
|
+
if (size > 32_000) throw integrationError("upstream", "Jira's rank result was too large. Refresh the board to check its position.", { status: 207 });
|
|
84
|
+
chunks.push(Buffer.from(chunk));
|
|
85
|
+
}
|
|
86
|
+
let json;
|
|
87
|
+
try { json = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { /* unknown result */ }
|
|
88
|
+
const entries = json?.entries;
|
|
89
|
+
const recognized = Array.isArray(entries) && entries.every(e => issueKeys.includes(e?.issueKey));
|
|
90
|
+
const results = new Map(issueKeys.map(key => {
|
|
91
|
+
const matches = recognized ? entries.filter(e => e.issueKey === key) : [];
|
|
92
|
+
const status = matches.length === 1 && Number.isInteger(matches[0].status) ? matches[0].status : null;
|
|
93
|
+
return [key, { status, state: status >= 200 && status < 300 ? "succeeded" : status >= 400 && status < 500 ? "failed" : "unknown" }];
|
|
94
|
+
}));
|
|
95
|
+
if ([...results.values()].every(r => r.state === "succeeded")) return;
|
|
96
|
+
const single = issueKeys.length === 1 ? results.get(issueKeys[0]) : null;
|
|
97
|
+
const err = single?.status >= 400 && single.status < 600
|
|
98
|
+
? errorFromStatus(single.status, res.headers, { label: "Jira" })
|
|
99
|
+
: integrationError("upstream", "Jira did not confirm every requested issue update. Some issues may have changed; refresh the board to check them.", { status: 207 });
|
|
100
|
+
err.writeOutcomes = results;
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
if (!res.ok) {
|
|
104
|
+
const err = errorFromStatus(res.status, res.headers, { label: "Jira" });
|
|
105
|
+
if (res.status === 403) err.message = "Jira refused the move: the account or token needs permission to edit and schedule this issue.";
|
|
106
|
+
throw err;
|
|
107
|
+
}
|
|
108
|
+
throw integrationError("upstream", "Jira did not confirm the write. Refresh the board to check the issue.", { status: res.status });
|
|
109
|
+
} finally {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
signal?.removeEventListener("abort", stop);
|
|
112
|
+
await res?.body?.cancel().catch(() => {});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return async (boardId, input, signal) => {
|
|
117
|
+
const move = parseJiraMove(input);
|
|
118
|
+
const { issueKeys, batch, target, beforeIssue, afterIssue } = move;
|
|
119
|
+
const anchor = beforeIssue ?? afterIssue;
|
|
120
|
+
const read = reader(signal);
|
|
121
|
+
const outcomes = new Map(issueKeys.map(key => [key, { membership: "unchanged", rank: "unchanged" }]));
|
|
122
|
+
let attempted = false;
|
|
123
|
+
let stage = "membership";
|
|
124
|
+
let pendingKeys = [];
|
|
125
|
+
try {
|
|
126
|
+
if (!/^[1-9]\d{0,11}$/.test(boardId) || boardId !== boardId.trim()) throw invalid("Not a board id.");
|
|
127
|
+
// No cached authorization, ordering, membership or sprint-state reads.
|
|
128
|
+
const board = await read.json(`${agile}/board/${boardId}`);
|
|
129
|
+
const cfg = await read.json(`${agile}/board/${boardId}/configuration`);
|
|
130
|
+
const capability = await readJiraMoveCapability(read, agile, rest, boardId, { ...cfg, type: board?.type });
|
|
131
|
+
if (!capability.enabled) throw invalid(capability.reason);
|
|
132
|
+
const keys = [...issueKeys, ...(anchor ? [anchor] : [])];
|
|
133
|
+
// The board may cap a page below 51 (50 moved keys plus their anchor).
|
|
134
|
+
// Read only these validated keys, stopping on no progress or at the bound.
|
|
135
|
+
const readIssues = async (suffix, selected, fields) => {
|
|
136
|
+
const found = new Map();
|
|
137
|
+
for (let startAt = 0, guard = 0; found.size < selected.length && guard < selected.length; guard++) {
|
|
138
|
+
const q = new URLSearchParams({ jql: `key in (${selected.join(",")})`, fields, maxResults: String(selected.length), startAt: String(startAt) });
|
|
139
|
+
const page = await read.json(`${agile}/board/${boardId}/${suffix}?${q}`);
|
|
140
|
+
const values = Array.isArray(page?.issues) ? page.issues : [];
|
|
141
|
+
const count = found.size;
|
|
142
|
+
for (const issue of values) if (selected.includes(issue?.key)) found.set(issue.key, issue);
|
|
143
|
+
if (found.size === count || page?.isLast === true || (Number.isInteger(page?.total) && startAt + values.length >= page.total)) break;
|
|
144
|
+
startAt += values.length;
|
|
145
|
+
}
|
|
146
|
+
return found;
|
|
147
|
+
};
|
|
148
|
+
const issues = await readIssues("issue", keys, "issuetype,status,sprint");
|
|
149
|
+
for (const key of keys) {
|
|
150
|
+
const issue = issues.get(key);
|
|
151
|
+
if (!issue) throw invalid("The issues and anchor must all belong to this board.");
|
|
152
|
+
if (issue.fields?.issuetype?.subtask !== false) throw invalid("The issues and rank anchor must be top-level issues.");
|
|
153
|
+
// Match Jira's issue normalizer, including renamed epic-level types.
|
|
154
|
+
const type = issue.fields?.issuetype;
|
|
155
|
+
const epic = type?.hierarchyLevel === 1 || /^epic$/i.test(String(type?.name ?? ""));
|
|
156
|
+
if (issueKeys.includes(key) && (epic || !["new", "indeterminate"].includes(issue.fields?.status?.statusCategory?.key))) {
|
|
157
|
+
throw invalid("Only unfinished top-level non-epic issues can be moved.");
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const sources = new Map();
|
|
161
|
+
const sameGroup = source => source.kind === target.kind && (source.kind === "backlog" || source.sprintId === target.sprintId);
|
|
162
|
+
const groupId = group => group.kind === "backlog" ? "backlog" : `sprint:${group.sprintId}`;
|
|
163
|
+
const groups = new Map();
|
|
164
|
+
const wanted = new Set(target.kind === "sprint" ? [target.sprintId] : []);
|
|
165
|
+
for (const key of issueKeys) {
|
|
166
|
+
const raw = issues.get(key).fields?.sprint;
|
|
167
|
+
const current = raw == null ? [] : Array.isArray(raw) ? raw : [raw];
|
|
168
|
+
if (current.length > 1 || current.some(s => !positiveId(s?.id) || !["active", "future"].includes(s?.state))) throw invalid("Every issue must be in the backlog or one active or future sprint.");
|
|
169
|
+
const source = current.length ? { kind: "sprint", sprintId: current[0].id } : { kind: "backlog" };
|
|
170
|
+
sources.set(key, source);
|
|
171
|
+
if (source.kind === "sprint") wanted.add(source.sprintId);
|
|
172
|
+
const id = groupId(source);
|
|
173
|
+
if (!groups.has(id)) groups.set(id, { group: source, keys: [] });
|
|
174
|
+
groups.get(id).keys.push(key);
|
|
175
|
+
}
|
|
176
|
+
// A sprint visible elsewhere is not enough: it must be on this board.
|
|
177
|
+
for (let startAt = 0, guard = 0; wanted.size && guard < 20; guard++) {
|
|
178
|
+
const q = new URLSearchParams({ state: "active,future", startAt: String(startAt), maxResults: "50" });
|
|
179
|
+
const sprints = await read.json(`${agile}/board/${boardId}/sprint?${q}`);
|
|
180
|
+
const values = Array.isArray(sprints?.values) ? sprints.values : [];
|
|
181
|
+
for (const s of values) if (["active", "future"].includes(s?.state)) wanted.delete(s.id);
|
|
182
|
+
if (!values.length || sprints.isLast === true) break;
|
|
183
|
+
startAt += values.length;
|
|
184
|
+
}
|
|
185
|
+
if (wanted.size) throw invalid("The source and target must be active or future sprints on this board.");
|
|
186
|
+
const groupSuffix = group => group.kind === "sprint" ? `sprint/${group.sprintId}/issue` : "backlog";
|
|
187
|
+
for (const { group, keys } of groups.values()) {
|
|
188
|
+
const found = await readIssues(groupSuffix(group), keys, "issuetype");
|
|
189
|
+
if (keys.some(key => !found.has(key))) throw invalid("An issue's source changed or is a closed sprint. Refresh the board.");
|
|
190
|
+
}
|
|
191
|
+
if (anchor && !(await readIssues(groupSuffix(target), [anchor], "issuetype")).has(anchor)) throw invalid("The rank anchor must be in the target group. Refresh the board.");
|
|
192
|
+
const needed = issueKeys.filter(key => !sameGroup(sources.get(key)));
|
|
193
|
+
if (needed.length) {
|
|
194
|
+
attempted = true;
|
|
195
|
+
pendingKeys = needed;
|
|
196
|
+
const suffix = target.kind === "sprint" ? `sprint/${target.sprintId}/issue` : "backlog/issue";
|
|
197
|
+
await write(suffix, "POST", { issues: needed }, needed, signal);
|
|
198
|
+
for (const key of needed) outcomes.get(key).membership = "moved";
|
|
199
|
+
}
|
|
200
|
+
if (anchor) {
|
|
201
|
+
stage = "rank";
|
|
202
|
+
attempted = true;
|
|
203
|
+
pendingKeys = issueKeys;
|
|
204
|
+
await write("issue/rank", "PUT", { issues: issueKeys, rankCustomFieldId: capability.rankCustomFieldId,
|
|
205
|
+
...(beforeIssue ? { rankBeforeIssue: beforeIssue } : { rankAfterIssue: afterIssue }) }, issueKeys, signal);
|
|
206
|
+
for (const key of issueKeys) outcomes.get(key).rank = "ranked";
|
|
207
|
+
}
|
|
208
|
+
return { status: 200, body: { ok: true, ...(batch ? { issueKeys } : { issueKey: issueKeys[0] }), target, refresh: true } };
|
|
209
|
+
} catch (err) {
|
|
210
|
+
const result = errorResponse(err);
|
|
211
|
+
if (attempted) {
|
|
212
|
+
const rejected = Number.isInteger(err?.status) && err.status >= 400 && err.status < 500;
|
|
213
|
+
for (const key of pendingKeys) {
|
|
214
|
+
const state = err?.writeOutcomes?.get(key)?.state ?? (rejected ? "failed" : "unknown");
|
|
215
|
+
outcomes.get(key)[stage] = state === "succeeded" ? (stage === "membership" ? "moved" : "ranked")
|
|
216
|
+
: state === "failed" ? (stage === "membership" ? "unchanged" : "failed") : "unknown";
|
|
217
|
+
}
|
|
218
|
+
const summarize = field => {
|
|
219
|
+
const states = new Set([...outcomes.values()].map(o => o[field]));
|
|
220
|
+
return states.size === 1 ? [...states][0] : states.has("unknown") ? "unknown" : "partial";
|
|
221
|
+
};
|
|
222
|
+
const outcome = { membership: summarize("membership"), rank: summarize("rank") };
|
|
223
|
+
const updated = [...outcomes.values()].some(o => o.membership === "moved" || o.rank === "ranked");
|
|
224
|
+
const prefix = batch && updated ? "Some issues were updated, but the whole batch was not confirmed. "
|
|
225
|
+
: !batch && outcome.membership === "moved" ? "The issue moved, but its requested position was not confirmed. " : "";
|
|
226
|
+
result.body.error.message = `${prefix}${result.body.error.message} Refresh the board before trying again.`;
|
|
227
|
+
result.body.refresh = true;
|
|
228
|
+
result.body.outcome = outcome;
|
|
229
|
+
if (batch) result.body.outcomes = issueKeys.map(issueKey => ({ issueKey, ...outcomes.get(issueKey) }));
|
|
230
|
+
}
|
|
231
|
+
return result;
|
|
232
|
+
} finally {
|
|
233
|
+
// Also after timeouts/redirects/partial failure: the remote may have
|
|
234
|
+
// applied a write. Replace the cache so older in-flight reads cannot
|
|
235
|
+
// repopulate the cache future requests use.
|
|
236
|
+
if (attempted) invalidate();
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
}
|
|
@@ -17,9 +17,10 @@
|
|
|
17
17
|
// Agile 1.0. `Authorization: Bearer <PAT>`. Personal access tokens
|
|
18
18
|
// arrived in Jira 8.14, so an older server is `incompatible`.
|
|
19
19
|
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
20
|
+
// Reads go through the core's GET-only proxy (proxy.mjs), which signs with
|
|
21
|
+
// `sign` below and only for the connection's allowed origins. The one move
|
|
22
|
+
// route uses jira-move.mjs's private, non-replaying write transport. Reads
|
|
23
|
+
// answer normalised shapes (see `normaliseIssue`), so
|
|
23
24
|
// the page draws Cloud and Server with one renderer: descriptions and comments
|
|
24
25
|
// are Jira's own `renderedFields` HTML on both, sanitised in the browser
|
|
25
26
|
// (src/web/jira-html.tsx).
|
|
@@ -27,6 +28,7 @@ import { createCache } from "./cache.mjs";
|
|
|
27
28
|
import { errorResponse, integrationError, IntegrationError } from "./errors.mjs";
|
|
28
29
|
import { createProxy, fetchImage, isLocalHost, isSafeTarget, normaliseBaseUrl, originOf } from "./proxy.mjs";
|
|
29
30
|
import { createRouter } from "./registry.mjs";
|
|
31
|
+
import { createJiraMover, readJiraMoveCapability } from "./jira-move.mjs";
|
|
30
32
|
|
|
31
33
|
export const MIN_SERVER_VERSION = [8, 14, 0];
|
|
32
34
|
const ATLASSIAN_API = "https://api.atlassian.com";
|
|
@@ -464,6 +466,7 @@ async function boardConfig(ctx, boardId) {
|
|
|
464
466
|
statusIds: (Array.isArray(c?.statuses) ? c.statuses : []).map(st => String(st?.id ?? "")).filter(id => /^\d{1,12}$/.test(id)),
|
|
465
467
|
}));
|
|
466
468
|
return {
|
|
469
|
+
moveConfig: cfg,
|
|
467
470
|
estimation: { kind, fieldId: fieldId || null, label: text(field?.displayName, 80) || (kind === "time" ? "Original Time Estimate" : kind === "points" ? "Story points" : "Issue count") },
|
|
468
471
|
columns,
|
|
469
472
|
};
|
|
@@ -788,6 +791,14 @@ export function registerJiraRoutes(router) {
|
|
|
788
791
|
hasSprints: scrum,
|
|
789
792
|
hasBacklog: backlog,
|
|
790
793
|
timeTracking: time,
|
|
794
|
+
moves: await ctx.cache.remember(`move-capability:${id}`, 10 * MINUTE, async () => {
|
|
795
|
+
try {
|
|
796
|
+
return await readJiraMoveCapability(ctx.client, agileBase(ctx.conn), restBase(ctx.conn), id, { ...config.moveConfig, type });
|
|
797
|
+
} catch {
|
|
798
|
+
// Viewing remains available when the token cannot inspect ordering.
|
|
799
|
+
return { enabled: false, reason: "The board's rank ordering could not be verified." };
|
|
800
|
+
}
|
|
801
|
+
}),
|
|
791
802
|
};
|
|
792
803
|
});
|
|
793
804
|
|
|
@@ -955,17 +966,22 @@ registerJiraRoutes(jiraRouter);
|
|
|
955
966
|
*/
|
|
956
967
|
export function createJiraClient(conn, secret, { fetchImpl, apiOrigin } = {}) {
|
|
957
968
|
let origins = Array.isArray(conn.allowedOrigins) && conn.allowedOrigins.length ? conn.allowedOrigins.slice() : [originOf(conn.baseUrl)].filter(Boolean);
|
|
958
|
-
|
|
969
|
+
let cache = createCache();
|
|
959
970
|
const proxy = (list, phase, signal) => createProxy({
|
|
960
971
|
conn: { ...conn, allowedOrigins: list }, secret, sign: signJira, phase, signal, fetchImpl,
|
|
961
972
|
label: "Jira", errorDetail: jiraErrorDetail, authCheck: jiraAuthCheck,
|
|
962
973
|
});
|
|
963
974
|
let useProxy = null;
|
|
964
975
|
const reader = () => (useProxy ??= proxy(origins, "use"));
|
|
976
|
+
const moveIssue = createJiraMover({ secret, origins: () => origins.slice(), sign: signJira, authCheck: jiraAuthCheck, fetchImpl,
|
|
977
|
+
reader: signal => ({ json: (url, opts = {}) => reader().json(url, { ...opts, signal }) }),
|
|
978
|
+
agile: agileBase(conn), rest: restBase(conn), invalidate: () => { cache = createCache(); },
|
|
979
|
+
});
|
|
965
980
|
return {
|
|
966
981
|
kind: "jira",
|
|
967
982
|
conn,
|
|
968
|
-
cache,
|
|
983
|
+
get cache() { return cache; },
|
|
984
|
+
moveIssue,
|
|
969
985
|
get allowedOrigins() { return origins.slice(); },
|
|
970
986
|
async validate({ phase = "validate", signal } = {}) {
|
|
971
987
|
const result = await validateJira(conn, secret, { phase, signal, client: list => proxy(list, phase, signal) }, { apiOrigin });
|
|
@@ -994,9 +1010,15 @@ export function createJiraClient(conn, secret, { fetchImpl, apiOrigin } = {}) {
|
|
|
994
1010
|
};
|
|
995
1011
|
}
|
|
996
1012
|
|
|
997
|
-
/** The panel's reads
|
|
998
|
-
export async function jiraRoutes(client, method, subpath, searchParams, _req, { signal } = {}) {
|
|
999
|
-
|
|
1013
|
+
/** The panel's reads and its one bounded move, as registry.mjs's `routes`. */
|
|
1014
|
+
export async function jiraRoutes(client, method, subpath, searchParams, _req, { signal, moveBody } = {}) {
|
|
1015
|
+
const move = /^board\/([1-9]\d{0,11})\/move$/.exec(subpath);
|
|
1016
|
+
if (method === "POST" && move) {
|
|
1017
|
+
if ([...searchParams].length) return errorResponse(integrationError("invalid", "Move parameters belong in the JSON body."));
|
|
1018
|
+
try { return await client.moveIssue(move[1], moveBody, signal); }
|
|
1019
|
+
catch (err) { return errorResponse(err); }
|
|
1020
|
+
}
|
|
1021
|
+
if (method !== "GET" && method !== "HEAD") return errorResponse(integrationError("invalid", "That Jira operation is not supported."));
|
|
1000
1022
|
const route = jiraRouter.find(subpath);
|
|
1001
1023
|
if (!route) return errorResponse(integrationError("not-found", "No such Jira read."));
|
|
1002
1024
|
try {
|
|
@@ -13,10 +13,9 @@
|
|
|
13
13
|
// again, and one anywhere else is an error — the token is never re-sent to a
|
|
14
14
|
// host the user did not connect.
|
|
15
15
|
//
|
|
16
|
-
// READ ONLY BY CONSTRUCTION.
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
// in the deck.
|
|
16
|
+
// READ ONLY BY CONSTRUCTION. This generic proxy sends GET and nothing else.
|
|
17
|
+
// Jira's bounded move has its own private write transport; it cannot turn this
|
|
18
|
+
// into a generic "fetch this URL with my token" route.
|
|
20
19
|
import { errorFromFetchFailure, errorFromStatus, integrationError } from "./errors.mjs";
|
|
21
20
|
|
|
22
21
|
/** HTTPS only, with one exception: a tracker on this machine (a mock, a
|
|
@@ -215,6 +214,14 @@ export function rasterMatches(type, b) {
|
|
|
215
214
|
return false;
|
|
216
215
|
}
|
|
217
216
|
|
|
217
|
+
/** The raster type the bytes are, by how they start, or null. An image is
|
|
218
|
+
* served under this, not its label: Jira Data Center labels an uploaded
|
|
219
|
+
* avatar's PNG image/jpeg. */
|
|
220
|
+
export function rasterTypeOf(b) {
|
|
221
|
+
for (const type of RASTER_TYPES) if (rasterMatches(type, b)) return type;
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
|
|
218
225
|
/** An address that names this machine or a private network: loopback,
|
|
219
226
|
* RFC 1918, link-local, CGNAT, unique-local IPv6, an IPv4-mapped one of
|
|
220
227
|
* those, or a name with no public suffix (an intranet host). Only a token
|
|
@@ -308,7 +315,8 @@ export async function fetchImage(target, {
|
|
|
308
315
|
}
|
|
309
316
|
let bytes;
|
|
310
317
|
try { bytes = await readCapped(res, maxBytes); } catch { throw integrationError("not-found", "The image is larger than the deck shows."); }
|
|
311
|
-
|
|
312
|
-
|
|
318
|
+
const actual = rasterTypeOf(bytes);
|
|
319
|
+
if (!actual) throw integrationError("not-found", "That is not an image the deck shows.");
|
|
320
|
+
return { contentType: actual, bytes };
|
|
313
321
|
}
|
|
314
322
|
}
|
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
// GET /api/integrations/<kind>/<id>/asset?url= an image, read by the provider's client from its
|
|
15
15
|
// own image hosts (raster only; empty 403/404)
|
|
16
16
|
// GET /api/integrations/<kind>/<id>/<subpath…> the provider's own reads (registry.mjs)
|
|
17
|
+
// POST /api/integrations/jira/<id>/board/<boardId>/move
|
|
18
|
+
// one validated issue's group/rank (jira-move.mjs)
|
|
17
19
|
//
|
|
18
20
|
// A route that would ask a provider that is not answering (registry.mjs,
|
|
19
21
|
// `available`), or ask for a saved connection whose provider this deck does
|
|
@@ -31,9 +33,9 @@
|
|
|
31
33
|
// And what comes back is sent without it: a tracker that echoes the token
|
|
32
34
|
// reaches the page, the saved connection and the log as `[redacted]`.
|
|
33
35
|
import { createHash } from "node:crypto";
|
|
34
|
-
import { readBody, send } from "../http-io.mjs";
|
|
36
|
+
import { readBody, readBytes, send } from "../http-io.mjs";
|
|
35
37
|
import { errorBody, errorResponse, integrationError, isTypedError } from "./errors.mjs";
|
|
36
|
-
import { fetchImage, IMAGE_MAX_BYTES, isSafeTarget, normaliseBaseUrl, originOf, RASTER_TYPES,
|
|
38
|
+
import { fetchImage, IMAGE_MAX_BYTES, isSafeTarget, normaliseBaseUrl, originOf, RASTER_TYPES, rasterTypeOf } from "./proxy.mjs";
|
|
37
39
|
import { getProvider, isAvailable, providerList } from "./registry.mjs";
|
|
38
40
|
import { integrationsStore } from "./store.mjs";
|
|
39
41
|
import "./providers.mjs";
|
|
@@ -160,10 +162,12 @@ async function serveAsset(res, conn, client, raw, { signal, method, fetchImpl })
|
|
|
160
162
|
const got = typeof client.fetchAsset === "function"
|
|
161
163
|
? await client.fetchAsset(target.href, { maxBytes: IMAGE_MAX_BYTES, signal })
|
|
162
164
|
: await genericAsset(client, target.href, { maxBytes: IMAGE_MAX_BYTES, signal, fetchImpl });
|
|
163
|
-
const
|
|
165
|
+
const declared = String(got?.contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
164
166
|
const bytes = got?.bytes;
|
|
165
|
-
// The route checks again what every client promised
|
|
166
|
-
|
|
167
|
+
// The route checks again what every client promised, and serves the
|
|
168
|
+
// image as the type its bytes are, whichever raster type it was labelled.
|
|
169
|
+
const contentType = Buffer.isBuffer(bytes) ? rasterTypeOf(bytes) : null;
|
|
170
|
+
if (!RASTER_TYPES.has(declared) || !contentType || bytes.length > IMAGE_MAX_BYTES) {
|
|
167
171
|
throw integrationError("not-found", "Not an image the deck shows.");
|
|
168
172
|
}
|
|
169
173
|
image = { at: Date.now(), contentType, bytes };
|
|
@@ -449,9 +453,21 @@ export async function handleIntegrations(req, res, url, deps = {}) {
|
|
|
449
453
|
// /api/integrations/<kind>/<id>/<subpath…>
|
|
450
454
|
const [kind, id, ...rest] = segments;
|
|
451
455
|
if (!id || rest.length === 0) return notFound(res);
|
|
452
|
-
//
|
|
453
|
-
//
|
|
454
|
-
|
|
456
|
+
// The only provider mutation is this narrowly shaped Jira operation.
|
|
457
|
+
// The server's normal mutation authentication and CSRF gates still apply.
|
|
458
|
+
const jiraMove = kind === "jira" && method === "POST" && rest.length === 3
|
|
459
|
+
&& rest[0] === "board" && /^[1-9]\d{0,11}$/.test(rest[1]) && rest[2] === "move";
|
|
460
|
+
if (method !== "GET" && method !== "HEAD" && !jiraMove) return notAllowed(res);
|
|
461
|
+
let moveBody;
|
|
462
|
+
if (jiraMove) {
|
|
463
|
+
if (!/^application\/json(?:\s*;|$)/i.test(String(req.headers["content-type"] ?? ""))) {
|
|
464
|
+
throw integrationError("invalid", "Send the move as application/json.");
|
|
465
|
+
}
|
|
466
|
+
const bytes = await readBytes(req, res, 4096).catch(err => { if (!res.headersSent) throw err; return null; });
|
|
467
|
+
if (bytes === null) return;
|
|
468
|
+
try { moveBody = JSON.parse(bytes.toString("utf8")); }
|
|
469
|
+
catch { throw integrationError("invalid", "The move body is not valid JSON."); }
|
|
470
|
+
}
|
|
455
471
|
const provider = getProvider(kind);
|
|
456
472
|
|
|
457
473
|
// An image: whatever goes wrong, an empty 403 or 404, and the connection
|
|
@@ -484,7 +500,7 @@ export async function handleIntegrations(req, res, url, deps = {}) {
|
|
|
484
500
|
if (secret == null) throw integrationError("expired", "No token is saved for this connection. Reconnect it in Settings.");
|
|
485
501
|
const client = clientFor(provider, conn, secret, { fetchImpl });
|
|
486
502
|
|
|
487
|
-
const read = await provider.routes(client, method, rest.join("/"), url.searchParams, req, { signal });
|
|
503
|
+
const read = await provider.routes(client, method, rest.join("/"), url.searchParams, req, { signal, ...(jiraMove ? { moveBody } : {}) });
|
|
488
504
|
if (res.writableEnded || signal.aborted) return;
|
|
489
505
|
const status = Number.isInteger(read?.status) ? read.status : 500;
|
|
490
506
|
return answer(status, read?.body ?? errorBody(null));
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// What keeps quota-closes.mjs fed while no page is open. Every five minutes it
|
|
2
|
+
// reads claude-swap's store for every account (two small files, no request),
|
|
3
|
+
// notes the plan the signed-in account is on, and closes the windows whose
|
|
4
|
+
// reset has passed. And once per weekly window about to reset that was last
|
|
5
|
+
// read over an hour ago, it asks for one fresh reading: the reading the whole
|
|
6
|
+
// record is about, at a cost of one collection a week per account.
|
|
7
|
+
//
|
|
8
|
+
// The quota modules are reached by `import()`, as account-watch.mjs reaches
|
|
9
|
+
// them, and are pinned with the rest (pinned-build.mjs).
|
|
10
|
+
import { dirname, join, resolve } from "node:path";
|
|
11
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
12
|
+
import { historyAccount } from "./quota-history.mjs";
|
|
13
|
+
import { quotaCloses } from "./quota-closes.mjs";
|
|
14
|
+
import { readLiveLogin } from "./claude-login.mjs";
|
|
15
|
+
|
|
16
|
+
const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
|
|
17
|
+
const lazy = name => import(pathToFileURL(join(PKG_ROOT, "src/server", name)).href);
|
|
18
|
+
export const CLOSE_WATCH_MS = 5 * 60_000;
|
|
19
|
+
|
|
20
|
+
/** One store row's windows, in the shape quota-history.mjs's historyWindows
|
|
21
|
+
* gives the published reading, so both sources land on the same window. */
|
|
22
|
+
export function storedWindows(lastGood) {
|
|
23
|
+
const win = (id, label, w, windowSec) => {
|
|
24
|
+
const resetMs = typeof w?.resets_at === "string" ? Date.parse(w.resets_at) : NaN;
|
|
25
|
+
return Number.isFinite(resetMs) && resetMs > 0 && typeof w?.pct === "number" && Number.isFinite(w.pct)
|
|
26
|
+
? { id, label, pct: Math.min(100, Math.max(0, w.pct)), resetAt: Math.floor(resetMs / 1000), windowSec } : null;
|
|
27
|
+
};
|
|
28
|
+
const five = win("five_hour", "5-hour window", lastGood?.five_hour, 18000);
|
|
29
|
+
const week = win("seven_day", "7-day window", lastGood?.seven_day, 604800);
|
|
30
|
+
// The store's fallback can copy the weekly reading into the session lane.
|
|
31
|
+
return [five && !(week && five.resetAt === week.resetAt && five.pct === week.pct) ? five : null, week].filter(Boolean);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function closingRead(due, liveKey) {
|
|
35
|
+
if (due.provider === "codex") { await (await lazy("codex-quota.mjs")).fetchCodexQuota({ force: true }); return; }
|
|
36
|
+
// claude-swap collects for every account it holds; the signed-in one is also
|
|
37
|
+
// read the way the Usage panel reads it, for a deck without claude-swap.
|
|
38
|
+
await (await lazy("claude-accounts.mjs")).requestCollection();
|
|
39
|
+
if (due.account === liveKey) await (await lazy("quota.mjs")).fetchClaudeQuota({ force: true });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let _running = null;
|
|
43
|
+
/** One pass, never two at once. Every failure ends here: a record that cannot
|
|
44
|
+
* be kept is not worth a line in anyone's way. `providers` is deck-scope's
|
|
45
|
+
* deckProviders, asked each pass as account-watch.mjs asks it. */
|
|
46
|
+
export function closeWatchOnce({ providers } = {}) {
|
|
47
|
+
if (_running) return _running;
|
|
48
|
+
_running = (async () => {
|
|
49
|
+
const closes = quotaCloses();
|
|
50
|
+
if (!closes) return;
|
|
51
|
+
const { claude = true, codex = true } = providers?.() ?? {};
|
|
52
|
+
const watched = { claude, codex };
|
|
53
|
+
let liveKey = null;
|
|
54
|
+
if (claude) {
|
|
55
|
+
const { storedUsageReadings } = await lazy("claude-accounts.mjs");
|
|
56
|
+
for (const r of await storedUsageReadings()) {
|
|
57
|
+
const key = historyAccount("claude", { email: r.email, organizationUuid: r.organizationUuid });
|
|
58
|
+
if (key) await closes.observe("claude", key, storedWindows(r.lastGood), r.fetchedAt);
|
|
59
|
+
}
|
|
60
|
+
const live = await readLiveLogin();
|
|
61
|
+
liveKey = live ? historyAccount("claude", { email: live.email, organizationUuid: live.orgUuid }) : null;
|
|
62
|
+
if (liveKey && live.plan) await closes.plan("claude", liveKey, live.plan);
|
|
63
|
+
}
|
|
64
|
+
await closes.sweep();
|
|
65
|
+
for (const due of await closes.closingReads()) {
|
|
66
|
+
if (watched[due.provider]) await closingRead(due, liveKey).catch(() => {});
|
|
67
|
+
}
|
|
68
|
+
})().catch(() => {}).finally(() => { _running = null; });
|
|
69
|
+
return _running;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let _timer = null;
|
|
73
|
+
/** Started from startServer once the port is bound, never at import; unref'd
|
|
74
|
+
* like every other timer the deck keeps. */
|
|
75
|
+
export function startQuotaCloseWatch({ providers } = {}) {
|
|
76
|
+
if (_timer) return;
|
|
77
|
+
_timer = setInterval(() => { void closeWatchOnce({ providers }); }, CLOSE_WATCH_MS);
|
|
78
|
+
_timer.unref?.();
|
|
79
|
+
const first = setTimeout(() => { void closeWatchOnce({ providers }); }, 30_000);
|
|
80
|
+
first.unref?.();
|
|
81
|
+
}
|