@adtl/gateway 0.1.1 → 0.2.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 +36 -3
- package/dist/approvals.d.ts +97 -0
- package/dist/approvals.d.ts.map +1 -0
- package/dist/approvals.js +151 -0
- package/dist/approvals.js.map +1 -0
- package/dist/audit.d.ts +7 -0
- package/dist/audit.d.ts.map +1 -1
- package/dist/audit.js.map +1 -1
- package/dist/config.d.ts +346 -4
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +63 -2
- package/dist/config.js.map +1 -1
- package/dist/email.d.ts +35 -0
- package/dist/email.d.ts.map +1 -0
- package/dist/email.js +63 -0
- package/dist/email.js.map +1 -0
- package/dist/gateway.d.ts +12 -2
- package/dist/gateway.d.ts.map +1 -1
- package/dist/gateway.js +75 -10
- package/dist/gateway.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/invoker.d.ts.map +1 -1
- package/dist/invoker.js +4 -2
- package/dist/invoker.js.map +1 -1
- package/dist/ntfy.d.ts +44 -0
- package/dist/ntfy.d.ts.map +1 -0
- package/dist/ntfy.js +133 -0
- package/dist/ntfy.js.map +1 -0
- package/dist/startup.d.ts +3 -0
- package/dist/startup.d.ts.map +1 -1
- package/dist/startup.js +34 -2
- package/dist/startup.js.map +1 -1
- package/package.json +4 -3
- package/src/approvals.ts +219 -0
- package/src/audit.ts +2 -0
- package/src/config.ts +65 -2
- package/src/email.ts +79 -0
- package/src/gateway.ts +87 -10
- package/src/index.ts +3 -0
- package/src/invoker.ts +3 -2
- package/src/ntfy.ts +154 -0
- package/src/startup.ts +32 -1
package/src/invoker.ts
CHANGED
|
@@ -174,10 +174,11 @@ export class InterceptorInvoker {
|
|
|
174
174
|
const r = s.value as ValidationResult;
|
|
175
175
|
out.results.push(r);
|
|
176
176
|
if (r.valid || r.severity !== "error" || this.isAudit(i)) return;
|
|
177
|
-
|
|
177
|
+
// Keep the strictest rejection, so an "ask" never hides another validator's "block".
|
|
178
|
+
if (!out.blocked || out.blocked.decision === "ask") {
|
|
178
179
|
const decision = (r.info?.[DECISION_INFO_KEY] as Decision | undefined) ?? "block";
|
|
179
180
|
const reason = r.messages?.map((m) => m.message).join("; ") || `${i.definition.name} rejected the call`;
|
|
180
|
-
out.blocked = { interceptor: i.definition.name, decision, reason };
|
|
181
|
+
if (!out.blocked || decision === "block") out.blocked = { interceptor: i.definition.name, decision, reason };
|
|
181
182
|
}
|
|
182
183
|
ok = false;
|
|
183
184
|
});
|
package/src/ntfy.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ntfy (https://ntfy.sh) push notifications with Allow / Deny buttons.
|
|
3
|
+
*
|
|
4
|
+
* The buttons make the phone POST a signed answer token to a reply topic on
|
|
5
|
+
* the same ntfy server, and the gateway subscribes to that topic. So answers
|
|
6
|
+
* reach the gateway without it ever accepting inbound connections.
|
|
7
|
+
*
|
|
8
|
+
* Messages name the tool, server and reason, never arguments or results.
|
|
9
|
+
* Anyone who can read the topic can press the buttons, so use a long random
|
|
10
|
+
* topic name or an access-controlled topic on your own server.
|
|
11
|
+
*/
|
|
12
|
+
import type { AnswerFn, ApprovalEvent, ApprovalRequest, Notifier } from "./approvals.js";
|
|
13
|
+
|
|
14
|
+
export interface NtfyOptions {
|
|
15
|
+
/** Server base URL, e.g. https://ntfy.sh */
|
|
16
|
+
server: string;
|
|
17
|
+
topic: string;
|
|
18
|
+
/** Topic answers are posted to. Default: `<topic>-reply`. */
|
|
19
|
+
replyTopic?: string;
|
|
20
|
+
/** Access token for protected topics. */
|
|
21
|
+
token?: string;
|
|
22
|
+
fetch?: typeof fetch;
|
|
23
|
+
/** Delay before re-subscribing after the stream drops, and the base delay between publish retries. */
|
|
24
|
+
reconnectMs?: number;
|
|
25
|
+
/** Publish attempts before giving up (network errors, 429 and 5xx are retried). */
|
|
26
|
+
publishAttempts?: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function describe(request: ApprovalRequest): string {
|
|
30
|
+
const secs = Math.max(0, Math.round((request.expiresAt.getTime() - request.createdAt.getTime()) / 1000));
|
|
31
|
+
return `${request.reason}\n\nRule: ${request.matched.join(", ") || "default"}\nExpires in ${secs}s; no answer means deny.`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class NtfyNotifier implements Notifier {
|
|
35
|
+
readonly name = "ntfy";
|
|
36
|
+
private readonly server: string;
|
|
37
|
+
private readonly topic: string;
|
|
38
|
+
private readonly replyTopic: string;
|
|
39
|
+
private readonly token: string | undefined;
|
|
40
|
+
private readonly fetch: typeof fetch;
|
|
41
|
+
private readonly reconnectMs: number;
|
|
42
|
+
private readonly publishAttempts: number;
|
|
43
|
+
|
|
44
|
+
constructor(opts: NtfyOptions) {
|
|
45
|
+
this.server = opts.server.replace(/\/+$/, "");
|
|
46
|
+
this.topic = opts.topic;
|
|
47
|
+
this.replyTopic = opts.replyTopic ?? `${opts.topic}-reply`;
|
|
48
|
+
this.token = opts.token;
|
|
49
|
+
this.fetch = opts.fetch ?? globalThis.fetch;
|
|
50
|
+
this.reconnectMs = opts.reconnectMs ?? 1000;
|
|
51
|
+
this.publishAttempts = opts.publishAttempts ?? 3;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private get auth(): Record<string, string> {
|
|
55
|
+
return this.token ? { Authorization: `Bearer ${this.token}` } : {};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async notify(event: ApprovalEvent): Promise<void> {
|
|
59
|
+
if (event.kind === "blocked") return; // push is for decisions; email covers blocked notices
|
|
60
|
+
const { request } = event;
|
|
61
|
+
const subject = `${request.server}.${request.tool}`;
|
|
62
|
+
let message: Record<string, unknown>;
|
|
63
|
+
if (event.kind === "pending") {
|
|
64
|
+
const reply = `${this.server}/${encodeURIComponent(this.replyTopic)}`;
|
|
65
|
+
const button = (label: string, body: string) => ({
|
|
66
|
+
action: "http",
|
|
67
|
+
label,
|
|
68
|
+
url: reply,
|
|
69
|
+
method: "POST",
|
|
70
|
+
body,
|
|
71
|
+
clear: true,
|
|
72
|
+
...(this.token ? { headers: this.auth } : {}),
|
|
73
|
+
});
|
|
74
|
+
message = {
|
|
75
|
+
title: `ADTL: allow ${subject}?`,
|
|
76
|
+
message: describe(request),
|
|
77
|
+
priority: 4,
|
|
78
|
+
tags: ["warning"],
|
|
79
|
+
actions: [button("Allow", event.tokens.allow), button("Deny", event.tokens.deny)],
|
|
80
|
+
};
|
|
81
|
+
} else {
|
|
82
|
+
message = {
|
|
83
|
+
title: `ADTL: ${subject} ${event.result.outcome}`,
|
|
84
|
+
message: `Approval ${event.result.outcome} after ${Math.round(event.result.waitedMs / 1000)}s.`,
|
|
85
|
+
priority: 2,
|
|
86
|
+
tags: [event.result.outcome === "approved" ? "white_check_mark" : "x"],
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
await this.publish(JSON.stringify({ topic: this.topic, ...message }));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** POST with retries: flaky networks should not turn an approval request into a denial. */
|
|
93
|
+
private async publish(body: string): Promise<void> {
|
|
94
|
+
for (let attempt = 1; ; attempt++) {
|
|
95
|
+
let res: Response | undefined;
|
|
96
|
+
try {
|
|
97
|
+
res = await this.fetch(this.server, { method: "POST", headers: { "Content-Type": "application/json", ...this.auth }, body });
|
|
98
|
+
} catch (err) {
|
|
99
|
+
if (attempt >= this.publishAttempts) throw err;
|
|
100
|
+
}
|
|
101
|
+
if (res?.ok) return;
|
|
102
|
+
if (res && ((res.status !== 429 && res.status < 500) || attempt >= this.publishAttempts)) {
|
|
103
|
+
throw new Error(`ntfy publish failed: HTTP ${res.status}`);
|
|
104
|
+
}
|
|
105
|
+
await new Promise((r) => setTimeout(r, this.reconnectMs * attempt));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async listen(request: ApprovalRequest, answer: AnswerFn, signal: AbortSignal): Promise<void> {
|
|
110
|
+
// `since` replays anything posted after the request was created, so a fast
|
|
111
|
+
// answer is not lost while (re)connecting.
|
|
112
|
+
const since = Math.floor(request.createdAt.getTime() / 1000) - 1;
|
|
113
|
+
const url = `${this.server}/${encodeURIComponent(this.replyTopic)}/json?since=${since}`;
|
|
114
|
+
while (!signal.aborted) {
|
|
115
|
+
try {
|
|
116
|
+
const res = await this.fetch(url, { headers: this.auth, signal });
|
|
117
|
+
if (!res.ok || !res.body) throw new Error(`ntfy subscribe failed: HTTP ${res.status}`);
|
|
118
|
+
await this.read(res.body, answer, signal);
|
|
119
|
+
} catch (err) {
|
|
120
|
+
if (signal.aborted) return;
|
|
121
|
+
if ((err as Error).message.includes("HTTP 401") || (err as Error).message.includes("HTTP 403")) throw err;
|
|
122
|
+
}
|
|
123
|
+
if (!signal.aborted) await sleep(this.reconnectMs, signal);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private async read(body: ReadableStream<Uint8Array>, answer: AnswerFn, signal: AbortSignal): Promise<void> {
|
|
128
|
+
const decoder = new TextDecoder();
|
|
129
|
+
let buf = "";
|
|
130
|
+
for await (const chunk of body as unknown as AsyncIterable<Uint8Array>) {
|
|
131
|
+
if (signal.aborted) return;
|
|
132
|
+
buf += decoder.decode(chunk, { stream: true });
|
|
133
|
+
let nl: number;
|
|
134
|
+
while ((nl = buf.indexOf("\n")) >= 0) {
|
|
135
|
+
const line = buf.slice(0, nl).trim();
|
|
136
|
+
buf = buf.slice(nl + 1);
|
|
137
|
+
if (!line) continue;
|
|
138
|
+
try {
|
|
139
|
+
const msg = JSON.parse(line) as { event?: string; message?: string };
|
|
140
|
+
if (msg.event === "message" && typeof msg.message === "string") answer(msg.message);
|
|
141
|
+
} catch {
|
|
142
|
+
// Not JSON: ignore.
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
150
|
+
return new Promise((resolve) => {
|
|
151
|
+
const t = setTimeout(resolve, ms);
|
|
152
|
+
signal.addEventListener("abort", () => (clearTimeout(t), resolve()), { once: true });
|
|
153
|
+
});
|
|
154
|
+
}
|
package/src/startup.ts
CHANGED
|
@@ -12,17 +12,21 @@ import { INTERCEPTORS_EXTENSION, LABEL_INTERCEPTOR, POLICY_INTERCEPTOR, parseCon
|
|
|
12
12
|
import type { AdtlConfig } from "@adtl/labels";
|
|
13
13
|
import { parse as parseYaml } from "yaml";
|
|
14
14
|
import { ZodError } from "zod";
|
|
15
|
+
import { ApprovalBroker, type Notifier } from "./approvals.js";
|
|
15
16
|
import { JsonlAuditLog } from "./audit.js";
|
|
16
17
|
import {
|
|
17
18
|
GatewayConfigSchema,
|
|
19
|
+
expandApprovals,
|
|
18
20
|
expandUpstream,
|
|
19
21
|
isHttpUpstream,
|
|
20
22
|
type GatewayConfig,
|
|
21
23
|
type StdioUpstream,
|
|
22
24
|
type Upstream,
|
|
23
25
|
} from "./config.js";
|
|
26
|
+
import { EmailNotifier } from "./email.js";
|
|
24
27
|
import { AdtlGateway, GATEWAY_VERSION, type GatewayLogger } from "./gateway.js";
|
|
25
28
|
import { InterceptorInvoker } from "./invoker.js";
|
|
29
|
+
import { NtfyNotifier } from "./ntfy.js";
|
|
26
30
|
|
|
27
31
|
export class GatewayConfigError extends Error {
|
|
28
32
|
constructor(message: string) {
|
|
@@ -93,6 +97,26 @@ async function connect(id: string, u: Upstream, baseDir: string): Promise<Client
|
|
|
93
97
|
return client;
|
|
94
98
|
}
|
|
95
99
|
|
|
100
|
+
/** Build the approval broker from `gateway.approvals`, or undefined if not configured. */
|
|
101
|
+
export function createApprovals(cfg: GatewayConfig, env: NodeJS.ProcessEnv, log: GatewayLogger): ApprovalBroker | undefined {
|
|
102
|
+
if (!cfg.approvals) return undefined;
|
|
103
|
+
const a = expandApprovals(cfg.approvals, env);
|
|
104
|
+
const notifiers: Notifier[] = [];
|
|
105
|
+
if (a.ntfy) {
|
|
106
|
+
if (/^https:\/\/ntfy\.sh\/?$/.test(a.ntfy.server) && a.ntfy.topic.length < 20 && !a.ntfy.token) {
|
|
107
|
+
log.warn("gateway.approvals.ntfy.topic is short and on the public ntfy.sh server: anyone who guesses it can approve calls. Use a long random topic.");
|
|
108
|
+
}
|
|
109
|
+
notifiers.push(new NtfyNotifier(a.ntfy));
|
|
110
|
+
}
|
|
111
|
+
if (a.email) {
|
|
112
|
+
notifiers.push(new EmailNotifier({ smtp: a.email.smtp, from: a.email.from, to: [a.email.to].flat(), on: a.email.on }));
|
|
113
|
+
}
|
|
114
|
+
if (notifiers.length === 0) return undefined;
|
|
115
|
+
if (!notifiers.some((n) => n.listen)) log.warn('no approval channel can carry answers (configure gateway.approvals.ntfy); "ask" still blocks');
|
|
116
|
+
log.info(`approvals: ${notifiers.map((n) => n.name).join(", ")} (timeout ${a.timeoutSeconds}s)`);
|
|
117
|
+
return new ApprovalBroker({ notifiers, timeoutMs: a.timeoutSeconds * 1000, log });
|
|
118
|
+
}
|
|
119
|
+
|
|
96
120
|
export interface StartedGateway {
|
|
97
121
|
gateway: AdtlGateway;
|
|
98
122
|
close(): Promise<void>;
|
|
@@ -152,7 +176,14 @@ export async function startGateway(
|
|
|
152
176
|
log.info(`upstreams: ${[...upstreams.keys()].join(", ")}`);
|
|
153
177
|
|
|
154
178
|
const auditLog = loaded.gateway.audit ? new JsonlAuditLog(resolve(baseDir, loaded.gateway.audit)) : undefined;
|
|
155
|
-
const
|
|
179
|
+
const approvals = createApprovals(loaded.gateway, env, log);
|
|
180
|
+
const gateway = new AdtlGateway({
|
|
181
|
+
upstreams,
|
|
182
|
+
invoker,
|
|
183
|
+
...(auditLog ? { audit: auditLog } : {}),
|
|
184
|
+
...(approvals ? { approvals } : {}),
|
|
185
|
+
logger: log,
|
|
186
|
+
});
|
|
156
187
|
return { gateway, close: closeAll };
|
|
157
188
|
} catch (err) {
|
|
158
189
|
await closeAll();
|