@jdcpuwiz/zoo-kit 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -3
- package/dist/cjs/categories.d.ts +31 -0
- package/dist/cjs/categories.js +47 -0
- package/dist/cjs/env.d.ts +62 -0
- package/dist/cjs/env.js +105 -0
- package/dist/cjs/generated/categories.d.ts +85 -0
- package/dist/cjs/generated/categories.js +10 -0
- package/dist/cjs/generated/contract.d.ts +7 -0
- package/dist/cjs/generated/contract.js +12 -0
- package/dist/cjs/generated/notifier.d.ts +230 -0
- package/dist/cjs/generated/notifier.js +5 -0
- package/dist/cjs/generated/people.d.ts +261 -0
- package/dist/cjs/generated/people.js +5 -0
- package/dist/cjs/health.d.ts +46 -0
- package/dist/cjs/health.js +132 -0
- package/dist/cjs/http.d.ts +51 -0
- package/dist/cjs/http.js +108 -0
- package/dist/cjs/index.d.ts +20 -0
- package/dist/cjs/index.js +62 -0
- package/dist/cjs/keys.d.ts +51 -0
- package/dist/cjs/keys.js +106 -0
- package/dist/cjs/notify.d.ts +79 -0
- package/dist/cjs/notify.js +131 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/people.d.ts +98 -0
- package/dist/cjs/people.js +225 -0
- package/dist/cjs/whoami.d.ts +86 -0
- package/dist/cjs/whoami.js +197 -0
- package/dist/generated/contract.d.ts +1 -1
- package/dist/generated/contract.js +1 -1
- package/dist/health.js +20 -5
- package/dist/index.d.ts +1 -1
- package/dist/notify.d.ts +5 -1
- package/dist/notify.js +13 -7
- package/dist/people.d.ts +39 -2
- package/dist/people.js +55 -0
- package/package.json +12 -4
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { components } from "./generated/people.js";
|
|
2
|
+
import { type FailoverOptions } from "./http.js";
|
|
3
|
+
/** A v1 Person — roster fields only (contracts/v1/zoo-health.v1.yaml). */
|
|
4
|
+
export type Person = components["schemas"]["Person"];
|
|
5
|
+
export type PeopleStatus = "fresh" | "stale" | "unavailable" | "unconfigured";
|
|
6
|
+
export interface PeopleList {
|
|
7
|
+
people: Person[];
|
|
8
|
+
/** fresh = loaded inside the TTL; stale = an older copy served because the directory failed; unavailable = never loaded. */
|
|
9
|
+
status: PeopleStatus;
|
|
10
|
+
loadedAt: Date | null;
|
|
11
|
+
error?: string;
|
|
12
|
+
}
|
|
13
|
+
export type ResolveStatus = "fresh" | "stale" | "not-found" | "unavailable" | "unconfigured";
|
|
14
|
+
export interface ResolvedUsername {
|
|
15
|
+
person: Person | null;
|
|
16
|
+
status: ResolveStatus;
|
|
17
|
+
error?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface PeopleOptions extends FailoverOptions {
|
|
20
|
+
/** How long a list or a lookup counts as fresh. Default 5 min. */
|
|
21
|
+
ttlMs?: number;
|
|
22
|
+
/** How long a username lookup may be served stale while the directory is down. Default 15 min. */
|
|
23
|
+
staleUsernameMs?: number;
|
|
24
|
+
/** How long a "no such username" answer is remembered. Default 60 s. */
|
|
25
|
+
notFoundTtlMs?: number;
|
|
26
|
+
/** Clock, for tests. */
|
|
27
|
+
now?: () => number;
|
|
28
|
+
}
|
|
29
|
+
export declare const PEOPLE_DEFAULTS: {
|
|
30
|
+
ttlMs: number;
|
|
31
|
+
staleUsernameMs: number;
|
|
32
|
+
notFoundTtlMs: number;
|
|
33
|
+
attemptTimeoutMs: number;
|
|
34
|
+
totalBudgetMs: number;
|
|
35
|
+
rounds: number;
|
|
36
|
+
roundBackoffMs: number;
|
|
37
|
+
};
|
|
38
|
+
export declare const PEOPLE_PATHS: {
|
|
39
|
+
readonly list: "/api/v1/people";
|
|
40
|
+
readonly whoamiResolve: "/api/v1/whoami-resolve";
|
|
41
|
+
readonly contactsSearch: "/api/v1/contacts/search";
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* A card from the directory's Contacts book (v1.2, additive — BP#127 P9c).
|
|
45
|
+
* Not a Person: the Contacts book is anyone Wiz keeps, not the family roster.
|
|
46
|
+
*/
|
|
47
|
+
export interface Contact {
|
|
48
|
+
uid: string | null;
|
|
49
|
+
name: string;
|
|
50
|
+
/** Lower-cased. */
|
|
51
|
+
emails: string[];
|
|
52
|
+
phones: string[];
|
|
53
|
+
org: string | null;
|
|
54
|
+
hasPhoto: boolean;
|
|
55
|
+
}
|
|
56
|
+
export type ContactsStatus = "fresh" | "stale" | "unavailable" | "unconfigured";
|
|
57
|
+
export interface ContactsResult {
|
|
58
|
+
contacts: Contact[];
|
|
59
|
+
status: ContactsStatus;
|
|
60
|
+
error?: string;
|
|
61
|
+
}
|
|
62
|
+
export interface Contacts {
|
|
63
|
+
/** Ranked search (exact email first, then name prefix …). Never throws; an outage is status "unavailable". */
|
|
64
|
+
search(q: string, opts?: {
|
|
65
|
+
limit?: number;
|
|
66
|
+
}): Promise<ContactsResult>;
|
|
67
|
+
/** The contact holding exactly this email, or null. Cached like search. */
|
|
68
|
+
byEmail(email: string): Promise<Contact | null>;
|
|
69
|
+
}
|
|
70
|
+
/** Keep only the contract's Person keys; null for anything that is not a usable person. */
|
|
71
|
+
export declare function toPerson(raw: unknown): Person | null;
|
|
72
|
+
export interface People {
|
|
73
|
+
list(): Promise<PeopleList>;
|
|
74
|
+
get(slug: string): Promise<Person | null>;
|
|
75
|
+
byAuthentikUsername(username: string): Promise<Person | null>;
|
|
76
|
+
/** byAuthentikUsername with the reason — what whoami uses. */
|
|
77
|
+
resolveUsername(username: string): Promise<ResolvedUsername>;
|
|
78
|
+
/** A health-handler check: throws when the roster never loaded; reports stale. */
|
|
79
|
+
healthCheck(): Promise<{
|
|
80
|
+
ok: true;
|
|
81
|
+
detail?: string;
|
|
82
|
+
}>;
|
|
83
|
+
/** Drop every cached answer. */
|
|
84
|
+
clear(): void;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The client {@link createPeople} returns: People plus the Contacts book
|
|
88
|
+
* (v1.2, additive). Kept OUT of the People interface so an app's hand-rolled
|
|
89
|
+
* People stub (whoami tests) still type-checks after the bump.
|
|
90
|
+
*/
|
|
91
|
+
export type PeopleClient = People & {
|
|
92
|
+
/** Search Wiz's own Contacts book through the directory. */
|
|
93
|
+
contacts: Contacts;
|
|
94
|
+
};
|
|
95
|
+
/** A people client with its own cache. Most apps use the shared {@link people}. */
|
|
96
|
+
export declare function createPeople(options?: PeopleOptions): PeopleClient;
|
|
97
|
+
/** The process-wide people client. */
|
|
98
|
+
export declare const people: PeopleClient;
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.people = exports.PEOPLE_PATHS = exports.PEOPLE_DEFAULTS = void 0;
|
|
4
|
+
exports.toPerson = toPerson;
|
|
5
|
+
exports.createPeople = createPeople;
|
|
6
|
+
/**
|
|
7
|
+
* people — the roster client (plan §3.3).
|
|
8
|
+
*
|
|
9
|
+
* Reads the people directory's v1 surface over the base URLs in
|
|
10
|
+
* ZOO_PEOPLE_URLS (today that is zoo-health; a later phase points the SAME
|
|
11
|
+
* names at a separate directory with no code change — so nothing here is
|
|
12
|
+
* specific to whichever service answers).
|
|
13
|
+
*
|
|
14
|
+
* GET /api/v1/people list (archived ones flagged enabled:false)
|
|
15
|
+
* GET /api/v1/whoami-resolve?username= one linked authentik username
|
|
16
|
+
*
|
|
17
|
+
* Auth: `Authorization: Bearer <ZOO_PEOPLE_TOKEN>` + `X-Dispenser-Consumer:
|
|
18
|
+
* <ZOO_PEOPLE_CONSUMER>` (the directory's declared-consumer gate).
|
|
19
|
+
*
|
|
20
|
+
* FAIL-SOFT: the list is cached ~5 min and served STALE on error; it is empty
|
|
21
|
+
* only if it never loaded, and `status` says which. A username lookup serves
|
|
22
|
+
* its last answer for <= 15 min while the directory is down, then null — whoami
|
|
23
|
+
* fails closed on null.
|
|
24
|
+
*/
|
|
25
|
+
const env_js_1 = require("./env.js");
|
|
26
|
+
const contract_js_1 = require("./generated/contract.js");
|
|
27
|
+
const http_js_1 = require("./http.js");
|
|
28
|
+
exports.PEOPLE_DEFAULTS = {
|
|
29
|
+
ttlMs: 5 * 60_000,
|
|
30
|
+
staleUsernameMs: 15 * 60_000,
|
|
31
|
+
notFoundTtlMs: 60_000,
|
|
32
|
+
attemptTimeoutMs: 5_000,
|
|
33
|
+
totalBudgetMs: 10_000,
|
|
34
|
+
rounds: 1,
|
|
35
|
+
roundBackoffMs: 250,
|
|
36
|
+
};
|
|
37
|
+
exports.PEOPLE_PATHS = {
|
|
38
|
+
list: "/api/v1/people",
|
|
39
|
+
whoamiResolve: "/api/v1/whoami-resolve",
|
|
40
|
+
contactsSearch: "/api/v1/contacts/search",
|
|
41
|
+
};
|
|
42
|
+
function toContact(raw) {
|
|
43
|
+
if (!raw || typeof raw !== "object")
|
|
44
|
+
return null;
|
|
45
|
+
const r = raw;
|
|
46
|
+
if (typeof r.name !== "string" || !r.name)
|
|
47
|
+
return null;
|
|
48
|
+
const strs = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
|
|
49
|
+
return {
|
|
50
|
+
uid: typeof r.uid === "string" ? r.uid : null,
|
|
51
|
+
name: r.name,
|
|
52
|
+
emails: strs(r.emails).map((e) => e.toLowerCase()),
|
|
53
|
+
phones: strs(r.phones),
|
|
54
|
+
org: typeof r.org === "string" ? r.org : null,
|
|
55
|
+
hasPhoto: r.hasPhoto === true,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const KEYS = new Set(contract_js_1.PERSON_KEYS);
|
|
59
|
+
/** Keep only the contract's Person keys; null for anything that is not a usable person. */
|
|
60
|
+
function toPerson(raw) {
|
|
61
|
+
if (!raw || typeof raw !== "object")
|
|
62
|
+
return null;
|
|
63
|
+
const r = raw;
|
|
64
|
+
if (typeof r.id !== "string" || !r.id || typeof r.slug !== "string" || !r.slug)
|
|
65
|
+
return null;
|
|
66
|
+
const out = {};
|
|
67
|
+
for (const k of Object.keys(r))
|
|
68
|
+
if (KEYS.has(k))
|
|
69
|
+
out[k] = r[k];
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
function config() {
|
|
73
|
+
const urls = (0, env_js_1.firstList)(env_js_1.ENV.PEOPLE_URLS);
|
|
74
|
+
const token = (0, env_js_1.str)(env_js_1.ENV.PEOPLE_TOKEN);
|
|
75
|
+
const consumer = (0, env_js_1.str)(env_js_1.ENV.PEOPLE_CONSUMER);
|
|
76
|
+
const missing = [];
|
|
77
|
+
if (!urls.length)
|
|
78
|
+
missing.push(env_js_1.ENV.PEOPLE_URLS);
|
|
79
|
+
if (!token)
|
|
80
|
+
missing.push(env_js_1.ENV.PEOPLE_TOKEN);
|
|
81
|
+
if (!consumer)
|
|
82
|
+
missing.push(env_js_1.ENV.PEOPLE_CONSUMER);
|
|
83
|
+
return { urls, token, consumer, missing };
|
|
84
|
+
}
|
|
85
|
+
/** A people client with its own cache. Most apps use the shared {@link people}. */
|
|
86
|
+
function createPeople(options = {}) {
|
|
87
|
+
const o = { ...exports.PEOPLE_DEFAULTS, ...(0, http_js_1.stripUndefined)(options) };
|
|
88
|
+
const now = options.now ?? Date.now;
|
|
89
|
+
let listCache = null;
|
|
90
|
+
let listInflight = null;
|
|
91
|
+
const users = new Map();
|
|
92
|
+
const searches = new Map();
|
|
93
|
+
async function get(path) {
|
|
94
|
+
const c = config();
|
|
95
|
+
if (c.missing.length) {
|
|
96
|
+
(0, env_js_1.warnOnce)("people-unconfigured", `people is unavailable: ${c.missing.join(", ")} not set`);
|
|
97
|
+
return { kind: "unconfigured", error: `not configured: ${c.missing.join(", ")} not set` };
|
|
98
|
+
}
|
|
99
|
+
const outcome = await (0, http_js_1.failoverFetch)(c.urls, path, { method: "GET", headers: { Authorization: `Bearer ${c.token}`, "X-Dispenser-Consumer": c.consumer, Accept: "application/json" } }, o);
|
|
100
|
+
if (outcome.kind === "failed")
|
|
101
|
+
return { kind: "error", error: outcome.error };
|
|
102
|
+
const { res } = outcome;
|
|
103
|
+
const json = await (0, http_js_1.readJson)(res);
|
|
104
|
+
if (res.status === 404)
|
|
105
|
+
return { kind: "not-found" };
|
|
106
|
+
if (!res.ok) {
|
|
107
|
+
const msg = json?.error;
|
|
108
|
+
(0, env_js_1.warnOnce)(`people-${res.status}`, `the people directory refused this app (${res.status}${msg ? `: ${msg}` : ""}) — check ${env_js_1.ENV.PEOPLE_TOKEN} / ${env_js_1.ENV.PEOPLE_CONSUMER}`);
|
|
109
|
+
return { kind: "error", error: `HTTP ${res.status}${msg ? `: ${msg}` : ""}` };
|
|
110
|
+
}
|
|
111
|
+
return { kind: "ok", json };
|
|
112
|
+
}
|
|
113
|
+
async function loadList() {
|
|
114
|
+
const got = await get(exports.PEOPLE_PATHS.list);
|
|
115
|
+
if (got.kind === "ok") {
|
|
116
|
+
const raw = got.json?.people;
|
|
117
|
+
if (Array.isArray(raw)) {
|
|
118
|
+
const ppl = raw.map(toPerson).filter((p) => p !== null);
|
|
119
|
+
listCache = { people: ppl, at: now() };
|
|
120
|
+
return { people: ppl, status: "fresh", loadedAt: new Date(listCache.at) };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const error = got.kind === "ok" ? "malformed people list" : got.kind === "not-found" ? "HTTP 404" : got.error;
|
|
124
|
+
if (listCache)
|
|
125
|
+
return { people: listCache.people, status: "stale", loadedAt: new Date(listCache.at), error };
|
|
126
|
+
return { people: [], status: got.kind === "unconfigured" ? "unconfigured" : "unavailable", loadedAt: null, error };
|
|
127
|
+
}
|
|
128
|
+
const api = {
|
|
129
|
+
async list() {
|
|
130
|
+
if (listCache && now() - listCache.at < o.ttlMs) {
|
|
131
|
+
return { people: listCache.people, status: "fresh", loadedAt: new Date(listCache.at) };
|
|
132
|
+
}
|
|
133
|
+
// One request in flight however many callers ask at once.
|
|
134
|
+
listInflight ??= loadList().finally(() => {
|
|
135
|
+
listInflight = null;
|
|
136
|
+
});
|
|
137
|
+
return listInflight;
|
|
138
|
+
},
|
|
139
|
+
async get(slug) {
|
|
140
|
+
const { people: ppl } = await api.list();
|
|
141
|
+
return ppl.find((p) => p.slug === slug) ?? null;
|
|
142
|
+
},
|
|
143
|
+
async resolveUsername(username) {
|
|
144
|
+
const u = (username ?? "").trim().toLowerCase();
|
|
145
|
+
if (!u)
|
|
146
|
+
return { person: null, status: "not-found" };
|
|
147
|
+
const hit = users.get(u);
|
|
148
|
+
const age = hit ? now() - hit.at : Infinity;
|
|
149
|
+
if (hit && age < (hit.person ? o.ttlMs : o.notFoundTtlMs)) {
|
|
150
|
+
return { person: hit.person, status: hit.person ? "fresh" : "not-found" };
|
|
151
|
+
}
|
|
152
|
+
const got = await get(`${exports.PEOPLE_PATHS.whoamiResolve}?username=${encodeURIComponent(u)}`);
|
|
153
|
+
if (got.kind === "ok") {
|
|
154
|
+
const person = toPerson(got.json?.person);
|
|
155
|
+
if (person) {
|
|
156
|
+
users.set(u, { person, at: now() });
|
|
157
|
+
return { person, status: "fresh" };
|
|
158
|
+
}
|
|
159
|
+
return { person: null, status: "unavailable", error: "malformed whoami-resolve answer" };
|
|
160
|
+
}
|
|
161
|
+
if (got.kind === "not-found") {
|
|
162
|
+
users.set(u, { person: null, at: now() });
|
|
163
|
+
return { person: null, status: "not-found" };
|
|
164
|
+
}
|
|
165
|
+
if (hit?.person && age <= o.staleUsernameMs)
|
|
166
|
+
return { person: hit.person, status: "stale", error: got.error };
|
|
167
|
+
return { person: null, status: got.kind === "unconfigured" ? "unconfigured" : "unavailable", error: got.error };
|
|
168
|
+
},
|
|
169
|
+
async byAuthentikUsername(username) {
|
|
170
|
+
return (await api.resolveUsername(username)).person;
|
|
171
|
+
},
|
|
172
|
+
async healthCheck() {
|
|
173
|
+
const l = await api.list();
|
|
174
|
+
if (l.status === "fresh")
|
|
175
|
+
return { ok: true, detail: `${l.people.length} people` };
|
|
176
|
+
if (l.status === "stale")
|
|
177
|
+
return { ok: true, detail: `stale since ${l.loadedAt?.toISOString()}: ${l.error ?? ""}`.trim() };
|
|
178
|
+
throw new Error(`roster ${l.status}${l.error ? `: ${l.error}` : ""}`);
|
|
179
|
+
},
|
|
180
|
+
contacts: {
|
|
181
|
+
async search(q, opts = {}) {
|
|
182
|
+
const needle = (q ?? "").trim().toLowerCase();
|
|
183
|
+
if (!needle)
|
|
184
|
+
return { contacts: [], status: "fresh" };
|
|
185
|
+
const limit = Math.max(1, Math.min(50, Math.floor(opts.limit ?? 20)));
|
|
186
|
+
const key = `${limit}|${needle}`;
|
|
187
|
+
const hit = searches.get(key);
|
|
188
|
+
const age = hit ? now() - hit.at : Infinity;
|
|
189
|
+
if (hit && age < o.ttlMs)
|
|
190
|
+
return hit.result;
|
|
191
|
+
const got = await get(`${exports.PEOPLE_PATHS.contactsSearch}?q=${encodeURIComponent(needle)}&limit=${limit}`);
|
|
192
|
+
if (got.kind === "ok") {
|
|
193
|
+
const j = got.json;
|
|
194
|
+
if (Array.isArray(j?.contacts)) {
|
|
195
|
+
const contacts = j.contacts.map(toContact).filter((c) => c !== null);
|
|
196
|
+
const result = { contacts, status: j?.status === "stale" ? "stale" : "fresh" };
|
|
197
|
+
if (searches.size > 500)
|
|
198
|
+
searches.clear();
|
|
199
|
+
searches.set(key, { result, at: now() });
|
|
200
|
+
return result;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const error = got.kind === "ok" ? "malformed contacts answer" : got.kind === "not-found" ? "HTTP 404" : got.error;
|
|
204
|
+
if (hit && age <= o.staleUsernameMs)
|
|
205
|
+
return { ...hit.result, status: "stale", error };
|
|
206
|
+
return { contacts: [], status: got.kind === "unconfigured" ? "unconfigured" : "unavailable", error };
|
|
207
|
+
},
|
|
208
|
+
async byEmail(email) {
|
|
209
|
+
const e = (email ?? "").trim().toLowerCase();
|
|
210
|
+
if (!e)
|
|
211
|
+
return null;
|
|
212
|
+
const r = await api.contacts.search(e, { limit: 5 });
|
|
213
|
+
return r.contacts.find((c) => c.emails.includes(e)) ?? null;
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
clear() {
|
|
217
|
+
listCache = null;
|
|
218
|
+
users.clear();
|
|
219
|
+
searches.clear();
|
|
220
|
+
},
|
|
221
|
+
};
|
|
222
|
+
return api;
|
|
223
|
+
}
|
|
224
|
+
/** The process-wide people client. */
|
|
225
|
+
exports.people = createPeople();
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { type AppIdentity, type HeaderBag, type RequestLike } from "./keys.js";
|
|
2
|
+
import { type People, type Person } from "./people.js";
|
|
3
|
+
export type { AppIdentity, HeaderBag, RequestLike } from "./keys.js";
|
|
4
|
+
export interface PersonIdentity {
|
|
5
|
+
kind: "person";
|
|
6
|
+
slug: string;
|
|
7
|
+
personId: string;
|
|
8
|
+
via: "authentik" | "session" | "device";
|
|
9
|
+
person: Person;
|
|
10
|
+
/** The authentik username, when the identity came from one. */
|
|
11
|
+
username?: string;
|
|
12
|
+
/** Whatever the app's device resolver returned as `device`. */
|
|
13
|
+
device?: unknown;
|
|
14
|
+
}
|
|
15
|
+
export interface Anonymous {
|
|
16
|
+
kind: "anonymous";
|
|
17
|
+
/** Why — for the app's own logs. Never sent to the client by requirePerson. */
|
|
18
|
+
reason?: string;
|
|
19
|
+
}
|
|
20
|
+
export type Identity = PersonIdentity | AppIdentity | Anonymous;
|
|
21
|
+
export interface AuthentikOptions {
|
|
22
|
+
/** Public host(s) the edge serves this app on. Default: ZOO_KIT_PUBLIC_HOSTS, else PUBLIC_HOST. */
|
|
23
|
+
publicHosts?: string[];
|
|
24
|
+
/** X-Zoo-Gate secret. Default: ZOO_KIT_GATE_SECRET, else AUTH_GATE_SECRET. */
|
|
25
|
+
gateSecret?: string;
|
|
26
|
+
/** Honour DEV_USER (a dev-box short-circuit). Never honoured when NODE_ENV=production. */
|
|
27
|
+
allowDevUser?: boolean;
|
|
28
|
+
}
|
|
29
|
+
export interface SessionAnswer {
|
|
30
|
+
/** Resolved like an authentik username (linked username on the roster). */
|
|
31
|
+
authentikUsername?: string | null;
|
|
32
|
+
/** Or a roster slug the app already knows. */
|
|
33
|
+
slug?: string | null;
|
|
34
|
+
}
|
|
35
|
+
export interface DeviceAnswer {
|
|
36
|
+
personSlug: string;
|
|
37
|
+
device: unknown;
|
|
38
|
+
}
|
|
39
|
+
export interface WhoamiOptions {
|
|
40
|
+
/** Allowed app callers (source 1). */
|
|
41
|
+
apps?: readonly string[];
|
|
42
|
+
/** Device-key resolver (source 2) — the app keeps its own Device table in v1. */
|
|
43
|
+
resolveDeviceKey?: (key: string) => Promise<DeviceAnswer | null>;
|
|
44
|
+
/** The authentik header (source 3). `true` = env defaults. */
|
|
45
|
+
authentik?: boolean | AuthentikOptions;
|
|
46
|
+
/** A session resolver (source 4), e.g. NextAuth's getServerSession. */
|
|
47
|
+
session?: (req: RequestLike) => Promise<SessionAnswer | null | undefined>;
|
|
48
|
+
/** The people client (default: the shared one). */
|
|
49
|
+
people?: People;
|
|
50
|
+
}
|
|
51
|
+
/** Did the request name one of the public hosts (Host, or the first X-Forwarded-Host)? */
|
|
52
|
+
export declare function cameThroughGate(h: HeaderBag, hosts: readonly string[]): boolean;
|
|
53
|
+
/** Does the request carry the gate secret? True when no secret is configured (warned once). */
|
|
54
|
+
export declare function gateSecretOk(h: HeaderBag, secret: string): boolean;
|
|
55
|
+
/**
|
|
56
|
+
* The authentik username this request may claim, lowercased — or a reason it
|
|
57
|
+
* may not. Pure apart from env reads; never touches the network.
|
|
58
|
+
*/
|
|
59
|
+
export declare function readAuthentikUsername(h: HeaderBag, o?: AuthentikOptions): {
|
|
60
|
+
username: string;
|
|
61
|
+
} | {
|
|
62
|
+
reason: string;
|
|
63
|
+
};
|
|
64
|
+
export declare function whoami(req: RequestLike, opts?: WhoamiOptions): Promise<Identity>;
|
|
65
|
+
/**
|
|
66
|
+
* Thrown by requirePerson / requireApp. Carries a ready Response with no
|
|
67
|
+
* detail beyond the status word, so nothing about WHY leaks to the caller.
|
|
68
|
+
*
|
|
69
|
+
* Next: catch (e) { if (e instanceof ZooKitAuthError) return e.response; throw e; }
|
|
70
|
+
* Hono: app.onError((e, c) => e instanceof ZooKitAuthError ? e.response : c.text("error", 500))
|
|
71
|
+
*/
|
|
72
|
+
export declare class ZooKitAuthError extends Error {
|
|
73
|
+
readonly status: 401 | 403;
|
|
74
|
+
/** Server-side reason for the app's own logs. */
|
|
75
|
+
readonly reason: string;
|
|
76
|
+
constructor(status: 401 | 403, reason?: string);
|
|
77
|
+
/** A fresh Response each read (a body can only be consumed once). */
|
|
78
|
+
get response(): Response;
|
|
79
|
+
}
|
|
80
|
+
/** The person, or throws a 401 ZooKitAuthError. */
|
|
81
|
+
export declare function requirePerson(req: RequestLike, opts?: WhoamiOptions): Promise<PersonIdentity>;
|
|
82
|
+
/**
|
|
83
|
+
* The calling app, or throws: 401 when no Bearer was sent, 403 when the Bearer
|
|
84
|
+
* belongs to no allowed caller (or none of them has a key configured).
|
|
85
|
+
*/
|
|
86
|
+
export declare function requireApp(req: RequestLike, allowed: readonly string[]): AppIdentity;
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ZooKitAuthError = void 0;
|
|
4
|
+
exports.cameThroughGate = cameThroughGate;
|
|
5
|
+
exports.gateSecretOk = gateSecretOk;
|
|
6
|
+
exports.readAuthentikUsername = readAuthentikUsername;
|
|
7
|
+
exports.whoami = whoami;
|
|
8
|
+
exports.requirePerson = requirePerson;
|
|
9
|
+
exports.requireApp = requireApp;
|
|
10
|
+
/**
|
|
11
|
+
* whoami — "who is this request?" (plan §3.2). FAILS CLOSED: anything that
|
|
12
|
+
* cannot be verified is `anonymous`, and requirePerson/requireApp turn that
|
|
13
|
+
* into a 401/403.
|
|
14
|
+
*
|
|
15
|
+
* Sources, each opt-in, tried in this order:
|
|
16
|
+
* 1. app keys — `apps: [...]`, Bearer = ZOO_KIT_APP_KEY_<CALLER> -> kind "app"
|
|
17
|
+
* 2. device key — `resolveDeviceKey(key)`, the app's own Device table -> via "device"
|
|
18
|
+
* 3. authentik — `authentik: true`, the edge's username header -> via "authentik"
|
|
19
|
+
* 4. session — `session(req)`, e.g. a NextAuth session lookup -> via "session"
|
|
20
|
+
*
|
|
21
|
+
* Every person is resolved through the people directory, so every app gets the
|
|
22
|
+
* same slug; an archived person (enabled:false) is refused.
|
|
23
|
+
*
|
|
24
|
+
* THE AUTHENTIK GATE mirrors zoo-health lib/identityGate.ts:
|
|
25
|
+
* - HOST GATE: the request must name a configured public host in `Host` OR
|
|
26
|
+
* in the FIRST value of `X-Forwarded-Host`. Both are needed (B517): Next
|
|
27
|
+
* fills x-forwarded-host only when absent, so Traefik's survives; and a
|
|
28
|
+
* server action's redirect() is re-rendered by Next from its own bind address with every
|
|
29
|
+
* header EXCEPT Host. Do not "simplify" this to Host-only.
|
|
30
|
+
* - GATE SECRET: when a gate secret is configured, `X-Zoo-Gate` must equal it
|
|
31
|
+
* (timing-safe). Empty = unenforced, warned once — the interim until
|
|
32
|
+
* Traefik stamps it. Both headers are forgeable from the LAN without it.
|
|
33
|
+
* - The username is lowercased (authentik lowercases usernames; a
|
|
34
|
+
* case-varying second lookup would split one person in two).
|
|
35
|
+
* - No public host configured = the source refuses everything (there is no
|
|
36
|
+
* default host in this package).
|
|
37
|
+
*/
|
|
38
|
+
const env_js_1 = require("./env.js");
|
|
39
|
+
const keys_js_1 = require("./keys.js");
|
|
40
|
+
const people_js_1 = require("./people.js");
|
|
41
|
+
const USERNAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
|
|
42
|
+
function bareHost(v) {
|
|
43
|
+
return (v || "").split(",")[0].trim().toLowerCase().split(":")[0];
|
|
44
|
+
}
|
|
45
|
+
function publicHosts(o) {
|
|
46
|
+
const hosts = o.publicHosts ?? (0, env_js_1.firstList)(env_js_1.ENV.PUBLIC_HOSTS, env_js_1.ENV.PUBLIC_HOST);
|
|
47
|
+
return hosts.map((h) => bareHost(h)).filter(Boolean);
|
|
48
|
+
}
|
|
49
|
+
/** Did the request name one of the public hosts (Host, or the first X-Forwarded-Host)? */
|
|
50
|
+
function cameThroughGate(h, hosts) {
|
|
51
|
+
if (!hosts.length)
|
|
52
|
+
return false;
|
|
53
|
+
const host = bareHost(h.get("host"));
|
|
54
|
+
const fwd = bareHost(h.get("x-forwarded-host"));
|
|
55
|
+
return hosts.includes(host) || (fwd !== "" && hosts.includes(fwd));
|
|
56
|
+
}
|
|
57
|
+
/** Does the request carry the gate secret? True when no secret is configured (warned once). */
|
|
58
|
+
function gateSecretOk(h, secret) {
|
|
59
|
+
if (!secret) {
|
|
60
|
+
(0, env_js_1.warnOnce)("gate-unenforced", "no gate secret configured (ZOO_KIT_GATE_SECRET / AUTH_GATE_SECRET) — X-Zoo-Gate is NOT enforced");
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
return (0, keys_js_1.safeEqual)(h.get("x-zoo-gate") ?? "", secret);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The authentik username this request may claim, lowercased — or a reason it
|
|
67
|
+
* may not. Pure apart from env reads; never touches the network.
|
|
68
|
+
*/
|
|
69
|
+
function readAuthentikUsername(h, o = {}) {
|
|
70
|
+
if (o.allowDevUser) {
|
|
71
|
+
const dev = (0, env_js_1.str)(env_js_1.ENV.DEV_USER);
|
|
72
|
+
if (dev) {
|
|
73
|
+
if (process.env.NODE_ENV === "production") {
|
|
74
|
+
(0, env_js_1.warnOnce)("dev-user-prod", "DEV_USER is set but NODE_ENV=production — ignored");
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
return { username: dev.toLowerCase() };
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const hosts = publicHosts(o);
|
|
82
|
+
if (!hosts.length) {
|
|
83
|
+
(0, env_js_1.warnOnce)("no-public-host", `authentik identity refused: ${env_js_1.ENV.PUBLIC_HOSTS} not set`);
|
|
84
|
+
return { reason: "no public host configured" };
|
|
85
|
+
}
|
|
86
|
+
if (!cameThroughGate(h, hosts))
|
|
87
|
+
return { reason: "not through the public host" };
|
|
88
|
+
const secret = o.gateSecret ?? (0, env_js_1.firstStr)(env_js_1.ENV.GATE_SECRET, env_js_1.ENV.AUTH_GATE_SECRET);
|
|
89
|
+
if (!gateSecretOk(h, secret))
|
|
90
|
+
return { reason: "gate secret mismatch" };
|
|
91
|
+
const raw = (h.get("x-authentik-username") || h.get("x-forwarded-preferred-username") || h.get("x-forwarded-user") || "").trim();
|
|
92
|
+
if (!raw)
|
|
93
|
+
return { reason: "no identity header" };
|
|
94
|
+
if (!USERNAME_RE.test(raw))
|
|
95
|
+
return { reason: "unusable username" };
|
|
96
|
+
return { username: raw.toLowerCase() };
|
|
97
|
+
}
|
|
98
|
+
function asPerson(p, via, extra = {}) {
|
|
99
|
+
if (!p)
|
|
100
|
+
return { kind: "anonymous", reason: "no such person on the roster" };
|
|
101
|
+
if (p.enabled === false)
|
|
102
|
+
return { kind: "anonymous", reason: "person is archived" };
|
|
103
|
+
return { kind: "person", slug: p.slug, personId: p.id, via, person: p, ...extra };
|
|
104
|
+
}
|
|
105
|
+
async function whoami(req, opts = {}) {
|
|
106
|
+
const dir = opts.people ?? people_js_1.people;
|
|
107
|
+
const h = req.headers;
|
|
108
|
+
const token = (0, keys_js_1.bearerOf)(h);
|
|
109
|
+
if (token && opts.apps?.length) {
|
|
110
|
+
const app = (0, keys_js_1.appForToken)(token, opts.apps);
|
|
111
|
+
if (app)
|
|
112
|
+
return { kind: "app", app, via: "key" };
|
|
113
|
+
}
|
|
114
|
+
if (token && opts.resolveDeviceKey) {
|
|
115
|
+
try {
|
|
116
|
+
const d = await opts.resolveDeviceKey(token);
|
|
117
|
+
if (d && typeof d.personSlug === "string" && d.personSlug) {
|
|
118
|
+
return asPerson(await dir.get(d.personSlug), "device", { device: d.device });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return { kind: "anonymous", reason: "device resolver failed" };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
let reason = token ? "bearer not recognised" : "no credentials";
|
|
126
|
+
if (opts.authentik) {
|
|
127
|
+
const a = readAuthentikUsername(h, opts.authentik === true ? {} : opts.authentik);
|
|
128
|
+
if ("username" in a) {
|
|
129
|
+
const r = await dir.resolveUsername(a.username);
|
|
130
|
+
if (r.person)
|
|
131
|
+
return asPerson(r.person, "authentik", { username: a.username });
|
|
132
|
+
// A real header whose lookup failed is a definitive answer: never fall
|
|
133
|
+
// through to a weaker source and never guess.
|
|
134
|
+
return { kind: "anonymous", reason: `username ${r.status}` };
|
|
135
|
+
}
|
|
136
|
+
reason = a.reason;
|
|
137
|
+
}
|
|
138
|
+
if (opts.session) {
|
|
139
|
+
try {
|
|
140
|
+
const s = await opts.session(req);
|
|
141
|
+
const su = (s?.authentikUsername ?? "").trim().toLowerCase();
|
|
142
|
+
if (su) {
|
|
143
|
+
const r = await dir.resolveUsername(su);
|
|
144
|
+
return r.person ? asPerson(r.person, "session", { username: su }) : { kind: "anonymous", reason: `username ${r.status}` };
|
|
145
|
+
}
|
|
146
|
+
if (s?.slug)
|
|
147
|
+
return asPerson(await dir.get(s.slug), "session");
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return { kind: "anonymous", reason: "session resolver failed" };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return { kind: "anonymous", reason };
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Thrown by requirePerson / requireApp. Carries a ready Response with no
|
|
157
|
+
* detail beyond the status word, so nothing about WHY leaks to the caller.
|
|
158
|
+
*
|
|
159
|
+
* Next: catch (e) { if (e instanceof ZooKitAuthError) return e.response; throw e; }
|
|
160
|
+
* Hono: app.onError((e, c) => e instanceof ZooKitAuthError ? e.response : c.text("error", 500))
|
|
161
|
+
*/
|
|
162
|
+
class ZooKitAuthError extends Error {
|
|
163
|
+
status;
|
|
164
|
+
/** Server-side reason for the app's own logs. */
|
|
165
|
+
reason;
|
|
166
|
+
constructor(status, reason = "") {
|
|
167
|
+
super(status === 401 ? "unauthorized" : "forbidden");
|
|
168
|
+
this.name = "ZooKitAuthError";
|
|
169
|
+
this.status = status;
|
|
170
|
+
this.reason = reason;
|
|
171
|
+
}
|
|
172
|
+
/** A fresh Response each read (a body can only be consumed once). */
|
|
173
|
+
get response() {
|
|
174
|
+
return new Response(JSON.stringify({ error: this.message }), {
|
|
175
|
+
status: this.status,
|
|
176
|
+
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
exports.ZooKitAuthError = ZooKitAuthError;
|
|
181
|
+
/** The person, or throws a 401 ZooKitAuthError. */
|
|
182
|
+
async function requirePerson(req, opts = {}) {
|
|
183
|
+
const who = await whoami(req, opts);
|
|
184
|
+
if (who.kind === "person")
|
|
185
|
+
return who;
|
|
186
|
+
throw new ZooKitAuthError(401, who.kind === "anonymous" ? (who.reason ?? "") : "an app key is not a person");
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The calling app, or throws: 401 when no Bearer was sent, 403 when the Bearer
|
|
190
|
+
* belongs to no allowed caller (or none of them has a key configured).
|
|
191
|
+
*/
|
|
192
|
+
function requireApp(req, allowed) {
|
|
193
|
+
const v = (0, keys_js_1.checkApp)(req, allowed);
|
|
194
|
+
if (v.ok)
|
|
195
|
+
return v.identity;
|
|
196
|
+
throw new ZooKitAuthError(v.status, v.status === 401 ? "no bearer" : "bearer matches no allowed caller");
|
|
197
|
+
}
|
|
@@ -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.0
|
|
2
|
+
export declare const KIT_VERSION = "1.2.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.0
|
|
4
|
+
export const KIT_VERSION = "1.2.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"];
|