@jdcpuwiz/zoo-kit 1.2.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 +48 -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 +1 -0
- package/dist/cjs/index.js +7 -1
- 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 +1 -0
- package/dist/index.js +1 -0
- package/dist/whoami.d.ts +11 -3
- package/dist/whoami.js +19 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -178,6 +178,54 @@ Answers are cached 5 min and served stale ≤15 min while the directory is down.
|
|
|
178
178
|
`People` itself is unchanged; the extra member lives on `PeopleClient`, so a
|
|
179
179
|
hand-rolled `People` stub still type-checks.
|
|
180
180
|
|
|
181
|
+
## 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
|
+
|
|
181
229
|
## Health route
|
|
182
230
|
|
|
183
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
|
@@ -13,6 +13,7 @@ export { ENV, appKeyEnv, appKeyForEnv, appUrlsEnv, checkConfig, envSuffix, type
|
|
|
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
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/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/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.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.
|
|
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
|
@@ -13,6 +13,7 @@ export { ENV, appKeyEnv, appKeyForEnv, appUrlsEnv, checkConfig, envSuffix, type
|
|
|
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
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/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