@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 +62 -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 +15 -0
- package/dist/cjs/people.js +25 -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 +15 -0
- package/dist/people.js +25 -0
- package/dist/whoami.d.ts +11 -3
- package/dist/whoami.js +19 -1
- package/package.json +1 -1
package/dist/cjs/whoami.js
CHANGED
|
@@ -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;
|
package/dist/devices.js
ADDED
|
@@ -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.
|
|
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"];
|
|
@@ -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.
|
|
4
|
+
export const KIT_VERSION = "1.4.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 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/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
|
@@ -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. */
|
package/dist/people.js
CHANGED
|
@@ -33,6 +33,7 @@ export const PEOPLE_PATHS = {
|
|
|
33
33
|
list: "/api/v1/people",
|
|
34
34
|
whoamiResolve: "/api/v1/whoami-resolve",
|
|
35
35
|
contactsSearch: "/api/v1/contacts/search",
|
|
36
|
+
signature: (slug) => `/api/v1/people/${encodeURIComponent(slug)}/signature`,
|
|
36
37
|
};
|
|
37
38
|
function toContact(raw) {
|
|
38
39
|
if (!raw || typeof raw !== "object")
|
|
@@ -208,6 +209,30 @@ export function createPeople(options = {}) {
|
|
|
208
209
|
return r.contacts.find((c) => c.emails.includes(e)) ?? null;
|
|
209
210
|
},
|
|
210
211
|
},
|
|
212
|
+
async signature(slug) {
|
|
213
|
+
const sl = (slug ?? "").trim().toLowerCase();
|
|
214
|
+
if (!sl)
|
|
215
|
+
return { status: "none", png: null, sha256: null };
|
|
216
|
+
const c = config();
|
|
217
|
+
if (c.missing.length) {
|
|
218
|
+
warnOnce("people-unconfigured", `people is unavailable: ${c.missing.join(", ")} not set`);
|
|
219
|
+
return { status: "unconfigured", png: null, sha256: null, error: `not configured: ${c.missing.join(", ")} not set` };
|
|
220
|
+
}
|
|
221
|
+
const outcome = await failoverFetch(c.urls, PEOPLE_PATHS.signature(sl), { method: "GET", headers: { Authorization: `Bearer ${c.token}`, Accept: "image/png" } }, o);
|
|
222
|
+
if (outcome.kind === "failed")
|
|
223
|
+
return { status: "unavailable", png: null, sha256: null, error: outcome.error };
|
|
224
|
+
const { res } = outcome;
|
|
225
|
+
if (res.status === 404)
|
|
226
|
+
return { status: "none", png: null, sha256: null };
|
|
227
|
+
if (!res.ok || !(res.headers.get("content-type") ?? "").startsWith("image/png")) {
|
|
228
|
+
if (!res.ok)
|
|
229
|
+
warnOnce(`people-signature-${res.status}`, `the people directory refused a signature read (${res.status}) — is this app in zoo-people's SIGNATURE_CALLERS?`);
|
|
230
|
+
return { status: "unavailable", png: null, sha256: null, error: `HTTP ${res.status}` };
|
|
231
|
+
}
|
|
232
|
+
const png = new Uint8Array(await res.arrayBuffer());
|
|
233
|
+
const sha = res.headers.get("x-signature-sha256") ?? ((res.headers.get("etag") ?? "").replace(/"/g, "") || null);
|
|
234
|
+
return { status: "ok", png, sha256: sha };
|
|
235
|
+
},
|
|
211
236
|
clear() {
|
|
212
237
|
listCache = null;
|
|
213
238
|
users.clear();
|
package/dist/whoami.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
}
|
package/dist/whoami.js
CHANGED
|
@@ -102,6 +102,22 @@ export async function whoami(req, opts = {}) {
|
|
|
102
102
|
if (app)
|
|
103
103
|
return { kind: "app", app, via: "key" };
|
|
104
104
|
}
|
|
105
|
+
if (token && opts.devices) {
|
|
106
|
+
const v = await opts.devices.resolveKey(token);
|
|
107
|
+
if (v.ok) {
|
|
108
|
+
const d = v.identity;
|
|
109
|
+
// The full roster Person when the directory has it; otherwise the
|
|
110
|
+
// device answer's own person fields, so an outage of the roster list
|
|
111
|
+
// never unpairs a phone zoo-people just vouched for.
|
|
112
|
+
const full = await dir.get(d.slug).catch(() => null);
|
|
113
|
+
const p = (full ?? { ...d.person });
|
|
114
|
+
return asPerson(p, "device", { device: { ...d.device, app: d.app, status: v.status } });
|
|
115
|
+
}
|
|
116
|
+
if (v.status === 503)
|
|
117
|
+
return { kind: "anonymous", reason: v.reason, unavailable: true };
|
|
118
|
+
if (!opts.resolveDeviceKey)
|
|
119
|
+
return { kind: "anonymous", reason: v.reason };
|
|
120
|
+
}
|
|
105
121
|
if (token && opts.resolveDeviceKey) {
|
|
106
122
|
try {
|
|
107
123
|
const d = await opts.resolveDeviceKey(token);
|
|
@@ -155,7 +171,7 @@ export class ZooKitAuthError extends Error {
|
|
|
155
171
|
/** Server-side reason for the app's own logs. */
|
|
156
172
|
reason;
|
|
157
173
|
constructor(status, reason = "") {
|
|
158
|
-
super(status === 401 ? "unauthorized" : "forbidden");
|
|
174
|
+
super(status === 401 ? "unauthorized" : status === 403 ? "forbidden" : "unavailable");
|
|
159
175
|
this.name = "ZooKitAuthError";
|
|
160
176
|
this.status = status;
|
|
161
177
|
this.reason = reason;
|
|
@@ -173,6 +189,8 @@ export async function requirePerson(req, opts = {}) {
|
|
|
173
189
|
const who = await whoami(req, opts);
|
|
174
190
|
if (who.kind === "person")
|
|
175
191
|
return who;
|
|
192
|
+
if (who.kind === "anonymous" && who.unavailable)
|
|
193
|
+
throw new ZooKitAuthError(503, who.reason ?? "");
|
|
176
194
|
throw new ZooKitAuthError(401, who.kind === "anonymous" ? (who.reason ?? "") : "an app key is not a person");
|
|
177
195
|
}
|
|
178
196
|
/**
|
package/package.json
CHANGED