@jdcpuwiz/zoo-kit 1.1.0 → 1.3.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.
@@ -37,7 +37,24 @@ exports.PEOPLE_DEFAULTS = {
37
37
  exports.PEOPLE_PATHS = {
38
38
  list: "/api/v1/people",
39
39
  whoamiResolve: "/api/v1/whoami-resolve",
40
+ contactsSearch: "/api/v1/contacts/search",
40
41
  };
42
+ function toContact(raw) {
43
+ if (!raw || typeof raw !== "object")
44
+ return null;
45
+ const r = raw;
46
+ if (typeof r.name !== "string" || !r.name)
47
+ return null;
48
+ const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
49
+ return {
50
+ uid: typeof r.uid === "string" ? r.uid : null,
51
+ name: r.name,
52
+ emails: strs(r.emails).map((e) => e.toLowerCase()),
53
+ phones: strs(r.phones),
54
+ org: typeof r.org === "string" ? r.org : null,
55
+ hasPhoto: r.hasPhoto === true,
56
+ };
57
+ }
41
58
  const KEYS = new Set(contract_js_1.PERSON_KEYS);
42
59
  /** Keep only the contract's Person keys; null for anything that is not a usable person. */
43
60
  function toPerson(raw) {
@@ -72,6 +89,7 @@ function createPeople(options = {}) {
72
89
  let listCache = null;
73
90
  let listInflight = null;
74
91
  const users = new Map();
92
+ const searches = new Map();
75
93
  async function get(path) {
76
94
  const c = config();
77
95
  if (c.missing.length) {
@@ -159,9 +177,46 @@ function createPeople(options = {}) {
159
177
  return { ok: true, detail: `stale since ${l.loadedAt?.toISOString()}: ${l.error ?? ""}`.trim() };
160
178
  throw new Error(`roster ${l.status}${l.error ? `: ${l.error}` : ""}`);
161
179
  },
180
+ contacts: {
181
+ async search(q, opts = {}) {
182
+ const needle = (q ?? "").trim().toLowerCase();
183
+ if (!needle)
184
+ return { contacts: [], status: "fresh" };
185
+ const limit = Math.max(1, Math.min(50, Math.floor(opts.limit ?? 20)));
186
+ const key = `${limit}|${needle}`;
187
+ const hit = searches.get(key);
188
+ const age = hit ? now() - hit.at : Infinity;
189
+ if (hit && age < o.ttlMs)
190
+ return hit.result;
191
+ const got = await get(`${exports.PEOPLE_PATHS.contactsSearch}?q=${encodeURIComponent(needle)}&limit=${limit}`);
192
+ if (got.kind === "ok") {
193
+ const j = got.json;
194
+ if (Array.isArray(j?.contacts)) {
195
+ const contacts = j.contacts.map(toContact).filter((c) => c !== null);
196
+ const result = { contacts, status: j?.status === "stale" ? "stale" : "fresh" };
197
+ if (searches.size > 500)
198
+ searches.clear();
199
+ searches.set(key, { result, at: now() });
200
+ return result;
201
+ }
202
+ }
203
+ const error = got.kind === "ok" ? "malformed contacts answer" : got.kind === "not-found" ? "HTTP 404" : got.error;
204
+ if (hit && age <= o.staleUsernameMs)
205
+ return { ...hit.result, status: "stale", error };
206
+ return { contacts: [], status: got.kind === "unconfigured" ? "unconfigured" : "unavailable", error };
207
+ },
208
+ async byEmail(email) {
209
+ const e = (email ?? "").trim().toLowerCase();
210
+ if (!e)
211
+ return null;
212
+ const r = await api.contacts.search(e, { limit: 5 });
213
+ return r.contacts.find((c) => c.emails.includes(e)) ?? null;
214
+ },
215
+ },
162
216
  clear() {
163
217
  listCache = null;
164
218
  users.clear();
219
+ searches.clear();
165
220
  },
166
221
  };
167
222
  return api;
@@ -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
  }
@@ -111,6 +111,22 @@ async function whoami(req, opts = {}) {
111
111
  if (app)
112
112
  return { kind: "app", app, via: "key" };
113
113
  }
114
+ if (token && opts.devices) {
115
+ const v = await opts.devices.resolveKey(token);
116
+ if (v.ok) {
117
+ const d = v.identity;
118
+ // The full roster Person when the directory has it; otherwise the
119
+ // device answer's own person fields, so an outage of the roster list
120
+ // never unpairs a phone zoo-people just vouched for.
121
+ const full = await dir.get(d.slug).catch(() => null);
122
+ const p = (full ?? { ...d.person });
123
+ return asPerson(p, "device", { device: { ...d.device, app: d.app, status: v.status } });
124
+ }
125
+ if (v.status === 503)
126
+ return { kind: "anonymous", reason: v.reason, unavailable: true };
127
+ if (!opts.resolveDeviceKey)
128
+ return { kind: "anonymous", reason: v.reason };
129
+ }
114
130
  if (token && opts.resolveDeviceKey) {
115
131
  try {
116
132
  const d = await opts.resolveDeviceKey(token);
@@ -164,7 +180,7 @@ class ZooKitAuthError extends Error {
164
180
  /** Server-side reason for the app's own logs. */
165
181
  reason;
166
182
  constructor(status, reason = "") {
167
- super(status === 401 ? "unauthorized" : "forbidden");
183
+ super(status === 401 ? "unauthorized" : status === 403 ? "forbidden" : "unavailable");
168
184
  this.name = "ZooKitAuthError";
169
185
  this.status = status;
170
186
  this.reason = reason;
@@ -183,6 +199,8 @@ async function requirePerson(req, opts = {}) {
183
199
  const who = await whoami(req, opts);
184
200
  if (who.kind === "person")
185
201
  return who;
202
+ if (who.kind === "anonymous" && who.unavailable)
203
+ throw new ZooKitAuthError(503, who.reason ?? "");
186
204
  throw new ZooKitAuthError(401, who.kind === "anonymous" ? (who.reason ?? "") : "an app key is not a person");
187
205
  }
188
206
  /**
@@ -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,301 @@
1
+ /**
2
+ * devices — one device pairing for the whole fleet (BP#129 P10c, kit 1.3.0).
3
+ *
4
+ * zoo-people owns every paired phone (contract: zoo-people docs/API.md →
5
+ * "Devices"). An app keeps its own redeem route and its own device header, and
6
+ * forwards to zoo-people through this module:
7
+ *
8
+ * POST /api/v1/devices/redeem {code, deviceName?, platform?} -> the key, ONCE
9
+ * POST /api/v1/devices/resolve {key} -> the device + its person, or 401
10
+ *
11
+ * Auth: `Authorization: Bearer <key>` where the key is this app's kit key ON
12
+ * zoo-people (ZOO_KIT_APP_KEY_FOR_ZOO_PEOPLE, else ZOO_PEOPLE_TOKEN — in the
13
+ * fleet the people token already IS that key). Base URLs: ZOO_PEOPLE_URLS,
14
+ * else ZOO_KIT_APP_URLS_ZOO_PEOPLE. No new env names.
15
+ *
16
+ * Cache rules (Wiz 2026-11-16):
17
+ * - a valid answer is reused for 60 s, then re-checked;
18
+ * - a revoke push (revokeHandler) evicts it at once — the next call is 401
19
+ * even inside the 60 s;
20
+ * - zoo-people unreachable: a key answered valid in the last 7 days keeps
21
+ * working; an UNKNOWN key is refused (fail closed). The refusal status is
22
+ * 503 by default, never 401, because zoo-health-ios forgets its key on a
23
+ * 401 (P10a) — an outage must not unpair a phone. `outageStatus: 401`
24
+ * opts out for an app whose clients don't care.
25
+ * - zoo-people's 401 "unknown-or-revoked" is final: the cache entry and its
26
+ * last-known-good copy are dropped.
27
+ *
28
+ * Keys are held in memory only as sha256 hashes. Nothing here logs a key.
29
+ */
30
+ import { createHash } from "node:crypto";
31
+ import { ENV, appKeyForEnv, appUrlsEnv, firstList, firstStr, warnOnce } from "./env.js";
32
+ import { failoverFetch, readJson, stripUndefined } from "./http.js";
33
+ import { bearerOf, checkApp } from "./keys.js";
34
+ export const DEVICES_PATHS = {
35
+ redeem: "/api/v1/devices/redeem",
36
+ resolve: "/api/v1/devices/resolve",
37
+ selfRevoke: "/api/v1/devices/self-revoke",
38
+ };
39
+ /** The conventional path an app mounts revokeHandler() on. */
40
+ export const DEVICE_REVOKE_PATH = "/api/internal/devices/revoked";
41
+ export const DEVICES_DEFAULTS = {
42
+ ttlMs: 60_000,
43
+ staleMs: 7 * 24 * 60 * 60_000,
44
+ outageStatus: 503,
45
+ maxEntries: 5_000,
46
+ /** A revoked deviceId is remembered this long, so an in-flight answer can't re-cache it. */
47
+ tombstoneMs: 10 * 60_000,
48
+ attemptTimeoutMs: 5_000,
49
+ totalBudgetMs: 10_000,
50
+ rounds: 1,
51
+ roundBackoffMs: 250,
52
+ };
53
+ const sha256 = (s) => createHash("sha256").update(s).digest("hex");
54
+ function cookieValue(h, name) {
55
+ for (const part of (h.get("cookie") ?? "").split(";")) {
56
+ const i = part.indexOf("=");
57
+ if (i < 0)
58
+ continue;
59
+ if (part.slice(0, i).trim() === name) {
60
+ const v = part.slice(i + 1).trim();
61
+ try {
62
+ return decodeURIComponent(v) || null;
63
+ }
64
+ catch {
65
+ return v || null;
66
+ }
67
+ }
68
+ }
69
+ return null;
70
+ }
71
+ function config() {
72
+ const urls = firstList(ENV.PEOPLE_URLS, appUrlsEnv("zoo-people"));
73
+ const key = firstStr(appKeyForEnv("zoo-people"), ENV.PEOPLE_TOKEN);
74
+ const missing = [];
75
+ if (!urls.length)
76
+ missing.push(ENV.PEOPLE_URLS);
77
+ if (!key)
78
+ missing.push(`${appKeyForEnv("zoo-people")} (or ${ENV.PEOPLE_TOKEN})`);
79
+ return { urls, key, missing };
80
+ }
81
+ const str = (v) => (typeof v === "string" ? v : "");
82
+ function toPersonPart(raw) {
83
+ if (!raw || typeof raw !== "object")
84
+ return null;
85
+ const p = raw;
86
+ if (!str(p.id) || !str(p.slug))
87
+ return null;
88
+ return { id: str(p.id), slug: str(p.slug), name: str(p.name), role: str(p.role), enabled: p.enabled !== false };
89
+ }
90
+ function toIdentity(raw) {
91
+ if (!raw || typeof raw !== "object")
92
+ return null;
93
+ const r = raw;
94
+ const person = toPersonPart(r.person);
95
+ if (!person || !str(r.deviceId) || !str(r.app))
96
+ return null;
97
+ return {
98
+ kind: "person",
99
+ via: "device",
100
+ slug: person.slug,
101
+ personId: person.id,
102
+ app: str(r.app),
103
+ device: { id: str(r.deviceId), name: str(r.name), appRole: typeof r.appRole === "string" ? r.appRole : null },
104
+ person,
105
+ };
106
+ }
107
+ const NO_STORE = { "Content-Type": "application/json", "Cache-Control": "no-store" };
108
+ const reply = (status, body) => new Response(JSON.stringify(body), { status, headers: NO_STORE });
109
+ export function createDevices(options = {}) {
110
+ const o = { ...DEVICES_DEFAULTS, ...stripUndefined(options) };
111
+ const now = options.now ?? Date.now;
112
+ const failover = {
113
+ attemptTimeoutMs: o.attemptTimeoutMs,
114
+ totalBudgetMs: o.totalBudgetMs,
115
+ rounds: o.rounds,
116
+ roundBackoffMs: o.roundBackoffMs,
117
+ };
118
+ const cache = new Map(); // sha256(key) -> answer
119
+ const tombstones = new Map(); // deviceId -> revoked at
120
+ const inflight = new Map();
121
+ const refuse = (status, reason) => ({ ok: false, status, reason });
122
+ function revoked(deviceId) {
123
+ const t = tombstones.get(deviceId);
124
+ if (t === undefined)
125
+ return false;
126
+ if (now() - t > o.tombstoneMs) {
127
+ tombstones.delete(deviceId);
128
+ return false;
129
+ }
130
+ return true;
131
+ }
132
+ function evict(deviceId) {
133
+ let hit = false;
134
+ for (const [h, e] of cache) {
135
+ if (e.identity.device.id === deviceId) {
136
+ cache.delete(h);
137
+ hit = true;
138
+ }
139
+ }
140
+ tombstones.set(deviceId, now());
141
+ if (tombstones.size > o.maxEntries) {
142
+ const oldest = tombstones.keys().next().value;
143
+ if (oldest !== undefined)
144
+ tombstones.delete(oldest);
145
+ }
146
+ return hit;
147
+ }
148
+ function remember(h, identity) {
149
+ cache.delete(h);
150
+ cache.set(h, { identity, at: now() });
151
+ if (cache.size > o.maxEntries) {
152
+ const oldest = cache.keys().next().value;
153
+ if (oldest !== undefined)
154
+ cache.delete(oldest);
155
+ }
156
+ }
157
+ async function post(path, body) {
158
+ const c = config();
159
+ if (c.missing.length) {
160
+ warnOnce("devices-config", `devices: not configured: ${c.missing.join(", ")} not set`);
161
+ return { kind: "failed", error: "unconfigured" };
162
+ }
163
+ // Primary-first failover is safe for resolve (read-only). Redeem is one-shot
164
+ // and goes to the primary only: a redeem that timed out may have landed.
165
+ const urls = path === DEVICES_PATHS.resolve ? c.urls : c.urls.slice(0, 1);
166
+ const out = await failoverFetch(urls, path, { method: "POST", headers: { Authorization: `Bearer ${c.key}`, "Content-Type": "application/json" }, body: JSON.stringify(body) }, failover);
167
+ if (out.kind === "failed")
168
+ return { kind: "failed", error: out.error };
169
+ return { kind: "response", status: out.res.status, json: await readJson(out.res) };
170
+ }
171
+ async function lookup(key, h, prev) {
172
+ const outage = (why) => {
173
+ if (prev && now() - prev.at < o.staleMs && !revoked(prev.identity.device.id)) {
174
+ return { ok: true, identity: prev.identity, status: "stale" };
175
+ }
176
+ return refuse(o.outageStatus, `zoo-people unavailable (${why}) and key not cached`);
177
+ };
178
+ const res = await post(DEVICES_PATHS.resolve, { key });
179
+ if (res.kind === "failed")
180
+ return outage(res.error);
181
+ const err = str(res.json?.error);
182
+ if (res.status === 200) {
183
+ const identity = toIdentity(res.json);
184
+ if (!identity)
185
+ return outage("malformed answer");
186
+ if (revoked(identity.device.id)) {
187
+ cache.delete(h);
188
+ return refuse(401, "device revoked");
189
+ }
190
+ if (options.app && identity.app !== options.app) {
191
+ cache.delete(h);
192
+ return refuse(401, "device belongs to another app");
193
+ }
194
+ if (!identity.person.enabled) {
195
+ cache.delete(h);
196
+ return refuse(401, "person is archived");
197
+ }
198
+ remember(h, identity);
199
+ return { ok: true, identity, status: "fresh" };
200
+ }
201
+ if (res.status === 401 && err === "unknown-or-revoked") {
202
+ cache.delete(h);
203
+ return refuse(401, "unknown or revoked device");
204
+ }
205
+ // Any other answer (our own app key refused, a 4xx we don't know) is OUR
206
+ // misconfiguration, not the phone's — never unpair a phone over it.
207
+ warnOnce(`devices-resolve-${res.status}`, `devices: zoo-people resolve answered ${res.status}${err ? ` (${err})` : ""} — check this app's key on zoo-people`);
208
+ return outage(`HTTP ${res.status}`);
209
+ }
210
+ async function resolveKey(key) {
211
+ if (!key || key.length > 200)
212
+ return refuse(401, "no device key");
213
+ const h = sha256(key);
214
+ const e = cache.get(h);
215
+ if (e && revoked(e.identity.device.id)) {
216
+ cache.delete(h);
217
+ return refuse(401, "device revoked");
218
+ }
219
+ if (e && now() - e.at < o.ttlMs)
220
+ return { ok: true, identity: e.identity, status: "cached" };
221
+ const running = inflight.get(h);
222
+ if (running)
223
+ return running;
224
+ const p = lookup(key, h, e).finally(() => inflight.delete(h));
225
+ inflight.set(h, p);
226
+ return p;
227
+ }
228
+ function readKey(hdrs) {
229
+ if (options.readKey)
230
+ return options.readKey(hdrs);
231
+ return bearerOf(hdrs) ?? (options.cookie ? cookieValue(hdrs, options.cookie) : null);
232
+ }
233
+ return {
234
+ async redeem(code, ro = {}) {
235
+ const body = { code: String(code ?? "") };
236
+ if (ro.deviceName)
237
+ body.deviceName = ro.deviceName;
238
+ if (ro.platform)
239
+ body.platform = ro.platform;
240
+ const res = await post(DEVICES_PATHS.redeem, body);
241
+ if (res.kind === "failed")
242
+ return { ok: false, status: 503, error: res.error === "unconfigured" ? "unconfigured" : "unavailable" };
243
+ const j = (res.json ?? {});
244
+ if (res.status !== 200)
245
+ return { ok: false, status: res.status, error: str(j.error) || `HTTP ${res.status}` };
246
+ const person = toPersonPart(j.person);
247
+ if (!person || !str(j.deviceId) || !str(j.key))
248
+ return { ok: false, status: 503, error: "malformed answer" };
249
+ const identity = toIdentity({ ...j, app: str(j.app) || options.app || "" });
250
+ if (identity && identity.app)
251
+ remember(sha256(str(j.key)), identity);
252
+ return {
253
+ ok: true,
254
+ deviceId: str(j.deviceId),
255
+ key: str(j.key),
256
+ keyPrefix: str(j.keyPrefix),
257
+ name: str(j.name),
258
+ appRole: typeof j.appRole === "string" ? j.appRole : null,
259
+ person,
260
+ };
261
+ },
262
+ resolve(req) {
263
+ const key = readKey(req.headers);
264
+ if (!key)
265
+ return Promise.resolve(refuse(401, "no device key"));
266
+ return resolveKey(key);
267
+ },
268
+ resolveKey,
269
+ async selfRevoke(key) {
270
+ if (!key)
271
+ return { ok: false, status: 401 };
272
+ const e = cache.get(sha256(key));
273
+ const res = await post(DEVICES_PATHS.selfRevoke, { key });
274
+ if (res.kind === "failed")
275
+ return { ok: false, status: 503 };
276
+ if (res.status === 200 && e)
277
+ evict(e.identity.device.id);
278
+ else
279
+ cache.delete(sha256(key));
280
+ return { ok: res.status === 200, status: res.status };
281
+ },
282
+ evict,
283
+ revokeHandler() {
284
+ const callers = options.revokeCallers ?? ["zoo-people"];
285
+ return async (req) => {
286
+ const v = checkApp(req, callers);
287
+ if (!v.ok)
288
+ return reply(v.status, { error: v.status === 401 ? "unauthorized" : "forbidden" });
289
+ const body = (await req.json().catch(() => null));
290
+ const deviceId = str(body?.deviceId);
291
+ if (!deviceId || deviceId.length > 200)
292
+ return reply(400, { error: "deviceId required" });
293
+ const evicted = evict(deviceId);
294
+ return reply(200, { ok: true, evicted });
295
+ };
296
+ },
297
+ size: () => cache.size,
298
+ };
299
+ }
300
+ /** The shared instance (env-configured). Apps that need `app`/`cookie` make their own with createDevices. */
301
+ export const 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.1.0";
2
+ export declare const KIT_VERSION = "1.3.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.1.0";
4
+ export const KIT_VERSION = "1.3.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/index.d.ts CHANGED
@@ -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 People, 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 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/index.js CHANGED
@@ -13,6 +13,7 @@ export { ENV, appKeyEnv, appKeyForEnv, appUrlsEnv, checkConfig, envSuffix } from
13
13
  export { CATEGORIES, CATEGORY_ALIASES, CATEGORY_SLUGS, canonicalCategory, customCategory, isCanonicalCategory, isCategoryAlias, toCategory, } from "./categories.js";
14
14
  export { NOTIFY_DEFAULTS, NOTIFY_PATH, dedupeKey, notify, notifyConfigured, } from "./notify.js";
15
15
  export { PEOPLE_DEFAULTS, PEOPLE_PATHS, createPeople, people, toPerson, } from "./people.js";
16
+ export { DEVICES_DEFAULTS, DEVICES_PATHS, DEVICE_REVOKE_PATH, createDevices, devices, } from "./devices.js";
16
17
  export { ZooKitAuthError, cameThroughGate, gateSecretOk, readAuthentikUsername, requireApp, requirePerson, whoami, } from "./whoami.js";
17
18
  export { ZooKitConfigError, bearerOf, callApp, checkApp, safeEqual, } from "./keys.js";
18
19
  export { healthBody, healthHandler } from "./health.js";
package/dist/people.d.ts CHANGED
@@ -38,7 +38,35 @@ export declare const PEOPLE_DEFAULTS: {
38
38
  export declare const PEOPLE_PATHS: {
39
39
  readonly list: "/api/v1/people";
40
40
  readonly whoamiResolve: "/api/v1/whoami-resolve";
41
+ readonly contactsSearch: "/api/v1/contacts/search";
41
42
  };
43
+ /**
44
+ * A card from the directory's Contacts book (v1.2, additive — BP#127 P9c).
45
+ * Not a Person: the Contacts book is anyone Wiz keeps, not the family roster.
46
+ */
47
+ export interface Contact {
48
+ uid: string | null;
49
+ name: string;
50
+ /** Lower-cased. */
51
+ emails: string[];
52
+ phones: string[];
53
+ org: string | null;
54
+ hasPhoto: boolean;
55
+ }
56
+ export type ContactsStatus = "fresh" | "stale" | "unavailable" | "unconfigured";
57
+ export interface ContactsResult {
58
+ contacts: Contact[];
59
+ status: ContactsStatus;
60
+ error?: string;
61
+ }
62
+ export interface Contacts {
63
+ /** Ranked search (exact email first, then name prefix …). Never throws; an outage is status "unavailable". */
64
+ search(q: string, opts?: {
65
+ limit?: number;
66
+ }): Promise<ContactsResult>;
67
+ /** The contact holding exactly this email, or null. Cached like search. */
68
+ byEmail(email: string): Promise<Contact | null>;
69
+ }
42
70
  /** Keep only the contract's Person keys; null for anything that is not a usable person. */
43
71
  export declare function toPerson(raw: unknown): Person | null;
44
72
  export interface People {
@@ -55,7 +83,16 @@ export interface People {
55
83
  /** Drop every cached answer. */
56
84
  clear(): void;
57
85
  }
86
+ /**
87
+ * The client {@link createPeople} returns: People plus the Contacts book
88
+ * (v1.2, additive). Kept OUT of the People interface so an app's hand-rolled
89
+ * People stub (whoami tests) still type-checks after the bump.
90
+ */
91
+ export type PeopleClient = People & {
92
+ /** Search Wiz's own Contacts book through the directory. */
93
+ contacts: Contacts;
94
+ };
58
95
  /** A people client with its own cache. Most apps use the shared {@link people}. */
59
- export declare function createPeople(options?: PeopleOptions): People;
96
+ export declare function createPeople(options?: PeopleOptions): PeopleClient;
60
97
  /** The process-wide people client. */
61
- export declare const people: People;
98
+ export declare const people: PeopleClient;