@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.
- package/README.md +65 -0
- package/dist/cjs/devices.d.ts +110 -0
- package/dist/cjs/devices.js +305 -0
- package/dist/cjs/generated/contract.d.ts +1 -1
- package/dist/cjs/generated/contract.js +1 -1
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/index.js +7 -1
- package/dist/cjs/people.d.ts +39 -2
- package/dist/cjs/people.js +55 -0
- package/dist/cjs/whoami.d.ts +11 -3
- package/dist/cjs/whoami.js +19 -1
- package/dist/devices.d.ts +110 -0
- package/dist/devices.js +301 -0
- package/dist/generated/contract.d.ts +1 -1
- package/dist/generated/contract.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/people.d.ts +39 -2
- package/dist/people.js +55 -0
- package/dist/whoami.d.ts +11 -3
- package/dist/whoami.js +19 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -161,6 +161,71 @@ const me = await people.byAuthentikUsername("Shad"); // Person | null
|
|
|
161
161
|
Person carries the contract's roster keys only (anything else in an answer is
|
|
162
162
|
dropped). Archived people are in the list with `enabled: false`.
|
|
163
163
|
|
|
164
|
+
### people.contacts (1.2.0, additive)
|
|
165
|
+
|
|
166
|
+
Wiz's own Contacts book (Radicale), searched through the directory — not the
|
|
167
|
+
family roster, so the result is a `Contact`, never a `Person`:
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
const r = await people.contacts.search("pat"); // {contacts, status, error?} — never throws
|
|
171
|
+
const c = await people.contacts.byEmail("pat@x.test"); // exact email match or null
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`GET /api/v1/contacts/search?q=&limit=` on the same `ZOO_PEOPLE_URLS` with the
|
|
175
|
+
same token. zoo-people admits it on its OWN caller list (`CONTACTS_CALLERS`,
|
|
176
|
+
default `snailslap`), so a roster reader is not automatically a contacts reader.
|
|
177
|
+
Answers are cached 5 min and served stale ≤15 min while the directory is down.
|
|
178
|
+
`People` itself is unchanged; the extra member lives on `PeopleClient`, so a
|
|
179
|
+
hand-rolled `People` stub still type-checks.
|
|
180
|
+
|
|
181
|
+
## devices (1.3.0, additive — BP#129 P10c)
|
|
182
|
+
|
|
183
|
+
One device pairing for the fleet: zoo-people owns every paired phone; an app
|
|
184
|
+
keeps its own redeem route and its own device header and forwards through the
|
|
185
|
+
kit. Contract: zoo-people `docs/API.md` → "Devices". No new env names — base
|
|
186
|
+
URLs are `ZOO_PEOPLE_URLS` (else `ZOO_KIT_APP_URLS_ZOO_PEOPLE`), the key is this
|
|
187
|
+
app's kit key ON zoo-people (`ZOO_KIT_APP_KEY_FOR_ZOO_PEOPLE`, else
|
|
188
|
+
`ZOO_PEOPLE_TOKEN`), and the revoke push is checked against
|
|
189
|
+
`ZOO_KIT_APP_KEY_ZOO_PEOPLE` (zoo-people's key, minted on your app).
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
import { createDevices, requirePerson, ZooKitAuthError } from "@jdcpuwiz/zoo-kit";
|
|
193
|
+
|
|
194
|
+
// ONE instance per process — resolve and the revoke receiver must share its cache.
|
|
195
|
+
export const devices = createDevices({ app: "zoo-health" /* , cookie: "ZSB_DEVICE" */ });
|
|
196
|
+
|
|
197
|
+
// the app's existing redeem route
|
|
198
|
+
const r = await devices.redeem(body.code, { deviceName: body.name, platform: "ios" });
|
|
199
|
+
if (!r.ok) return Response.json({ error: r.error }, { status: r.status }); // 404/409/410/429/503
|
|
200
|
+
return Response.json({ key: r.key }); // hand to the phone; never log it
|
|
201
|
+
|
|
202
|
+
// any device-authenticated route
|
|
203
|
+
const v = await devices.resolve(req); // Bearer (or the legacy cookie)
|
|
204
|
+
if (!v.ok) return new Response(null, { status: v.status }); // 401, or 503 when zoo-people is down
|
|
205
|
+
v.identity; // {kind:"person", via:"device", slug, personId, app, device:{id,name,appRole}, person}
|
|
206
|
+
|
|
207
|
+
// or through whoami / requirePerson (device source tried before resolveDeviceKey)
|
|
208
|
+
const who = await requirePerson(req, { devices }); // throws ZooKitAuthError 401 / 503
|
|
209
|
+
|
|
210
|
+
// app/api/internal/devices/revoked/route.ts (DEVICE_REVOKE_PATH)
|
|
211
|
+
export const POST = devices.revokeHandler();
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
| Situation | Answer |
|
|
215
|
+
|---|---|
|
|
216
|
+
| valid key | 200, cached 60 s (`status: "fresh"` then `"cached"`) |
|
|
217
|
+
| 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) |
|
|
218
|
+
| zoo-people says `unknown-or-revoked` | 401, cache + last-known-good dropped |
|
|
219
|
+
| zoo-people down, key answered valid in the last 7 days | 200 (`status: "stale"`) |
|
|
220
|
+
| zoo-people down, key unknown | refused — **503 by default**, never 401 (zoo-health-ios forgets its key on a 401). `outageStatus: 401` opts out. |
|
|
221
|
+
| zoo-people refuses THIS app's key | treated as an outage (warned once), never as the phone's 401 |
|
|
222
|
+
| `app` set and the answer is another app's device | 401 |
|
|
223
|
+
|
|
224
|
+
Keys live in memory only as sha256 hashes; `redeem` goes to the primary URL
|
|
225
|
+
only (a timed-out redeem may have landed) and primes the cache with the new
|
|
226
|
+
device. `selfRevoke(key)` forwards a phone's own Unpair. `ZooKitAuthError.status`
|
|
227
|
+
gained `503` in 1.3.0.
|
|
228
|
+
|
|
164
229
|
## Health route
|
|
165
230
|
|
|
166
231
|
```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
|
+
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"];
|
|
@@ -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.
|
|
7
|
+
exports.KIT_VERSION = "1.3.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"];
|
package/dist/cjs/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/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; } });
|
package/dist/cjs/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):
|
|
96
|
+
export declare function createPeople(options?: PeopleOptions): PeopleClient;
|
|
60
97
|
/** The process-wide people client. */
|
|
61
|
-
export declare const people:
|
|
98
|
+
export declare const people: PeopleClient;
|