@jdcpuwiz/zoo-kit 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/README.md +238 -2
- package/dist/categories.d.ts +31 -0
- package/dist/categories.js +36 -0
- package/dist/env.d.ts +62 -0
- package/dist/env.js +91 -0
- package/dist/generated/categories.d.ts +85 -0
- package/dist/generated/categories.js +7 -0
- package/dist/generated/contract.d.ts +7 -0
- package/dist/generated/contract.js +9 -0
- package/dist/generated/notifier.d.ts +230 -0
- package/dist/generated/notifier.js +4 -0
- package/dist/generated/people.d.ts +261 -0
- package/dist/generated/people.js +4 -0
- package/dist/health.d.ts +46 -0
- package/dist/health.js +112 -0
- package/dist/http.d.ts +51 -0
- package/dist/http.js +102 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +19 -0
- package/dist/keys.d.ts +51 -0
- package/dist/keys.js +97 -0
- package/dist/notify.d.ts +75 -0
- package/dist/notify.js +119 -0
- package/dist/people.d.ts +61 -0
- package/dist/people.js +165 -0
- package/dist/whoami.d.ts +86 -0
- package/dist/whoami.js +187 -0
- package/package.json +50 -4
package/dist/people.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* people — the roster client (plan §3.3).
|
|
3
|
+
*
|
|
4
|
+
* Reads the people directory's v1 surface over the base URLs in
|
|
5
|
+
* ZOO_PEOPLE_URLS (today that is zoo-health; a later phase points the SAME
|
|
6
|
+
* names at a separate directory with no code change — so nothing here is
|
|
7
|
+
* specific to whichever service answers).
|
|
8
|
+
*
|
|
9
|
+
* GET /api/v1/people list (archived ones flagged enabled:false)
|
|
10
|
+
* GET /api/v1/whoami-resolve?username= one linked authentik username
|
|
11
|
+
*
|
|
12
|
+
* Auth: `Authorization: Bearer <ZOO_PEOPLE_TOKEN>` + `X-Dispenser-Consumer:
|
|
13
|
+
* <ZOO_PEOPLE_CONSUMER>` (the directory's declared-consumer gate).
|
|
14
|
+
*
|
|
15
|
+
* FAIL-SOFT: the list is cached ~5 min and served STALE on error; it is empty
|
|
16
|
+
* only if it never loaded, and `status` says which. A username lookup serves
|
|
17
|
+
* its last answer for <= 15 min while the directory is down, then null — whoami
|
|
18
|
+
* fails closed on null.
|
|
19
|
+
*/
|
|
20
|
+
import { ENV, firstList, str, warnOnce } from "./env.js";
|
|
21
|
+
import { PERSON_KEYS } from "./generated/contract.js";
|
|
22
|
+
import { failoverFetch, readJson, stripUndefined } from "./http.js";
|
|
23
|
+
export const PEOPLE_DEFAULTS = {
|
|
24
|
+
ttlMs: 5 * 60_000,
|
|
25
|
+
staleUsernameMs: 15 * 60_000,
|
|
26
|
+
notFoundTtlMs: 60_000,
|
|
27
|
+
attemptTimeoutMs: 5_000,
|
|
28
|
+
totalBudgetMs: 10_000,
|
|
29
|
+
rounds: 1,
|
|
30
|
+
roundBackoffMs: 250,
|
|
31
|
+
};
|
|
32
|
+
export const PEOPLE_PATHS = {
|
|
33
|
+
list: "/api/v1/people",
|
|
34
|
+
whoamiResolve: "/api/v1/whoami-resolve",
|
|
35
|
+
};
|
|
36
|
+
const KEYS = new Set(PERSON_KEYS);
|
|
37
|
+
/** Keep only the contract's Person keys; null for anything that is not a usable person. */
|
|
38
|
+
export function toPerson(raw) {
|
|
39
|
+
if (!raw || typeof raw !== "object")
|
|
40
|
+
return null;
|
|
41
|
+
const r = raw;
|
|
42
|
+
if (typeof r.id !== "string" || !r.id || typeof r.slug !== "string" || !r.slug)
|
|
43
|
+
return null;
|
|
44
|
+
const out = {};
|
|
45
|
+
for (const k of Object.keys(r))
|
|
46
|
+
if (KEYS.has(k))
|
|
47
|
+
out[k] = r[k];
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
function config() {
|
|
51
|
+
const urls = firstList(ENV.PEOPLE_URLS);
|
|
52
|
+
const token = str(ENV.PEOPLE_TOKEN);
|
|
53
|
+
const consumer = str(ENV.PEOPLE_CONSUMER);
|
|
54
|
+
const missing = [];
|
|
55
|
+
if (!urls.length)
|
|
56
|
+
missing.push(ENV.PEOPLE_URLS);
|
|
57
|
+
if (!token)
|
|
58
|
+
missing.push(ENV.PEOPLE_TOKEN);
|
|
59
|
+
if (!consumer)
|
|
60
|
+
missing.push(ENV.PEOPLE_CONSUMER);
|
|
61
|
+
return { urls, token, consumer, missing };
|
|
62
|
+
}
|
|
63
|
+
/** A people client with its own cache. Most apps use the shared {@link people}. */
|
|
64
|
+
export function createPeople(options = {}) {
|
|
65
|
+
const o = { ...PEOPLE_DEFAULTS, ...stripUndefined(options) };
|
|
66
|
+
const now = options.now ?? Date.now;
|
|
67
|
+
let listCache = null;
|
|
68
|
+
let listInflight = null;
|
|
69
|
+
const users = new Map();
|
|
70
|
+
async function get(path) {
|
|
71
|
+
const c = config();
|
|
72
|
+
if (c.missing.length) {
|
|
73
|
+
warnOnce("people-unconfigured", `people is unavailable: ${c.missing.join(", ")} not set`);
|
|
74
|
+
return { kind: "unconfigured", error: `not configured: ${c.missing.join(", ")} not set` };
|
|
75
|
+
}
|
|
76
|
+
const outcome = await failoverFetch(c.urls, path, { method: "GET", headers: { Authorization: `Bearer ${c.token}`, "X-Dispenser-Consumer": c.consumer, Accept: "application/json" } }, o);
|
|
77
|
+
if (outcome.kind === "failed")
|
|
78
|
+
return { kind: "error", error: outcome.error };
|
|
79
|
+
const { res } = outcome;
|
|
80
|
+
const json = await readJson(res);
|
|
81
|
+
if (res.status === 404)
|
|
82
|
+
return { kind: "not-found" };
|
|
83
|
+
if (!res.ok) {
|
|
84
|
+
const msg = json?.error;
|
|
85
|
+
warnOnce(`people-${res.status}`, `the people directory refused this app (${res.status}${msg ? `: ${msg}` : ""}) — check ${ENV.PEOPLE_TOKEN} / ${ENV.PEOPLE_CONSUMER}`);
|
|
86
|
+
return { kind: "error", error: `HTTP ${res.status}${msg ? `: ${msg}` : ""}` };
|
|
87
|
+
}
|
|
88
|
+
return { kind: "ok", json };
|
|
89
|
+
}
|
|
90
|
+
async function loadList() {
|
|
91
|
+
const got = await get(PEOPLE_PATHS.list);
|
|
92
|
+
if (got.kind === "ok") {
|
|
93
|
+
const raw = got.json?.people;
|
|
94
|
+
if (Array.isArray(raw)) {
|
|
95
|
+
const ppl = raw.map(toPerson).filter((p) => p !== null);
|
|
96
|
+
listCache = { people: ppl, at: now() };
|
|
97
|
+
return { people: ppl, status: "fresh", loadedAt: new Date(listCache.at) };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const error = got.kind === "ok" ? "malformed people list" : got.kind === "not-found" ? "HTTP 404" : got.error;
|
|
101
|
+
if (listCache)
|
|
102
|
+
return { people: listCache.people, status: "stale", loadedAt: new Date(listCache.at), error };
|
|
103
|
+
return { people: [], status: got.kind === "unconfigured" ? "unconfigured" : "unavailable", loadedAt: null, error };
|
|
104
|
+
}
|
|
105
|
+
const api = {
|
|
106
|
+
async list() {
|
|
107
|
+
if (listCache && now() - listCache.at < o.ttlMs) {
|
|
108
|
+
return { people: listCache.people, status: "fresh", loadedAt: new Date(listCache.at) };
|
|
109
|
+
}
|
|
110
|
+
// One request in flight however many callers ask at once.
|
|
111
|
+
listInflight ??= loadList().finally(() => {
|
|
112
|
+
listInflight = null;
|
|
113
|
+
});
|
|
114
|
+
return listInflight;
|
|
115
|
+
},
|
|
116
|
+
async get(slug) {
|
|
117
|
+
const { people: ppl } = await api.list();
|
|
118
|
+
return ppl.find((p) => p.slug === slug) ?? null;
|
|
119
|
+
},
|
|
120
|
+
async resolveUsername(username) {
|
|
121
|
+
const u = (username ?? "").trim().toLowerCase();
|
|
122
|
+
if (!u)
|
|
123
|
+
return { person: null, status: "not-found" };
|
|
124
|
+
const hit = users.get(u);
|
|
125
|
+
const age = hit ? now() - hit.at : Infinity;
|
|
126
|
+
if (hit && age < (hit.person ? o.ttlMs : o.notFoundTtlMs)) {
|
|
127
|
+
return { person: hit.person, status: hit.person ? "fresh" : "not-found" };
|
|
128
|
+
}
|
|
129
|
+
const got = await get(`${PEOPLE_PATHS.whoamiResolve}?username=${encodeURIComponent(u)}`);
|
|
130
|
+
if (got.kind === "ok") {
|
|
131
|
+
const person = toPerson(got.json?.person);
|
|
132
|
+
if (person) {
|
|
133
|
+
users.set(u, { person, at: now() });
|
|
134
|
+
return { person, status: "fresh" };
|
|
135
|
+
}
|
|
136
|
+
return { person: null, status: "unavailable", error: "malformed whoami-resolve answer" };
|
|
137
|
+
}
|
|
138
|
+
if (got.kind === "not-found") {
|
|
139
|
+
users.set(u, { person: null, at: now() });
|
|
140
|
+
return { person: null, status: "not-found" };
|
|
141
|
+
}
|
|
142
|
+
if (hit?.person && age <= o.staleUsernameMs)
|
|
143
|
+
return { person: hit.person, status: "stale", error: got.error };
|
|
144
|
+
return { person: null, status: got.kind === "unconfigured" ? "unconfigured" : "unavailable", error: got.error };
|
|
145
|
+
},
|
|
146
|
+
async byAuthentikUsername(username) {
|
|
147
|
+
return (await api.resolveUsername(username)).person;
|
|
148
|
+
},
|
|
149
|
+
async healthCheck() {
|
|
150
|
+
const l = await api.list();
|
|
151
|
+
if (l.status === "fresh")
|
|
152
|
+
return { ok: true, detail: `${l.people.length} people` };
|
|
153
|
+
if (l.status === "stale")
|
|
154
|
+
return { ok: true, detail: `stale since ${l.loadedAt?.toISOString()}: ${l.error ?? ""}`.trim() };
|
|
155
|
+
throw new Error(`roster ${l.status}${l.error ? `: ${l.error}` : ""}`);
|
|
156
|
+
},
|
|
157
|
+
clear() {
|
|
158
|
+
listCache = null;
|
|
159
|
+
users.clear();
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
return api;
|
|
163
|
+
}
|
|
164
|
+
/** The process-wide people client. */
|
|
165
|
+
export const people = createPeople();
|
package/dist/whoami.d.ts
ADDED
|
@@ -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;
|
package/dist/whoami.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* whoami — "who is this request?" (plan §3.2). FAILS CLOSED: anything that
|
|
3
|
+
* cannot be verified is `anonymous`, and requirePerson/requireApp turn that
|
|
4
|
+
* into a 401/403.
|
|
5
|
+
*
|
|
6
|
+
* Sources, each opt-in, tried in this order:
|
|
7
|
+
* 1. app keys — `apps: [...]`, Bearer = ZOO_KIT_APP_KEY_<CALLER> -> kind "app"
|
|
8
|
+
* 2. device key — `resolveDeviceKey(key)`, the app's own Device table -> via "device"
|
|
9
|
+
* 3. authentik — `authentik: true`, the edge's username header -> via "authentik"
|
|
10
|
+
* 4. session — `session(req)`, e.g. a NextAuth session lookup -> via "session"
|
|
11
|
+
*
|
|
12
|
+
* Every person is resolved through the people directory, so every app gets the
|
|
13
|
+
* same slug; an archived person (enabled:false) is refused.
|
|
14
|
+
*
|
|
15
|
+
* THE AUTHENTIK GATE mirrors zoo-health lib/identityGate.ts:
|
|
16
|
+
* - HOST GATE: the request must name a configured public host in `Host` OR
|
|
17
|
+
* in the FIRST value of `X-Forwarded-Host`. Both are needed (B517): Next
|
|
18
|
+
* fills x-forwarded-host only when absent, so Traefik's survives; and a
|
|
19
|
+
* server action's redirect() is re-rendered by Next from its own bind address with every
|
|
20
|
+
* header EXCEPT Host. Do not "simplify" this to Host-only.
|
|
21
|
+
* - GATE SECRET: when a gate secret is configured, `X-Zoo-Gate` must equal it
|
|
22
|
+
* (timing-safe). Empty = unenforced, warned once — the interim until
|
|
23
|
+
* Traefik stamps it. Both headers are forgeable from the LAN without it.
|
|
24
|
+
* - The username is lowercased (authentik lowercases usernames; a
|
|
25
|
+
* case-varying second lookup would split one person in two).
|
|
26
|
+
* - No public host configured = the source refuses everything (there is no
|
|
27
|
+
* default host in this package).
|
|
28
|
+
*/
|
|
29
|
+
import { ENV, firstList, firstStr, str, warnOnce } from "./env.js";
|
|
30
|
+
import { appForToken, bearerOf, checkApp, safeEqual } from "./keys.js";
|
|
31
|
+
import { people as sharedPeople } from "./people.js";
|
|
32
|
+
const USERNAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
|
|
33
|
+
function bareHost(v) {
|
|
34
|
+
return (v || "").split(",")[0].trim().toLowerCase().split(":")[0];
|
|
35
|
+
}
|
|
36
|
+
function publicHosts(o) {
|
|
37
|
+
const hosts = o.publicHosts ?? firstList(ENV.PUBLIC_HOSTS, ENV.PUBLIC_HOST);
|
|
38
|
+
return hosts.map((h) => bareHost(h)).filter(Boolean);
|
|
39
|
+
}
|
|
40
|
+
/** Did the request name one of the public hosts (Host, or the first X-Forwarded-Host)? */
|
|
41
|
+
export function cameThroughGate(h, hosts) {
|
|
42
|
+
if (!hosts.length)
|
|
43
|
+
return false;
|
|
44
|
+
const host = bareHost(h.get("host"));
|
|
45
|
+
const fwd = bareHost(h.get("x-forwarded-host"));
|
|
46
|
+
return hosts.includes(host) || (fwd !== "" && hosts.includes(fwd));
|
|
47
|
+
}
|
|
48
|
+
/** Does the request carry the gate secret? True when no secret is configured (warned once). */
|
|
49
|
+
export function gateSecretOk(h, secret) {
|
|
50
|
+
if (!secret) {
|
|
51
|
+
warnOnce("gate-unenforced", "no gate secret configured (ZOO_KIT_GATE_SECRET / AUTH_GATE_SECRET) — X-Zoo-Gate is NOT enforced");
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
return safeEqual(h.get("x-zoo-gate") ?? "", secret);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The authentik username this request may claim, lowercased — or a reason it
|
|
58
|
+
* may not. Pure apart from env reads; never touches the network.
|
|
59
|
+
*/
|
|
60
|
+
export function readAuthentikUsername(h, o = {}) {
|
|
61
|
+
if (o.allowDevUser) {
|
|
62
|
+
const dev = str(ENV.DEV_USER);
|
|
63
|
+
if (dev) {
|
|
64
|
+
if (process.env.NODE_ENV === "production") {
|
|
65
|
+
warnOnce("dev-user-prod", "DEV_USER is set but NODE_ENV=production — ignored");
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
return { username: dev.toLowerCase() };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const hosts = publicHosts(o);
|
|
73
|
+
if (!hosts.length) {
|
|
74
|
+
warnOnce("no-public-host", `authentik identity refused: ${ENV.PUBLIC_HOSTS} not set`);
|
|
75
|
+
return { reason: "no public host configured" };
|
|
76
|
+
}
|
|
77
|
+
if (!cameThroughGate(h, hosts))
|
|
78
|
+
return { reason: "not through the public host" };
|
|
79
|
+
const secret = o.gateSecret ?? firstStr(ENV.GATE_SECRET, ENV.AUTH_GATE_SECRET);
|
|
80
|
+
if (!gateSecretOk(h, secret))
|
|
81
|
+
return { reason: "gate secret mismatch" };
|
|
82
|
+
const raw = (h.get("x-authentik-username") || h.get("x-forwarded-preferred-username") || h.get("x-forwarded-user") || "").trim();
|
|
83
|
+
if (!raw)
|
|
84
|
+
return { reason: "no identity header" };
|
|
85
|
+
if (!USERNAME_RE.test(raw))
|
|
86
|
+
return { reason: "unusable username" };
|
|
87
|
+
return { username: raw.toLowerCase() };
|
|
88
|
+
}
|
|
89
|
+
function asPerson(p, via, extra = {}) {
|
|
90
|
+
if (!p)
|
|
91
|
+
return { kind: "anonymous", reason: "no such person on the roster" };
|
|
92
|
+
if (p.enabled === false)
|
|
93
|
+
return { kind: "anonymous", reason: "person is archived" };
|
|
94
|
+
return { kind: "person", slug: p.slug, personId: p.id, via, person: p, ...extra };
|
|
95
|
+
}
|
|
96
|
+
export async function whoami(req, opts = {}) {
|
|
97
|
+
const dir = opts.people ?? sharedPeople;
|
|
98
|
+
const h = req.headers;
|
|
99
|
+
const token = bearerOf(h);
|
|
100
|
+
if (token && opts.apps?.length) {
|
|
101
|
+
const app = appForToken(token, opts.apps);
|
|
102
|
+
if (app)
|
|
103
|
+
return { kind: "app", app, via: "key" };
|
|
104
|
+
}
|
|
105
|
+
if (token && opts.resolveDeviceKey) {
|
|
106
|
+
try {
|
|
107
|
+
const d = await opts.resolveDeviceKey(token);
|
|
108
|
+
if (d && typeof d.personSlug === "string" && d.personSlug) {
|
|
109
|
+
return asPerson(await dir.get(d.personSlug), "device", { device: d.device });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return { kind: "anonymous", reason: "device resolver failed" };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
let reason = token ? "bearer not recognised" : "no credentials";
|
|
117
|
+
if (opts.authentik) {
|
|
118
|
+
const a = readAuthentikUsername(h, opts.authentik === true ? {} : opts.authentik);
|
|
119
|
+
if ("username" in a) {
|
|
120
|
+
const r = await dir.resolveUsername(a.username);
|
|
121
|
+
if (r.person)
|
|
122
|
+
return asPerson(r.person, "authentik", { username: a.username });
|
|
123
|
+
// A real header whose lookup failed is a definitive answer: never fall
|
|
124
|
+
// through to a weaker source and never guess.
|
|
125
|
+
return { kind: "anonymous", reason: `username ${r.status}` };
|
|
126
|
+
}
|
|
127
|
+
reason = a.reason;
|
|
128
|
+
}
|
|
129
|
+
if (opts.session) {
|
|
130
|
+
try {
|
|
131
|
+
const s = await opts.session(req);
|
|
132
|
+
const su = (s?.authentikUsername ?? "").trim().toLowerCase();
|
|
133
|
+
if (su) {
|
|
134
|
+
const r = await dir.resolveUsername(su);
|
|
135
|
+
return r.person ? asPerson(r.person, "session", { username: su }) : { kind: "anonymous", reason: `username ${r.status}` };
|
|
136
|
+
}
|
|
137
|
+
if (s?.slug)
|
|
138
|
+
return asPerson(await dir.get(s.slug), "session");
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return { kind: "anonymous", reason: "session resolver failed" };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return { kind: "anonymous", reason };
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Thrown by requirePerson / requireApp. Carries a ready Response with no
|
|
148
|
+
* detail beyond the status word, so nothing about WHY leaks to the caller.
|
|
149
|
+
*
|
|
150
|
+
* Next: catch (e) { if (e instanceof ZooKitAuthError) return e.response; throw e; }
|
|
151
|
+
* Hono: app.onError((e, c) => e instanceof ZooKitAuthError ? e.response : c.text("error", 500))
|
|
152
|
+
*/
|
|
153
|
+
export class ZooKitAuthError extends Error {
|
|
154
|
+
status;
|
|
155
|
+
/** Server-side reason for the app's own logs. */
|
|
156
|
+
reason;
|
|
157
|
+
constructor(status, reason = "") {
|
|
158
|
+
super(status === 401 ? "unauthorized" : "forbidden");
|
|
159
|
+
this.name = "ZooKitAuthError";
|
|
160
|
+
this.status = status;
|
|
161
|
+
this.reason = reason;
|
|
162
|
+
}
|
|
163
|
+
/** A fresh Response each read (a body can only be consumed once). */
|
|
164
|
+
get response() {
|
|
165
|
+
return new Response(JSON.stringify({ error: this.message }), {
|
|
166
|
+
status: this.status,
|
|
167
|
+
headers: { "Content-Type": "application/json", "Cache-Control": "no-store" },
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/** The person, or throws a 401 ZooKitAuthError. */
|
|
172
|
+
export async function requirePerson(req, opts = {}) {
|
|
173
|
+
const who = await whoami(req, opts);
|
|
174
|
+
if (who.kind === "person")
|
|
175
|
+
return who;
|
|
176
|
+
throw new ZooKitAuthError(401, who.kind === "anonymous" ? (who.reason ?? "") : "an app key is not a person");
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The calling app, or throws: 401 when no Bearer was sent, 403 when the Bearer
|
|
180
|
+
* belongs to no allowed caller (or none of them has a key configured).
|
|
181
|
+
*/
|
|
182
|
+
export function requireApp(req, allowed) {
|
|
183
|
+
const v = checkApp(req, allowed);
|
|
184
|
+
if (v.ok)
|
|
185
|
+
return v.identity;
|
|
186
|
+
throw new ZooKitAuthError(v.status, v.status === 401 ? "no bearer" : "bearer matches no allowed caller");
|
|
187
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jdcpuwiz/zoo-kit",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Thin, pinned server-side client for the homelab's shared services: notify, whoami, people, health, app keys.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=20"
|
|
9
|
+
},
|
|
10
|
+
"sideEffects": false,
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./package.json": "./package.json"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist/**/*.js",
|
|
22
|
+
"dist/**/*.d.ts",
|
|
23
|
+
"README.md",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/JdCpuWiz/zoo-kit.git",
|
|
32
|
+
"directory": "packages/zoo-kit"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"gen": "node scripts/generate.mjs",
|
|
36
|
+
"gen:check": "node scripts/generate.mjs --check",
|
|
37
|
+
"typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.test.json",
|
|
38
|
+
"test": "npm run gen:check && vitest run",
|
|
39
|
+
"build": "npm run gen:check && rm -rf dist && tsc -p tsconfig.build.json",
|
|
40
|
+
"prepack": "npm run build",
|
|
41
|
+
"smoke:live": "npm run build && node scripts/live-smoke.mjs"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/node": "^20.17.0",
|
|
45
|
+
"ajv": "^8.17.1",
|
|
46
|
+
"ajv-formats": "^3.0.1",
|
|
47
|
+
"openapi-typescript": "7.13.0",
|
|
48
|
+
"typescript": "^5.6.3",
|
|
49
|
+
"vitest": "^2.1.9",
|
|
50
|
+
"yaml": "^2.6.1"
|
|
51
|
+
}
|
|
52
|
+
}
|