my-durable 0.0.40 → 0.0.42
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/apps/dpi-backend/src/backup-cli.ts +220 -0
- package/apps/dpi-backend/src/backup.ts +523 -0
- package/apps/dpi-backend/src/doctor.ts +19 -1
- package/apps/dpi-backend/src/env-vars.ts +234 -0
- package/apps/dpi-backend/src/main.ts +1 -0
- package/apps/dpi-backend/src/notify-cli.ts +211 -0
- package/apps/dpi-backend/src/notify-sinks.ts +947 -0
- package/apps/dpi-backend/src/projects.ts +18 -1
- package/apps/dpi-backend/src/routes.ts +29 -1
- package/apps/dpi-backend/src/store.ts +170 -9
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DaurAPEn.css +1 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-o6Rn26ft.js +81 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/EnvPanel.vue +268 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +8 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NewSessionDialog.vue +37 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NotifyPanel.vue +292 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ProjectBar.vue +41 -1
- package/apps/dpi-sdk/src/api.ts +79 -1
- package/apps/dpi-sdk/src/client.ts +32 -0
- package/apps/dpi-sdk/src/protocol/rest-routes.ts +9 -0
- package/bin/dpi.mjs +15 -0
- package/docs/host-project-checklist.md +6 -6
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DMJMesxP.css +0 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-jDhVa5sg.js +0 -81
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Device env-file editing — "Env-var management UI", Wave 2 SHOULD of
|
|
3
|
+
* docs/host-project-checklist.md.
|
|
4
|
+
*
|
|
5
|
+
* orca edits a host's default agent environment (HostAgentEnvironmentEditor);
|
|
6
|
+
* the device equivalent is the env file loadConfig reads at boot
|
|
7
|
+
* (~/.dpi/backend.env or $DPI_ENV_FILE — the same file `just net up` writes
|
|
8
|
+
* from dpi-network.yaml's env/env_keys). This module is the guarded read/edit
|
|
9
|
+
* surface for THAT file: list with secrets masked, set/unset one key, and a
|
|
10
|
+
* restart hint, because nothing takes effect until the daemon reboots.
|
|
11
|
+
*
|
|
12
|
+
* Three deliberate rules:
|
|
13
|
+
* - Managed/self-referential keys (DPI_TOKEN, DPI_PORT, DPI_HOME, …) are
|
|
14
|
+
* refused: each has its own dedicated setting, and editing them from a
|
|
15
|
+
* remote browser is how a device gets locked out.
|
|
16
|
+
* - Variables that came from the process (systemd `Environment=`, shell) are
|
|
17
|
+
* listed read-only: `process.loadEnvFile` does not override an existing
|
|
18
|
+
* value, so writing them to the file would look saved but never apply.
|
|
19
|
+
* - Secret-looking values are never returned over the wire — only a mask and
|
|
20
|
+
* the last 4 characters, enough to recognise, not enough to copy.
|
|
21
|
+
*
|
|
22
|
+
* Node builtins only; every fs access and the clock go through `io`.
|
|
23
|
+
*/
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
|
|
26
|
+
/** Same validation as dpi-network.yaml's envMap: UPPER_SNAKE_CASE only. */
|
|
27
|
+
const KEY_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
|
|
28
|
+
|
|
29
|
+
/** Keys with a dedicated setting (config.ts MANAGED_ENV) or that change where the daemon looks. */
|
|
30
|
+
export const READONLY_KEYS: readonly string[] = [
|
|
31
|
+
"DPI_TOKEN",
|
|
32
|
+
"DPI_DEVICE_NAME",
|
|
33
|
+
"DPI_PORT",
|
|
34
|
+
"DPI_HOST",
|
|
35
|
+
"DPI_START_DIRS",
|
|
36
|
+
"DPI_DATA_DIR",
|
|
37
|
+
"DPI_HOME",
|
|
38
|
+
"DPI_ENV_FILE",
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A key that likely holds a credential. Matching is on the NAME, never the
|
|
43
|
+
* value. Bare `PRIVATE` is deliberately absent: `DPI_NOTIFY_ALLOW_PRIVATE=1`
|
|
44
|
+
* is a flag, not a secret.
|
|
45
|
+
*/
|
|
46
|
+
const SECRET_KEY = /TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|_KEY$|PRIVATE_KEY|CREDENTIAL/i;
|
|
47
|
+
|
|
48
|
+
export const MAX_VALUE_LENGTH = 2000;
|
|
49
|
+
|
|
50
|
+
export type EnvErrorCode = "invalid" | "not_found";
|
|
51
|
+
|
|
52
|
+
/** Typed failure so routes can answer 400 (`invalid`) or 404 (`not_found`) without string matching. */
|
|
53
|
+
export class EnvError extends Error {
|
|
54
|
+
readonly code: EnvErrorCode;
|
|
55
|
+
|
|
56
|
+
constructor(code: EnvErrorCode, message: string) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = "EnvError";
|
|
59
|
+
this.code = code;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface EnvVarView {
|
|
64
|
+
key: string;
|
|
65
|
+
/** The value as the UI may show it: masked for secrets, verbatim otherwise. */
|
|
66
|
+
masked: string;
|
|
67
|
+
secret: boolean;
|
|
68
|
+
/** "file" = editable here; "process" = inherited (systemd/shell), read-only. */
|
|
69
|
+
source: "file" | "process";
|
|
70
|
+
/** Managed keys have a dedicated setting; the editor refuses them. */
|
|
71
|
+
managed: boolean;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface EnvFileView {
|
|
75
|
+
envFile: string;
|
|
76
|
+
exists: boolean;
|
|
77
|
+
/** True once a set/unset happened since this process booted — changes apply after restart. */
|
|
78
|
+
restartRequired: boolean;
|
|
79
|
+
vars: EnvVarView[];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface EnvIo {
|
|
83
|
+
readFile(path: string): Promise<string>;
|
|
84
|
+
writeFile(path: string, data: string): Promise<void>;
|
|
85
|
+
chmod(path: string, mode: number): Promise<void>;
|
|
86
|
+
exists(path: string): Promise<boolean>;
|
|
87
|
+
/** Read-only view of the daemon's own environment (default: process.env). */
|
|
88
|
+
processEnv(): Record<string, string | undefined>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export const defaultEnvIo = (): EnvIo => ({
|
|
92
|
+
readFile: async (path) => (await import("node:fs/promises")).readFile(path, "utf8"),
|
|
93
|
+
writeFile: async (path, data) => {
|
|
94
|
+
const fs = await import("node:fs/promises");
|
|
95
|
+
await fs.writeFile(path, data, { mode: 0o600 });
|
|
96
|
+
},
|
|
97
|
+
chmod: async (path, mode) => (await import("node:fs/promises")).chmod(path, mode),
|
|
98
|
+
exists: async (path) =>
|
|
99
|
+
(await import("node:fs/promises"))
|
|
100
|
+
.access(path)
|
|
101
|
+
.then(() => true)
|
|
102
|
+
.catch(() => false),
|
|
103
|
+
processEnv: () => process.env as Record<string, string | undefined>,
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
const invalid = (message: string) => new EnvError("invalid", message);
|
|
107
|
+
|
|
108
|
+
/** `•` + the tail: enough to recognise a saved key, not enough to copy it. */
|
|
109
|
+
export function maskValue(value: string): string {
|
|
110
|
+
if (value.length <= 8) return "•".repeat(Math.max(value.length, 4));
|
|
111
|
+
return `${"•".repeat(8)}${value.slice(-4)}`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const isSecret = (key: string) => SECRET_KEY.test(key);
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Parse `KEY=VALUE` lines; comments/blanks/unparsed lines are preserved but not
|
|
118
|
+
* vars. The empty string after a trailing newline is an artifact of `split`,
|
|
119
|
+
* not a line — drop it so a rewrite does not grow blank lines.
|
|
120
|
+
*/
|
|
121
|
+
function parseLines(text: string): Array<{ key?: string; value?: string; line: string }> {
|
|
122
|
+
if (text === "") return [];
|
|
123
|
+
const raw = text.split("\n");
|
|
124
|
+
if (raw.length > 1 && raw[raw.length - 1] === "") raw.pop();
|
|
125
|
+
return raw.map((line) => {
|
|
126
|
+
const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
|
|
127
|
+
return m ? { key: m[1], value: m[2], line } : { line };
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* One env file. Line-preserving: a rewrite keeps every comment and order
|
|
133
|
+
* intact and only touches the line being set or removed. Writes are atomic in
|
|
134
|
+
* the caller's hands (write the whole new text at once); the mode is forced to
|
|
135
|
+
* 0600 because provider keys live here.
|
|
136
|
+
*/
|
|
137
|
+
export class EnvFileEditor {
|
|
138
|
+
private readonly io: EnvIo;
|
|
139
|
+
readonly path: string;
|
|
140
|
+
private restartRequired = false;
|
|
141
|
+
|
|
142
|
+
constructor(path: string, io: EnvIo = defaultEnvIo()) {
|
|
143
|
+
this.path = path;
|
|
144
|
+
this.io = io;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private async read(): Promise<string> {
|
|
148
|
+
return (await this.io.exists(this.path)) ? await this.io.readFile(this.path) : "";
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Full view: file vars first (editable), then DPI_* process-only vars (read-only). */
|
|
152
|
+
async view(): Promise<EnvFileView> {
|
|
153
|
+
const text = await this.read();
|
|
154
|
+
const seen = new Set<string>();
|
|
155
|
+
const vars: EnvVarView[] = [];
|
|
156
|
+
for (const { key, value } of parseLines(text)) {
|
|
157
|
+
if (!key || value === undefined || seen.has(key)) continue;
|
|
158
|
+
seen.add(key);
|
|
159
|
+
vars.push({
|
|
160
|
+
key,
|
|
161
|
+
masked: isSecret(key) ? maskValue(value) : value,
|
|
162
|
+
secret: isSecret(key),
|
|
163
|
+
source: "file",
|
|
164
|
+
managed: (READONLY_KEYS as readonly string[]).includes(key),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
for (const [key, value] of Object.entries(this.io.processEnv())) {
|
|
168
|
+
if (!key.startsWith("DPI_") || seen.has(key) || value === undefined || value === "") continue;
|
|
169
|
+
seen.add(key);
|
|
170
|
+
vars.push({
|
|
171
|
+
key,
|
|
172
|
+
masked: isSecret(key) ? maskValue(value) : value,
|
|
173
|
+
secret: isSecret(key),
|
|
174
|
+
source: "process",
|
|
175
|
+
managed: (READONLY_KEYS as readonly string[]).includes(key),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
vars.sort((a, b) => a.key.localeCompare(b.key));
|
|
179
|
+
return {
|
|
180
|
+
envFile: this.path,
|
|
181
|
+
exists: await this.io.exists(this.path),
|
|
182
|
+
restartRequired: this.restartRequired,
|
|
183
|
+
vars,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Set one key. Refuses managed/self-referential keys and multi-line values. */
|
|
188
|
+
async set(key: string, value: string): Promise<EnvVarView> {
|
|
189
|
+
if (!KEY_PATTERN.test(key)) throw invalid(`${key}: keys are UPPER_SNAKE_CASE`);
|
|
190
|
+
if ((READONLY_KEYS as readonly string[]).includes(key))
|
|
191
|
+
throw invalid(`${key} has its own setting (port, host, start_dirs, …); change that instead`);
|
|
192
|
+
if (typeof value !== "string" || !value.length) throw invalid("a value is required");
|
|
193
|
+
if (/[\n\r]/.test(value)) throw invalid("the value must be a single line");
|
|
194
|
+
if (value.length > MAX_VALUE_LENGTH) throw invalid(`the value is longer than ${MAX_VALUE_LENGTH} characters`);
|
|
195
|
+
const lines = parseLines(await this.read());
|
|
196
|
+
const next = `${key}=${value}`;
|
|
197
|
+
let replaced = false;
|
|
198
|
+
const out = lines.map((entry) => {
|
|
199
|
+
if (entry.key !== key || replaced) return entry.line;
|
|
200
|
+
replaced = true;
|
|
201
|
+
return next;
|
|
202
|
+
});
|
|
203
|
+
if (!replaced) out.push(next);
|
|
204
|
+
await this.write(out);
|
|
205
|
+
return {
|
|
206
|
+
key,
|
|
207
|
+
masked: isSecret(key) ? maskValue(value) : value,
|
|
208
|
+
secret: isSecret(key),
|
|
209
|
+
source: "file",
|
|
210
|
+
managed: (READONLY_KEYS as readonly string[]).includes(key),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Remove one key's line. Only file-sourced keys can be removed. */
|
|
215
|
+
async unset(key: string): Promise<{ removed: boolean }> {
|
|
216
|
+
const lines = parseLines(await this.read());
|
|
217
|
+
const kept = lines.filter((entry) => entry.key !== key);
|
|
218
|
+
if (kept.length === lines.length) return { removed: false };
|
|
219
|
+
await this.write(kept.map((entry) => entry.line));
|
|
220
|
+
return { removed: true };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private async write(lines: string[]): Promise<void> {
|
|
224
|
+
const text = lines.filter((line) => line !== "").length ? `${lines.join("\n").replace(/\n+$/, "")}\n` : "";
|
|
225
|
+
await this.io.writeFile(this.path, text);
|
|
226
|
+
await this.io.chmod(this.path, 0o600).catch(() => {});
|
|
227
|
+
this.restartRequired = true;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Default env-file path for a home dir (mirrors config.ts's fallback). */
|
|
232
|
+
export function envFileForHome(home: string): string {
|
|
233
|
+
return join(home, "backend.env");
|
|
234
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `dpi notify` — outbound notification sinks (webhook / ntfy) from the CLI.
|
|
3
|
+
*
|
|
4
|
+
* Same shape as `dpi schedule`: the CLI edits the device's own records over its
|
|
5
|
+
* local API, so a running daemon picks changes up immediately.
|
|
6
|
+
*/
|
|
7
|
+
import { authHeaders, deviceEndpoint, defaultDoctorIo } from "./doctor.js";
|
|
8
|
+
import type { ScheduleIo } from "./schedule-cli.js";
|
|
9
|
+
|
|
10
|
+
export interface SinkView {
|
|
11
|
+
id: string;
|
|
12
|
+
kind: "webhook" | "ntfy";
|
|
13
|
+
url: string;
|
|
14
|
+
enabled: boolean;
|
|
15
|
+
events?: string[];
|
|
16
|
+
label?: string;
|
|
17
|
+
lastDeliveryAt?: number;
|
|
18
|
+
lastError?: string;
|
|
19
|
+
lastStatus?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface Delivery {
|
|
23
|
+
id: string;
|
|
24
|
+
kind: string;
|
|
25
|
+
status: "sent" | "skipped" | "failed";
|
|
26
|
+
detail?: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const NOTIFY_HELP = `dpi notify — outbound notifications (webhook / ntfy)
|
|
30
|
+
|
|
31
|
+
dpi notify list
|
|
32
|
+
dpi notify add --kind webhook|ntfy --url <url> [--events a,b|schedule.*] [--label <text>]
|
|
33
|
+
[--priority min|low|default|high|max] [--tags a,b] [--disabled]
|
|
34
|
+
dpi notify enable|disable <id-prefix>
|
|
35
|
+
dpi notify remove <id-prefix>
|
|
36
|
+
dpi notify test
|
|
37
|
+
dpi notify events
|
|
38
|
+
The event kinds this device emits today.
|
|
39
|
+
|
|
40
|
+
LAN sinks (http://192.168.x.x, http://localhost) are refused by default:
|
|
41
|
+
start the device with DPI_NOTIFY_ALLOW_PRIVATE=1 to allow them.`;
|
|
42
|
+
|
|
43
|
+
export const EMITTED_EVENTS = ["session.failed", "schedule.ok", "schedule.failed", "test"] as const;
|
|
44
|
+
|
|
45
|
+
export const defaultNotifyIo = (): ScheduleIo => ({
|
|
46
|
+
...defaultDoctorIo(),
|
|
47
|
+
print: (line) => process.stdout.write(`${line}\n`),
|
|
48
|
+
printErr: (line) => process.stderr.write(`${line}\n`),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const flag = (argv: readonly string[], name: string): string | undefined => {
|
|
52
|
+
const i = argv.indexOf(name);
|
|
53
|
+
return i >= 0 ? argv[i + 1] : undefined;
|
|
54
|
+
};
|
|
55
|
+
const positional = (argv: readonly string[]): string[] =>
|
|
56
|
+
argv.filter((arg, i) => !arg.startsWith("--") && !(i > 0 && argv[i - 1]?.startsWith("--")));
|
|
57
|
+
|
|
58
|
+
async function call<T>(
|
|
59
|
+
io: ScheduleIo,
|
|
60
|
+
method: string,
|
|
61
|
+
path: string,
|
|
62
|
+
body?: unknown,
|
|
63
|
+
): Promise<{ ok: true; data: T } | { ok: false; error: string }> {
|
|
64
|
+
const cfg = deviceEndpoint(io);
|
|
65
|
+
if (!cfg.token) return { ok: false, error: `no DPI_TOKEN (looked in ${cfg.envFile})` };
|
|
66
|
+
try {
|
|
67
|
+
const res = await io.fetchImpl(`${cfg.baseUrl}${path}`, {
|
|
68
|
+
method,
|
|
69
|
+
headers: {
|
|
70
|
+
...authHeaders(cfg.token),
|
|
71
|
+
...(body === undefined ? {} : { "content-type": "application/json" }),
|
|
72
|
+
},
|
|
73
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
74
|
+
signal: AbortSignal.timeout(io.timeoutMs),
|
|
75
|
+
});
|
|
76
|
+
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
|
77
|
+
if (!res.ok) return { ok: false, error: `${res.status} ${(data.error as { message?: string })?.message ?? ""}`.trim() };
|
|
78
|
+
return { ok: true, data: data as T };
|
|
79
|
+
} catch (e) {
|
|
80
|
+
return { ok: false, error: e instanceof Error ? e.message : String(e) };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const ago = (at?: number): string => {
|
|
85
|
+
if (!at) return "never";
|
|
86
|
+
const mins = Math.round((Date.now() - at) / 60_000);
|
|
87
|
+
return mins < 1 ? "just now" : mins < 60 ? `${mins}m ago` : `${Math.round(mins / 60)}h ago`;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
export function formatSinks(list: readonly SinkView[]): string[] {
|
|
91
|
+
if (!list.length) return ["no sinks. Add one with `dpi notify add --url <url> --kind webhook|ntfy`."];
|
|
92
|
+
return list.map((s) => {
|
|
93
|
+
const filters = s.events?.length ? s.events.join(",") : "all events";
|
|
94
|
+
const last = s.lastError ? `last failed: ${s.lastError.slice(0, 60)}` : `last sent ${ago(s.lastDeliveryAt)}`;
|
|
95
|
+
return `${s.id.slice(0, 8)} ${s.kind} ${s.enabled ? "" : "(disabled) "}${s.label ?? ""}\n ${s.url}\n ${filters} · ${last}`;
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function matchSink(list: readonly SinkView[], prefix: string): SinkView[] {
|
|
100
|
+
const needle = prefix.toLowerCase();
|
|
101
|
+
return list.filter((s) => s.id.toLowerCase().startsWith(needle));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function formatResults(results: readonly Delivery[]): string[] {
|
|
105
|
+
if (!results.length) return ["no enabled sinks matched — nothing was sent."];
|
|
106
|
+
return results.map((r) => {
|
|
107
|
+
const tail = r.detail ? ` — ${r.detail}` : "";
|
|
108
|
+
return `${r.status.padEnd(7)} ${r.kind} ${r.id.slice(0, 8)}${tail}`;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function notifyCli(argv: readonly string[], io: ScheduleIo = defaultNotifyIo()): Promise<number> {
|
|
113
|
+
const [sub, ...rest] = argv;
|
|
114
|
+
if (sub === "--help" || sub === "-h") {
|
|
115
|
+
io.print(NOTIFY_HELP);
|
|
116
|
+
return 0;
|
|
117
|
+
}
|
|
118
|
+
if (sub === "events") {
|
|
119
|
+
io.print(`events this device emits: ${EMITTED_EVENTS.join(", ")}`);
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
if (!sub || sub === "list") {
|
|
123
|
+
const listed = await call<{ sinks: SinkView[] }>(io, "GET", "/v1/notify/sinks");
|
|
124
|
+
if (!listed.ok) {
|
|
125
|
+
io.printErr(`dpi notify: ${listed.error}`);
|
|
126
|
+
return 1;
|
|
127
|
+
}
|
|
128
|
+
for (const line of formatSinks(listed.data.sinks ?? [])) io.print(line);
|
|
129
|
+
return 0;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (sub === "test") {
|
|
133
|
+
const sent = await call<{ results: Delivery[] }>(io, "POST", "/v1/notify/test", {});
|
|
134
|
+
if (!sent.ok) {
|
|
135
|
+
io.printErr(`dpi notify: ${sent.error}`);
|
|
136
|
+
return 1;
|
|
137
|
+
}
|
|
138
|
+
for (const line of formatResults(sent.data.results ?? [])) io.print(line);
|
|
139
|
+
return (sent.data.results ?? []).some((r) => r.status === "failed") ? 1 : 0;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (sub === "add") {
|
|
143
|
+
const kind = flag(rest, "--kind") ?? "webhook";
|
|
144
|
+
const url = flag(rest, "--url");
|
|
145
|
+
if (!url || (kind !== "webhook" && kind !== "ntfy")) {
|
|
146
|
+
io.printErr(`dpi notify add: --url is required and --kind is webhook|ntfy\n\n${NOTIFY_HELP}`);
|
|
147
|
+
return 2;
|
|
148
|
+
}
|
|
149
|
+
const events = flag(rest, "--events");
|
|
150
|
+
const tags = flag(rest, "--tags");
|
|
151
|
+
const body = {
|
|
152
|
+
kind,
|
|
153
|
+
url,
|
|
154
|
+
...(flag(rest, "--label") ? { label: flag(rest, "--label") } : {}),
|
|
155
|
+
...(events ? { events: events.split(",").map((e) => e.trim()).filter(Boolean) } : {}),
|
|
156
|
+
...(flag(rest, "--priority") ? { priority: flag(rest, "--priority") } : {}),
|
|
157
|
+
...(tags ? { tags: tags.split(",").map((t) => t.trim()).filter(Boolean) } : {}),
|
|
158
|
+
...(rest.includes("--disabled") ? { enabled: false } : {}),
|
|
159
|
+
};
|
|
160
|
+
const created = await call<SinkView>(io, "POST", "/v1/notify/sinks", body);
|
|
161
|
+
if (!created.ok) {
|
|
162
|
+
io.printErr(`dpi notify: ${created.error}`);
|
|
163
|
+
return 1;
|
|
164
|
+
}
|
|
165
|
+
io.print(`created ${created.data.id.slice(0, 8)} — ${created.data.kind} ${created.data.url}`);
|
|
166
|
+
return 0;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const prefix = positional(rest)[0];
|
|
170
|
+
if (!prefix) {
|
|
171
|
+
io.printErr(`dpi notify ${sub}: an id prefix is required\n\n${NOTIFY_HELP}`);
|
|
172
|
+
return 2;
|
|
173
|
+
}
|
|
174
|
+
const listed = await call<{ sinks: SinkView[] }>(io, "GET", "/v1/notify/sinks");
|
|
175
|
+
if (!listed.ok) {
|
|
176
|
+
io.printErr(`dpi notify: ${listed.error}`);
|
|
177
|
+
return 1;
|
|
178
|
+
}
|
|
179
|
+
const matches = matchSink(listed.data.sinks ?? [], prefix);
|
|
180
|
+
if (!matches.length) {
|
|
181
|
+
io.printErr(`dpi notify: no sink starts with '${prefix}'`);
|
|
182
|
+
return 1;
|
|
183
|
+
}
|
|
184
|
+
if (matches.length > 1) {
|
|
185
|
+
io.printErr(`dpi notify: '${prefix}' matches ${matches.length} sinks — be more specific:`);
|
|
186
|
+
for (const m of matches) io.printErr(` ${m.id.slice(0, 8)} ${m.kind} ${m.url}`);
|
|
187
|
+
return 2;
|
|
188
|
+
}
|
|
189
|
+
const target = matches[0];
|
|
190
|
+
|
|
191
|
+
if (sub === "enable" || sub === "disable") {
|
|
192
|
+
const patched = await call<SinkView>(io, "PATCH", `/v1/notify/sinks/${target.id}`, { enabled: sub === "enable" });
|
|
193
|
+
if (!patched.ok) {
|
|
194
|
+
io.printErr(`dpi notify: ${patched.error}`);
|
|
195
|
+
return 1;
|
|
196
|
+
}
|
|
197
|
+
io.print(`${sub}d ${target.id.slice(0, 8)} — ${target.kind} ${target.url}`);
|
|
198
|
+
return 0;
|
|
199
|
+
}
|
|
200
|
+
if (sub === "remove") {
|
|
201
|
+
const removed = await call<{ removed: boolean }>(io, "DELETE", `/v1/notify/sinks/${target.id}`);
|
|
202
|
+
if (!removed.ok) {
|
|
203
|
+
io.printErr(`dpi notify: ${removed.error}`);
|
|
204
|
+
return 1;
|
|
205
|
+
}
|
|
206
|
+
io.print(`removed ${target.id.slice(0, 8)} — ${target.url}`);
|
|
207
|
+
return 0;
|
|
208
|
+
}
|
|
209
|
+
io.printErr(`dpi notify: unknown subcommand '${sub}'\n\n${NOTIFY_HELP}`);
|
|
210
|
+
return 2;
|
|
211
|
+
}
|