@jdcpuwiz/zoo-kit 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/README.md +238 -2
- package/dist/categories.d.ts +31 -0
- package/dist/categories.js +36 -0
- package/dist/env.d.ts +62 -0
- package/dist/env.js +91 -0
- package/dist/generated/categories.d.ts +85 -0
- package/dist/generated/categories.js +7 -0
- package/dist/generated/contract.d.ts +7 -0
- package/dist/generated/contract.js +9 -0
- package/dist/generated/notifier.d.ts +230 -0
- package/dist/generated/notifier.js +4 -0
- package/dist/generated/people.d.ts +261 -0
- package/dist/generated/people.js +4 -0
- package/dist/health.d.ts +46 -0
- package/dist/health.js +112 -0
- package/dist/http.d.ts +51 -0
- package/dist/http.js +102 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +19 -0
- package/dist/keys.d.ts +51 -0
- package/dist/keys.js +97 -0
- package/dist/notify.d.ts +75 -0
- package/dist/notify.js +119 -0
- package/dist/people.d.ts +61 -0
- package/dist/people.js +165 -0
- package/dist/whoami.d.ts +86 -0
- package/dist/whoami.js +187 -0
- package/package.json +50 -4
package/dist/http.d.ts
ADDED
|
@@ -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>;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
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 const DEFAULT_FAILOVER = {
|
|
14
|
+
attemptTimeoutMs: 5_000,
|
|
15
|
+
totalBudgetMs: 15_000,
|
|
16
|
+
rounds: 2,
|
|
17
|
+
roundBackoffMs: 250,
|
|
18
|
+
};
|
|
19
|
+
function describe(err) {
|
|
20
|
+
if (err instanceof Error) {
|
|
21
|
+
if (err.name === "TimeoutError" || err.name === "AbortError")
|
|
22
|
+
return "timeout";
|
|
23
|
+
const cause = err.cause;
|
|
24
|
+
return cause?.code ? `${err.message} (${cause.code})` : err.message;
|
|
25
|
+
}
|
|
26
|
+
return String(err);
|
|
27
|
+
}
|
|
28
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
29
|
+
/**
|
|
30
|
+
* Try `path` against each base URL until one answers below 500.
|
|
31
|
+
* The body in `init` must be replayable (a string or bytes) — a stream cannot
|
|
32
|
+
* be sent twice.
|
|
33
|
+
*/
|
|
34
|
+
export async function failoverFetch(urls, path, init, opts = {}) {
|
|
35
|
+
const o = { ...DEFAULT_FAILOVER, ...stripUndefined(opts) };
|
|
36
|
+
const attempts = [];
|
|
37
|
+
if (!urls.length)
|
|
38
|
+
return { kind: "failed", error: "no base URL configured", status: null, attempts };
|
|
39
|
+
const deadline = Date.now() + o.totalBudgetMs;
|
|
40
|
+
let lastStatus = null;
|
|
41
|
+
let lastError = "";
|
|
42
|
+
for (let round = 0; round < Math.max(1, o.rounds); round++) {
|
|
43
|
+
if (round > 0) {
|
|
44
|
+
const wait = Math.min(o.roundBackoffMs, deadline - Date.now());
|
|
45
|
+
if (wait > 0)
|
|
46
|
+
await sleep(wait);
|
|
47
|
+
}
|
|
48
|
+
for (const base of urls) {
|
|
49
|
+
const remaining = deadline - Date.now();
|
|
50
|
+
if (remaining <= 0) {
|
|
51
|
+
return { kind: "failed", error: `total budget of ${o.totalBudgetMs} ms spent (last: ${lastError || "none"})`, status: lastStatus, attempts };
|
|
52
|
+
}
|
|
53
|
+
const url = `${base}${path}`;
|
|
54
|
+
const started = Date.now();
|
|
55
|
+
const ctl = new AbortController();
|
|
56
|
+
const timer = setTimeout(() => ctl.abort(new DOMException("timeout", "TimeoutError")), Math.min(o.attemptTimeoutMs, remaining));
|
|
57
|
+
try {
|
|
58
|
+
// Raced against the abort as well: a timeout must hold even if the
|
|
59
|
+
// fetch implementation ignores its signal.
|
|
60
|
+
const res = await Promise.race([
|
|
61
|
+
// cache:no-store keeps Next's patched fetch from caching a health or roster answer.
|
|
62
|
+
fetch(url, { ...init, signal: ctl.signal, cache: "no-store" }),
|
|
63
|
+
new Promise((_, reject) => ctl.signal.addEventListener("abort", () => reject(ctl.signal.reason), { once: true })),
|
|
64
|
+
]);
|
|
65
|
+
const ms = Date.now() - started;
|
|
66
|
+
if (res.status >= 500) {
|
|
67
|
+
lastStatus = res.status;
|
|
68
|
+
lastError = `HTTP ${res.status}`;
|
|
69
|
+
attempts.push({ url, status: res.status, error: lastError, ms });
|
|
70
|
+
await res.body?.cancel().catch(() => undefined);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
attempts.push({ url, status: res.status, ms });
|
|
74
|
+
return { kind: "response", res, url, base, attempts };
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
lastStatus = null;
|
|
78
|
+
lastError = describe(err);
|
|
79
|
+
attempts.push({ url, status: null, error: lastError, ms: Date.now() - started });
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { kind: "failed", error: lastError || "every base URL failed", status: lastStatus, attempts };
|
|
87
|
+
}
|
|
88
|
+
export function stripUndefined(o) {
|
|
89
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
90
|
+
}
|
|
91
|
+
/** Parse a JSON body; `undefined` when it is not JSON. */
|
|
92
|
+
export async function readJson(res) {
|
|
93
|
+
const text = await res.text().catch(() => "");
|
|
94
|
+
if (!text)
|
|
95
|
+
return undefined;
|
|
96
|
+
try {
|
|
97
|
+
return JSON.parse(text);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -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";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
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 } from "./env.js";
|
|
13
|
+
export { CATEGORIES, CATEGORY_ALIASES, CATEGORY_SLUGS, canonicalCategory, customCategory, isCanonicalCategory, isCategoryAlias, toCategory, } from "./categories.js";
|
|
14
|
+
export { NOTIFY_DEFAULTS, NOTIFY_PATH, dedupeKey, notify, notifyConfigured, } from "./notify.js";
|
|
15
|
+
export { PEOPLE_DEFAULTS, PEOPLE_PATHS, createPeople, people, toPerson, } from "./people.js";
|
|
16
|
+
export { ZooKitAuthError, cameThroughGate, gateSecretOk, readAuthentikUsername, requireApp, requirePerson, whoami, } from "./whoami.js";
|
|
17
|
+
export { ZooKitConfigError, bearerOf, callApp, checkApp, safeEqual, } from "./keys.js";
|
|
18
|
+
export { healthBody, healthHandler } from "./health.js";
|
|
19
|
+
export { KIT_VERSION, PERSON_KEYS } from "./generated/contract.js";
|
package/dist/keys.d.ts
ADDED
|
@@ -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>;
|
package/dist/keys.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* App-to-app keys (plan §3.5). Apps calling apps only — a phone or a kiosk is
|
|
3
|
+
* a device key, a human is whoami.
|
|
4
|
+
*
|
|
5
|
+
* Inbound: `requireApp(req, ["zoo-vet"])` accepts `Authorization: Bearer <k>`
|
|
6
|
+
* where k equals ZOO_KIT_APP_KEY_<CALLER> for one of the allowed
|
|
7
|
+
* callers. Nothing else (no X-API-Key, no ?key=).
|
|
8
|
+
* Outbound: `callApp("zoo-where", "/api/people")` sends ZOO_KIT_APP_KEY_FOR_<APP>
|
|
9
|
+
* to the base URLs in ZOO_KIT_APP_URLS_<APP>.
|
|
10
|
+
*
|
|
11
|
+
* FAIL CLOSED: no configured key = no caller gets in. Every comparison is
|
|
12
|
+
* timing-safe and every allowed caller's key is compared (no early exit), so
|
|
13
|
+
* the response time does not say which caller a key nearly matched.
|
|
14
|
+
*/
|
|
15
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
16
|
+
import { appKeyEnv, appKeyForEnv, appUrlsEnv, list, str, warnOnce } from "./env.js";
|
|
17
|
+
import { failoverFetch, stripUndefined } from "./http.js";
|
|
18
|
+
/** The Bearer token, or null. A bare token without the scheme is NOT accepted. */
|
|
19
|
+
export function bearerOf(h) {
|
|
20
|
+
const m = /^Bearer[ \t]+(\S+)[ \t]*$/i.exec(h.get("authorization") ?? "");
|
|
21
|
+
return m?.[1] ?? null;
|
|
22
|
+
}
|
|
23
|
+
/** Constant-time string equality, length-safe (both sides hashed to 32 bytes). */
|
|
24
|
+
export function safeEqual(a, b) {
|
|
25
|
+
const ha = createHash("sha256").update(a).digest();
|
|
26
|
+
const hb = createHash("sha256").update(b).digest();
|
|
27
|
+
return timingSafeEqual(ha, hb) && a.length === b.length;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Which allowed caller presented this token, or null. Every allowed caller's
|
|
31
|
+
* key is compared before answering.
|
|
32
|
+
*/
|
|
33
|
+
export function appForToken(token, allowed) {
|
|
34
|
+
let found = null;
|
|
35
|
+
let configured = 0;
|
|
36
|
+
for (const app of allowed) {
|
|
37
|
+
const key = str(appKeyEnv(app));
|
|
38
|
+
if (!key)
|
|
39
|
+
continue;
|
|
40
|
+
configured++;
|
|
41
|
+
if (safeEqual(token, key) && found === null)
|
|
42
|
+
found = app;
|
|
43
|
+
}
|
|
44
|
+
if (!configured && allowed.length) {
|
|
45
|
+
warnOnce(`appkeys-${allowed.join(",")}`, `no app key configured for ${allowed.map(appKeyEnv).join(", ")} — every caller is refused`);
|
|
46
|
+
}
|
|
47
|
+
return found;
|
|
48
|
+
}
|
|
49
|
+
/** The non-throwing app-key check. 401 = no Bearer at all, 403 = a Bearer no allowed caller owns. */
|
|
50
|
+
export function checkApp(req, allowed) {
|
|
51
|
+
const token = bearerOf(req.headers);
|
|
52
|
+
if (!token)
|
|
53
|
+
return { ok: false, status: 401 };
|
|
54
|
+
const app = appForToken(token, allowed);
|
|
55
|
+
if (!app)
|
|
56
|
+
return { ok: false, status: 403 };
|
|
57
|
+
return { ok: true, identity: { kind: "app", app, via: "key" } };
|
|
58
|
+
}
|
|
59
|
+
export class ZooKitConfigError extends Error {
|
|
60
|
+
missing;
|
|
61
|
+
constructor(missing) {
|
|
62
|
+
super(`zoo-kit: not configured: ${missing.join(", ")} not set`);
|
|
63
|
+
this.name = "ZooKitConfigError";
|
|
64
|
+
this.missing = missing;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const SAFE = new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
|
|
68
|
+
/**
|
|
69
|
+
* Call another app with this app's key for it. Returns the target's Response
|
|
70
|
+
* (any status below 500 — a 4xx is the caller's to handle); throws
|
|
71
|
+
* ZooKitConfigError when the URLs or the key are not configured, and an Error
|
|
72
|
+
* when every URL failed (network error, timeout or 5xx).
|
|
73
|
+
* The body must be replayable (string / bytes / URLSearchParams).
|
|
74
|
+
*/
|
|
75
|
+
export async function callApp(app, path, init = {}, opts = {}) {
|
|
76
|
+
const urls = list(appUrlsEnv(app));
|
|
77
|
+
const key = str(appKeyForEnv(app));
|
|
78
|
+
const missing = [...(urls.length ? [] : [appUrlsEnv(app)]), ...(key ? [] : [appKeyForEnv(app)])];
|
|
79
|
+
if (missing.length)
|
|
80
|
+
throw new ZooKitConfigError(missing);
|
|
81
|
+
if (!path.startsWith("/"))
|
|
82
|
+
throw new TypeError(`callApp path must start with "/", got ${JSON.stringify(path)}`);
|
|
83
|
+
const headers = new Headers(init.headers);
|
|
84
|
+
headers.set("Authorization", `Bearer ${key}`);
|
|
85
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
86
|
+
const { retryUnsafe, ...failover } = opts;
|
|
87
|
+
const targets = SAFE.has(method) || retryUnsafe ? urls : urls.slice(0, 1);
|
|
88
|
+
const outcome = await failoverFetch(targets, path, { ...init, method, headers }, {
|
|
89
|
+
attemptTimeoutMs: 10_000,
|
|
90
|
+
totalBudgetMs: 20_000,
|
|
91
|
+
rounds: 1,
|
|
92
|
+
...stripUndefined(failover),
|
|
93
|
+
});
|
|
94
|
+
if (outcome.kind === "response")
|
|
95
|
+
return outcome.res;
|
|
96
|
+
throw new Error(`callApp(${app}): ${outcome.error}`);
|
|
97
|
+
}
|
package/dist/notify.d.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
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
|
+
}
|
|
15
|
+
export interface NotifySent {
|
|
16
|
+
ok: true;
|
|
17
|
+
/** The notification id — for a duplicate, the ORIGINAL one. */
|
|
18
|
+
id: string;
|
|
19
|
+
/** true = a new notification was stored; false = a duplicate, nothing new sent. */
|
|
20
|
+
queued: boolean;
|
|
21
|
+
deduped: boolean;
|
|
22
|
+
status: number;
|
|
23
|
+
/** The base URL that answered. */
|
|
24
|
+
url: string;
|
|
25
|
+
dryRun?: false;
|
|
26
|
+
}
|
|
27
|
+
export interface NotifyDryRun {
|
|
28
|
+
ok: true;
|
|
29
|
+
dryRun: true;
|
|
30
|
+
queued: false;
|
|
31
|
+
deduped: false;
|
|
32
|
+
id?: undefined;
|
|
33
|
+
urls: string[];
|
|
34
|
+
path: "/api/v1/notify";
|
|
35
|
+
body: Schemas["NotifyInput"];
|
|
36
|
+
}
|
|
37
|
+
export interface NotifyFailed {
|
|
38
|
+
ok: false;
|
|
39
|
+
error: string;
|
|
40
|
+
/** The last HTTP status seen; null when nothing answered. */
|
|
41
|
+
status: number | null;
|
|
42
|
+
/** Set when nothing was sent at all. */
|
|
43
|
+
skipped?: "unconfigured" | "invalid";
|
|
44
|
+
attempts: Attempt[];
|
|
45
|
+
}
|
|
46
|
+
export type NotifyResult = NotifySent | NotifyDryRun | NotifyFailed;
|
|
47
|
+
export declare const NOTIFY_PATH: "/api/v1/notify";
|
|
48
|
+
/** Notify's defaults: 5 s per attempt, 15 s in total, two passes over the list. */
|
|
49
|
+
export declare const NOTIFY_DEFAULTS: Required<FailoverOptions>;
|
|
50
|
+
/**
|
|
51
|
+
* A table-prefixed dedupe key, so a bare id can never collide across kinds
|
|
52
|
+
* (claude-peek B206: Change 12 and Bug 12 swallowed each other's pushes).
|
|
53
|
+
*
|
|
54
|
+
* dedupeKey("change", 1463) -> "change:1463"
|
|
55
|
+
* dedupeKey("backup-failed", job, day) -> "backup-failed:7:2026-11-03"
|
|
56
|
+
*
|
|
57
|
+
* Parts are escaped so ("a", "b:c") and ("a:b", "c") stay different; null and
|
|
58
|
+
* undefined parts become "-". A key past the hub's 200-char limit is hashed.
|
|
59
|
+
* Throws TypeError on an unusable `kind` — that is a bug at the call site.
|
|
60
|
+
*/
|
|
61
|
+
export declare function dedupeKey(kind: string, ...parts: Array<string | number | bigint | boolean | null | undefined>): string;
|
|
62
|
+
/** Is notify configured? Names only. */
|
|
63
|
+
export declare function notifyConfigured(): {
|
|
64
|
+
ok: boolean;
|
|
65
|
+
missing: string[];
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Send one push. Resolves; never rejects.
|
|
69
|
+
*
|
|
70
|
+
* When the input carries no dedupeKey the kit adds a one-off one, so a retry
|
|
71
|
+
* after a timeout on a hub that DID store the first attempt answers
|
|
72
|
+
* `deduped: true` instead of pushing twice. A caller-supplied key is sent as is.
|
|
73
|
+
*/
|
|
74
|
+
export declare function notify(input: NotifyInput, opts?: NotifyOptions): Promise<NotifyResult>;
|
|
75
|
+
export {};
|
package/dist/notify.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* notify — the zoo-notifier v1 client (plan §3.1).
|
|
3
|
+
*
|
|
4
|
+
* POST {base}/api/v1/notify, `Authorization: Bearer <ZOO_NOTIFIER_KEY>`, over
|
|
5
|
+
* the base URLs in ZOO_NOTIFIER_URLS (else the legacy ZOO_NOTIFIER_URL).
|
|
6
|
+
*
|
|
7
|
+
* FIRE-AND-FORGET: notify() NEVER throws. A down hub must not fail a backup,
|
|
8
|
+
* a grab or an order — it retries a bounded number of times across the URL
|
|
9
|
+
* list, logs one line and resolves `{ ok: false, error }`.
|
|
10
|
+
*
|
|
11
|
+
* Missing config is one logged warning and a no-op — never a guessed host.
|
|
12
|
+
*/
|
|
13
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
14
|
+
import { ENV, firstList, str, warnOnce } from "./env.js";
|
|
15
|
+
import { failoverFetch, readJson, stripUndefined } from "./http.js";
|
|
16
|
+
export const NOTIFY_PATH = "/api/v1/notify";
|
|
17
|
+
/** Notify's defaults: 5 s per attempt, 15 s in total, two passes over the list. */
|
|
18
|
+
export const NOTIFY_DEFAULTS = {
|
|
19
|
+
attemptTimeoutMs: 5_000,
|
|
20
|
+
totalBudgetMs: 15_000,
|
|
21
|
+
rounds: 2,
|
|
22
|
+
roundBackoffMs: 250,
|
|
23
|
+
};
|
|
24
|
+
const KIND_RE = /^[a-z0-9][a-z0-9_-]{0,39}$/i;
|
|
25
|
+
const MAX_DEDUPE = 200;
|
|
26
|
+
/**
|
|
27
|
+
* A table-prefixed dedupe key, so a bare id can never collide across kinds
|
|
28
|
+
* (claude-peek B206: Change 12 and Bug 12 swallowed each other's pushes).
|
|
29
|
+
*
|
|
30
|
+
* dedupeKey("change", 1463) -> "change:1463"
|
|
31
|
+
* dedupeKey("backup-failed", job, day) -> "backup-failed:7:2026-11-03"
|
|
32
|
+
*
|
|
33
|
+
* Parts are escaped so ("a", "b:c") and ("a:b", "c") stay different; null and
|
|
34
|
+
* undefined parts become "-". A key past the hub's 200-char limit is hashed.
|
|
35
|
+
* Throws TypeError on an unusable `kind` — that is a bug at the call site.
|
|
36
|
+
*/
|
|
37
|
+
export function dedupeKey(kind, ...parts) {
|
|
38
|
+
if (!KIND_RE.test(kind))
|
|
39
|
+
throw new TypeError(`dedupeKey kind must be a short slug, got ${JSON.stringify(kind)}`);
|
|
40
|
+
const esc = (p) => p === null || p === undefined ? "-" : String(p).replace(/%/g, "%25").replace(/:/g, "%3A");
|
|
41
|
+
const key = [kind.toLowerCase(), ...parts.map(esc)].join(":");
|
|
42
|
+
if (key.length <= MAX_DEDUPE)
|
|
43
|
+
return key;
|
|
44
|
+
return `${kind.toLowerCase()}:sha256-${createHash("sha256").update(key).digest("hex").slice(0, 48)}`;
|
|
45
|
+
}
|
|
46
|
+
function config() {
|
|
47
|
+
const urls = firstList(ENV.NOTIFIER_URLS, ENV.NOTIFIER_URL);
|
|
48
|
+
const key = str(ENV.NOTIFIER_KEY);
|
|
49
|
+
const missing = [];
|
|
50
|
+
if (!urls.length)
|
|
51
|
+
missing.push(ENV.NOTIFIER_URLS);
|
|
52
|
+
if (!key)
|
|
53
|
+
missing.push(ENV.NOTIFIER_KEY);
|
|
54
|
+
return { urls, key, missing };
|
|
55
|
+
}
|
|
56
|
+
/** Is notify configured? Names only. */
|
|
57
|
+
export function notifyConfigured() {
|
|
58
|
+
const { missing } = config();
|
|
59
|
+
return { ok: missing.length === 0, missing };
|
|
60
|
+
}
|
|
61
|
+
function failed(error, extra = {}) {
|
|
62
|
+
return { ok: false, error, status: null, attempts: [], ...extra };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Send one push. Resolves; never rejects.
|
|
66
|
+
*
|
|
67
|
+
* When the input carries no dedupeKey the kit adds a one-off one, so a retry
|
|
68
|
+
* after a timeout on a hub that DID store the first attempt answers
|
|
69
|
+
* `deduped: true` instead of pushing twice. A caller-supplied key is sent as is.
|
|
70
|
+
*/
|
|
71
|
+
export async function notify(input, opts = {}) {
|
|
72
|
+
try {
|
|
73
|
+
const { urls, key, missing } = config();
|
|
74
|
+
if (missing.length) {
|
|
75
|
+
warnOnce("notify-unconfigured", `notify is a no-op: ${missing.join(", ")} not set`);
|
|
76
|
+
return failed(`not configured: ${missing.join(", ")} not set`, { skipped: "unconfigured" });
|
|
77
|
+
}
|
|
78
|
+
if (!input || typeof input.title !== "string" || !input.title.trim()) {
|
|
79
|
+
return failed("title is required", { skipped: "invalid" });
|
|
80
|
+
}
|
|
81
|
+
if (typeof input.category !== "string" || !input.category) {
|
|
82
|
+
return failed("category is required", { skipped: "invalid" });
|
|
83
|
+
}
|
|
84
|
+
const body = stripUndefined({ ...input });
|
|
85
|
+
if (!body.dedupeKey)
|
|
86
|
+
body.dedupeKey = dedupeKey("kit-once", randomUUID());
|
|
87
|
+
if (opts.dryRun) {
|
|
88
|
+
return { ok: true, dryRun: true, queued: false, deduped: false, urls, path: NOTIFY_PATH, body };
|
|
89
|
+
}
|
|
90
|
+
const outcome = await failoverFetch(urls, NOTIFY_PATH, {
|
|
91
|
+
method: "POST",
|
|
92
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
|
|
93
|
+
body: JSON.stringify(body),
|
|
94
|
+
}, { ...NOTIFY_DEFAULTS, ...stripUndefined(opts) });
|
|
95
|
+
if (outcome.kind === "failed") {
|
|
96
|
+
console.warn(`[zoo-kit] notify failed after ${outcome.attempts.length} attempt(s): ${outcome.error}`);
|
|
97
|
+
return failed(outcome.error, { status: outcome.status, attempts: outcome.attempts });
|
|
98
|
+
}
|
|
99
|
+
const { res, attempts } = outcome;
|
|
100
|
+
const json = (await readJson(res));
|
|
101
|
+
if (res.ok && json && json.ok === true && typeof json.id === "string") {
|
|
102
|
+
return {
|
|
103
|
+
ok: true,
|
|
104
|
+
id: json.id,
|
|
105
|
+
queued: json.queued === true,
|
|
106
|
+
deduped: json.deduped === true,
|
|
107
|
+
status: res.status,
|
|
108
|
+
url: outcome.base,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
const error = (json && typeof json.error === "string" && json.error) || `HTTP ${res.status}`;
|
|
112
|
+
console.warn(`[zoo-kit] notify refused by the hub (${res.status}): ${error}`);
|
|
113
|
+
return failed(error, { status: res.status, attempts });
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
// Belt and braces: nothing above should throw, but notify() must not.
|
|
117
|
+
return failed(err instanceof Error ? err.message : String(err));
|
|
118
|
+
}
|
|
119
|
+
}
|
package/dist/people.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { components } from "./generated/people.js";
|
|
2
|
+
import { type FailoverOptions } from "./http.js";
|
|
3
|
+
/** A v1 Person — roster fields only (contracts/v1/zoo-health.v1.yaml). */
|
|
4
|
+
export type Person = components["schemas"]["Person"];
|
|
5
|
+
export type PeopleStatus = "fresh" | "stale" | "unavailable" | "unconfigured";
|
|
6
|
+
export interface PeopleList {
|
|
7
|
+
people: Person[];
|
|
8
|
+
/** fresh = loaded inside the TTL; stale = an older copy served because the directory failed; unavailable = never loaded. */
|
|
9
|
+
status: PeopleStatus;
|
|
10
|
+
loadedAt: Date | null;
|
|
11
|
+
error?: string;
|
|
12
|
+
}
|
|
13
|
+
export type ResolveStatus = "fresh" | "stale" | "not-found" | "unavailable" | "unconfigured";
|
|
14
|
+
export interface ResolvedUsername {
|
|
15
|
+
person: Person | null;
|
|
16
|
+
status: ResolveStatus;
|
|
17
|
+
error?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface PeopleOptions extends FailoverOptions {
|
|
20
|
+
/** How long a list or a lookup counts as fresh. Default 5 min. */
|
|
21
|
+
ttlMs?: number;
|
|
22
|
+
/** How long a username lookup may be served stale while the directory is down. Default 15 min. */
|
|
23
|
+
staleUsernameMs?: number;
|
|
24
|
+
/** How long a "no such username" answer is remembered. Default 60 s. */
|
|
25
|
+
notFoundTtlMs?: number;
|
|
26
|
+
/** Clock, for tests. */
|
|
27
|
+
now?: () => number;
|
|
28
|
+
}
|
|
29
|
+
export declare const PEOPLE_DEFAULTS: {
|
|
30
|
+
ttlMs: number;
|
|
31
|
+
staleUsernameMs: number;
|
|
32
|
+
notFoundTtlMs: number;
|
|
33
|
+
attemptTimeoutMs: number;
|
|
34
|
+
totalBudgetMs: number;
|
|
35
|
+
rounds: number;
|
|
36
|
+
roundBackoffMs: number;
|
|
37
|
+
};
|
|
38
|
+
export declare const PEOPLE_PATHS: {
|
|
39
|
+
readonly list: "/api/v1/people";
|
|
40
|
+
readonly whoamiResolve: "/api/v1/whoami-resolve";
|
|
41
|
+
};
|
|
42
|
+
/** Keep only the contract's Person keys; null for anything that is not a usable person. */
|
|
43
|
+
export declare function toPerson(raw: unknown): Person | null;
|
|
44
|
+
export interface People {
|
|
45
|
+
list(): Promise<PeopleList>;
|
|
46
|
+
get(slug: string): Promise<Person | null>;
|
|
47
|
+
byAuthentikUsername(username: string): Promise<Person | null>;
|
|
48
|
+
/** byAuthentikUsername with the reason — what whoami uses. */
|
|
49
|
+
resolveUsername(username: string): Promise<ResolvedUsername>;
|
|
50
|
+
/** A health-handler check: throws when the roster never loaded; reports stale. */
|
|
51
|
+
healthCheck(): Promise<{
|
|
52
|
+
ok: true;
|
|
53
|
+
detail?: string;
|
|
54
|
+
}>;
|
|
55
|
+
/** Drop every cached answer. */
|
|
56
|
+
clear(): void;
|
|
57
|
+
}
|
|
58
|
+
/** A people client with its own cache. Most apps use the shared {@link people}. */
|
|
59
|
+
export declare function createPeople(options?: PeopleOptions): People;
|
|
60
|
+
/** The process-wide people client. */
|
|
61
|
+
export declare const people: People;
|