@jdcpuwiz/zoo-kit 1.0.1 → 1.1.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.
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The one failover loop every module uses.
3
+ *
4
+ * Rules (zoo-kit plan §4, contracts/README "Failover-ready by construction"):
5
+ * - a service is a LIST of base URLs, tried in LIST ORDER — primary first,
6
+ * never rotated, so behaviour is predictable;
7
+ * - move to the next URL ONLY on a network error, a timeout or a 5xx;
8
+ * - a 4xx is the caller's bug (or a real "no") and is returned at once —
9
+ * asking a second instance the same wrong question gets the same answer;
10
+ * - every attempt has its own timeout and the whole call a total budget, so
11
+ * a black-holed host can never hang the caller.
12
+ */
13
+ export interface FailoverOptions {
14
+ /** Per-attempt timeout. */
15
+ attemptTimeoutMs?: number;
16
+ /** Hard ceiling across every attempt, waits included. */
17
+ totalBudgetMs?: number;
18
+ /** Passes over the URL list (1 = each URL once). */
19
+ rounds?: number;
20
+ /** Pause between passes, bounded by the remaining budget. */
21
+ roundBackoffMs?: number;
22
+ }
23
+ export interface Attempt {
24
+ url: string;
25
+ /** HTTP status, or null when no answer arrived. */
26
+ status: number | null;
27
+ error?: string;
28
+ ms: number;
29
+ }
30
+ export type FailoverOutcome = {
31
+ kind: "response";
32
+ res: Response;
33
+ url: string;
34
+ base: string;
35
+ attempts: Attempt[];
36
+ } | {
37
+ kind: "failed";
38
+ error: string;
39
+ status: number | null;
40
+ attempts: Attempt[];
41
+ };
42
+ export declare const DEFAULT_FAILOVER: Required<FailoverOptions>;
43
+ /**
44
+ * Try `path` against each base URL until one answers below 500.
45
+ * The body in `init` must be replayable (a string or bytes) — a stream cannot
46
+ * be sent twice.
47
+ */
48
+ export declare function failoverFetch(urls: readonly string[], path: string, init: RequestInit, opts?: FailoverOptions): Promise<FailoverOutcome>;
49
+ export declare function stripUndefined<T extends object>(o: T): Partial<T>;
50
+ /** Parse a JSON body; `undefined` when it is not JSON. */
51
+ export declare function readJson(res: Response): Promise<unknown>;
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ /**
3
+ * The one failover loop every module uses.
4
+ *
5
+ * Rules (zoo-kit plan §4, contracts/README "Failover-ready by construction"):
6
+ * - a service is a LIST of base URLs, tried in LIST ORDER — primary first,
7
+ * never rotated, so behaviour is predictable;
8
+ * - move to the next URL ONLY on a network error, a timeout or a 5xx;
9
+ * - a 4xx is the caller's bug (or a real "no") and is returned at once —
10
+ * asking a second instance the same wrong question gets the same answer;
11
+ * - every attempt has its own timeout and the whole call a total budget, so
12
+ * a black-holed host can never hang the caller.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.DEFAULT_FAILOVER = void 0;
16
+ exports.failoverFetch = failoverFetch;
17
+ exports.stripUndefined = stripUndefined;
18
+ exports.readJson = readJson;
19
+ exports.DEFAULT_FAILOVER = {
20
+ attemptTimeoutMs: 5_000,
21
+ totalBudgetMs: 15_000,
22
+ rounds: 2,
23
+ roundBackoffMs: 250,
24
+ };
25
+ function describe(err) {
26
+ if (err instanceof Error) {
27
+ if (err.name === "TimeoutError" || err.name === "AbortError")
28
+ return "timeout";
29
+ const cause = err.cause;
30
+ return cause?.code ? `${err.message} (${cause.code})` : err.message;
31
+ }
32
+ return String(err);
33
+ }
34
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
35
+ /**
36
+ * Try `path` against each base URL until one answers below 500.
37
+ * The body in `init` must be replayable (a string or bytes) — a stream cannot
38
+ * be sent twice.
39
+ */
40
+ async function failoverFetch(urls, path, init, opts = {}) {
41
+ const o = { ...exports.DEFAULT_FAILOVER, ...stripUndefined(opts) };
42
+ const attempts = [];
43
+ if (!urls.length)
44
+ return { kind: "failed", error: "no base URL configured", status: null, attempts };
45
+ const deadline = Date.now() + o.totalBudgetMs;
46
+ let lastStatus = null;
47
+ let lastError = "";
48
+ for (let round = 0; round < Math.max(1, o.rounds); round++) {
49
+ if (round > 0) {
50
+ const wait = Math.min(o.roundBackoffMs, deadline - Date.now());
51
+ if (wait > 0)
52
+ await sleep(wait);
53
+ }
54
+ for (const base of urls) {
55
+ const remaining = deadline - Date.now();
56
+ if (remaining <= 0) {
57
+ return { kind: "failed", error: `total budget of ${o.totalBudgetMs} ms spent (last: ${lastError || "none"})`, status: lastStatus, attempts };
58
+ }
59
+ const url = `${base}${path}`;
60
+ const started = Date.now();
61
+ const ctl = new AbortController();
62
+ const timer = setTimeout(() => ctl.abort(new DOMException("timeout", "TimeoutError")), Math.min(o.attemptTimeoutMs, remaining));
63
+ try {
64
+ // Raced against the abort as well: a timeout must hold even if the
65
+ // fetch implementation ignores its signal.
66
+ const res = await Promise.race([
67
+ // cache:no-store keeps Next's patched fetch from caching a health or roster answer.
68
+ fetch(url, { ...init, signal: ctl.signal, cache: "no-store" }),
69
+ new Promise((_, reject) => ctl.signal.addEventListener("abort", () => reject(ctl.signal.reason), { once: true })),
70
+ ]);
71
+ const ms = Date.now() - started;
72
+ if (res.status >= 500) {
73
+ lastStatus = res.status;
74
+ lastError = `HTTP ${res.status}`;
75
+ attempts.push({ url, status: res.status, error: lastError, ms });
76
+ await res.body?.cancel().catch(() => undefined);
77
+ continue;
78
+ }
79
+ attempts.push({ url, status: res.status, ms });
80
+ return { kind: "response", res, url, base, attempts };
81
+ }
82
+ catch (err) {
83
+ lastStatus = null;
84
+ lastError = describe(err);
85
+ attempts.push({ url, status: null, error: lastError, ms: Date.now() - started });
86
+ }
87
+ finally {
88
+ clearTimeout(timer);
89
+ }
90
+ }
91
+ }
92
+ return { kind: "failed", error: lastError || "every base URL failed", status: lastStatus, attempts };
93
+ }
94
+ function stripUndefined(o) {
95
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
96
+ }
97
+ /** Parse a JSON body; `undefined` when it is not JSON. */
98
+ async function readJson(res) {
99
+ const text = await res.text().catch(() => "");
100
+ if (!text)
101
+ return undefined;
102
+ try {
103
+ return JSON.parse(text);
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @jdcpuwiz/zoo-kit — the homelab apps' shared plumbing (server-only).
3
+ *
4
+ * A THIN, pinned client of the shared services' v1 contract
5
+ * (contracts/v1 in the zoo-kit repo). It carries no hosts, IPs or keys: every
6
+ * address and secret comes from the app's environment (see ENV).
7
+ *
8
+ * Server-only by construction: it imports node:crypto / node:fs, so a browser
9
+ * bundle fails at build time. It deliberately does NOT import Next's
10
+ * "server-only" marker, which would break Hono, Express, Fastify and Bun.
11
+ */
12
+ export { ENV, appKeyEnv, appKeyForEnv, appUrlsEnv, checkConfig, envSuffix, type ConfigReport } from "./env.js";
13
+ export { CATEGORIES, CATEGORY_ALIASES, CATEGORY_SLUGS, canonicalCategory, customCategory, isCanonicalCategory, isCategoryAlias, toCategory, type CategoryAlias, type CategoryInput, type CustomCategory, type NotifyCategory, } from "./categories.js";
14
+ export { NOTIFY_DEFAULTS, NOTIFY_PATH, dedupeKey, notify, notifyConfigured, type NotifyAction, type NotifyDryRun, type NotifyFailed, type NotifyInput, type NotifyOptions, type NotifyPriority, type NotifyResult, type NotifySent, } from "./notify.js";
15
+ export { PEOPLE_DEFAULTS, PEOPLE_PATHS, createPeople, people, toPerson, type People, type PeopleList, type PeopleOptions, type PeopleStatus, type Person, type ResolveStatus, type ResolvedUsername, } from "./people.js";
16
+ export { ZooKitAuthError, cameThroughGate, gateSecretOk, readAuthentikUsername, requireApp, requirePerson, whoami, type Anonymous, type AuthentikOptions, type DeviceAnswer, type Identity, type PersonIdentity, type SessionAnswer, type WhoamiOptions, } from "./whoami.js";
17
+ export { ZooKitConfigError, bearerOf, callApp, checkApp, safeEqual, type AppIdentity, type AppVerdict, type CallAppOptions, type HeaderBag, type RequestLike, } from "./keys.js";
18
+ export { healthBody, healthHandler, type CheckFn, type CheckResult, type HealthBody, type HealthOptions } from "./health.js";
19
+ export { KIT_VERSION, PERSON_KEYS } from "./generated/contract.js";
20
+ export type { Attempt, FailoverOptions } from "./http.js";
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PERSON_KEYS = exports.KIT_VERSION = exports.healthHandler = exports.healthBody = exports.safeEqual = exports.checkApp = exports.callApp = exports.bearerOf = exports.ZooKitConfigError = exports.whoami = exports.requirePerson = exports.requireApp = exports.readAuthentikUsername = exports.gateSecretOk = exports.cameThroughGate = exports.ZooKitAuthError = exports.toPerson = exports.people = exports.createPeople = exports.PEOPLE_PATHS = exports.PEOPLE_DEFAULTS = exports.notifyConfigured = exports.notify = exports.dedupeKey = exports.NOTIFY_PATH = exports.NOTIFY_DEFAULTS = exports.toCategory = exports.isCategoryAlias = exports.isCanonicalCategory = exports.customCategory = exports.canonicalCategory = exports.CATEGORY_SLUGS = exports.CATEGORY_ALIASES = exports.CATEGORIES = exports.envSuffix = exports.checkConfig = exports.appUrlsEnv = exports.appKeyForEnv = exports.appKeyEnv = exports.ENV = void 0;
4
+ /**
5
+ * @jdcpuwiz/zoo-kit — the homelab apps' shared plumbing (server-only).
6
+ *
7
+ * A THIN, pinned client of the shared services' v1 contract
8
+ * (contracts/v1 in the zoo-kit repo). It carries no hosts, IPs or keys: every
9
+ * address and secret comes from the app's environment (see ENV).
10
+ *
11
+ * Server-only by construction: it imports node:crypto / node:fs, so a browser
12
+ * bundle fails at build time. It deliberately does NOT import Next's
13
+ * "server-only" marker, which would break Hono, Express, Fastify and Bun.
14
+ */
15
+ var env_js_1 = require("./env.js");
16
+ Object.defineProperty(exports, "ENV", { enumerable: true, get: function () { return env_js_1.ENV; } });
17
+ Object.defineProperty(exports, "appKeyEnv", { enumerable: true, get: function () { return env_js_1.appKeyEnv; } });
18
+ Object.defineProperty(exports, "appKeyForEnv", { enumerable: true, get: function () { return env_js_1.appKeyForEnv; } });
19
+ Object.defineProperty(exports, "appUrlsEnv", { enumerable: true, get: function () { return env_js_1.appUrlsEnv; } });
20
+ Object.defineProperty(exports, "checkConfig", { enumerable: true, get: function () { return env_js_1.checkConfig; } });
21
+ Object.defineProperty(exports, "envSuffix", { enumerable: true, get: function () { return env_js_1.envSuffix; } });
22
+ var categories_js_1 = require("./categories.js");
23
+ Object.defineProperty(exports, "CATEGORIES", { enumerable: true, get: function () { return categories_js_1.CATEGORIES; } });
24
+ Object.defineProperty(exports, "CATEGORY_ALIASES", { enumerable: true, get: function () { return categories_js_1.CATEGORY_ALIASES; } });
25
+ Object.defineProperty(exports, "CATEGORY_SLUGS", { enumerable: true, get: function () { return categories_js_1.CATEGORY_SLUGS; } });
26
+ Object.defineProperty(exports, "canonicalCategory", { enumerable: true, get: function () { return categories_js_1.canonicalCategory; } });
27
+ Object.defineProperty(exports, "customCategory", { enumerable: true, get: function () { return categories_js_1.customCategory; } });
28
+ Object.defineProperty(exports, "isCanonicalCategory", { enumerable: true, get: function () { return categories_js_1.isCanonicalCategory; } });
29
+ Object.defineProperty(exports, "isCategoryAlias", { enumerable: true, get: function () { return categories_js_1.isCategoryAlias; } });
30
+ Object.defineProperty(exports, "toCategory", { enumerable: true, get: function () { return categories_js_1.toCategory; } });
31
+ var notify_js_1 = require("./notify.js");
32
+ Object.defineProperty(exports, "NOTIFY_DEFAULTS", { enumerable: true, get: function () { return notify_js_1.NOTIFY_DEFAULTS; } });
33
+ Object.defineProperty(exports, "NOTIFY_PATH", { enumerable: true, get: function () { return notify_js_1.NOTIFY_PATH; } });
34
+ Object.defineProperty(exports, "dedupeKey", { enumerable: true, get: function () { return notify_js_1.dedupeKey; } });
35
+ Object.defineProperty(exports, "notify", { enumerable: true, get: function () { return notify_js_1.notify; } });
36
+ Object.defineProperty(exports, "notifyConfigured", { enumerable: true, get: function () { return notify_js_1.notifyConfigured; } });
37
+ var people_js_1 = require("./people.js");
38
+ Object.defineProperty(exports, "PEOPLE_DEFAULTS", { enumerable: true, get: function () { return people_js_1.PEOPLE_DEFAULTS; } });
39
+ Object.defineProperty(exports, "PEOPLE_PATHS", { enumerable: true, get: function () { return people_js_1.PEOPLE_PATHS; } });
40
+ Object.defineProperty(exports, "createPeople", { enumerable: true, get: function () { return people_js_1.createPeople; } });
41
+ Object.defineProperty(exports, "people", { enumerable: true, get: function () { return people_js_1.people; } });
42
+ Object.defineProperty(exports, "toPerson", { enumerable: true, get: function () { return people_js_1.toPerson; } });
43
+ var whoami_js_1 = require("./whoami.js");
44
+ Object.defineProperty(exports, "ZooKitAuthError", { enumerable: true, get: function () { return whoami_js_1.ZooKitAuthError; } });
45
+ Object.defineProperty(exports, "cameThroughGate", { enumerable: true, get: function () { return whoami_js_1.cameThroughGate; } });
46
+ Object.defineProperty(exports, "gateSecretOk", { enumerable: true, get: function () { return whoami_js_1.gateSecretOk; } });
47
+ Object.defineProperty(exports, "readAuthentikUsername", { enumerable: true, get: function () { return whoami_js_1.readAuthentikUsername; } });
48
+ Object.defineProperty(exports, "requireApp", { enumerable: true, get: function () { return whoami_js_1.requireApp; } });
49
+ Object.defineProperty(exports, "requirePerson", { enumerable: true, get: function () { return whoami_js_1.requirePerson; } });
50
+ Object.defineProperty(exports, "whoami", { enumerable: true, get: function () { return whoami_js_1.whoami; } });
51
+ var keys_js_1 = require("./keys.js");
52
+ Object.defineProperty(exports, "ZooKitConfigError", { enumerable: true, get: function () { return keys_js_1.ZooKitConfigError; } });
53
+ Object.defineProperty(exports, "bearerOf", { enumerable: true, get: function () { return keys_js_1.bearerOf; } });
54
+ Object.defineProperty(exports, "callApp", { enumerable: true, get: function () { return keys_js_1.callApp; } });
55
+ Object.defineProperty(exports, "checkApp", { enumerable: true, get: function () { return keys_js_1.checkApp; } });
56
+ Object.defineProperty(exports, "safeEqual", { enumerable: true, get: function () { return keys_js_1.safeEqual; } });
57
+ var health_js_1 = require("./health.js");
58
+ Object.defineProperty(exports, "healthBody", { enumerable: true, get: function () { return health_js_1.healthBody; } });
59
+ Object.defineProperty(exports, "healthHandler", { enumerable: true, get: function () { return health_js_1.healthHandler; } });
60
+ var contract_js_1 = require("./generated/contract.js");
61
+ Object.defineProperty(exports, "KIT_VERSION", { enumerable: true, get: function () { return contract_js_1.KIT_VERSION; } });
62
+ Object.defineProperty(exports, "PERSON_KEYS", { enumerable: true, get: function () { return contract_js_1.PERSON_KEYS; } });
@@ -0,0 +1,51 @@
1
+ import { type FailoverOptions } from "./http.js";
2
+ export interface HeaderBag {
3
+ get(name: string): string | null;
4
+ }
5
+ /** Anything with request headers: a Fetch `Request`, a NextRequest, Hono's `c.req.raw`. */
6
+ export interface RequestLike {
7
+ headers: HeaderBag;
8
+ }
9
+ /** The Bearer token, or null. A bare token without the scheme is NOT accepted. */
10
+ export declare function bearerOf(h: HeaderBag): string | null;
11
+ /** Constant-time string equality, length-safe (both sides hashed to 32 bytes). */
12
+ export declare function safeEqual(a: string, b: string): boolean;
13
+ /**
14
+ * Which allowed caller presented this token, or null. Every allowed caller's
15
+ * key is compared before answering.
16
+ */
17
+ export declare function appForToken(token: string, allowed: readonly string[]): string | null;
18
+ export interface AppIdentity {
19
+ kind: "app";
20
+ app: string;
21
+ via: "key";
22
+ }
23
+ export type AppVerdict = {
24
+ ok: true;
25
+ identity: AppIdentity;
26
+ } | {
27
+ ok: false;
28
+ status: 401 | 403;
29
+ };
30
+ /** The non-throwing app-key check. 401 = no Bearer at all, 403 = a Bearer no allowed caller owns. */
31
+ export declare function checkApp(req: RequestLike, allowed: readonly string[]): AppVerdict;
32
+ export interface CallAppOptions extends FailoverOptions {
33
+ /**
34
+ * Fail over a non-idempotent method (POST/PATCH) too. Off by default: a POST
35
+ * that timed out may still have landed, and replaying it on the next
36
+ * instance would do it twice unless the target dedupes.
37
+ */
38
+ retryUnsafe?: boolean;
39
+ }
40
+ export declare class ZooKitConfigError extends Error {
41
+ readonly missing: string[];
42
+ constructor(missing: string[]);
43
+ }
44
+ /**
45
+ * Call another app with this app's key for it. Returns the target's Response
46
+ * (any status below 500 — a 4xx is the caller's to handle); throws
47
+ * ZooKitConfigError when the URLs or the key are not configured, and an Error
48
+ * when every URL failed (network error, timeout or 5xx).
49
+ * The body must be replayable (string / bytes / URLSearchParams).
50
+ */
51
+ export declare function callApp(app: string, path: string, init?: RequestInit, opts?: CallAppOptions): Promise<Response>;
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ZooKitConfigError = void 0;
4
+ exports.bearerOf = bearerOf;
5
+ exports.safeEqual = safeEqual;
6
+ exports.appForToken = appForToken;
7
+ exports.checkApp = checkApp;
8
+ exports.callApp = callApp;
9
+ /**
10
+ * App-to-app keys (plan §3.5). Apps calling apps only — a phone or a kiosk is
11
+ * a device key, a human is whoami.
12
+ *
13
+ * Inbound: `requireApp(req, ["zoo-vet"])` accepts `Authorization: Bearer <k>`
14
+ * where k equals ZOO_KIT_APP_KEY_<CALLER> for one of the allowed
15
+ * callers. Nothing else (no X-API-Key, no ?key=).
16
+ * Outbound: `callApp("zoo-where", "/api/people")` sends ZOO_KIT_APP_KEY_FOR_<APP>
17
+ * to the base URLs in ZOO_KIT_APP_URLS_<APP>.
18
+ *
19
+ * FAIL CLOSED: no configured key = no caller gets in. Every comparison is
20
+ * timing-safe and every allowed caller's key is compared (no early exit), so
21
+ * the response time does not say which caller a key nearly matched.
22
+ */
23
+ const node_crypto_1 = require("node:crypto");
24
+ const env_js_1 = require("./env.js");
25
+ const http_js_1 = require("./http.js");
26
+ /** The Bearer token, or null. A bare token without the scheme is NOT accepted. */
27
+ function bearerOf(h) {
28
+ const m = /^Bearer[ \t]+(\S+)[ \t]*$/i.exec(h.get("authorization") ?? "");
29
+ return m?.[1] ?? null;
30
+ }
31
+ /** Constant-time string equality, length-safe (both sides hashed to 32 bytes). */
32
+ function safeEqual(a, b) {
33
+ const ha = (0, node_crypto_1.createHash)("sha256").update(a).digest();
34
+ const hb = (0, node_crypto_1.createHash)("sha256").update(b).digest();
35
+ return (0, node_crypto_1.timingSafeEqual)(ha, hb) && a.length === b.length;
36
+ }
37
+ /**
38
+ * Which allowed caller presented this token, or null. Every allowed caller's
39
+ * key is compared before answering.
40
+ */
41
+ function appForToken(token, allowed) {
42
+ let found = null;
43
+ let configured = 0;
44
+ for (const app of allowed) {
45
+ const key = (0, env_js_1.str)((0, env_js_1.appKeyEnv)(app));
46
+ if (!key)
47
+ continue;
48
+ configured++;
49
+ if (safeEqual(token, key) && found === null)
50
+ found = app;
51
+ }
52
+ if (!configured && allowed.length) {
53
+ (0, env_js_1.warnOnce)(`appkeys-${allowed.join(",")}`, `no app key configured for ${allowed.map(env_js_1.appKeyEnv).join(", ")} — every caller is refused`);
54
+ }
55
+ return found;
56
+ }
57
+ /** The non-throwing app-key check. 401 = no Bearer at all, 403 = a Bearer no allowed caller owns. */
58
+ function checkApp(req, allowed) {
59
+ const token = bearerOf(req.headers);
60
+ if (!token)
61
+ return { ok: false, status: 401 };
62
+ const app = appForToken(token, allowed);
63
+ if (!app)
64
+ return { ok: false, status: 403 };
65
+ return { ok: true, identity: { kind: "app", app, via: "key" } };
66
+ }
67
+ class ZooKitConfigError extends Error {
68
+ missing;
69
+ constructor(missing) {
70
+ super(`zoo-kit: not configured: ${missing.join(", ")} not set`);
71
+ this.name = "ZooKitConfigError";
72
+ this.missing = missing;
73
+ }
74
+ }
75
+ exports.ZooKitConfigError = ZooKitConfigError;
76
+ const SAFE = new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
77
+ /**
78
+ * Call another app with this app's key for it. Returns the target's Response
79
+ * (any status below 500 — a 4xx is the caller's to handle); throws
80
+ * ZooKitConfigError when the URLs or the key are not configured, and an Error
81
+ * when every URL failed (network error, timeout or 5xx).
82
+ * The body must be replayable (string / bytes / URLSearchParams).
83
+ */
84
+ async function callApp(app, path, init = {}, opts = {}) {
85
+ const urls = (0, env_js_1.list)((0, env_js_1.appUrlsEnv)(app));
86
+ const key = (0, env_js_1.str)((0, env_js_1.appKeyForEnv)(app));
87
+ const missing = [...(urls.length ? [] : [(0, env_js_1.appUrlsEnv)(app)]), ...(key ? [] : [(0, env_js_1.appKeyForEnv)(app)])];
88
+ if (missing.length)
89
+ throw new ZooKitConfigError(missing);
90
+ if (!path.startsWith("/"))
91
+ throw new TypeError(`callApp path must start with "/", got ${JSON.stringify(path)}`);
92
+ const headers = new Headers(init.headers);
93
+ headers.set("Authorization", `Bearer ${key}`);
94
+ const method = (init.method ?? "GET").toUpperCase();
95
+ const { retryUnsafe, ...failover } = opts;
96
+ const targets = SAFE.has(method) || retryUnsafe ? urls : urls.slice(0, 1);
97
+ const outcome = await (0, http_js_1.failoverFetch)(targets, path, { ...init, method, headers }, {
98
+ attemptTimeoutMs: 10_000,
99
+ totalBudgetMs: 20_000,
100
+ rounds: 1,
101
+ ...(0, http_js_1.stripUndefined)(failover),
102
+ });
103
+ if (outcome.kind === "response")
104
+ return outcome.res;
105
+ throw new Error(`callApp(${app}): ${outcome.error}`);
106
+ }
@@ -0,0 +1,79 @@
1
+ import type { CategoryInput } from "./categories.js";
2
+ import type { components } from "./generated/notifier.js";
3
+ import { type Attempt, type FailoverOptions } from "./http.js";
4
+ type Schemas = components["schemas"];
5
+ export type NotifyPriority = NonNullable<Schemas["NotifyInput"]["priority"]>;
6
+ export type NotifyAction = Schemas["NotifyAction"];
7
+ /** The v1 notify input (contracts/v1/zoo-notifier.v1.yaml NotifyInput), with a typed category. */
8
+ export type NotifyInput = Omit<Schemas["NotifyInput"], "category"> & {
9
+ category: CategoryInput;
10
+ };
11
+ export interface NotifyOptions extends FailoverOptions {
12
+ /** Build and return the request, send nothing. Still requires the config. */
13
+ dryRun?: boolean;
14
+ /** Hub base URLs for this call, instead of ZOO_NOTIFIER_URLS. Empty = use the env. */
15
+ urls?: string[];
16
+ /** This app's hub key for this call, instead of ZOO_NOTIFIER_KEY. Empty = use the env. */
17
+ key?: string;
18
+ }
19
+ export interface NotifySent {
20
+ ok: true;
21
+ /** The notification id — for a duplicate, the ORIGINAL one. */
22
+ id: string;
23
+ /** true = a new notification was stored; false = a duplicate, nothing new sent. */
24
+ queued: boolean;
25
+ deduped: boolean;
26
+ status: number;
27
+ /** The base URL that answered. */
28
+ url: string;
29
+ dryRun?: false;
30
+ }
31
+ export interface NotifyDryRun {
32
+ ok: true;
33
+ dryRun: true;
34
+ queued: false;
35
+ deduped: false;
36
+ id?: undefined;
37
+ urls: string[];
38
+ path: "/api/v1/notify";
39
+ body: Schemas["NotifyInput"];
40
+ }
41
+ export interface NotifyFailed {
42
+ ok: false;
43
+ error: string;
44
+ /** The last HTTP status seen; null when nothing answered. */
45
+ status: number | null;
46
+ /** Set when nothing was sent at all. */
47
+ skipped?: "unconfigured" | "invalid";
48
+ attempts: Attempt[];
49
+ }
50
+ export type NotifyResult = NotifySent | NotifyDryRun | NotifyFailed;
51
+ export declare const NOTIFY_PATH: "/api/v1/notify";
52
+ /** Notify's defaults: 5 s per attempt, 15 s in total, two passes over the list. */
53
+ export declare const NOTIFY_DEFAULTS: Required<FailoverOptions>;
54
+ /**
55
+ * A table-prefixed dedupe key, so a bare id can never collide across kinds
56
+ * (claude-peek B206: Change 12 and Bug 12 swallowed each other's pushes).
57
+ *
58
+ * dedupeKey("change", 1463) -> "change:1463"
59
+ * dedupeKey("backup-failed", job, day) -> "backup-failed:7:2026-11-03"
60
+ *
61
+ * Parts are escaped so ("a", "b:c") and ("a:b", "c") stay different; null and
62
+ * undefined parts become "-". A key past the hub's 200-char limit is hashed.
63
+ * Throws TypeError on an unusable `kind` — that is a bug at the call site.
64
+ */
65
+ export declare function dedupeKey(kind: string, ...parts: Array<string | number | bigint | boolean | null | undefined>): string;
66
+ /** Is notify configured through the env? Names only; per-call overrides are not counted. */
67
+ export declare function notifyConfigured(): {
68
+ ok: boolean;
69
+ missing: string[];
70
+ };
71
+ /**
72
+ * Send one push. Resolves; never rejects.
73
+ *
74
+ * When the input carries no dedupeKey the kit adds a one-off one, so a retry
75
+ * after a timeout on a hub that DID store the first attempt answers
76
+ * `deduped: true` instead of pushing twice. A caller-supplied key is sent as is.
77
+ */
78
+ export declare function notify(input: NotifyInput, opts?: NotifyOptions): Promise<NotifyResult>;
79
+ export {};
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NOTIFY_DEFAULTS = exports.NOTIFY_PATH = void 0;
4
+ exports.dedupeKey = dedupeKey;
5
+ exports.notifyConfigured = notifyConfigured;
6
+ exports.notify = notify;
7
+ /**
8
+ * notify — the zoo-notifier v1 client (plan §3.1).
9
+ *
10
+ * POST {base}/api/v1/notify, `Authorization: Bearer <ZOO_NOTIFIER_KEY>`, over
11
+ * the base URLs in ZOO_NOTIFIER_URLS (else the legacy ZOO_NOTIFIER_URL).
12
+ *
13
+ * FIRE-AND-FORGET: notify() NEVER throws. A down hub must not fail a backup,
14
+ * a grab or an order — it retries a bounded number of times across the URL
15
+ * list, logs one line and resolves `{ ok: false, error }`.
16
+ *
17
+ * Missing config is one logged warning and a no-op — never a guessed host.
18
+ *
19
+ * An app that keeps its hub settings somewhere other than env (an encrypted
20
+ * settings table) passes `{ urls, key }` per call; the key is sent as the Bearer
21
+ * header and nowhere else, so it never reaches a result or a log line.
22
+ */
23
+ const node_crypto_1 = require("node:crypto");
24
+ const env_js_1 = require("./env.js");
25
+ const http_js_1 = require("./http.js");
26
+ exports.NOTIFY_PATH = "/api/v1/notify";
27
+ /** Notify's defaults: 5 s per attempt, 15 s in total, two passes over the list. */
28
+ exports.NOTIFY_DEFAULTS = {
29
+ attemptTimeoutMs: 5_000,
30
+ totalBudgetMs: 15_000,
31
+ rounds: 2,
32
+ roundBackoffMs: 250,
33
+ };
34
+ const KIND_RE = /^[a-z0-9][a-z0-9_-]{0,39}$/i;
35
+ const MAX_DEDUPE = 200;
36
+ /**
37
+ * A table-prefixed dedupe key, so a bare id can never collide across kinds
38
+ * (claude-peek B206: Change 12 and Bug 12 swallowed each other's pushes).
39
+ *
40
+ * dedupeKey("change", 1463) -> "change:1463"
41
+ * dedupeKey("backup-failed", job, day) -> "backup-failed:7:2026-11-03"
42
+ *
43
+ * Parts are escaped so ("a", "b:c") and ("a:b", "c") stay different; null and
44
+ * undefined parts become "-". A key past the hub's 200-char limit is hashed.
45
+ * Throws TypeError on an unusable `kind` — that is a bug at the call site.
46
+ */
47
+ function dedupeKey(kind, ...parts) {
48
+ if (!KIND_RE.test(kind))
49
+ throw new TypeError(`dedupeKey kind must be a short slug, got ${JSON.stringify(kind)}`);
50
+ const esc = (p) => p === null || p === undefined ? "-" : String(p).replace(/%/g, "%25").replace(/:/g, "%3A");
51
+ const key = [kind.toLowerCase(), ...parts.map(esc)].join(":");
52
+ if (key.length <= MAX_DEDUPE)
53
+ return key;
54
+ return `${kind.toLowerCase()}:sha256-${(0, node_crypto_1.createHash)("sha256").update(key).digest("hex").slice(0, 48)}`;
55
+ }
56
+ function config(override = {}) {
57
+ const urlsOverride = (override.urls ?? []).map((u) => u.trim().replace(/\/+$/, "")).filter(Boolean);
58
+ const urls = urlsOverride.length ? urlsOverride : (0, env_js_1.firstList)(env_js_1.ENV.NOTIFIER_URLS, env_js_1.ENV.NOTIFIER_URL);
59
+ const key = override.key?.trim() || (0, env_js_1.str)(env_js_1.ENV.NOTIFIER_KEY);
60
+ const missing = [];
61
+ if (!urls.length)
62
+ missing.push(env_js_1.ENV.NOTIFIER_URLS);
63
+ if (!key)
64
+ missing.push(env_js_1.ENV.NOTIFIER_KEY);
65
+ return { urls, key, missing };
66
+ }
67
+ /** Is notify configured through the env? Names only; per-call overrides are not counted. */
68
+ function notifyConfigured() {
69
+ const { missing } = config();
70
+ return { ok: missing.length === 0, missing };
71
+ }
72
+ function failed(error, extra = {}) {
73
+ return { ok: false, error, status: null, attempts: [], ...extra };
74
+ }
75
+ /**
76
+ * Send one push. Resolves; never rejects.
77
+ *
78
+ * When the input carries no dedupeKey the kit adds a one-off one, so a retry
79
+ * after a timeout on a hub that DID store the first attempt answers
80
+ * `deduped: true` instead of pushing twice. A caller-supplied key is sent as is.
81
+ */
82
+ async function notify(input, opts = {}) {
83
+ try {
84
+ const { urls: urlsOverride, key: keyOverride, dryRun, ...failover } = opts;
85
+ const { urls, key, missing } = config({ urls: urlsOverride, key: keyOverride });
86
+ if (missing.length) {
87
+ (0, env_js_1.warnOnce)("notify-unconfigured", `notify is a no-op: ${missing.join(", ")} not set`);
88
+ return failed(`not configured: ${missing.join(", ")} not set`, { skipped: "unconfigured" });
89
+ }
90
+ if (!input || typeof input.title !== "string" || !input.title.trim()) {
91
+ return failed("title is required", { skipped: "invalid" });
92
+ }
93
+ if (typeof input.category !== "string" || !input.category) {
94
+ return failed("category is required", { skipped: "invalid" });
95
+ }
96
+ const body = (0, http_js_1.stripUndefined)({ ...input });
97
+ if (!body.dedupeKey)
98
+ body.dedupeKey = dedupeKey("kit-once", (0, node_crypto_1.randomUUID)());
99
+ if (dryRun) {
100
+ return { ok: true, dryRun: true, queued: false, deduped: false, urls, path: exports.NOTIFY_PATH, body };
101
+ }
102
+ const outcome = await (0, http_js_1.failoverFetch)(urls, exports.NOTIFY_PATH, {
103
+ method: "POST",
104
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
105
+ body: JSON.stringify(body),
106
+ }, { ...exports.NOTIFY_DEFAULTS, ...(0, http_js_1.stripUndefined)(failover) });
107
+ if (outcome.kind === "failed") {
108
+ console.warn(`[zoo-kit] notify failed after ${outcome.attempts.length} attempt(s): ${outcome.error}`);
109
+ return failed(outcome.error, { status: outcome.status, attempts: outcome.attempts });
110
+ }
111
+ const { res, attempts } = outcome;
112
+ const json = (await (0, http_js_1.readJson)(res));
113
+ if (res.ok && json && json.ok === true && typeof json.id === "string") {
114
+ return {
115
+ ok: true,
116
+ id: json.id,
117
+ queued: json.queued === true,
118
+ deduped: json.deduped === true,
119
+ status: res.status,
120
+ url: outcome.base,
121
+ };
122
+ }
123
+ const error = (json && typeof json.error === "string" && json.error) || `HTTP ${res.status}`;
124
+ console.warn(`[zoo-kit] notify refused by the hub (${res.status}): ${error}`);
125
+ return failed(error, { status: res.status, attempts });
126
+ }
127
+ catch (err) {
128
+ // Belt and braces: nothing above should throw, but notify() must not.
129
+ return failed(err instanceof Error ? err.message : String(err));
130
+ }
131
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}