@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,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;
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.people = exports.PEOPLE_PATHS = exports.PEOPLE_DEFAULTS = void 0;
4
+ exports.toPerson = toPerson;
5
+ exports.createPeople = createPeople;
6
+ /**
7
+ * people — the roster client (plan §3.3).
8
+ *
9
+ * Reads the people directory's v1 surface over the base URLs in
10
+ * ZOO_PEOPLE_URLS (today that is zoo-health; a later phase points the SAME
11
+ * names at a separate directory with no code change — so nothing here is
12
+ * specific to whichever service answers).
13
+ *
14
+ * GET /api/v1/people list (archived ones flagged enabled:false)
15
+ * GET /api/v1/whoami-resolve?username= one linked authentik username
16
+ *
17
+ * Auth: `Authorization: Bearer <ZOO_PEOPLE_TOKEN>` + `X-Dispenser-Consumer:
18
+ * <ZOO_PEOPLE_CONSUMER>` (the directory's declared-consumer gate).
19
+ *
20
+ * FAIL-SOFT: the list is cached ~5 min and served STALE on error; it is empty
21
+ * only if it never loaded, and `status` says which. A username lookup serves
22
+ * its last answer for <= 15 min while the directory is down, then null — whoami
23
+ * fails closed on null.
24
+ */
25
+ const env_js_1 = require("./env.js");
26
+ const contract_js_1 = require("./generated/contract.js");
27
+ const http_js_1 = require("./http.js");
28
+ exports.PEOPLE_DEFAULTS = {
29
+ ttlMs: 5 * 60_000,
30
+ staleUsernameMs: 15 * 60_000,
31
+ notFoundTtlMs: 60_000,
32
+ attemptTimeoutMs: 5_000,
33
+ totalBudgetMs: 10_000,
34
+ rounds: 1,
35
+ roundBackoffMs: 250,
36
+ };
37
+ exports.PEOPLE_PATHS = {
38
+ list: "/api/v1/people",
39
+ whoamiResolve: "/api/v1/whoami-resolve",
40
+ };
41
+ const KEYS = new Set(contract_js_1.PERSON_KEYS);
42
+ /** Keep only the contract's Person keys; null for anything that is not a usable person. */
43
+ function toPerson(raw) {
44
+ if (!raw || typeof raw !== "object")
45
+ return null;
46
+ const r = raw;
47
+ if (typeof r.id !== "string" || !r.id || typeof r.slug !== "string" || !r.slug)
48
+ return null;
49
+ const out = {};
50
+ for (const k of Object.keys(r))
51
+ if (KEYS.has(k))
52
+ out[k] = r[k];
53
+ return out;
54
+ }
55
+ function config() {
56
+ const urls = (0, env_js_1.firstList)(env_js_1.ENV.PEOPLE_URLS);
57
+ const token = (0, env_js_1.str)(env_js_1.ENV.PEOPLE_TOKEN);
58
+ const consumer = (0, env_js_1.str)(env_js_1.ENV.PEOPLE_CONSUMER);
59
+ const missing = [];
60
+ if (!urls.length)
61
+ missing.push(env_js_1.ENV.PEOPLE_URLS);
62
+ if (!token)
63
+ missing.push(env_js_1.ENV.PEOPLE_TOKEN);
64
+ if (!consumer)
65
+ missing.push(env_js_1.ENV.PEOPLE_CONSUMER);
66
+ return { urls, token, consumer, missing };
67
+ }
68
+ /** A people client with its own cache. Most apps use the shared {@link people}. */
69
+ function createPeople(options = {}) {
70
+ const o = { ...exports.PEOPLE_DEFAULTS, ...(0, http_js_1.stripUndefined)(options) };
71
+ const now = options.now ?? Date.now;
72
+ let listCache = null;
73
+ let listInflight = null;
74
+ const users = new Map();
75
+ async function get(path) {
76
+ const c = config();
77
+ if (c.missing.length) {
78
+ (0, env_js_1.warnOnce)("people-unconfigured", `people is unavailable: ${c.missing.join(", ")} not set`);
79
+ return { kind: "unconfigured", error: `not configured: ${c.missing.join(", ")} not set` };
80
+ }
81
+ const outcome = await (0, http_js_1.failoverFetch)(c.urls, path, { method: "GET", headers: { Authorization: `Bearer ${c.token}`, "X-Dispenser-Consumer": c.consumer, Accept: "application/json" } }, o);
82
+ if (outcome.kind === "failed")
83
+ return { kind: "error", error: outcome.error };
84
+ const { res } = outcome;
85
+ const json = await (0, http_js_1.readJson)(res);
86
+ if (res.status === 404)
87
+ return { kind: "not-found" };
88
+ if (!res.ok) {
89
+ const msg = json?.error;
90
+ (0, env_js_1.warnOnce)(`people-${res.status}`, `the people directory refused this app (${res.status}${msg ? `: ${msg}` : ""}) — check ${env_js_1.ENV.PEOPLE_TOKEN} / ${env_js_1.ENV.PEOPLE_CONSUMER}`);
91
+ return { kind: "error", error: `HTTP ${res.status}${msg ? `: ${msg}` : ""}` };
92
+ }
93
+ return { kind: "ok", json };
94
+ }
95
+ async function loadList() {
96
+ const got = await get(exports.PEOPLE_PATHS.list);
97
+ if (got.kind === "ok") {
98
+ const raw = got.json?.people;
99
+ if (Array.isArray(raw)) {
100
+ const ppl = raw.map(toPerson).filter((p) => p !== null);
101
+ listCache = { people: ppl, at: now() };
102
+ return { people: ppl, status: "fresh", loadedAt: new Date(listCache.at) };
103
+ }
104
+ }
105
+ const error = got.kind === "ok" ? "malformed people list" : got.kind === "not-found" ? "HTTP 404" : got.error;
106
+ if (listCache)
107
+ return { people: listCache.people, status: "stale", loadedAt: new Date(listCache.at), error };
108
+ return { people: [], status: got.kind === "unconfigured" ? "unconfigured" : "unavailable", loadedAt: null, error };
109
+ }
110
+ const api = {
111
+ async list() {
112
+ if (listCache && now() - listCache.at < o.ttlMs) {
113
+ return { people: listCache.people, status: "fresh", loadedAt: new Date(listCache.at) };
114
+ }
115
+ // One request in flight however many callers ask at once.
116
+ listInflight ??= loadList().finally(() => {
117
+ listInflight = null;
118
+ });
119
+ return listInflight;
120
+ },
121
+ async get(slug) {
122
+ const { people: ppl } = await api.list();
123
+ return ppl.find((p) => p.slug === slug) ?? null;
124
+ },
125
+ async resolveUsername(username) {
126
+ const u = (username ?? "").trim().toLowerCase();
127
+ if (!u)
128
+ return { person: null, status: "not-found" };
129
+ const hit = users.get(u);
130
+ const age = hit ? now() - hit.at : Infinity;
131
+ if (hit && age < (hit.person ? o.ttlMs : o.notFoundTtlMs)) {
132
+ return { person: hit.person, status: hit.person ? "fresh" : "not-found" };
133
+ }
134
+ const got = await get(`${exports.PEOPLE_PATHS.whoamiResolve}?username=${encodeURIComponent(u)}`);
135
+ if (got.kind === "ok") {
136
+ const person = toPerson(got.json?.person);
137
+ if (person) {
138
+ users.set(u, { person, at: now() });
139
+ return { person, status: "fresh" };
140
+ }
141
+ return { person: null, status: "unavailable", error: "malformed whoami-resolve answer" };
142
+ }
143
+ if (got.kind === "not-found") {
144
+ users.set(u, { person: null, at: now() });
145
+ return { person: null, status: "not-found" };
146
+ }
147
+ if (hit?.person && age <= o.staleUsernameMs)
148
+ return { person: hit.person, status: "stale", error: got.error };
149
+ return { person: null, status: got.kind === "unconfigured" ? "unconfigured" : "unavailable", error: got.error };
150
+ },
151
+ async byAuthentikUsername(username) {
152
+ return (await api.resolveUsername(username)).person;
153
+ },
154
+ async healthCheck() {
155
+ const l = await api.list();
156
+ if (l.status === "fresh")
157
+ return { ok: true, detail: `${l.people.length} people` };
158
+ if (l.status === "stale")
159
+ return { ok: true, detail: `stale since ${l.loadedAt?.toISOString()}: ${l.error ?? ""}`.trim() };
160
+ throw new Error(`roster ${l.status}${l.error ? `: ${l.error}` : ""}`);
161
+ },
162
+ clear() {
163
+ listCache = null;
164
+ users.clear();
165
+ },
166
+ };
167
+ return api;
168
+ }
169
+ /** The process-wide people client. */
170
+ exports.people = createPeople();
@@ -0,0 +1,86 @@
1
+ import { type AppIdentity, type HeaderBag, type RequestLike } from "./keys.js";
2
+ import { type People, type Person } from "./people.js";
3
+ export type { AppIdentity, HeaderBag, RequestLike } from "./keys.js";
4
+ export interface PersonIdentity {
5
+ kind: "person";
6
+ slug: string;
7
+ personId: string;
8
+ via: "authentik" | "session" | "device";
9
+ person: Person;
10
+ /** The authentik username, when the identity came from one. */
11
+ username?: string;
12
+ /** Whatever the app's device resolver returned as `device`. */
13
+ device?: unknown;
14
+ }
15
+ export interface Anonymous {
16
+ kind: "anonymous";
17
+ /** Why — for the app's own logs. Never sent to the client by requirePerson. */
18
+ reason?: string;
19
+ }
20
+ export type Identity = PersonIdentity | AppIdentity | Anonymous;
21
+ export interface AuthentikOptions {
22
+ /** Public host(s) the edge serves this app on. Default: ZOO_KIT_PUBLIC_HOSTS, else PUBLIC_HOST. */
23
+ publicHosts?: string[];
24
+ /** X-Zoo-Gate secret. Default: ZOO_KIT_GATE_SECRET, else AUTH_GATE_SECRET. */
25
+ gateSecret?: string;
26
+ /** Honour DEV_USER (a dev-box short-circuit). Never honoured when NODE_ENV=production. */
27
+ allowDevUser?: boolean;
28
+ }
29
+ export interface SessionAnswer {
30
+ /** Resolved like an authentik username (linked username on the roster). */
31
+ authentikUsername?: string | null;
32
+ /** Or a roster slug the app already knows. */
33
+ slug?: string | null;
34
+ }
35
+ export interface DeviceAnswer {
36
+ personSlug: string;
37
+ device: unknown;
38
+ }
39
+ export interface WhoamiOptions {
40
+ /** Allowed app callers (source 1). */
41
+ apps?: readonly string[];
42
+ /** Device-key resolver (source 2) — the app keeps its own Device table in v1. */
43
+ resolveDeviceKey?: (key: string) => Promise<DeviceAnswer | null>;
44
+ /** The authentik header (source 3). `true` = env defaults. */
45
+ authentik?: boolean | AuthentikOptions;
46
+ /** A session resolver (source 4), e.g. NextAuth's getServerSession. */
47
+ session?: (req: RequestLike) => Promise<SessionAnswer | null | undefined>;
48
+ /** The people client (default: the shared one). */
49
+ people?: People;
50
+ }
51
+ /** Did the request name one of the public hosts (Host, or the first X-Forwarded-Host)? */
52
+ export declare function cameThroughGate(h: HeaderBag, hosts: readonly string[]): boolean;
53
+ /** Does the request carry the gate secret? True when no secret is configured (warned once). */
54
+ export declare function gateSecretOk(h: HeaderBag, secret: string): boolean;
55
+ /**
56
+ * The authentik username this request may claim, lowercased — or a reason it
57
+ * may not. Pure apart from env reads; never touches the network.
58
+ */
59
+ export declare function readAuthentikUsername(h: HeaderBag, o?: AuthentikOptions): {
60
+ username: string;
61
+ } | {
62
+ reason: string;
63
+ };
64
+ export declare function whoami(req: RequestLike, opts?: WhoamiOptions): Promise<Identity>;
65
+ /**
66
+ * Thrown by requirePerson / requireApp. Carries a ready Response with no
67
+ * detail beyond the status word, so nothing about WHY leaks to the caller.
68
+ *
69
+ * Next: catch (e) { if (e instanceof ZooKitAuthError) return e.response; throw e; }
70
+ * Hono: app.onError((e, c) => e instanceof ZooKitAuthError ? e.response : c.text("error", 500))
71
+ */
72
+ export declare class ZooKitAuthError extends Error {
73
+ readonly status: 401 | 403;
74
+ /** Server-side reason for the app's own logs. */
75
+ readonly reason: string;
76
+ constructor(status: 401 | 403, reason?: string);
77
+ /** A fresh Response each read (a body can only be consumed once). */
78
+ get response(): Response;
79
+ }
80
+ /** The person, or throws a 401 ZooKitAuthError. */
81
+ export declare function requirePerson(req: RequestLike, opts?: WhoamiOptions): Promise<PersonIdentity>;
82
+ /**
83
+ * The calling app, or throws: 401 when no Bearer was sent, 403 when the Bearer
84
+ * belongs to no allowed caller (or none of them has a key configured).
85
+ */
86
+ export declare function requireApp(req: RequestLike, allowed: readonly string[]): AppIdentity;
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ZooKitAuthError = void 0;
4
+ exports.cameThroughGate = cameThroughGate;
5
+ exports.gateSecretOk = gateSecretOk;
6
+ exports.readAuthentikUsername = readAuthentikUsername;
7
+ exports.whoami = whoami;
8
+ exports.requirePerson = requirePerson;
9
+ exports.requireApp = requireApp;
10
+ /**
11
+ * whoami — "who is this request?" (plan §3.2). FAILS CLOSED: anything that
12
+ * cannot be verified is `anonymous`, and requirePerson/requireApp turn that
13
+ * into a 401/403.
14
+ *
15
+ * Sources, each opt-in, tried in this order:
16
+ * 1. app keys — `apps: [...]`, Bearer = ZOO_KIT_APP_KEY_<CALLER> -> kind "app"
17
+ * 2. device key — `resolveDeviceKey(key)`, the app's own Device table -> via "device"
18
+ * 3. authentik — `authentik: true`, the edge's username header -> via "authentik"
19
+ * 4. session — `session(req)`, e.g. a NextAuth session lookup -> via "session"
20
+ *
21
+ * Every person is resolved through the people directory, so every app gets the
22
+ * same slug; an archived person (enabled:false) is refused.
23
+ *
24
+ * THE AUTHENTIK GATE mirrors zoo-health lib/identityGate.ts:
25
+ * - HOST GATE: the request must name a configured public host in `Host` OR
26
+ * in the FIRST value of `X-Forwarded-Host`. Both are needed (B517): Next
27
+ * fills x-forwarded-host only when absent, so Traefik's survives; and a
28
+ * server action's redirect() is re-rendered by Next from its own bind address with every
29
+ * header EXCEPT Host. Do not "simplify" this to Host-only.
30
+ * - GATE SECRET: when a gate secret is configured, `X-Zoo-Gate` must equal it
31
+ * (timing-safe). Empty = unenforced, warned once — the interim until
32
+ * Traefik stamps it. Both headers are forgeable from the LAN without it.
33
+ * - The username is lowercased (authentik lowercases usernames; a
34
+ * case-varying second lookup would split one person in two).
35
+ * - No public host configured = the source refuses everything (there is no
36
+ * default host in this package).
37
+ */
38
+ const env_js_1 = require("./env.js");
39
+ const keys_js_1 = require("./keys.js");
40
+ const people_js_1 = require("./people.js");
41
+ const USERNAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
42
+ function bareHost(v) {
43
+ return (v || "").split(",")[0].trim().toLowerCase().split(":")[0];
44
+ }
45
+ function publicHosts(o) {
46
+ const hosts = o.publicHosts ?? (0, env_js_1.firstList)(env_js_1.ENV.PUBLIC_HOSTS, env_js_1.ENV.PUBLIC_HOST);
47
+ return hosts.map((h) => bareHost(h)).filter(Boolean);
48
+ }
49
+ /** Did the request name one of the public hosts (Host, or the first X-Forwarded-Host)? */
50
+ function cameThroughGate(h, hosts) {
51
+ if (!hosts.length)
52
+ return false;
53
+ const host = bareHost(h.get("host"));
54
+ const fwd = bareHost(h.get("x-forwarded-host"));
55
+ return hosts.includes(host) || (fwd !== "" && hosts.includes(fwd));
56
+ }
57
+ /** Does the request carry the gate secret? True when no secret is configured (warned once). */
58
+ function gateSecretOk(h, secret) {
59
+ if (!secret) {
60
+ (0, env_js_1.warnOnce)("gate-unenforced", "no gate secret configured (ZOO_KIT_GATE_SECRET / AUTH_GATE_SECRET) — X-Zoo-Gate is NOT enforced");
61
+ return true;
62
+ }
63
+ return (0, keys_js_1.safeEqual)(h.get("x-zoo-gate") ?? "", secret);
64
+ }
65
+ /**
66
+ * The authentik username this request may claim, lowercased — or a reason it
67
+ * may not. Pure apart from env reads; never touches the network.
68
+ */
69
+ function readAuthentikUsername(h, o = {}) {
70
+ if (o.allowDevUser) {
71
+ const dev = (0, env_js_1.str)(env_js_1.ENV.DEV_USER);
72
+ if (dev) {
73
+ if (process.env.NODE_ENV === "production") {
74
+ (0, env_js_1.warnOnce)("dev-user-prod", "DEV_USER is set but NODE_ENV=production — ignored");
75
+ }
76
+ else {
77
+ return { username: dev.toLowerCase() };
78
+ }
79
+ }
80
+ }
81
+ const hosts = publicHosts(o);
82
+ if (!hosts.length) {
83
+ (0, env_js_1.warnOnce)("no-public-host", `authentik identity refused: ${env_js_1.ENV.PUBLIC_HOSTS} not set`);
84
+ return { reason: "no public host configured" };
85
+ }
86
+ if (!cameThroughGate(h, hosts))
87
+ return { reason: "not through the public host" };
88
+ const secret = o.gateSecret ?? (0, env_js_1.firstStr)(env_js_1.ENV.GATE_SECRET, env_js_1.ENV.AUTH_GATE_SECRET);
89
+ if (!gateSecretOk(h, secret))
90
+ return { reason: "gate secret mismatch" };
91
+ const raw = (h.get("x-authentik-username") || h.get("x-forwarded-preferred-username") || h.get("x-forwarded-user") || "").trim();
92
+ if (!raw)
93
+ return { reason: "no identity header" };
94
+ if (!USERNAME_RE.test(raw))
95
+ return { reason: "unusable username" };
96
+ return { username: raw.toLowerCase() };
97
+ }
98
+ function asPerson(p, via, extra = {}) {
99
+ if (!p)
100
+ return { kind: "anonymous", reason: "no such person on the roster" };
101
+ if (p.enabled === false)
102
+ return { kind: "anonymous", reason: "person is archived" };
103
+ return { kind: "person", slug: p.slug, personId: p.id, via, person: p, ...extra };
104
+ }
105
+ async function whoami(req, opts = {}) {
106
+ const dir = opts.people ?? people_js_1.people;
107
+ const h = req.headers;
108
+ const token = (0, keys_js_1.bearerOf)(h);
109
+ if (token && opts.apps?.length) {
110
+ const app = (0, keys_js_1.appForToken)(token, opts.apps);
111
+ if (app)
112
+ return { kind: "app", app, via: "key" };
113
+ }
114
+ if (token && opts.resolveDeviceKey) {
115
+ try {
116
+ const d = await opts.resolveDeviceKey(token);
117
+ if (d && typeof d.personSlug === "string" && d.personSlug) {
118
+ return asPerson(await dir.get(d.personSlug), "device", { device: d.device });
119
+ }
120
+ }
121
+ catch {
122
+ return { kind: "anonymous", reason: "device resolver failed" };
123
+ }
124
+ }
125
+ let reason = token ? "bearer not recognised" : "no credentials";
126
+ if (opts.authentik) {
127
+ const a = readAuthentikUsername(h, opts.authentik === true ? {} : opts.authentik);
128
+ if ("username" in a) {
129
+ const r = await dir.resolveUsername(a.username);
130
+ if (r.person)
131
+ return asPerson(r.person, "authentik", { username: a.username });
132
+ // A real header whose lookup failed is a definitive answer: never fall
133
+ // through to a weaker source and never guess.
134
+ return { kind: "anonymous", reason: `username ${r.status}` };
135
+ }
136
+ reason = a.reason;
137
+ }
138
+ if (opts.session) {
139
+ try {
140
+ const s = await opts.session(req);
141
+ const su = (s?.authentikUsername ?? "").trim().toLowerCase();
142
+ if (su) {
143
+ const r = await dir.resolveUsername(su);
144
+ return r.person ? asPerson(r.person, "session", { username: su }) : { kind: "anonymous", reason: `username ${r.status}` };
145
+ }
146
+ if (s?.slug)
147
+ return asPerson(await dir.get(s.slug), "session");
148
+ }
149
+ catch {
150
+ return { kind: "anonymous", reason: "session resolver failed" };
151
+ }
152
+ }
153
+ return { kind: "anonymous", reason };
154
+ }
155
+ /**
156
+ * Thrown by requirePerson / requireApp. Carries a ready Response with no
157
+ * detail beyond the status word, so nothing about WHY leaks to the caller.
158
+ *
159
+ * Next: catch (e) { if (e instanceof ZooKitAuthError) return e.response; throw e; }
160
+ * Hono: app.onError((e, c) => e instanceof ZooKitAuthError ? e.response : c.text("error", 500))
161
+ */
162
+ class ZooKitAuthError extends Error {
163
+ status;
164
+ /** Server-side reason for the app's own logs. */
165
+ reason;
166
+ constructor(status, reason = "") {
167
+ super(status === 401 ? "unauthorized" : "forbidden");
168
+ this.name = "ZooKitAuthError";
169
+ this.status = status;
170
+ this.reason = reason;
171
+ }
172
+ /** A fresh Response each read (a body can only be consumed once). */
173
+ get response() {
174
+ return new Response(JSON.stringify({ error: this.message }), {
175
+ status: this.status,
176
+ headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
177
+ });
178
+ }
179
+ }
180
+ exports.ZooKitAuthError = ZooKitAuthError;
181
+ /** The person, or throws a 401 ZooKitAuthError. */
182
+ async function requirePerson(req, opts = {}) {
183
+ const who = await whoami(req, opts);
184
+ if (who.kind === "person")
185
+ return who;
186
+ throw new ZooKitAuthError(401, who.kind === "anonymous" ? (who.reason ?? "") : "an app key is not a person");
187
+ }
188
+ /**
189
+ * The calling app, or throws: 401 when no Bearer was sent, 403 when the Bearer
190
+ * belongs to no allowed caller (or none of them has a key configured).
191
+ */
192
+ function requireApp(req, allowed) {
193
+ const v = (0, keys_js_1.checkApp)(req, allowed);
194
+ if (v.ok)
195
+ return v.identity;
196
+ throw new ZooKitAuthError(v.status, v.status === 401 ? "no bearer" : "bearer matches no allowed caller");
197
+ }
@@ -1,5 +1,5 @@
1
1
  /** The kit's own version — reported as `kit` by the health handler. */
2
- export declare const KIT_VERSION = "1.0.1";
2
+ export declare const KIT_VERSION = "1.1.0";
3
3
  /** The exact keys a v1 Person may carry; anything else is dropped. */
4
4
  export declare const PERSON_KEYS: readonly ["authentikUsername", "dob", "enabled", "haEntityId", "headingColor", "id", "kind", "name", "photoUrl", "role", "slug", "sortOrder", "traccarDeviceId"];
5
5
  export declare const NOTIFY_PRIORITIES: readonly ["passive", "active", "time-sensitive", "critical"];
@@ -1,7 +1,7 @@
1
1
  // GENERATED by packages/zoo-kit/scripts/generate.mjs from contracts/v1/*.v1.yaml + packages/zoo-kit/package.json.
2
2
  // Do not edit — change the contract and run `npm run gen`.
3
3
  /** The kit's own version — reported as `kit` by the health handler. */
4
- export const KIT_VERSION = "1.0.1";
4
+ export const KIT_VERSION = "1.1.0";
5
5
  /** The exact keys a v1 Person may carry; anything else is dropped. */
6
6
  export const PERSON_KEYS = ["authentikUsername", "dob", "enabled", "haEntityId", "headingColor", "id", "kind", "name", "photoUrl", "role", "slug", "sortOrder", "traccarDeviceId"];
7
7
  export const NOTIFY_PRIORITIES = ["passive", "active", "time-sensitive", "critical"];
package/dist/health.js CHANGED
@@ -7,6 +7,12 @@
7
7
  * a check that throws, returns false or outlives its timeout marks itself and
8
8
  * `ok` false; it never makes the route throw or hang.
9
9
  *
10
+ * ERROR TEXT IS GENERIC, ALWAYS. This route is open on the LAN and a raw error
11
+ * (a Prisma one names the database host and port) must not be readable there.
12
+ * A thrown check reports "check failed" and its real message goes to the app's
13
+ * log, one console.warn per failure. A timeout keeps "timed out after N ms",
14
+ * which the kit wrote itself. `detail` is the app's own text and stays as is.
15
+ *
10
16
  * version: opts.version, else APP_VERSION, else the `version` in the package.json
11
17
  * in the working directory, else null.
12
18
  * sha: opts.sha, else GIT_SHA, else null. "unknown" counts as unknown.
@@ -33,14 +39,18 @@ function packageVersion() {
33
39
  }
34
40
  return cwdVersion;
35
41
  }
36
- async function runCheck(fn, timeoutMs) {
42
+ const messageOf = (err) => (err instanceof Error ? err.message : String(err));
43
+ async function runCheck(name, fn, timeoutMs) {
37
44
  const started = Date.now();
38
45
  let timer;
46
+ // Compared by identity: a check that throws its own "timed out…" text is
47
+ // still app text and may name a host.
48
+ const timedOut = new Error(`timed out after ${timeoutMs} ms`);
39
49
  try {
40
50
  const value = await Promise.race([
41
51
  Promise.resolve().then(fn),
42
52
  new Promise((_, reject) => {
43
- timer = setTimeout(() => reject(new Error(`timed out after ${timeoutMs} ms`)), timeoutMs);
53
+ timer = setTimeout(() => reject(timedOut), timeoutMs);
44
54
  }),
45
55
  ]);
46
56
  const ms = Date.now() - started;
@@ -53,7 +63,11 @@ async function runCheck(fn, timeoutMs) {
53
63
  return { ok: true, ms };
54
64
  }
55
65
  catch (err) {
56
- return { ok: false, ms: Date.now() - started, error: (err instanceof Error ? err.message : String(err)).slice(0, 300) };
66
+ const ms = Date.now() - started;
67
+ if (err === timedOut)
68
+ return { ok: false, ms, error: timedOut.message };
69
+ console.warn(`[zoo-kit] health check "${name}" failed: ${messageOf(err)}`);
70
+ return { ok: false, ms, error: "check failed" };
57
71
  }
58
72
  finally {
59
73
  clearTimeout(timer);
@@ -63,7 +77,7 @@ async function runCheck(fn, timeoutMs) {
63
77
  export async function healthBody(opts) {
64
78
  const timeout = opts.checkTimeoutMs ?? 3_000;
65
79
  const names = Object.keys(opts.checks ?? {});
66
- const results = await Promise.all(names.map((n) => runCheck(opts.checks[n], timeout)));
80
+ const results = await Promise.all(names.map((n) => runCheck(n, opts.checks[n], timeout)));
67
81
  const checks = Object.fromEntries(names.map((n, i) => [n, results[i]]));
68
82
  if (opts.requiredEnv?.length)
69
83
  checks.config = checkConfig(opts.requiredEnv);
@@ -90,6 +104,7 @@ export function healthHandler(opts) {
90
104
  body = await healthBody(opts);
91
105
  }
92
106
  catch (err) {
107
+ console.warn(`[zoo-kit] health failed: ${messageOf(err)}`);
93
108
  body = {
94
109
  ok: false,
95
110
  app: opts.app,
@@ -97,7 +112,7 @@ export function healthHandler(opts) {
97
112
  sha: null,
98
113
  kit: KIT_VERSION,
99
114
  uptimeS: Math.floor(process.uptime()),
100
- checks: { kit: { ok: false, ms: 0, error: err instanceof Error ? err.message : String(err) } },
115
+ checks: { kit: { ok: false, ms: 0, error: "health failed" } },
101
116
  };
102
117
  }
103
118
  return new Response(JSON.stringify(body), {
package/dist/notify.d.ts CHANGED
@@ -11,6 +11,10 @@ export type NotifyInput = Omit<Schemas["NotifyInput"], "category"> & {
11
11
  export interface NotifyOptions extends FailoverOptions {
12
12
  /** Build and return the request, send nothing. Still requires the config. */
13
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;
14
18
  }
15
19
  export interface NotifySent {
16
20
  ok: true;
@@ -59,7 +63,7 @@ export declare const NOTIFY_DEFAULTS: Required<FailoverOptions>;
59
63
  * Throws TypeError on an unusable `kind` — that is a bug at the call site.
60
64
  */
61
65
  export declare function dedupeKey(kind: string, ...parts: Array<string | number | bigint | boolean | null | undefined>): string;
62
- /** Is notify configured? Names only. */
66
+ /** Is notify configured through the env? Names only; per-call overrides are not counted. */
63
67
  export declare function notifyConfigured(): {
64
68
  ok: boolean;
65
69
  missing: string[];