@apet97/clockify-cli-115 6.0.0 → 7.0.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 +167 -21
- package/dist/client.js +30 -7
- package/dist/commands/api.js +44 -76
- package/dist/commands/approvals.js +2 -5
- package/dist/commands/auth.js +229 -0
- package/dist/commands/batch.js +226 -0
- package/dist/commands/clients.js +11 -65
- package/dist/commands/doctor.js +65 -66
- package/dist/commands/expenses.js +21 -24
- package/dist/commands/helpers.js +46 -2
- package/dist/commands/leaf-command.js +7 -0
- package/dist/commands/manifest.js +63 -0
- package/dist/commands/operations.js +271 -0
- package/dist/commands/projects.js +10 -23
- package/dist/commands/reports.js +22 -7
- package/dist/commands/shared-report-body.js +3 -81
- package/dist/commands/sharedReports.js +1 -21
- package/dist/commands/skill.js +85 -0
- package/dist/commands/status.js +18 -12
- package/dist/commands/stop.js +3 -12
- package/dist/commands/tags.js +5 -7
- package/dist/commands/tasks.js +19 -120
- package/dist/commands/users.js +4 -14
- package/dist/commands/webhook-delivery.js +331 -0
- package/dist/commands/webhooks.js +31 -97
- package/dist/completions.js +2 -1
- package/dist/config.js +166 -63
- package/dist/credentials.js +164 -0
- package/dist/failure.js +4 -9
- package/dist/flags.js +14 -4
- package/dist/generated/version.js +1 -1
- package/dist/index.js +38 -14
- package/dist/interrupts.js +28 -0
- package/dist/output.js +137 -48
- package/dist/receipt.js +2 -10
- package/dist/stdin.js +6 -0
- package/dist/stdout.js +38 -0
- package/dist/write-outcome.js +1 -1
- package/package.json +5 -3
- package/plugin/.claude-plugin/plugin.json +16 -0
- package/plugin/skills/clockify-cli/SKILL.md +88 -0
- package/plugin/skills/clockify-mcp/SKILL.md +48 -0
- package/plugin/skills/clockify-sdk/SKILL.md +85 -0
- package/dist/error-codes.js +0 -300
package/dist/commands/status.js
CHANGED
|
@@ -1,12 +1,25 @@
|
|
|
1
1
|
import { entityId } from "clockify-sdk-ts-115/operation-receipt";
|
|
2
|
+
import { runningEntryOf } from "clockify-sdk-ts-115/timer";
|
|
2
3
|
import { formatIsoDuration } from "../duration.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
4
|
+
import { resolveFlags } from "../flags.js";
|
|
5
|
+
import { fixedColumns, printObject } from "../output.js";
|
|
6
|
+
import { resolveBaseContext, rootProgram } from "./helpers.js";
|
|
5
7
|
import { leafCommand } from "./leaf-command.js";
|
|
6
8
|
const TIMER_UNAVAILABLE = {
|
|
7
9
|
user_id_missing: "(timer lookup skipped: current user ID unavailable)",
|
|
8
10
|
response_unrecognized: "(timer state unknown: unrecognized response to the timer lookup)",
|
|
9
11
|
};
|
|
12
|
+
const STATUS_KEYS = [
|
|
13
|
+
"workspaceId",
|
|
14
|
+
"userId",
|
|
15
|
+
"email",
|
|
16
|
+
"name",
|
|
17
|
+
"timerState",
|
|
18
|
+
"timerStateReason",
|
|
19
|
+
"runningEntry",
|
|
20
|
+
"availableWorkspaces",
|
|
21
|
+
"hint",
|
|
22
|
+
];
|
|
10
23
|
export const registerStatusCommand = (program, services) => {
|
|
11
24
|
leafCommand(program, "status", "read")
|
|
12
25
|
.description("Show the configured workspace, current user, and running timer.")
|
|
@@ -14,7 +27,8 @@ export const registerStatusCommand = (program, services) => {
|
|
|
14
27
|
" $ clk115 status\n" +
|
|
15
28
|
" $ clk115 status --json\n")
|
|
16
29
|
.action(async function () {
|
|
17
|
-
const
|
|
30
|
+
const output = fixedColumns(STATUS_KEYS, resolveFlags(rootProgram(this)));
|
|
31
|
+
const { client, config } = await resolveBaseContext(this, services, output);
|
|
18
32
|
const user = await client.users.getCurrentUser();
|
|
19
33
|
let statusState;
|
|
20
34
|
if (!config.workspaceId) {
|
|
@@ -37,7 +51,7 @@ export const registerStatusCommand = (program, services) => {
|
|
|
37
51
|
"in-progress": true,
|
|
38
52
|
"page-size": 1,
|
|
39
53
|
}));
|
|
40
|
-
const entry = entries
|
|
54
|
+
const entry = entries && runningEntryOf(entries, userId);
|
|
41
55
|
if (entries === undefined) {
|
|
42
56
|
statusState = { kind: "unavailable", workspaceId, reason: "response_unrecognized" };
|
|
43
57
|
}
|
|
@@ -92,14 +106,6 @@ function normaliseEntries(resp) {
|
|
|
92
106
|
}
|
|
93
107
|
return undefined;
|
|
94
108
|
}
|
|
95
|
-
function isOwn(entry, user) {
|
|
96
|
-
const entryUserId = entry.userId;
|
|
97
|
-
const userId = entityId(user);
|
|
98
|
-
return entryUserId !== undefined && userId !== undefined && entryUserId === userId;
|
|
99
|
-
}
|
|
100
|
-
function isRunning(entry) {
|
|
101
|
-
return entry.timeInterval?.end == null;
|
|
102
|
-
}
|
|
103
109
|
function extractStart(entry) {
|
|
104
110
|
const interval = entry.timeInterval;
|
|
105
111
|
return interval?.start ?? "";
|
package/dist/commands/stop.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { findRunningEntry } from "clockify-sdk-ts-115/timer";
|
|
1
2
|
import { printReceipt } from "../receipt.js";
|
|
2
3
|
import { dispatchedWrite } from "../write-outcome.js";
|
|
3
4
|
import { requireCurrentUserId, resolveContext } from "./helpers.js";
|
|
@@ -11,18 +12,8 @@ export const registerStopCommand = (program, services) => {
|
|
|
11
12
|
.action(async function () {
|
|
12
13
|
const { client, workspaceId, output } = await resolveContext(this, services);
|
|
13
14
|
const userId = await requireCurrentUserId(client);
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
workspaceId,
|
|
17
|
-
userId,
|
|
18
|
-
"in-progress": true,
|
|
19
|
-
"page-size": 1,
|
|
20
|
-
});
|
|
21
|
-
const running = entries.find((entry) => entry.userId === userId && entry.id && entry.timeInterval?.end == null);
|
|
22
|
-
if (running?.id && running.userId) {
|
|
23
|
-
timerState = { kind: "running", entry: { id: running.id, userId: running.userId } };
|
|
24
|
-
}
|
|
25
|
-
if (timerState.kind === "idle") {
|
|
15
|
+
const running = await findRunningEntry(client, { workspaceId, userId });
|
|
16
|
+
if (running === undefined) {
|
|
26
17
|
printReceipt({
|
|
27
18
|
ok: true,
|
|
28
19
|
action: "timer.stop",
|
package/dist/commands/tags.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { tagUpdate } from "clockify-sdk-ts-115/updates";
|
|
1
2
|
import { UsageError } from "../failure.js";
|
|
2
3
|
import { printObject, printRecords } from "../output.js";
|
|
3
4
|
import { printReceipt } from "../receipt.js";
|
|
@@ -81,13 +82,10 @@ export const registerTagsCommand = (program, services) => {
|
|
|
81
82
|
throw new UsageError("tags.update needs a change: provide at least one tag field.");
|
|
82
83
|
}
|
|
83
84
|
const { client, workspaceId, output } = await resolveContext(this, services);
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
const body =
|
|
88
|
-
name: opts.name ? opts.name : (current.name ?? ""),
|
|
89
|
-
archived: opts.archived ?? current.archived ?? false,
|
|
90
|
-
};
|
|
85
|
+
const patch = { name: opts.name || undefined, archived: opts.archived };
|
|
86
|
+
const complete = patch.name !== undefined && patch.archived !== undefined;
|
|
87
|
+
const current = complete ? {} : await client.tags.get({ workspaceId, tagId: id });
|
|
88
|
+
const body = tagUpdate.body(current, patch);
|
|
91
89
|
const req = { workspaceId, tagId: id, body };
|
|
92
90
|
const updated = (await dispatchedWrite(this, client.tags.update(req)));
|
|
93
91
|
const data = { id: updated.id ?? id, name: updated.name ?? "" };
|
package/dist/commands/tasks.js
CHANGED
|
@@ -1,89 +1,17 @@
|
|
|
1
|
+
import { taskUpdate } from "clockify-sdk-ts-115/updates";
|
|
1
2
|
import { PartialDeleteError, UsageError } from "../failure.js";
|
|
2
3
|
import { printObject, printRecords } from "../output.js";
|
|
3
4
|
import { printReceipt } from "../receipt.js";
|
|
4
5
|
import { dispatchedWrite } from "../write-outcome.js";
|
|
5
6
|
import { clampPageSize, parseIntArg, resolveContext } from "./helpers.js";
|
|
6
7
|
import { leafCommand } from "./leaf-command.js";
|
|
7
|
-
function
|
|
8
|
-
if (typeof value !== "string" || value.trim() === "") {
|
|
9
|
-
throw new Error(`${source} is missing the required task name; refusing to mutate.`);
|
|
10
|
-
}
|
|
11
|
-
return value;
|
|
12
|
-
}
|
|
13
|
-
function taskStatus(value, source, operatorInput = false) {
|
|
8
|
+
function taskStatus(value) {
|
|
14
9
|
const status = String(value).toUpperCase();
|
|
15
10
|
if (status !== "ACTIVE" && status !== "DONE") {
|
|
16
|
-
|
|
17
|
-
throw operatorInput ? new UsageError(message) : new Error(message);
|
|
11
|
+
throw new UsageError(`Task update request has unknown task status: ${String(value)}; provide ACTIVE or DONE`);
|
|
18
12
|
}
|
|
19
13
|
return status;
|
|
20
14
|
}
|
|
21
|
-
function stringList(value, field) {
|
|
22
|
-
if (value === undefined)
|
|
23
|
-
return undefined;
|
|
24
|
-
if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
|
|
25
|
-
throw new Error(`Current task has invalid ${field}; refusing to mutate.`);
|
|
26
|
-
}
|
|
27
|
-
return [...value];
|
|
28
|
-
}
|
|
29
|
-
function optionalTaskString(value, field) {
|
|
30
|
-
if (value === undefined)
|
|
31
|
-
return undefined;
|
|
32
|
-
if (typeof value !== "string") {
|
|
33
|
-
throw new Error(`Current task has invalid ${field}; refusing to mutate.`);
|
|
34
|
-
}
|
|
35
|
-
return value;
|
|
36
|
-
}
|
|
37
|
-
function optionalNullableTaskString(value, field) {
|
|
38
|
-
if (value === null)
|
|
39
|
-
return undefined;
|
|
40
|
-
return optionalTaskString(value, field);
|
|
41
|
-
}
|
|
42
|
-
function requiredTaskBoolean(value, field) {
|
|
43
|
-
if (typeof value !== "boolean") {
|
|
44
|
-
throw new Error(`Current task has invalid or missing ${field}; refusing to mutate.`);
|
|
45
|
-
}
|
|
46
|
-
return value;
|
|
47
|
-
}
|
|
48
|
-
function optionalTaskInteger(value, field) {
|
|
49
|
-
if (value === undefined)
|
|
50
|
-
return undefined;
|
|
51
|
-
if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) {
|
|
52
|
-
throw new Error(`Current task has invalid ${field}; refusing to mutate.`);
|
|
53
|
-
}
|
|
54
|
-
return value;
|
|
55
|
-
}
|
|
56
|
-
function sameStringList(left, right) {
|
|
57
|
-
return left !== undefined && left.length === right.length && left.every((item, i) => item === right[i]);
|
|
58
|
-
}
|
|
59
|
-
function reconstructTaskBody(current, suppliedName) {
|
|
60
|
-
const body = {
|
|
61
|
-
name: suppliedName !== undefined
|
|
62
|
-
? requireTaskName(suppliedName, "Task update request")
|
|
63
|
-
: requireTaskName(current.name, "Current task"),
|
|
64
|
-
};
|
|
65
|
-
const assigneeId = optionalNullableTaskString(current.assigneeId, "assigneeId");
|
|
66
|
-
if (assigneeId !== undefined)
|
|
67
|
-
body.assigneeId = assigneeId;
|
|
68
|
-
const assigneeIds = stringList(current.assigneeIds, "assigneeIds");
|
|
69
|
-
if (assigneeIds !== undefined)
|
|
70
|
-
body.assigneeIds = assigneeIds;
|
|
71
|
-
body.billable = requiredTaskBoolean(current.billable, "billable");
|
|
72
|
-
const budgetEstimate = optionalTaskInteger(current.budgetEstimate, "budgetEstimate");
|
|
73
|
-
if (budgetEstimate !== undefined)
|
|
74
|
-
body.budgetEstimate = budgetEstimate;
|
|
75
|
-
const estimate = optionalTaskString(current.estimate, "estimate");
|
|
76
|
-
if (estimate !== undefined)
|
|
77
|
-
body.estimate = estimate;
|
|
78
|
-
if (current.status === undefined) {
|
|
79
|
-
throw new Error("Current task is missing the required status; refusing to mutate.");
|
|
80
|
-
}
|
|
81
|
-
body.status = taskStatus(current.status, "Current task");
|
|
82
|
-
const userGroupIds = stringList(current.userGroupIds, "userGroupIds");
|
|
83
|
-
if (userGroupIds !== undefined)
|
|
84
|
-
body.userGroupIds = userGroupIds;
|
|
85
|
-
return body;
|
|
86
|
-
}
|
|
87
15
|
export const registerTasksCommand = (program, services) => {
|
|
88
16
|
const tasks = program.command("tasks").description("Manage tasks.");
|
|
89
17
|
leafCommand(tasks, "list", "read")
|
|
@@ -129,7 +57,8 @@ export const registerTasksCommand = (program, services) => {
|
|
|
129
57
|
" $ clk115 tasks create project_123 Design --billable --estimate PT8H\n")
|
|
130
58
|
.action(async function (projectId, name, opts) {
|
|
131
59
|
const { client, workspaceId, output } = await resolveContext(this, services);
|
|
132
|
-
|
|
60
|
+
if (name.trim() === "")
|
|
61
|
+
throw new Error("Task create request is missing the required task name.");
|
|
133
62
|
const body = { name };
|
|
134
63
|
if (opts.billable !== undefined)
|
|
135
64
|
body.billable = opts.billable;
|
|
@@ -191,34 +120,17 @@ export const registerTasksCommand = (program, services) => {
|
|
|
191
120
|
if (!hasChanges) {
|
|
192
121
|
throw new UsageError("tasks.update needs a change: provide at least one task field.");
|
|
193
122
|
}
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
:
|
|
123
|
+
const patch = {
|
|
124
|
+
name: opts.name,
|
|
125
|
+
estimate: opts.estimate,
|
|
126
|
+
billable: opts.billable,
|
|
127
|
+
assigneeIds: opts.assignee,
|
|
128
|
+
...(opts.status === undefined ? {} : { status: taskStatus(opts.status) }),
|
|
129
|
+
};
|
|
197
130
|
const { client, workspaceId, output } = await resolveContext(this, services);
|
|
198
|
-
const current =
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
taskId: id,
|
|
202
|
-
}));
|
|
203
|
-
const body = reconstructTaskBody(current, opts.name);
|
|
204
|
-
let changed = opts.name !== undefined && opts.name !== current.name;
|
|
205
|
-
if (requestedStatus !== undefined) {
|
|
206
|
-
changed = changed || requestedStatus !== body.status;
|
|
207
|
-
body.status = requestedStatus;
|
|
208
|
-
}
|
|
209
|
-
if (opts.estimate !== undefined) {
|
|
210
|
-
changed = changed || opts.estimate !== body.estimate;
|
|
211
|
-
body.estimate = opts.estimate;
|
|
212
|
-
}
|
|
213
|
-
if (opts.billable !== undefined) {
|
|
214
|
-
changed = changed || opts.billable !== body.billable;
|
|
215
|
-
body.billable = opts.billable;
|
|
216
|
-
}
|
|
217
|
-
if (Array.isArray(opts.assignee)) {
|
|
218
|
-
changed = changed || !sameStringList(body.assigneeIds, opts.assignee);
|
|
219
|
-
body.assigneeIds = opts.assignee;
|
|
220
|
-
}
|
|
221
|
-
if (!changed) {
|
|
131
|
+
const current = await client.tasks.get({ workspaceId, projectId, taskId: id });
|
|
132
|
+
const body = taskUpdate.body(current, patch);
|
|
133
|
+
if (taskUpdate.changed(current, patch).length === 0) {
|
|
222
134
|
throw new Error("tasks.update values are unchanged; provide a different value.");
|
|
223
135
|
}
|
|
224
136
|
const req = {
|
|
@@ -251,24 +163,11 @@ export const registerTasksCommand = (program, services) => {
|
|
|
251
163
|
.addHelpText("after", "\nExamples:\n" + " $ clk115 tasks delete project_123 task_456\n")
|
|
252
164
|
.action(async function (projectId, id) {
|
|
253
165
|
const { client, workspaceId, output } = await resolveContext(this, services);
|
|
254
|
-
const current =
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
taskId: id,
|
|
258
|
-
}));
|
|
259
|
-
const originalBody = reconstructTaskBody(current);
|
|
260
|
-
if (originalBody.status === undefined) {
|
|
261
|
-
throw new Error("Current task is missing the required status for safe delete.");
|
|
262
|
-
}
|
|
263
|
-
const changedStatus = originalBody.status !== "DONE";
|
|
166
|
+
const current = await client.tasks.get({ workspaceId, projectId, taskId: id });
|
|
167
|
+
const changedStatus = taskUpdate.changed(current, { status: "DONE" }).length > 0;
|
|
168
|
+
const body = taskUpdate.body(current, { status: "DONE" });
|
|
264
169
|
if (changedStatus) {
|
|
265
|
-
|
|
266
|
-
workspaceId,
|
|
267
|
-
projectId,
|
|
268
|
-
taskId: id,
|
|
269
|
-
body: { ...originalBody, status: "DONE" },
|
|
270
|
-
};
|
|
271
|
-
await dispatchedWrite(this, client.tasks.update(doneRequest));
|
|
170
|
+
await dispatchedWrite(this, client.tasks.update({ workspaceId, projectId, taskId: id, body }));
|
|
272
171
|
}
|
|
273
172
|
try {
|
|
274
173
|
await dispatchedWrite(this, client.tasks.delete({ workspaceId, projectId, taskId: id }));
|
package/dist/commands/users.js
CHANGED
|
@@ -1,23 +1,13 @@
|
|
|
1
|
+
import { DAYS_OF_WEEK } from "clockify-sdk-ts-115/requests";
|
|
1
2
|
import { UsageError } from "../failure.js";
|
|
2
3
|
import { printObject, printRecords } from "../output.js";
|
|
3
4
|
import { printReceipt } from "../receipt.js";
|
|
4
5
|
import { dispatchedWrite } from "../write-outcome.js";
|
|
5
6
|
import { clampPageSize, parseIntArg, resolveBaseContext, resolveContext } from "./helpers.js";
|
|
6
7
|
import { leafCommand } from "./leaf-command.js";
|
|
7
|
-
const USER_DAYS = [
|
|
8
|
-
"MONDAY",
|
|
9
|
-
"TUESDAY",
|
|
10
|
-
"WEDNESDAY",
|
|
11
|
-
"THURSDAY",
|
|
12
|
-
"FRIDAY",
|
|
13
|
-
"SATURDAY",
|
|
14
|
-
"SUNDAY",
|
|
15
|
-
];
|
|
16
|
-
const userDaysExhaustive = true;
|
|
17
|
-
void userDaysExhaustive;
|
|
18
8
|
function requireUserDay(value, message) {
|
|
19
9
|
const day = String(value).toUpperCase();
|
|
20
|
-
if (!
|
|
10
|
+
if (!DAYS_OF_WEEK.includes(day)) {
|
|
21
11
|
throw new UsageError(message);
|
|
22
12
|
}
|
|
23
13
|
return day;
|
|
@@ -123,14 +113,14 @@ export const registerUsersCommand = (program, services) => {
|
|
|
123
113
|
if (opts.removeImage)
|
|
124
114
|
body.removeProfileImage = true;
|
|
125
115
|
if (opts.weekStart !== undefined) {
|
|
126
|
-
body.weekStart = requireUserDay(opts.weekStart, `--week-start must be one of: ${
|
|
116
|
+
body.weekStart = requireUserDay(opts.weekStart, `--week-start must be one of: ${DAYS_OF_WEEK.join(", ")}.`);
|
|
127
117
|
}
|
|
128
118
|
if (opts.workCapacity !== undefined)
|
|
129
119
|
body.workCapacity = opts.workCapacity;
|
|
130
120
|
if (Array.isArray(opts.workingDays) && opts.workingDays.length > 0) {
|
|
131
121
|
const days = [];
|
|
132
122
|
for (const raw of opts.workingDays) {
|
|
133
|
-
days.push(requireUserDay(raw, `--working-days entries must be one of: ${
|
|
123
|
+
days.push(requireUserDay(raw, `--working-days entries must be one of: ${DAYS_OF_WEEK.join(", ")}.`));
|
|
134
124
|
}
|
|
135
125
|
body.workingDays = days;
|
|
136
126
|
}
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { CLOCKIFY_WEBHOOK_EVENT_NAMES } from "clockify-sdk-ts-115/webhook-events";
|
|
2
|
+
import { CLOCKIFY_SIGNATURE_HEADER, CLOCKIFY_WEBHOOK_EVENT_HEADER, createWebhookReceiver, undeliveredWebhookEvents, } from "clockify-sdk-ts-115/webhooks";
|
|
3
|
+
import { InvalidArgumentError, Option } from "commander";
|
|
4
|
+
import { UsageError } from "../failure.js";
|
|
5
|
+
import { resolveFlags } from "../flags.js";
|
|
6
|
+
import { watchInterrupts } from "../interrupts.js";
|
|
7
|
+
import { AlreadyReportedError, fixedColumns, printObject, printRecords, printWarning, rowLine, } from "../output.js";
|
|
8
|
+
import { writeLine } from "../stdout.js";
|
|
9
|
+
import { isSuccess } from "../write-outcome.js";
|
|
10
|
+
import { parseIntArg, parseJson, readTextInput, resolveContext, rootProgram } from "./helpers.js";
|
|
11
|
+
import { leafCommand } from "./leaf-command.js";
|
|
12
|
+
const HEADER_VALUE = /^[\x20-\x7e]+$/;
|
|
13
|
+
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
14
|
+
const LISTEN_KEYS = ["event", "payload", "forwarded"];
|
|
15
|
+
const TRIGGER_KEYS = ["ok", "event", "url", "status"];
|
|
16
|
+
const RECOVER_KEYS = ["id", "event", "status", "statusCode", "retryCount", "respondedAt", "payload", "forwarded"];
|
|
17
|
+
function parsePort(value) {
|
|
18
|
+
const port = value === "0" ? 0 : parseIntArg(value);
|
|
19
|
+
if (port > 65_535)
|
|
20
|
+
throw new InvalidArgumentError("must be at most 65535.");
|
|
21
|
+
return port;
|
|
22
|
+
}
|
|
23
|
+
function parseLoopbackUrl(value) {
|
|
24
|
+
const url = URL.canParse(value) ? new URL(value) : undefined;
|
|
25
|
+
if (url?.protocol !== "http:" || !LOOPBACK.has(url.hostname) || url.username !== "" || url.password !== "") {
|
|
26
|
+
throw new InvalidArgumentError("must be an http:// URL on localhost, 127.0.0.1 or [::1].");
|
|
27
|
+
}
|
|
28
|
+
return url.href;
|
|
29
|
+
}
|
|
30
|
+
function parseDeliveryStatus(value) {
|
|
31
|
+
const status = value.toUpperCase();
|
|
32
|
+
if (status !== "FAILED" && status !== "RETRYING")
|
|
33
|
+
throw new InvalidArgumentError("must be FAILED or RETRYING.");
|
|
34
|
+
return status;
|
|
35
|
+
}
|
|
36
|
+
async function signingSecret(command, services, { webhook, secretStdin }) {
|
|
37
|
+
if ((webhook === undefined) === (secretStdin !== true)) {
|
|
38
|
+
throw new UsageError("Provide the signing secret with exactly one of --webhook <id> and --secret-stdin.");
|
|
39
|
+
}
|
|
40
|
+
if (webhook === undefined) {
|
|
41
|
+
const secret = ((await readTextInput("-", "--secret-stdin")) ?? "").trim();
|
|
42
|
+
if (secret === "")
|
|
43
|
+
throw new UsageError("--secret-stdin read nothing; provide the webhook's signing secret on stdin.");
|
|
44
|
+
if (!HEADER_VALUE.test(secret))
|
|
45
|
+
throw new UsageError("--secret-stdin must be one line of printable ASCII.");
|
|
46
|
+
return secret;
|
|
47
|
+
}
|
|
48
|
+
const { client, workspaceId } = await resolveContext(command, services);
|
|
49
|
+
return await webhookSecret(client, workspaceId, webhook);
|
|
50
|
+
}
|
|
51
|
+
async function webhookSecret(client, workspaceId, webhookId) {
|
|
52
|
+
const { authToken } = await client.webhooks.get({ workspaceId, webhookId });
|
|
53
|
+
if (!authToken)
|
|
54
|
+
throw new Error(`Clockify did not return the signing secret of webhook ${webhookId}.`);
|
|
55
|
+
if (!HEADER_VALUE.test(authToken))
|
|
56
|
+
throw new Error(`The signing secret of webhook ${webhookId} does not fit into a header.`);
|
|
57
|
+
return authToken;
|
|
58
|
+
}
|
|
59
|
+
function reason(error) {
|
|
60
|
+
const { message, code } = error;
|
|
61
|
+
return message || code || String(error);
|
|
62
|
+
}
|
|
63
|
+
async function deliver(url, event, secret, body, signal) {
|
|
64
|
+
try {
|
|
65
|
+
const response = await fetch(url, {
|
|
66
|
+
method: "POST",
|
|
67
|
+
redirect: "manual",
|
|
68
|
+
...(signal && { signal }),
|
|
69
|
+
headers: {
|
|
70
|
+
"Content-Type": "application/json",
|
|
71
|
+
[CLOCKIFY_SIGNATURE_HEADER]: secret,
|
|
72
|
+
...(event !== undefined && { [CLOCKIFY_WEBHOOK_EVENT_HEADER]: event }),
|
|
73
|
+
},
|
|
74
|
+
body,
|
|
75
|
+
});
|
|
76
|
+
await response.body?.cancel();
|
|
77
|
+
return response.status;
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
const { cause } = error;
|
|
81
|
+
throw new Error(`Could not reach ${url}: ${reason(cause ?? error)}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function serve(port, stop, quit, handle) {
|
|
85
|
+
const { createServer } = await import("node:http");
|
|
86
|
+
const server = createServer();
|
|
87
|
+
const sockets = new Set();
|
|
88
|
+
const unanswered = new Set();
|
|
89
|
+
const handling = new Set();
|
|
90
|
+
const close = () => {
|
|
91
|
+
server.close();
|
|
92
|
+
const busy = new Set([...unanswered].filter(({ complete }) => complete).map(({ socket }) => socket));
|
|
93
|
+
for (const socket of sockets)
|
|
94
|
+
if (!busy.has(socket))
|
|
95
|
+
socket.destroySoon();
|
|
96
|
+
};
|
|
97
|
+
stop.addEventListener("abort", close);
|
|
98
|
+
quit.addEventListener("abort", () => {
|
|
99
|
+
server.closeAllConnections();
|
|
100
|
+
});
|
|
101
|
+
try {
|
|
102
|
+
await new Promise((resolve, reject) => {
|
|
103
|
+
server.on("close", resolve);
|
|
104
|
+
server.on("error", (err) => {
|
|
105
|
+
reject(new Error(`Could not listen on 127.0.0.1:${port}: ${err.message}`));
|
|
106
|
+
});
|
|
107
|
+
server.on("connection", (socket) => {
|
|
108
|
+
sockets.add(socket);
|
|
109
|
+
socket.on("close", () => sockets.delete(socket));
|
|
110
|
+
});
|
|
111
|
+
server.on("request", (request, response) => {
|
|
112
|
+
unanswered.add(request);
|
|
113
|
+
response.on("close", () => {
|
|
114
|
+
unanswered.delete(request);
|
|
115
|
+
if (stop.aborted)
|
|
116
|
+
close();
|
|
117
|
+
});
|
|
118
|
+
const handled = handle(request, response).catch(reject).finally(() => handling.delete(handled));
|
|
119
|
+
handling.add(handled);
|
|
120
|
+
});
|
|
121
|
+
server.listen(port, "127.0.0.1", () => {
|
|
122
|
+
process.stderr.write(`Listening on http://127.0.0.1:${server.address().port}\n`);
|
|
123
|
+
if (stop.aborted)
|
|
124
|
+
close();
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
await Promise.all(handling);
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
server.close();
|
|
131
|
+
server.closeAllConnections();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
async function* recorded(chunks, received) {
|
|
135
|
+
for await (const chunk of chunks) {
|
|
136
|
+
received.push(chunk);
|
|
137
|
+
yield chunk;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const secretOptions = (command) => command
|
|
141
|
+
.option("--webhook <id>", "Webhook whose signing secret is used. It is read from Clockify.")
|
|
142
|
+
.option("--secret-stdin", "Read the signing secret from stdin instead. Needs no credentials.");
|
|
143
|
+
export function registerWebhookDeliveryCommands(webhooks, services) {
|
|
144
|
+
leafCommand(webhooks, "events", "read")
|
|
145
|
+
.description("List the event names a webhook can subscribe to. Needs no credentials.")
|
|
146
|
+
.addHelpText("after", "\nExamples:\n $ clk115 webhooks events\n")
|
|
147
|
+
.action(function () {
|
|
148
|
+
const output = fixedColumns(["event"], resolveFlags(rootProgram(this)));
|
|
149
|
+
printRecords(CLOCKIFY_WEBHOOK_EVENT_NAMES.map((event) => ({ event })), output);
|
|
150
|
+
});
|
|
151
|
+
secretOptions(leafCommand(webhooks, "listen", "local"))
|
|
152
|
+
.description("Receive deliveries on a loopback port, verify each one and print it as a JSON line.")
|
|
153
|
+
.addOption(new Option("--port <n>", "Loopback port; 0 picks a free one.").argParser(parsePort).default(4040))
|
|
154
|
+
.addOption(new Option("--forward <url>", "Pass each verified delivery to this loopback URL and answer as it does.").argParser(parseLoopbackUrl))
|
|
155
|
+
.option("--max <n>", "Stop after printing this many verified deliveries.", parseIntArg)
|
|
156
|
+
.addHelpText("after", "\nExamples:\n" +
|
|
157
|
+
" $ clk115 webhooks listen --webhook 64c777ddd3fcab07cfbb210c --forward http://localhost:3000/hooks\n" +
|
|
158
|
+
" $ echo local-secret | clk115 webhooks listen --secret-stdin --max 1 > delivery.json\n" +
|
|
159
|
+
"\nClockify delivers to public https:// URLs only, so put your own tunnel in front of the port.\n" +
|
|
160
|
+
"A delivery that the handler does not accept, or that cannot be printed, is answered with 500, and Clockify\n" +
|
|
161
|
+
"sends it again. An interrupt before --max deliveries exits with 128 plus the signal number.\n")
|
|
162
|
+
.action(async function (opts) {
|
|
163
|
+
const output = fixedColumns(LISTEN_KEYS, resolveFlags(rootProgram(this)));
|
|
164
|
+
if (output.mode === "csv")
|
|
165
|
+
throw new UsageError("webhooks listen prints JSON lines; --output csv does not apply.");
|
|
166
|
+
const secret = await signingSecret(this, services, opts);
|
|
167
|
+
const stop = new AbortController();
|
|
168
|
+
const quit = new AbortController();
|
|
169
|
+
const interrupts = watchInterrupts(() => {
|
|
170
|
+
stop.abort();
|
|
171
|
+
}, () => {
|
|
172
|
+
quit.abort();
|
|
173
|
+
});
|
|
174
|
+
const { forward, max } = opts;
|
|
175
|
+
let taken = 0;
|
|
176
|
+
let printed = 0;
|
|
177
|
+
let unwritten = 0;
|
|
178
|
+
const print = async (delivery) => {
|
|
179
|
+
try {
|
|
180
|
+
await writeLine(rowLine(delivery, output), interrupts.abandoned);
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
unwritten += 1;
|
|
184
|
+
throw new Error(`The delivery could not be printed: ${reason(error)}`);
|
|
185
|
+
}
|
|
186
|
+
printed += 1;
|
|
187
|
+
};
|
|
188
|
+
const receiver = (received) => createWebhookReceiver({
|
|
189
|
+
expectedToken: secret,
|
|
190
|
+
handlers: {},
|
|
191
|
+
onUnhandled: async ({ event, payload }) => {
|
|
192
|
+
if (taken === max)
|
|
193
|
+
throw new Error(`--max ${max} was reached.`);
|
|
194
|
+
taken += 1;
|
|
195
|
+
let status;
|
|
196
|
+
try {
|
|
197
|
+
if (forward !== undefined)
|
|
198
|
+
status = await deliver(forward, event, secret, Buffer.concat(received), quit.signal);
|
|
199
|
+
await print({ event: event ?? null, payload, ...(status !== undefined && { forwarded: status }) });
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
taken -= 1;
|
|
203
|
+
throw error;
|
|
204
|
+
}
|
|
205
|
+
if (status !== undefined && !isSuccess(status))
|
|
206
|
+
throw new Error(`${forward ?? ""} answered ${status}`);
|
|
207
|
+
},
|
|
208
|
+
onError: (error) => {
|
|
209
|
+
printWarning(reason(error), output);
|
|
210
|
+
},
|
|
211
|
+
});
|
|
212
|
+
const answer = async (request, response) => {
|
|
213
|
+
const { method, headers } = request;
|
|
214
|
+
const received = [];
|
|
215
|
+
await receiver(received).node({ method, headers, [Symbol.asyncIterator]: () => recorded(request, received) }, response);
|
|
216
|
+
if (response.statusCode !== 200)
|
|
217
|
+
printWarning(`Answered ${response.statusCode} to ${method ?? ""}.`, output);
|
|
218
|
+
if (unwritten > 0 || printed === max)
|
|
219
|
+
stop.abort();
|
|
220
|
+
};
|
|
221
|
+
try {
|
|
222
|
+
await serve(opts.port, stop.signal, quit.signal, answer);
|
|
223
|
+
}
|
|
224
|
+
finally {
|
|
225
|
+
interrupts.release();
|
|
226
|
+
}
|
|
227
|
+
const interrupted = interrupts.exitCode();
|
|
228
|
+
if (unwritten > 0)
|
|
229
|
+
throw new AlreadyReportedError(interrupts.abandoned.aborted ? interrupted : 1);
|
|
230
|
+
if (interrupted !== undefined && max !== undefined && printed < max)
|
|
231
|
+
throw new AlreadyReportedError(interrupted);
|
|
232
|
+
});
|
|
233
|
+
secretOptions(leafCommand(webhooks, "trigger <event>", "local"))
|
|
234
|
+
.description("Send a signed delivery to a handler on this machine.")
|
|
235
|
+
.requiredOption("--data <json>", "The payload as JSON, as @file, or as - for stdin.")
|
|
236
|
+
.addOption(new Option("--url <url>", "Loopback URL of the handler.").argParser(parseLoopbackUrl).default("http://127.0.0.1:4040/"))
|
|
237
|
+
.addHelpText("after", "\nExamples:\n" +
|
|
238
|
+
" $ echo local-secret | clk115 webhooks trigger NEW_TAG --secret-stdin --data '{\"id\":\"t1\",\"name\":\"focus\"}'\n" +
|
|
239
|
+
" $ clk115 webhooks trigger NEW_TIME_ENTRY --webhook 64c777ddd3fcab07cfbb210c --data @entry.json --url http://localhost:3000/hooks\n")
|
|
240
|
+
.action(async function (name, opts) {
|
|
241
|
+
const output = fixedColumns(TRIGGER_KEYS, resolveFlags(rootProgram(this)));
|
|
242
|
+
const event = name.toUpperCase();
|
|
243
|
+
if (!CLOCKIFY_WEBHOOK_EVENT_NAMES.includes(event)) {
|
|
244
|
+
throw new UsageError(`Unknown webhook event: ${name}. Run \`clk115 webhooks events\` for the names.`);
|
|
245
|
+
}
|
|
246
|
+
if (opts.data === "-" && opts.secretStdin) {
|
|
247
|
+
throw new UsageError("--data - and --secret-stdin both read stdin; provide the payload as @file.");
|
|
248
|
+
}
|
|
249
|
+
const payload = parseJson((await readTextInput(opts.data, "--data")) ?? "", "--data");
|
|
250
|
+
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
|
|
251
|
+
throw new UsageError("--data must be a JSON object.");
|
|
252
|
+
}
|
|
253
|
+
const secret = await signingSecret(this, services, opts);
|
|
254
|
+
const status = await deliver(opts.url, event, secret, JSON.stringify(payload));
|
|
255
|
+
printObject({ ok: isSuccess(status), event, url: opts.url, status }, output);
|
|
256
|
+
if (!isSuccess(status))
|
|
257
|
+
throw new AlreadyReportedError();
|
|
258
|
+
});
|
|
259
|
+
leafCommand(webhooks, "recover <id>", "local")
|
|
260
|
+
.description("List the deliveries of a webhook that Clockify could not complete, and optionally hand them to a local handler.")
|
|
261
|
+
.option("--status <status>", "Delivery state to list: FAILED or RETRYING.", parseDeliveryStatus, "FAILED")
|
|
262
|
+
.addOption(new Option("--forward <url>", "Send each recorded body, signed, to this loopback URL.").argParser(parseLoopbackUrl))
|
|
263
|
+
.option("--limit <n>", "List at most this many deliveries.", parseIntArg, 100)
|
|
264
|
+
.addHelpText("after", "\nExamples:\n" +
|
|
265
|
+
" $ clk115 webhooks recover 64c777ddd3fcab07cfbb210c\n" +
|
|
266
|
+
" $ clk115 webhooks recover 64c777ddd3fcab07cfbb210c --forward http://localhost:3000/hooks --json\n" +
|
|
267
|
+
"\nClockify keeps its delivery log for 7 days. The log does not change when a delivery is forwarded,\n" +
|
|
268
|
+
"so a handler that runs twice must recognise a record it already has. An interrupt, or a failure after the\n" +
|
|
269
|
+
"first delivery, still prints what was listed and forwarded until then.\n")
|
|
270
|
+
.action(async function (id, opts) {
|
|
271
|
+
const output = fixedColumns(RECOVER_KEYS, resolveFlags(rootProgram(this)));
|
|
272
|
+
const { client, workspaceId } = await resolveContext(this, services, output);
|
|
273
|
+
const { forward, limit, status } = opts;
|
|
274
|
+
const withPayload = output.mode !== "table" || output.fields !== undefined;
|
|
275
|
+
const secret = forward === undefined ? "" : await webhookSecret(client, workspaceId, id);
|
|
276
|
+
const rows = [];
|
|
277
|
+
let refused = 0;
|
|
278
|
+
let cut = 0;
|
|
279
|
+
const print = () => {
|
|
280
|
+
printRecords(rows, output);
|
|
281
|
+
};
|
|
282
|
+
const quit = new AbortController();
|
|
283
|
+
const interrupts = watchInterrupts(() => {
|
|
284
|
+
printWarning("Finishing the delivery in progress. Interrupt again to give it up.", output);
|
|
285
|
+
}, () => {
|
|
286
|
+
quit.abort();
|
|
287
|
+
});
|
|
288
|
+
const events = undeliveredWebhookEvents(client, { workspaceId, webhookId: id, status, signal: quit.signal });
|
|
289
|
+
try {
|
|
290
|
+
for await (const { body, payload, ...row } of events) {
|
|
291
|
+
if (rows.length === limit) {
|
|
292
|
+
printWarning(`--limit ${limit} was reached; there are more deliveries.`, output);
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
if (interrupts.exitCode() !== undefined) {
|
|
296
|
+
cut += 1;
|
|
297
|
+
break;
|
|
298
|
+
}
|
|
299
|
+
let forwarded;
|
|
300
|
+
if (forward !== undefined) {
|
|
301
|
+
forwarded = body === undefined
|
|
302
|
+
? "no recorded body"
|
|
303
|
+
: await deliver(forward, row.event, secret, body, quit.signal).catch(reason);
|
|
304
|
+
if (typeof forwarded !== "number" || !isSuccess(forwarded))
|
|
305
|
+
refused += 1;
|
|
306
|
+
}
|
|
307
|
+
const recordedBody = withPayload && { payload: payload ?? body ?? null };
|
|
308
|
+
rows.push({ ...row, ...recordedBody, ...(forwarded !== undefined && { forwarded }) });
|
|
309
|
+
if (quit.signal.aborted)
|
|
310
|
+
cut += 1;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
catch (err) {
|
|
314
|
+
if (!quit.signal.aborted) {
|
|
315
|
+
if (rows.length > 0)
|
|
316
|
+
print();
|
|
317
|
+
throw err;
|
|
318
|
+
}
|
|
319
|
+
cut += 1;
|
|
320
|
+
}
|
|
321
|
+
finally {
|
|
322
|
+
interrupts.release();
|
|
323
|
+
}
|
|
324
|
+
if (cut === 0 || rows.length > 0)
|
|
325
|
+
print();
|
|
326
|
+
if (refused > 0)
|
|
327
|
+
printWarning(`${refused} of ${rows.length} deliveries were not accepted.`, output);
|
|
328
|
+
if (cut > 0 || refused > 0)
|
|
329
|
+
throw new AlreadyReportedError(cut > 0 ? interrupts.exitCode() : 1);
|
|
330
|
+
});
|
|
331
|
+
}
|