- KNOWN_SECRET_KEYS now covers LLM, embedding, and Phoenix API keys - Logger redaction paths extended to cover the new credential keys - nats-skill-acl maps each skill to allowed publish/subscribe subjects - NATS publish runs ACL check with log-only/enforce/off modes
197 lines
5.0 KiB
TypeScript
197 lines
5.0 KiB
TypeScript
import {
|
|
type Msg,
|
|
type NatsConnection,
|
|
StringCodec,
|
|
connect,
|
|
type Subscription,
|
|
} from "nats";
|
|
import { getSecret } from "@common/secret-manager";
|
|
import { getNatsAclMode } from "../config.js";
|
|
import { getContext } from "../observability/context.js";
|
|
import { getLogger } from "@obs/logger";
|
|
import {
|
|
checkPublishAllowed,
|
|
checkSubscribeAllowed,
|
|
} from "./nats-skill-acl.js";
|
|
|
|
export interface NatsMessageContext<T = unknown> {
|
|
data: T;
|
|
raw: Msg;
|
|
reply: string | undefined;
|
|
subject: string;
|
|
subscriptionSubject: string;
|
|
}
|
|
|
|
export class NatsClient {
|
|
private client: NatsConnection | null = null;
|
|
private readonly stringCodec = StringCodec();
|
|
private readonly logger = getLogger();
|
|
|
|
private getConnection(): NatsConnection {
|
|
if (!this.client) {
|
|
throw new Error("NATS client not connected");
|
|
}
|
|
|
|
return this.client;
|
|
}
|
|
|
|
private decodeMessage<T>(msg: Msg): T {
|
|
return JSON.parse(this.stringCodec.decode(msg.data)) as T;
|
|
}
|
|
|
|
async connect(): Promise<void> {
|
|
const endpoint = getSecret("NATS_ENDPOINT");
|
|
const user = getSecret("NATS_USER");
|
|
const password = getSecret("NATS_PASS");
|
|
|
|
if (!endpoint || !user || !password) {
|
|
throw new Error("Missing NATS credentials in secrets");
|
|
}
|
|
|
|
this.client = await connect({
|
|
name: process.env["SERVICE_NAME"] || "lolympus-agent",
|
|
servers: [endpoint],
|
|
tls: {},
|
|
maxReconnectAttempts: -1,
|
|
reconnectTimeWait: 500,
|
|
reconnect: true,
|
|
pingInterval: 20000,
|
|
timeout: 5000,
|
|
user: user,
|
|
pass: password,
|
|
});
|
|
|
|
this.logger.info("✓ NATS connected");
|
|
}
|
|
|
|
async subscribe<T = unknown>(
|
|
subject: string,
|
|
handler: (
|
|
data: T,
|
|
context: NatsMessageContext<T>,
|
|
) => void | Promise<void>,
|
|
): Promise<Subscription> {
|
|
return this.subscribeRaw(subject, async (msg) => {
|
|
const data = this.decodeMessage<T>(msg);
|
|
await handler(data, {
|
|
data,
|
|
raw: msg,
|
|
reply: msg.reply || undefined,
|
|
subject: msg.subject,
|
|
subscriptionSubject: subject,
|
|
});
|
|
});
|
|
}
|
|
|
|
subscribeRaw(
|
|
subject: string,
|
|
handler: (msg: Msg) => void | Promise<void>,
|
|
): Promise<Subscription> {
|
|
this.checkSubjectAcl("subscribe", subject);
|
|
const subscription = this.getConnection().subscribe(subject);
|
|
|
|
void (async () => {
|
|
for await (const msg of subscription) {
|
|
try {
|
|
await handler(msg);
|
|
} catch (error) {
|
|
this.logger.error(
|
|
{ err: error, subject: msg.subject },
|
|
"[NATS] Error processing message",
|
|
);
|
|
}
|
|
}
|
|
})();
|
|
|
|
this.logger.info({ subject }, "✓ Subscribed to subject");
|
|
return Promise.resolve(subscription);
|
|
}
|
|
|
|
async publish<T = unknown>(subject: string, data: T): Promise<void> {
|
|
this.checkSubjectAcl("publish", subject);
|
|
const client = this.getConnection();
|
|
client.publish(subject, this.stringCodec.encode(JSON.stringify(data)));
|
|
await client.flush();
|
|
}
|
|
|
|
async request<TRequest = unknown, TResponse = unknown>(
|
|
subject: string,
|
|
data: TRequest,
|
|
options?: { timeoutMs?: number | undefined },
|
|
): Promise<TResponse> {
|
|
this.checkSubjectAcl("publish", subject);
|
|
const requestOptions =
|
|
options?.timeoutMs !== undefined
|
|
? {
|
|
timeout: options.timeoutMs,
|
|
}
|
|
: undefined;
|
|
const response = await this.getConnection().request(
|
|
subject,
|
|
this.stringCodec.encode(JSON.stringify(data)),
|
|
requestOptions,
|
|
);
|
|
|
|
return this.decodeMessage<TResponse>(response);
|
|
}
|
|
|
|
private checkSubjectAcl(
|
|
operation: "publish" | "subscribe",
|
|
subject: string,
|
|
): void {
|
|
const mode = getNatsAclMode();
|
|
if (mode === "off") {
|
|
return;
|
|
}
|
|
const skill = getContext()?.skill;
|
|
if (!skill) {
|
|
return;
|
|
}
|
|
const allowed =
|
|
operation === "publish"
|
|
? checkPublishAllowed(skill, subject)
|
|
: checkSubscribeAllowed(skill, subject);
|
|
if (allowed) {
|
|
return;
|
|
}
|
|
|
|
const payload = { mode, operation, skill, subject };
|
|
if (mode === "enforce") {
|
|
this.logger.error(payload, "[NATS ACL] Subject denied");
|
|
throw new Error(
|
|
`NATS ${operation} denied for skill ${skill} on subject ${subject}`,
|
|
);
|
|
}
|
|
this.logger.warn(payload, "[NATS ACL] Subject would be denied");
|
|
}
|
|
|
|
respond(msg: Msg, data: unknown): Promise<void> {
|
|
if (!msg.reply) {
|
|
this.logger.warn(
|
|
{ subject: msg.subject },
|
|
"[NATS] Cannot respond: no reply subject",
|
|
);
|
|
return Promise.resolve();
|
|
}
|
|
msg.respond(this.stringCodec.encode(JSON.stringify(data)));
|
|
return Promise.resolve();
|
|
}
|
|
|
|
async close(): Promise<void> {
|
|
if (!this.client) return;
|
|
|
|
try {
|
|
const closed = this.client.closed();
|
|
await this.client.drain();
|
|
const err = await closed;
|
|
if (err) {
|
|
this.logger.error({ err }, "[NATS] Closed with error");
|
|
}
|
|
} catch {
|
|
try {
|
|
await this.client.close();
|
|
} catch {}
|
|
}
|
|
}
|
|
}
|