@jdcpuwiz/zoo-kit 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -178,6 +178,68 @@ Answers are cached 5 min and served stale ≤15 min while the directory is down.
178
178
  `People` itself is unchanged; the extra member lives on `PeopleClient`, so a
179
179
  hand-rolled `People` stub still type-checks.
180
180
 
181
+ ### people.signature (1.4.0, additive — BP#130 S8a)
182
+
183
+ A person's one signature, set on their zoo-people profile (draw, type or
184
+ upload; a PNG with a transparent background):
185
+
186
+ ```ts
187
+ const s = await people.signature("shad"); // {status: ok|none|unavailable|unconfigured, png, sha256, error?}
188
+ ```
189
+
190
+ `GET /api/v1/people/{slug}/signature` on the same `ZOO_PEOPLE_URLS` with the
191
+ same token. zoo-people admits it on its OWN caller list (`SIGNATURE_CALLERS`,
192
+ default `timesheet`, `zoo-studio`); any other key gets 401. Never cached, never
193
+ throws.
194
+
195
+ ## devices (1.3.0, additive — BP#129 P10c)
196
+
197
+ One device pairing for the fleet: zoo-people owns every paired phone; an app
198
+ keeps its own redeem route and its own device header and forwards through the
199
+ kit. Contract: zoo-people `docs/API.md` → "Devices". No new env names — base
200
+ URLs are `ZOO_PEOPLE_URLS` (else `ZOO_KIT_APP_URLS_ZOO_PEOPLE`), the key is this
201
+ app's kit key ON zoo-people (`ZOO_KIT_APP_KEY_FOR_ZOO_PEOPLE`, else
202
+ `ZOO_PEOPLE_TOKEN`), and the revoke push is checked against
203
+ `ZOO_KIT_APP_KEY_ZOO_PEOPLE` (zoo-people's key, minted on your app).
204
+
205
+ ```ts
206
+ import { createDevices, requirePerson, ZooKitAuthError } from "@jdcpuwiz/zoo-kit";
207
+
208
+ // ONE instance per process — resolve and the revoke receiver must share its cache.
209
+ export const devices = createDevices({ app: "zoo-health" /* , cookie: "ZSB_DEVICE" */ });
210
+
211
+ // the app's existing redeem route
212
+ const r = await devices.redeem(body.code, { deviceName: body.name, platform: "ios" });
213
+ if (!r.ok) return Response.json({ error: r.error }, { status: r.status }); // 404/409/410/429/503
214
+ return Response.json({ key: r.key }); // hand to the phone; never log it
215
+
216
+ // any device-authenticated route
217
+ const v = await devices.resolve(req); // Bearer (or the legacy cookie)
218
+ if (!v.ok) return new Response(null, { status: v.status }); // 401, or 503 when zoo-people is down
219
+ v.identity; // {kind:"person", via:"device", slug, personId, app, device:{id,name,appRole}, person}
220
+
221
+ // or through whoami / requirePerson (device source tried before resolveDeviceKey)
222
+ const who = await requirePerson(req, { devices }); // throws ZooKitAuthError 401 / 503
223
+
224
+ // app/api/internal/devices/revoked/route.ts (DEVICE_REVOKE_PATH)
225
+ export const POST = devices.revokeHandler();
226
+ ```
227
+
228
+ | Situation | Answer |
229
+ |---|---|
230
+ | valid key | 200, cached 60 s (`status: "fresh"` then `"cached"`) |
231
+ | revoke push arrived | the very next call is 401, even inside the 60 s (and an answer in flight when it landed is not re-cached) |
232
+ | zoo-people says `unknown-or-revoked` | 401, cache + last-known-good dropped |
233
+ | zoo-people down, key answered valid in the last 7 days | 200 (`status: "stale"`) |
234
+ | zoo-people down, key unknown | refused — **503 by default**, never 401 (zoo-health-ios forgets its key on a 401). `outageStatus: 401` opts out. |
235
+ | zoo-people refuses THIS app's key | treated as an outage (warned once), never as the phone's 401 |
236
+ | `app` set and the answer is another app's device | 401 |
237
+
238
+ Keys live in memory only as sha256 hashes; `redeem` goes to the primary URL
239
+ only (a timed-out redeem may have landed) and primes the cache with the new
240
+ device. `selfRevoke(key)` forwards a phone's own Unpair. `ZooKitAuthError.status`
241
+ gained `503` in 1.3.0.
242
+
181
243
  ## Health route
182
244
 
183
245
  ```ts
@@ -0,0 +1,110 @@
1
+ import { type FailoverOptions } from "./http.js";
2
+ import { type HeaderBag, type RequestLike } from "./keys.js";
3
+ export declare const DEVICES_PATHS: {
4
+ readonly redeem: "/api/v1/devices/redeem";
5
+ readonly resolve: "/api/v1/devices/resolve";
6
+ readonly selfRevoke: "/api/v1/devices/self-revoke";
7
+ };
8
+ /** The conventional path an app mounts revokeHandler() on. */
9
+ export declare const DEVICE_REVOKE_PATH = "/api/internal/devices/revoked";
10
+ export declare const DEVICES_DEFAULTS: {
11
+ ttlMs: number;
12
+ staleMs: number;
13
+ outageStatus: 401 | 503;
14
+ maxEntries: number;
15
+ /** A revoked deviceId is remembered this long, so an in-flight answer can't re-cache it. */
16
+ tombstoneMs: number;
17
+ attemptTimeoutMs: number;
18
+ totalBudgetMs: number;
19
+ rounds: number;
20
+ roundBackoffMs: number;
21
+ };
22
+ export interface DevicePerson {
23
+ id: string;
24
+ slug: string;
25
+ name: string;
26
+ role: string;
27
+ enabled: boolean;
28
+ }
29
+ export interface DeviceInfo {
30
+ id: string;
31
+ name: string;
32
+ appRole: string | null;
33
+ }
34
+ export interface DeviceIdentity {
35
+ kind: "person";
36
+ via: "device";
37
+ slug: string;
38
+ personId: string;
39
+ app: string;
40
+ device: DeviceInfo;
41
+ person: DevicePerson;
42
+ }
43
+ /** fresh = zoo-people just said so; cached = inside the 60 s; stale = last-known-good during an outage. */
44
+ export type DeviceStatus = "fresh" | "cached" | "stale";
45
+ export type DeviceVerdict = {
46
+ ok: true;
47
+ identity: DeviceIdentity;
48
+ status: DeviceStatus;
49
+ } | {
50
+ ok: false;
51
+ status: 401 | 503;
52
+ reason: string;
53
+ };
54
+ export interface RedeemOptions {
55
+ deviceName?: string;
56
+ platform?: "ios" | "macos" | "web";
57
+ }
58
+ export type RedeemResult = {
59
+ ok: true;
60
+ deviceId: string;
61
+ /** The raw key — hand it to the phone, never log or store it. */
62
+ key: string;
63
+ keyPrefix: string;
64
+ name: string;
65
+ appRole: string | null;
66
+ person: DevicePerson;
67
+ } | {
68
+ ok: false;
69
+ status: number;
70
+ error: string;
71
+ };
72
+ export interface DevicesOptions extends FailoverOptions {
73
+ /** This app's slug; when set, an answer for another app's device is refused. */
74
+ app?: string;
75
+ /** Legacy cookie to read the key from when there is no Bearer (e.g. "ZSB_DEVICE"). */
76
+ cookie?: string;
77
+ /** Custom key reader; replaces Bearer + cookie. */
78
+ readKey?: (h: HeaderBag) => string | null;
79
+ ttlMs?: number;
80
+ staleMs?: number;
81
+ outageStatus?: 401 | 503;
82
+ maxEntries?: number;
83
+ tombstoneMs?: number;
84
+ /** Who may send the revoke push. Default ["zoo-people"] (ZOO_KIT_APP_KEY_ZOO_PEOPLE). */
85
+ revokeCallers?: readonly string[];
86
+ /** Clock, for tests. */
87
+ now?: () => number;
88
+ }
89
+ export interface Devices {
90
+ /** Forward a pairing code to zoo-people. Never throws. */
91
+ redeem(code: string, opts?: RedeemOptions): Promise<RedeemResult>;
92
+ /** Read the device key from the request and resolve it. */
93
+ resolve(req: RequestLike): Promise<DeviceVerdict>;
94
+ /** Resolve a raw key. */
95
+ resolveKey(key: string): Promise<DeviceVerdict>;
96
+ /** The phone's own "Unpair": forwards to zoo-people and evicts locally. */
97
+ selfRevoke(key: string): Promise<{
98
+ ok: boolean;
99
+ status: number;
100
+ }>;
101
+ /** Drop every cached answer for this device and refuse it from now on. */
102
+ evict(deviceId: string): boolean;
103
+ /** The route handler for zoo-people's revoke push (mount on DEVICE_REVOKE_PATH). */
104
+ revokeHandler(): (req: Request) => Promise<Response>;
105
+ /** Cached entries, for tests and health. */
106
+ size(): number;
107
+ }
108
+ export declare function createDevices(options?: DevicesOptions): Devices;
109
+ /** The shared instance (env-configured). Apps that need `app`/`cookie` make their own with createDevices. */
110
+ export declare const devices: Devices;
@@ -0,0 +1,305 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.devices = exports.DEVICES_DEFAULTS = exports.DEVICE_REVOKE_PATH = exports.DEVICES_PATHS = void 0;
4
+ exports.createDevices = createDevices;
5
+ /**
6
+ * devices — one device pairing for the whole fleet (BP#129 P10c, kit 1.3.0).
7
+ *
8
+ * zoo-people owns every paired phone (contract: zoo-people docs/API.md →
9
+ * "Devices"). An app keeps its own redeem route and its own device header, and
10
+ * forwards to zoo-people through this module:
11
+ *
12
+ * POST /api/v1/devices/redeem {code, deviceName?, platform?} -> the key, ONCE
13
+ * POST /api/v1/devices/resolve {key} -> the device + its person, or 401
14
+ *
15
+ * Auth: `Authorization: Bearer <key>` where the key is this app's kit key ON
16
+ * zoo-people (ZOO_KIT_APP_KEY_FOR_ZOO_PEOPLE, else ZOO_PEOPLE_TOKEN — in the
17
+ * fleet the people token already IS that key). Base URLs: ZOO_PEOPLE_URLS,
18
+ * else ZOO_KIT_APP_URLS_ZOO_PEOPLE. No new env names.
19
+ *
20
+ * Cache rules (Wiz 2026-11-16):
21
+ * - a valid answer is reused for 60 s, then re-checked;
22
+ * - a revoke push (revokeHandler) evicts it at once — the next call is 401
23
+ * even inside the 60 s;
24
+ * - zoo-people unreachable: a key answered valid in the last 7 days keeps
25
+ * working; an UNKNOWN key is refused (fail closed). The refusal status is
26
+ * 503 by default, never 401, because zoo-health-ios forgets its key on a
27
+ * 401 (P10a) — an outage must not unpair a phone. `outageStatus: 401`
28
+ * opts out for an app whose clients don't care.
29
+ * - zoo-people's 401 "unknown-or-revoked" is final: the cache entry and its
30
+ * last-known-good copy are dropped.
31
+ *
32
+ * Keys are held in memory only as sha256 hashes. Nothing here logs a key.
33
+ */
34
+ const node_crypto_1 = require("node:crypto");
35
+ const env_js_1 = require("./env.js");
36
+ const http_js_1 = require("./http.js");
37
+ const keys_js_1 = require("./keys.js");
38
+ exports.DEVICES_PATHS = {
39
+ redeem: "/api/v1/devices/redeem",
40
+ resolve: "/api/v1/devices/resolve",
41
+ selfRevoke: "/api/v1/devices/self-revoke",
42
+ };
43
+ /** The conventional path an app mounts revokeHandler() on. */
44
+ exports.DEVICE_REVOKE_PATH = "/api/internal/devices/revoked";
45
+ exports.DEVICES_DEFAULTS = {
46
+ ttlMs: 60_000,
47
+ staleMs: 7 * 24 * 60 * 60_000,
48
+ outageStatus: 503,
49
+ maxEntries: 5_000,
50
+ /** A revoked deviceId is remembered this long, so an in-flight answer can't re-cache it. */
51
+ tombstoneMs: 10 * 60_000,
52
+ attemptTimeoutMs: 5_000,
53
+ totalBudgetMs: 10_000,
54
+ rounds: 1,
55
+ roundBackoffMs: 250,
56
+ };
57
+ const sha256 = (s) => (0, node_crypto_1.createHash)("sha256").update(s).digest("hex");
58
+ function cookieValue(h, name) {
59
+ for (const part of (h.get("cookie") ?? "").split(";")) {
60
+ const i = part.indexOf("=");
61
+ if (i < 0)
62
+ continue;
63
+ if (part.slice(0, i).trim() === name) {
64
+ const v = part.slice(i + 1).trim();
65
+ try {
66
+ return decodeURIComponent(v) || null;
67
+ }
68
+ catch {
69
+ return v || null;
70
+ }
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+ function config() {
76
+ const urls = (0, env_js_1.firstList)(env_js_1.ENV.PEOPLE_URLS, (0, env_js_1.appUrlsEnv)("zoo-people"));
77
+ const key = (0, env_js_1.firstStr)((0, env_js_1.appKeyForEnv)("zoo-people"), env_js_1.ENV.PEOPLE_TOKEN);
78
+ const missing = [];
79
+ if (!urls.length)
80
+ missing.push(env_js_1.ENV.PEOPLE_URLS);
81
+ if (!key)
82
+ missing.push(`${(0, env_js_1.appKeyForEnv)("zoo-people")} (or ${env_js_1.ENV.PEOPLE_TOKEN})`);
83
+ return { urls, key, missing };
84
+ }
85
+ const str = (v) => (typeof v === "string" ? v : "");
86
+ function toPersonPart(raw) {
87
+ if (!raw || typeof raw !== "object")
88
+ return null;
89
+ const p = raw;
90
+ if (!str(p.id) || !str(p.slug))
91
+ return null;
92
+ return { id: str(p.id), slug: str(p.slug), name: str(p.name), role: str(p.role), enabled: p.enabled !== false };
93
+ }
94
+ function toIdentity(raw) {
95
+ if (!raw || typeof raw !== "object")
96
+ return null;
97
+ const r = raw;
98
+ const person = toPersonPart(r.person);
99
+ if (!person || !str(r.deviceId) || !str(r.app))
100
+ return null;
101
+ return {
102
+ kind: "person",
103
+ via: "device",
104
+ slug: person.slug,
105
+ personId: person.id,
106
+ app: str(r.app),
107
+ device: { id: str(r.deviceId), name: str(r.name), appRole: typeof r.appRole === "string" ? r.appRole : null },
108
+ person,
109
+ };
110
+ }
111
+ const NO_STORE = { "Content-Type": "application/json", "Cache-Control": "no-store" };
112
+ const reply = (status, body) => new Response(JSON.stringify(body), { status, headers: NO_STORE });
113
+ function createDevices(options = {}) {
114
+ const o = { ...exports.DEVICES_DEFAULTS, ...(0, http_js_1.stripUndefined)(options) };
115
+ const now = options.now ?? Date.now;
116
+ const failover = {
117
+ attemptTimeoutMs: o.attemptTimeoutMs,
118
+ totalBudgetMs: o.totalBudgetMs,
119
+ rounds: o.rounds,
120
+ roundBackoffMs: o.roundBackoffMs,
121
+ };
122
+ const cache = new Map(); // sha256(key) -> answer
123
+ const tombstones = new Map(); // deviceId -> revoked at
124
+ const inflight = new Map();
125
+ const refuse = (status, reason) => ({ ok: false, status, reason });
126
+ function revoked(deviceId) {
127
+ const t = tombstones.get(deviceId);
128
+ if (t === undefined)
129
+ return false;
130
+ if (now() - t > o.tombstoneMs) {
131
+ tombstones.delete(deviceId);
132
+ return false;
133
+ }
134
+ return true;
135
+ }
136
+ function evict(deviceId) {
137
+ let hit = false;
138
+ for (const [h, e] of cache) {
139
+ if (e.identity.device.id === deviceId) {
140
+ cache.delete(h);
141
+ hit = true;
142
+ }
143
+ }
144
+ tombstones.set(deviceId, now());
145
+ if (tombstones.size > o.maxEntries) {
146
+ const oldest = tombstones.keys().next().value;
147
+ if (oldest !== undefined)
148
+ tombstones.delete(oldest);
149
+ }
150
+ return hit;
151
+ }
152
+ function remember(h, identity) {
153
+ cache.delete(h);
154
+ cache.set(h, { identity, at: now() });
155
+ if (cache.size > o.maxEntries) {
156
+ const oldest = cache.keys().next().value;
157
+ if (oldest !== undefined)
158
+ cache.delete(oldest);
159
+ }
160
+ }
161
+ async function post(path, body) {
162
+ const c = config();
163
+ if (c.missing.length) {
164
+ (0, env_js_1.warnOnce)("devices-config", `devices: not configured: ${c.missing.join(", ")} not set`);
165
+ return { kind: "failed", error: "unconfigured" };
166
+ }
167
+ // Primary-first failover is safe for resolve (read-only). Redeem is one-shot
168
+ // and goes to the primary only: a redeem that timed out may have landed.
169
+ const urls = path === exports.DEVICES_PATHS.resolve ? c.urls : c.urls.slice(0, 1);
170
+ const out = await (0, http_js_1.failoverFetch)(urls, path, { method: "POST", headers: { Authorization: `Bearer ${c.key}`, "Content-Type": "application/json" }, body: JSON.stringify(body) }, failover);
171
+ if (out.kind === "failed")
172
+ return { kind: "failed", error: out.error };
173
+ return { kind: "response", status: out.res.status, json: await (0, http_js_1.readJson)(out.res) };
174
+ }
175
+ async function lookup(key, h, prev) {
176
+ const outage = (why) => {
177
+ if (prev && now() - prev.at < o.staleMs && !revoked(prev.identity.device.id)) {
178
+ return { ok: true, identity: prev.identity, status: "stale" };
179
+ }
180
+ return refuse(o.outageStatus, `zoo-people unavailable (${why}) and key not cached`);
181
+ };
182
+ const res = await post(exports.DEVICES_PATHS.resolve, { key });
183
+ if (res.kind === "failed")
184
+ return outage(res.error);
185
+ const err = str(res.json?.error);
186
+ if (res.status === 200) {
187
+ const identity = toIdentity(res.json);
188
+ if (!identity)
189
+ return outage("malformed answer");
190
+ if (revoked(identity.device.id)) {
191
+ cache.delete(h);
192
+ return refuse(401, "device revoked");
193
+ }
194
+ if (options.app && identity.app !== options.app) {
195
+ cache.delete(h);
196
+ return refuse(401, "device belongs to another app");
197
+ }
198
+ if (!identity.person.enabled) {
199
+ cache.delete(h);
200
+ return refuse(401, "person is archived");
201
+ }
202
+ remember(h, identity);
203
+ return { ok: true, identity, status: "fresh" };
204
+ }
205
+ if (res.status === 401 && err === "unknown-or-revoked") {
206
+ cache.delete(h);
207
+ return refuse(401, "unknown or revoked device");
208
+ }
209
+ // Any other answer (our own app key refused, a 4xx we don't know) is OUR
210
+ // misconfiguration, not the phone's — never unpair a phone over it.
211
+ (0, env_js_1.warnOnce)(`devices-resolve-${res.status}`, `devices: zoo-people resolve answered ${res.status}${err ? ` (${err})` : ""} — check this app's key on zoo-people`);
212
+ return outage(`HTTP ${res.status}`);
213
+ }
214
+ async function resolveKey(key) {
215
+ if (!key || key.length > 200)
216
+ return refuse(401, "no device key");
217
+ const h = sha256(key);
218
+ const e = cache.get(h);
219
+ if (e && revoked(e.identity.device.id)) {
220
+ cache.delete(h);
221
+ return refuse(401, "device revoked");
222
+ }
223
+ if (e && now() - e.at < o.ttlMs)
224
+ return { ok: true, identity: e.identity, status: "cached" };
225
+ const running = inflight.get(h);
226
+ if (running)
227
+ return running;
228
+ const p = lookup(key, h, e).finally(() => inflight.delete(h));
229
+ inflight.set(h, p);
230
+ return p;
231
+ }
232
+ function readKey(hdrs) {
233
+ if (options.readKey)
234
+ return options.readKey(hdrs);
235
+ return (0, keys_js_1.bearerOf)(hdrs) ?? (options.cookie ? cookieValue(hdrs, options.cookie) : null);
236
+ }
237
+ return {
238
+ async redeem(code, ro = {}) {
239
+ const body = { code: String(code ?? "") };
240
+ if (ro.deviceName)
241
+ body.deviceName = ro.deviceName;
242
+ if (ro.platform)
243
+ body.platform = ro.platform;
244
+ const res = await post(exports.DEVICES_PATHS.redeem, body);
245
+ if (res.kind === "failed")
246
+ return { ok: false, status: 503, error: res.error === "unconfigured" ? "unconfigured" : "unavailable" };
247
+ const j = (res.json ?? {});
248
+ if (res.status !== 200)
249
+ return { ok: false, status: res.status, error: str(j.error) || `HTTP ${res.status}` };
250
+ const person = toPersonPart(j.person);
251
+ if (!person || !str(j.deviceId) || !str(j.key))
252
+ return { ok: false, status: 503, error: "malformed answer" };
253
+ const identity = toIdentity({ ...j, app: str(j.app) || options.app || "" });
254
+ if (identity && identity.app)
255
+ remember(sha256(str(j.key)), identity);
256
+ return {
257
+ ok: true,
258
+ deviceId: str(j.deviceId),
259
+ key: str(j.key),
260
+ keyPrefix: str(j.keyPrefix),
261
+ name: str(j.name),
262
+ appRole: typeof j.appRole === "string" ? j.appRole : null,
263
+ person,
264
+ };
265
+ },
266
+ resolve(req) {
267
+ const key = readKey(req.headers);
268
+ if (!key)
269
+ return Promise.resolve(refuse(401, "no device key"));
270
+ return resolveKey(key);
271
+ },
272
+ resolveKey,
273
+ async selfRevoke(key) {
274
+ if (!key)
275
+ return { ok: false, status: 401 };
276
+ const e = cache.get(sha256(key));
277
+ const res = await post(exports.DEVICES_PATHS.selfRevoke, { key });
278
+ if (res.kind === "failed")
279
+ return { ok: false, status: 503 };
280
+ if (res.status === 200 && e)
281
+ evict(e.identity.device.id);
282
+ else
283
+ cache.delete(sha256(key));
284
+ return { ok: res.status === 200, status: res.status };
285
+ },
286
+ evict,
287
+ revokeHandler() {
288
+ const callers = options.revokeCallers ?? ["zoo-people"];
289
+ return async (req) => {
290
+ const v = (0, keys_js_1.checkApp)(req, callers);
291
+ if (!v.ok)
292
+ return reply(v.status, { error: v.status === 401 ? "unauthorized" : "forbidden" });
293
+ const body = (await req.json().catch(() => null));
294
+ const deviceId = str(body?.deviceId);
295
+ if (!deviceId || deviceId.length > 200)
296
+ return reply(400, { error: "deviceId required" });
297
+ const evicted = evict(deviceId);
298
+ return reply(200, { ok: true, evicted });
299
+ };
300
+ },
301
+ size: () => cache.size,
302
+ };
303
+ }
304
+ /** The shared instance (env-configured). Apps that need `app`/`cookie` make their own with createDevices. */
305
+ exports.devices = createDevices();
@@ -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.2.0";
2
+ export declare const KIT_VERSION = "1.4.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"];
@@ -4,7 +4,7 @@
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.SLUG_PATTERN = exports.NOTIFY_PRIORITIES = exports.PERSON_KEYS = exports.KIT_VERSION = void 0;
6
6
  /** The kit's own version — reported as `kit` by the health handler. */
7
- exports.KIT_VERSION = "1.2.0";
7
+ exports.KIT_VERSION = "1.4.0";
8
8
  /** The exact keys a v1 Person may carry; anything else is dropped. */
9
9
  exports.PERSON_KEYS = ["authentikUsername", "dob", "enabled", "haEntityId", "headingColor", "id", "kind", "name", "photoUrl", "role", "slug", "sortOrder", "traccarDeviceId"];
10
10
  exports.NOTIFY_PRIORITIES = ["passive", "active", "time-sensitive", "critical"];
@@ -12,7 +12,8 @@
12
12
  export { ENV, appKeyEnv, appKeyForEnv, appUrlsEnv, checkConfig, envSuffix, type ConfigReport } from "./env.js";
13
13
  export { CATEGORIES, CATEGORY_ALIASES, CATEGORY_SLUGS, canonicalCategory, customCategory, isCanonicalCategory, isCategoryAlias, toCategory, type CategoryAlias, type CategoryInput, type CustomCategory, type NotifyCategory, } from "./categories.js";
14
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 Contact, type Contacts, type ContactsResult, type ContactsStatus, type People, type PeopleClient, type PeopleList, type PeopleOptions, type PeopleStatus, type Person, type ResolveStatus, type ResolvedUsername, } from "./people.js";
15
+ export { PEOPLE_DEFAULTS, PEOPLE_PATHS, createPeople, people, toPerson, type Contact, type Contacts, type ContactsResult, type ContactsStatus, type People, type PeopleClient, type SignatureResult, type PeopleList, type PeopleOptions, type PeopleStatus, type Person, type ResolveStatus, type ResolvedUsername, } from "./people.js";
16
+ export { DEVICES_DEFAULTS, DEVICES_PATHS, DEVICE_REVOKE_PATH, createDevices, devices, type DeviceIdentity, type DeviceInfo, type DevicePerson, type DeviceStatus, type DeviceVerdict, type Devices, type DevicesOptions, type RedeemOptions, type RedeemResult, } from "./devices.js";
16
17
  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
18
  export { ZooKitConfigError, bearerOf, callApp, checkApp, safeEqual, type AppIdentity, type AppVerdict, type CallAppOptions, type HeaderBag, type RequestLike, } from "./keys.js";
18
19
  export { healthBody, healthHandler, type CheckFn, type CheckResult, type HealthBody, type HealthOptions } from "./health.js";
package/dist/cjs/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
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;
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.devices = exports.createDevices = exports.DEVICE_REVOKE_PATH = exports.DEVICES_PATHS = exports.DEVICES_DEFAULTS = 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
4
  /**
5
5
  * @jdcpuwiz/zoo-kit — the homelab apps' shared plumbing (server-only).
6
6
  *
@@ -40,6 +40,12 @@ Object.defineProperty(exports, "PEOPLE_PATHS", { enumerable: true, get: function
40
40
  Object.defineProperty(exports, "createPeople", { enumerable: true, get: function () { return people_js_1.createPeople; } });
41
41
  Object.defineProperty(exports, "people", { enumerable: true, get: function () { return people_js_1.people; } });
42
42
  Object.defineProperty(exports, "toPerson", { enumerable: true, get: function () { return people_js_1.toPerson; } });
43
+ var devices_js_1 = require("./devices.js");
44
+ Object.defineProperty(exports, "DEVICES_DEFAULTS", { enumerable: true, get: function () { return devices_js_1.DEVICES_DEFAULTS; } });
45
+ Object.defineProperty(exports, "DEVICES_PATHS", { enumerable: true, get: function () { return devices_js_1.DEVICES_PATHS; } });
46
+ Object.defineProperty(exports, "DEVICE_REVOKE_PATH", { enumerable: true, get: function () { return devices_js_1.DEVICE_REVOKE_PATH; } });
47
+ Object.defineProperty(exports, "createDevices", { enumerable: true, get: function () { return devices_js_1.createDevices; } });
48
+ Object.defineProperty(exports, "devices", { enumerable: true, get: function () { return devices_js_1.devices; } });
43
49
  var whoami_js_1 = require("./whoami.js");
44
50
  Object.defineProperty(exports, "ZooKitAuthError", { enumerable: true, get: function () { return whoami_js_1.ZooKitAuthError; } });
45
51
  Object.defineProperty(exports, "cameThroughGate", { enumerable: true, get: function () { return whoami_js_1.cameThroughGate; } });
@@ -39,6 +39,7 @@ export declare const PEOPLE_PATHS: {
39
39
  readonly list: "/api/v1/people";
40
40
  readonly whoamiResolve: "/api/v1/whoami-resolve";
41
41
  readonly contactsSearch: "/api/v1/contacts/search";
42
+ readonly signature: (slug: string) => string;
42
43
  };
43
44
  /**
44
45
  * A card from the directory's Contacts book (v1.2, additive — BP#127 P9c).
@@ -91,7 +92,21 @@ export interface People {
91
92
  export type PeopleClient = People & {
92
93
  /** Search Wiz's own Contacts book through the directory. */
93
94
  contacts: Contacts;
95
+ /**
96
+ * A person's signature PNG (transparent background) — v1.4, additive, BP#130 S8a.
97
+ * zoo-people admits it on its OWN caller list (`SIGNATURE_CALLERS`: timesheet,
98
+ * zoo-studio). Never throws; never cached (a person can redraw it any time).
99
+ */
100
+ signature(slug: string): Promise<SignatureResult>;
94
101
  };
102
+ /** `status`: ok = png set; none = that person has no signature (or no such person). */
103
+ export interface SignatureResult {
104
+ status: "ok" | "none" | "unavailable" | "unconfigured";
105
+ png: Uint8Array | null;
106
+ /** Hex sha256 of `png`, as zoo-people reports it (ETag). */
107
+ sha256: string | null;
108
+ error?: string;
109
+ }
95
110
  /** A people client with its own cache. Most apps use the shared {@link people}. */
96
111
  export declare function createPeople(options?: PeopleOptions): PeopleClient;
97
112
  /** The process-wide people client. */
@@ -38,6 +38,7 @@ exports.PEOPLE_PATHS = {
38
38
  list: "/api/v1/people",
39
39
  whoamiResolve: "/api/v1/whoami-resolve",
40
40
  contactsSearch: "/api/v1/contacts/search",
41
+ signature: (slug) => `/api/v1/people/${encodeURIComponent(slug)}/signature`,
41
42
  };
42
43
  function toContact(raw) {
43
44
  if (!raw || typeof raw !== "object")
@@ -213,6 +214,30 @@ function createPeople(options = {}) {
213
214
  return r.contacts.find((c) => c.emails.includes(e)) ?? null;
214
215
  },
215
216
  },
217
+ async signature(slug) {
218
+ const sl = (slug ?? "").trim().toLowerCase();
219
+ if (!sl)
220
+ return { status: "none", png: null, sha256: null };
221
+ const c = config();
222
+ if (c.missing.length) {
223
+ (0, env_js_1.warnOnce)("people-unconfigured", `people is unavailable: ${c.missing.join(", ")} not set`);
224
+ return { status: "unconfigured", png: null, sha256: null, error: `not configured: ${c.missing.join(", ")} not set` };
225
+ }
226
+ const outcome = await (0, http_js_1.failoverFetch)(c.urls, exports.PEOPLE_PATHS.signature(sl), { method: "GET", headers: { Authorization: `Bearer ${c.token}`, Accept: "image/png" } }, o);
227
+ if (outcome.kind === "failed")
228
+ return { status: "unavailable", png: null, sha256: null, error: outcome.error };
229
+ const { res } = outcome;
230
+ if (res.status === 404)
231
+ return { status: "none", png: null, sha256: null };
232
+ if (!res.ok || !(res.headers.get("content-type") ?? "").startsWith("image/png")) {
233
+ if (!res.ok)
234
+ (0, env_js_1.warnOnce)(`people-signature-${res.status}`, `the people directory refused a signature read (${res.status}) — is this app in zoo-people's SIGNATURE_CALLERS?`);
235
+ return { status: "unavailable", png: null, sha256: null, error: `HTTP ${res.status}` };
236
+ }
237
+ const png = new Uint8Array(await res.arrayBuffer());
238
+ const sha = res.headers.get("x-signature-sha256") ?? ((res.headers.get("etag") ?? "").replace(/"/g, "") || null);
239
+ return { status: "ok", png, sha256: sha };
240
+ },
216
241
  clear() {
217
242
  listCache = null;
218
243
  users.clear();
@@ -1,4 +1,5 @@
1
1
  import { type AppIdentity, type HeaderBag, type RequestLike } from "./keys.js";
2
+ import type { Devices } from "./devices.js";
2
3
  import { type People, type Person } from "./people.js";
3
4
  export type { AppIdentity, HeaderBag, RequestLike } from "./keys.js";
4
5
  export interface PersonIdentity {
@@ -16,6 +17,8 @@ export interface Anonymous {
16
17
  kind: "anonymous";
17
18
  /** Why — for the app's own logs. Never sent to the client by requirePerson. */
18
19
  reason?: string;
20
+ /** True when the answer is "could not check" (zoo-people down) rather than "no" — requirePerson answers 503. */
21
+ unavailable?: boolean;
19
22
  }
20
23
  export type Identity = PersonIdentity | AppIdentity | Anonymous;
21
24
  export interface AuthentikOptions {
@@ -39,7 +42,12 @@ export interface DeviceAnswer {
39
42
  export interface WhoamiOptions {
40
43
  /** Allowed app callers (source 1). */
41
44
  apps?: readonly string[];
42
- /** Device-key resolver (source 2) — the app keeps its own Device table in v1. */
45
+ /**
46
+ * zoo-people device pairing (source 2, kit 1.3.0): the Bearer is resolved as
47
+ * a device key through this client. Tried before `resolveDeviceKey`.
48
+ */
49
+ devices?: Devices;
50
+ /** Device-key resolver (source 2, legacy) — the app's own Device table. */
43
51
  resolveDeviceKey?: (key: string) => Promise<DeviceAnswer | null>;
44
52
  /** The authentik header (source 3). `true` = env defaults. */
45
53
  authentik?: boolean | AuthentikOptions;
@@ -70,10 +78,10 @@ export declare function whoami(req: RequestLike, opts?: WhoamiOptions): Promise<
70
78
  * Hono: app.onError((e, c) => e instanceof ZooKitAuthError ? e.response : c.text("error", 500))
71
79
  */
72
80
  export declare class ZooKitAuthError extends Error {
73
- readonly status: 401 | 403;
81
+ readonly status: 401 | 403 | 503;
74
82
  /** Server-side reason for the app's own logs. */
75
83
  readonly reason: string;
76
- constructor(status: 401 | 403, reason?: string);
84
+ constructor(status: 401 | 403 | 503, reason?: string);
77
85
  /** A fresh Response each read (a body can only be consumed once). */
78
86
  get response(): Response;
79
87
  }