@tensile-tools/auth 0.0.0-stage → 0.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.
@@ -0,0 +1,73 @@
1
+ import type { CheckRequest, CheckResult } from './api.ts';
2
+ /** Options of the cache. */
3
+ export interface CacheOptions {
4
+ /** How long an allowed answer may be served, in milliseconds. At most and by default 30,000. */
5
+ ttlMs?: number;
6
+ /** How many answers to hold. Defaults to 10,000; the oldest goes first. */
7
+ maxEntries?: number;
8
+ }
9
+ /** What a cache reports about itself. */
10
+ export interface CacheState {
11
+ /** True while the event stream is connected and has sent `ready`. */
12
+ readonly active: boolean;
13
+ /** How many answers it holds. */
14
+ readonly size: number;
15
+ }
16
+ /** The longest an answer is served: 30 seconds. */
17
+ export declare const maxCacheTtlMs = 30000;
18
+ type Allowed = Extract<CheckResult, {
19
+ allowed: true;
20
+ }>;
21
+ /**
22
+ * Holds allowed check answers by the SHA-256 of their credential and the
23
+ * facts the answer depends on. It never holds the credential itself.
24
+ */
25
+ export declare class CheckCache implements CacheState {
26
+ #private;
27
+ constructor(o?: CacheOptions);
28
+ get active(): boolean;
29
+ get size(): number;
30
+ /** The stream sent `ready`: clear what may be stale, then serve. */
31
+ activate(): void;
32
+ /** The stream dropped: serve nothing until the next `ready`. */
33
+ deactivate(): void;
34
+ /** The stream sent `invalidate`: drop everything. */
35
+ clear(): void;
36
+ /** Returns a fresh allowed answer for `key`, or `undefined`. */
37
+ get(key: string): Allowed | undefined;
38
+ /**
39
+ * Holds an answer, if it may be held: only an allowed answer that sets
40
+ * no cookie, until 30 seconds pass or the session expires, whichever
41
+ * comes first. `generation` is the cache's generation when the call
42
+ * began, so an answer that raced an invalidation is dropped.
43
+ */
44
+ set(key: string, result: CheckResult, generation: number): void;
45
+ /** Counts invalidations, so a call can tell whether one happened while it ran. */
46
+ get generation(): number;
47
+ /** Marks an invalidation: answers fetched before it are never held. */
48
+ bump(): void;
49
+ }
50
+ /**
51
+ * Returns the cache key of a check, or `undefined` when the check must
52
+ * never be cached: a DPoP request, an approval, or a need with freshness
53
+ * or assurance.
54
+ */
55
+ export declare function cacheKey(body: CheckRequest): Promise<string | undefined>;
56
+ /** Options of `watchEvents`. */
57
+ export interface WatchOptions {
58
+ url: URL;
59
+ headers: Record<string, string>;
60
+ fetch: typeof globalThis.fetch;
61
+ cache: CheckCache;
62
+ warn: (message: string) => void;
63
+ /** How long the stream may stay silent before it counts as dropped. The server sends a comment every 15 seconds. Defaults to 45,000. */
64
+ idleMs?: number;
65
+ }
66
+ /**
67
+ * Holds GET /v1/events/stream for the cache: `ready` turns the cache on,
68
+ * `invalidate` clears it, and a stream that ends, fails, or stays silent
69
+ * turns it off until the next `ready`. It reconnects with backoff, from 1
70
+ * second to 30. Returns a function that stops it.
71
+ */
72
+ export declare function watchEvents(o: WatchOptions): () => void;
73
+ export {};
package/dist/cache.js ADDED
@@ -0,0 +1,222 @@
1
+ // The opt-in cache of /v1/check answers, and the event stream that keeps
2
+ // it honest. It follows the rules of cachestore with pgstore.Watch
3
+ // (invariants 20 and 21): it serves nothing unless GET /v1/events/stream
4
+ // is connected, clears itself on every event, and serves only allowed
5
+ // answers, for at most 30 seconds.
6
+ /** The longest an answer is served: 30 seconds. */
7
+ export const maxCacheTtlMs = 30_000;
8
+ /**
9
+ * Holds allowed check answers by the SHA-256 of their credential and the
10
+ * facts the answer depends on. It never holds the credential itself.
11
+ */
12
+ export class CheckCache {
13
+ #ttl;
14
+ #max;
15
+ #entries = new Map();
16
+ #active = false;
17
+ #generation = 0;
18
+ constructor(o = {}) {
19
+ this.#ttl = Math.min(o.ttlMs ?? maxCacheTtlMs, maxCacheTtlMs);
20
+ this.#max = o.maxEntries ?? 10_000;
21
+ if (!(this.#ttl > 0) || !(this.#max > 0))
22
+ throw new RangeError('tensile: cache ttlMs and maxEntries must be positive');
23
+ }
24
+ get active() {
25
+ return this.#active;
26
+ }
27
+ get size() {
28
+ return this.#entries.size;
29
+ }
30
+ /** The stream sent `ready`: clear what may be stale, then serve. */
31
+ activate() {
32
+ this.#entries.clear();
33
+ this.#active = true;
34
+ }
35
+ /** The stream dropped: serve nothing until the next `ready`. */
36
+ deactivate() {
37
+ this.#active = false;
38
+ this.#entries.clear();
39
+ }
40
+ /** The stream sent `invalidate`: drop everything. */
41
+ clear() {
42
+ this.#entries.clear();
43
+ }
44
+ /** Returns a fresh allowed answer for `key`, or `undefined`. */
45
+ get(key) {
46
+ if (!this.#active)
47
+ return undefined;
48
+ const e = this.#entries.get(key);
49
+ if (!e)
50
+ return undefined;
51
+ if (e.expires <= Date.now()) {
52
+ this.#entries.delete(key);
53
+ return undefined;
54
+ }
55
+ return structuredClone(e.result);
56
+ }
57
+ /**
58
+ * Holds an answer, if it may be held: only an allowed answer that sets
59
+ * no cookie, until 30 seconds pass or the session expires, whichever
60
+ * comes first. `generation` is the cache's generation when the call
61
+ * began, so an answer that raced an invalidation is dropped.
62
+ */
63
+ set(key, result, generation) {
64
+ if (!this.#active || generation !== this.#generation || !result.allowed || result.set_cookies.length)
65
+ return;
66
+ const expires = Math.min(Date.now() + this.#ttl, Date.parse(result.principal.expires_at));
67
+ if (!(expires > Date.now()))
68
+ return;
69
+ if (this.#entries.size >= this.#max)
70
+ this.#entries.delete(this.#entries.keys().next().value);
71
+ this.#entries.set(key, { result: structuredClone(result), expires });
72
+ }
73
+ /** Counts invalidations, so a call can tell whether one happened while it ran. */
74
+ get generation() {
75
+ return this.#generation;
76
+ }
77
+ /** Marks an invalidation: answers fetched before it are never held. */
78
+ bump() {
79
+ this.#generation++;
80
+ }
81
+ }
82
+ /**
83
+ * Returns the cache key of a check, or `undefined` when the check must
84
+ * never be cached: a DPoP request, an approval, or a need with freshness
85
+ * or assurance.
86
+ */
87
+ export async function cacheKey(body) {
88
+ const c = body.credential;
89
+ if (c.dpop || (c.authorization && /^dpop\s/i.test(c.authorization)))
90
+ return undefined;
91
+ if (body.approval)
92
+ return undefined;
93
+ const n = body.need;
94
+ if (n && (n.within_seconds !== undefined || n.assurance))
95
+ return undefined;
96
+ const r = body.request;
97
+ let origin;
98
+ try {
99
+ origin = new URL(r.url).origin;
100
+ }
101
+ catch {
102
+ return undefined;
103
+ }
104
+ // The answer depends on the credential, the need, the resource, the
105
+ // app's origin, and, for a cookie, the method and the browser's
106
+ // cross-origin headers. The path and the client's address don't change
107
+ // it.
108
+ const facts = JSON.stringify([
109
+ (r.method ?? 'GET').toUpperCase(), origin, r.origin ?? '', r.sec_fetch_site ?? '', body.resource ?? '',
110
+ n ? [n.action, n.human ?? false, [...(n.scopes ?? [])].sort(), n.approval_ttl_seconds ?? 0] : null,
111
+ ]);
112
+ return `${await sha256(c.cookie ? `cookie ${c.cookie}` : `authorization ${c.authorization}`)}:${await sha256(facts)}`;
113
+ }
114
+ async function sha256(s) {
115
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)));
116
+ let hex = '';
117
+ for (const b of d)
118
+ hex += b.toString(16).padStart(2, '0');
119
+ return hex;
120
+ }
121
+ /**
122
+ * Holds GET /v1/events/stream for the cache: `ready` turns the cache on,
123
+ * `invalidate` clears it, and a stream that ends, fails, or stays silent
124
+ * turns it off until the next `ready`. It reconnects with backoff, from 1
125
+ * second to 30. Returns a function that stops it.
126
+ */
127
+ export function watchEvents(o) {
128
+ let stopped = false;
129
+ let current;
130
+ let wake;
131
+ let delay = 1000;
132
+ let warned = false;
133
+ const idleMs = o.idleMs ?? 45_000;
134
+ const down = () => {
135
+ o.cache.bump();
136
+ o.cache.deactivate();
137
+ };
138
+ async function once() {
139
+ const ac = new AbortController();
140
+ current = ac;
141
+ let idle;
142
+ const touch = () => {
143
+ clearTimeout(idle);
144
+ idle = setTimeout(() => ac.abort(new Error('the event stream went silent')), idleMs);
145
+ };
146
+ try {
147
+ touch();
148
+ const res = await o.fetch(o.url, { headers: { ...o.headers, accept: 'text/event-stream' }, signal: ac.signal, redirect: 'manual' });
149
+ if (res.status !== 200 || !res.body) {
150
+ await res.body?.cancel();
151
+ const retry = Number(res.headers.get('retry-after'));
152
+ if (retry > 0)
153
+ delay = Math.max(delay, retry * 1000);
154
+ if (!warned) {
155
+ warned = true;
156
+ o.warn(`tensile: the event stream answered ${res.status}; the cache stays off until it connects`);
157
+ }
158
+ return;
159
+ }
160
+ const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
161
+ // Cancel the read itself on abort, for a fetch that stops watching
162
+ // its signal once the headers arrive.
163
+ ac.signal.addEventListener('abort', () => void reader.cancel(ac.signal.reason).catch(() => { }), { once: true });
164
+ let buf = '';
165
+ let event = 'message';
166
+ for (;;) {
167
+ const { value, done } = await reader.read();
168
+ if (done)
169
+ return;
170
+ touch();
171
+ buf += value;
172
+ let i;
173
+ while ((i = buf.search(/\r?\n/)) >= 0) {
174
+ const line = buf.slice(0, i);
175
+ buf = buf.slice(i + (buf[i] === '\r' ? 2 : 1));
176
+ if (line === '') {
177
+ if (event === 'ready') {
178
+ o.cache.bump();
179
+ o.cache.activate();
180
+ delay = 1000;
181
+ warned = false;
182
+ }
183
+ else if (event === 'invalidate') {
184
+ o.cache.bump();
185
+ o.cache.clear();
186
+ }
187
+ event = 'message';
188
+ }
189
+ else if (line.startsWith('event:')) {
190
+ event = line.slice(6).trim();
191
+ }
192
+ }
193
+ }
194
+ }
195
+ catch {
196
+ // Any failure turns the cache off below.
197
+ }
198
+ finally {
199
+ clearTimeout(idle);
200
+ down();
201
+ }
202
+ }
203
+ void (async () => {
204
+ while (!stopped) {
205
+ await once();
206
+ if (stopped)
207
+ break;
208
+ const wait = delay * (0.8 + Math.random() * 0.4);
209
+ delay = Math.min(delay * 2, 30_000);
210
+ await new Promise(resolve => {
211
+ const t = setTimeout(resolve, wait);
212
+ wake = () => { clearTimeout(t); resolve(); };
213
+ });
214
+ }
215
+ })();
216
+ return () => {
217
+ stopped = true;
218
+ current?.abort();
219
+ wake?.();
220
+ down();
221
+ };
222
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Which forwarded header to read for the client's address:
3
+ *
4
+ * - `false` or unset: none. The adapter uses the socket's address, or none.
5
+ * - `{ header: 'x-forwarded-for', hops: n }`: the `n`th `X-Forwarded-For`
6
+ * entry from the right, for `n` proxies in a chain.
7
+ * - `{ header: 'x-real-ip' }`: `X-Real-IP`, for a proxy that sets it.
8
+ * - `true`: shorthand for `x-forwarded-for` with 1 hop.
9
+ * - A number `n`: shorthand for `x-forwarded-for` with `n` hops.
10
+ *
11
+ * The adapter reads only the header named, and never falls back to the
12
+ * other one.
13
+ */
14
+ export type TrustProxy = boolean | number | {
15
+ header: 'x-forwarded-for';
16
+ hops: number;
17
+ } | {
18
+ header: 'x-real-ip';
19
+ };
20
+ /** The options that decide where the client's address comes from. */
21
+ export interface ClientIpOptions {
22
+ trustProxy?: TrustProxy;
23
+ /**
24
+ * The proxies' own addresses, as CIDRs such as `10.0.0.0/8` or
25
+ * `fd00::/8`. Where the socket's address is known, the adapter reads the
26
+ * `trustProxy` header only when the socket's address is in one of these.
27
+ * Defaults to none, so `trustProxy` alone reads headers only where the
28
+ * runtime exposes no socket address.
29
+ */
30
+ trustedProxies?: readonly string[];
31
+ }
32
+ /** The connection a request came over: `undefined` when the runtime exposes no socket address. */
33
+ export type Peer = {
34
+ address: string | undefined;
35
+ } | undefined;
36
+ /**
37
+ * Returns the function that reads the client's address from a request's
38
+ * headers and its peer. It throws when `trustProxy` or `trustedProxies` is
39
+ * malformed, so a bad configuration fails at startup.
40
+ */
41
+ export declare function clientIpReader(options: ClientIpOptions): (h: Headers, peer: Peer) => string | undefined;
42
+ /** Returns `s` when it is an IPv4 or IPv6 address, and `undefined` otherwise. */
43
+ export declare function ipOrUndefined(s: string | null | undefined): string | undefined;
@@ -0,0 +1,151 @@
1
+ // The client's address, for rate limits and the audit log.
2
+ //
3
+ // Anyone who connects to the app directly can send X-Forwarded-For and
4
+ // X-Real-IP. The adapters read one of them only when the app names it in
5
+ // trustProxy and, where the socket's address is known, only when that
6
+ // address is in trustedProxies, as authhttp.WithClientIP does. Otherwise
7
+ // they use the socket's address where the framework exposes it, and send
8
+ // none where it doesn't.
9
+ /**
10
+ * Returns the function that reads the client's address from a request's
11
+ * headers and its peer. It throws when `trustProxy` or `trustedProxies` is
12
+ * malformed, so a bad configuration fails at startup.
13
+ */
14
+ export function clientIpReader(options) {
15
+ const rule = parseRule(options.trustProxy);
16
+ const trusted = (options.trustedProxies ?? []).map(parsePrefix);
17
+ const isTrusted = (a) => trusted.some(p => contains(p, a));
18
+ return (h, peer) => {
19
+ const socket = peer ? parseIp(peer.address) : undefined;
20
+ const fallback = socket ? peer.address.trim() : undefined;
21
+ if (!rule)
22
+ return fallback;
23
+ if (peer && (!socket || !isTrusted(socket.addr)))
24
+ return fallback;
25
+ if (rule.header === 'x-real-ip')
26
+ return ipOrUndefined(h.get('x-real-ip')) ?? fallback;
27
+ return forwardedFor(h.get('x-forwarded-for'), rule.hops, trusted.length ? isTrusted : undefined) ?? fallback;
28
+ };
29
+ }
30
+ // forwardedFor walks X-Forwarded-For from the right for up to hops
31
+ // entries, as authhttp's forwardedFor does: it stops at an entry it can't
32
+ // parse, and, when trusted proxies are set, at the first entry outside
33
+ // them. It returns the last entry it read.
34
+ function forwardedFor(xff, hops, isTrusted) {
35
+ if (xff === null)
36
+ return undefined;
37
+ const entries = xff.split(',').map(s => s.trim());
38
+ let out;
39
+ for (let i = 0; i < hops && i < entries.length; i++) {
40
+ const hop = parseIp(entries[entries.length - 1 - i]);
41
+ if (!hop)
42
+ return out;
43
+ out = hop.text;
44
+ if (isTrusted && !isTrusted(hop.addr))
45
+ return out;
46
+ }
47
+ return out;
48
+ }
49
+ function parseRule(t) {
50
+ if (t === undefined || t === false)
51
+ return undefined;
52
+ if (t === true)
53
+ return { header: 'x-forwarded-for', hops: 1 };
54
+ if (typeof t === 'number')
55
+ return { header: 'x-forwarded-for', hops: hopsOf(t) };
56
+ if (t.header === 'x-real-ip')
57
+ return { header: 'x-real-ip' };
58
+ if (t.header === 'x-forwarded-for')
59
+ return { header: 'x-forwarded-for', hops: hopsOf(t.hops) };
60
+ throw new TypeError(`trustProxy: unknown header ${JSON.stringify(t.header)}`);
61
+ }
62
+ function hopsOf(n) {
63
+ if (!Number.isInteger(n) || n < 1)
64
+ throw new TypeError(`trustProxy: hops must be a positive integer, got ${n}`);
65
+ return n;
66
+ }
67
+ /** Returns `s` when it is an IPv4 or IPv6 address, and `undefined` otherwise. */
68
+ export function ipOrUndefined(s) {
69
+ return parseIp(s)?.text;
70
+ }
71
+ function parseIp(s) {
72
+ if (!s)
73
+ return undefined;
74
+ let text = s.trim();
75
+ if (text.startsWith('[') && text.endsWith(']'))
76
+ text = text.slice(1, -1);
77
+ const addr = text.includes(':') ? parse6(text) : parse4(text);
78
+ return addr ? { text, addr: unmap(addr) } : undefined;
79
+ }
80
+ function parse4(s) {
81
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(s);
82
+ if (!m)
83
+ return undefined;
84
+ let n = 0n;
85
+ for (const part of m.slice(1)) {
86
+ const v = Number(part);
87
+ if (v > 255)
88
+ return undefined;
89
+ n = (n << 8n) | BigInt(v);
90
+ }
91
+ return { v6: false, n };
92
+ }
93
+ function parse6(s) {
94
+ if (s.length > 45 || !/^[0-9a-f:.]+$/i.test(s))
95
+ return undefined;
96
+ const halves = s.split('::');
97
+ if (halves.length > 2)
98
+ return undefined;
99
+ const groups = (part) => {
100
+ if (part === '')
101
+ return [];
102
+ const out = [];
103
+ const parts = part.split(':');
104
+ for (let i = 0; i < parts.length; i++) {
105
+ const p = parts[i];
106
+ if (i === parts.length - 1 && p.includes('.')) {
107
+ const v4 = parse4(p);
108
+ if (!v4)
109
+ return undefined;
110
+ out.push(v4.n >> 16n, v4.n & 0xffffn);
111
+ }
112
+ else if (/^[0-9a-f]{1,4}$/i.test(p)) {
113
+ out.push(BigInt(parseInt(p, 16)));
114
+ }
115
+ else {
116
+ return undefined;
117
+ }
118
+ }
119
+ return out;
120
+ };
121
+ const head = groups(halves[0]);
122
+ const tail = halves.length === 2 ? groups(halves[1]) : [];
123
+ if (!head || !tail)
124
+ return undefined;
125
+ const missing = 8 - head.length - tail.length;
126
+ if (halves.length === 2 ? missing < 1 : missing !== 0)
127
+ return undefined;
128
+ let n = 0n;
129
+ for (const g of [...head, ...Array(missing).fill(0n), ...tail])
130
+ n = (n << 16n) | g;
131
+ return { v6: true, n };
132
+ }
133
+ // unmap turns an IPv4-mapped IPv6 address, ::ffff:a.b.c.d, into IPv4.
134
+ function unmap(a) {
135
+ return a.v6 && a.n >> 32n === 0xffffn ? { v6: false, n: a.n & 0xffffffffn } : a;
136
+ }
137
+ function parsePrefix(cidr) {
138
+ const [ip, bits, extra] = cidr.split('/');
139
+ const a = parseIp(ip)?.addr;
140
+ const max = a?.v6 ? 128 : 32;
141
+ const b = bits === undefined ? max : /^\d{1,3}$/.test(bits) ? Number(bits) : NaN;
142
+ if (!a || extra !== undefined || !(b >= 0 && b <= max))
143
+ throw new TypeError(`trustedProxies: ${JSON.stringify(cidr)} is not a CIDR`);
144
+ return { ...a, bits: b };
145
+ }
146
+ function contains(p, a) {
147
+ if (p.v6 !== a.v6)
148
+ return false;
149
+ const shift = BigInt((p.v6 ? 128 : 32) - p.bits);
150
+ return a.n >> shift === p.n >> shift;
151
+ }