oculon 0.1.5 → 0.1.7

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.
Files changed (58) hide show
  1. package/README.md +72 -4
  2. package/dist/cli/main.js +184 -0
  3. package/dist/core/calls.d.ts +63 -0
  4. package/dist/core/calls.js +120 -0
  5. package/dist/core/evm.d.ts +20 -0
  6. package/dist/core/evm.js +165 -0
  7. package/dist/core/http.d.ts +11 -0
  8. package/dist/core/http.js +113 -30
  9. package/dist/core/pdf.d.ts +51 -0
  10. package/dist/core/pdf.js +211 -0
  11. package/dist/core/quota.js +3 -0
  12. package/dist/core/verdict.d.ts +30 -0
  13. package/dist/core/verdict.js +164 -0
  14. package/dist/index.d.ts +38 -0
  15. package/dist/index.js +54 -0
  16. package/dist/mcp.d.ts +1 -0
  17. package/dist/mcp.js +159 -5
  18. package/dist/modules/address.d.ts +32 -0
  19. package/dist/modules/address.js +91 -0
  20. package/dist/modules/checks.d.ts +59 -0
  21. package/dist/modules/checks.js +134 -0
  22. package/dist/modules/doc.d.ts +61 -0
  23. package/dist/modules/doc.js +715 -0
  24. package/dist/modules/headers.d.ts +50 -0
  25. package/dist/modules/headers.js +108 -0
  26. package/dist/modules/honeypot.d.ts +36 -0
  27. package/dist/modules/honeypot.js +53 -0
  28. package/dist/modules/iban.d.ts +30 -0
  29. package/dist/modules/iban.js +82 -0
  30. package/dist/modules/lookalike.d.ts +34 -0
  31. package/dist/modules/lookalike.js +122 -0
  32. package/dist/modules/personal.d.ts +1 -1
  33. package/dist/modules/personal.js +14 -4
  34. package/dist/modules/utility.d.ts +147 -0
  35. package/dist/modules/utility.js +403 -0
  36. package/dist/report-pdf.d.ts +7 -0
  37. package/dist/report-pdf.js +81 -0
  38. package/dist/telegram.d.ts +2 -0
  39. package/dist/telegram.js +43 -6
  40. package/dist/web/assets/logo-200.png +0 -0
  41. package/dist/web/burns.d.ts +21 -0
  42. package/dist/web/burns.js +53 -0
  43. package/dist/web/card.d.ts +28 -0
  44. package/dist/web/card.js +75 -0
  45. package/dist/web/index.html +76 -4
  46. package/dist/web/landing.html +1 -1
  47. package/dist/web/legal.html +1 -1
  48. package/dist/web/mcp.html +1 -1
  49. package/dist/web/openapi.js +6 -0
  50. package/dist/web/pages.d.ts +24 -0
  51. package/dist/web/pages.js +139 -0
  52. package/dist/web/public.js +7 -1
  53. package/dist/web/server.d.ts +17 -0
  54. package/dist/web/server.js +207 -7
  55. package/dist/web/token.html +98 -0
  56. package/dist/web/token.json +9 -0
  57. package/dist/web/utility.html +251 -0
  58. package/package.json +1 -1
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Minimal EVM cryptography with no dependencies: keccak256 and secp256k1 public-key recovery, enough to
3
+ * check an Ethereum "personal_sign" signature (Sign-In with Ethereum) and turn it into the signer's address.
4
+ * Plain BigInt arithmetic: slow next to native code, but a sign-in needs one recovery.
5
+ */
6
+ const M64 = (1n << 64n) - 1n;
7
+ const RC = [
8
+ 0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n, 0x000000000000808bn, 0x0000000080000001n,
9
+ 0x8000000080008081n, 0x8000000000008009n, 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
10
+ 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n, 0x8000000000008002n, 0x8000000000000080n,
11
+ 0x000000000000800an, 0x800000008000000an, 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n,
12
+ ];
13
+ // Rotation offsets r[x][y] of the Keccak specification.
14
+ const ROT = [[0, 36, 3, 41, 18], [1, 44, 10, 45, 2], [62, 6, 43, 15, 61], [28, 55, 25, 21, 56], [27, 20, 39, 8, 14]];
15
+ const rotl = (v, n) => (n === 0 ? v : ((v << BigInt(n)) | (v >> BigInt(64 - n))) & M64);
16
+ function keccakF(A) {
17
+ const C = new Array(5), B = new Array(25);
18
+ for (let round = 0; round < 24; round++) {
19
+ for (let x = 0; x < 5; x++)
20
+ C[x] = A[x] ^ A[x + 5] ^ A[x + 10] ^ A[x + 15] ^ A[x + 20];
21
+ for (let x = 0; x < 5; x++) {
22
+ const d = C[(x + 4) % 5] ^ rotl(C[(x + 1) % 5], 1);
23
+ for (let y = 0; y < 25; y += 5)
24
+ A[x + y] = A[x + y] ^ d;
25
+ }
26
+ for (let x = 0; x < 5; x++)
27
+ for (let y = 0; y < 5; y++)
28
+ B[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(A[x + 5 * y], ROT[x][y]);
29
+ for (let x = 0; x < 5; x++)
30
+ for (let y = 0; y < 25; y += 5)
31
+ A[x + y] = (B[x + y] ^ (~B[((x + 1) % 5) + y] & M64 & B[((x + 2) % 5) + y])) & M64;
32
+ A[0] = A[0] ^ RC[round];
33
+ }
34
+ }
35
+ /** Keccak-256 as used by Ethereum (original Keccak padding, not NIST SHA3-256). */
36
+ export function keccak256(data) {
37
+ const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;
38
+ const rate = 136;
39
+ const padded = new Uint8Array(Math.ceil((bytes.length + 1) / rate) * rate);
40
+ padded.set(bytes);
41
+ padded[bytes.length] = padded[bytes.length] ^ 0x01;
42
+ padded[padded.length - 1] = padded[padded.length - 1] ^ 0x80;
43
+ const A = new Array(25).fill(0n);
44
+ for (let off = 0; off < padded.length; off += rate) {
45
+ for (let i = 0; i < rate / 8; i++) {
46
+ let lane = 0n;
47
+ for (let b = 7; b >= 0; b--)
48
+ lane = (lane << 8n) | BigInt(padded[off + i * 8 + b]);
49
+ A[i] = A[i] ^ lane;
50
+ }
51
+ keccakF(A);
52
+ }
53
+ const out = new Uint8Array(32);
54
+ for (let i = 0; i < 4; i++)
55
+ for (let b = 0; b < 8; b++)
56
+ out[i * 8 + b] = Number((A[i] >> BigInt(8 * b)) & 0xffn);
57
+ return out;
58
+ }
59
+ export const toHex = (b) => [...b].map((x) => x.toString(16).padStart(2, '0')).join('');
60
+ export const fromHex = (h) => { const s = h.replace(/^0x/, ''); if (s.length % 2 || /[^0-9a-f]/i.test(s))
61
+ throw new Error('not hex'); return Uint8Array.from(s.match(/../g) ?? [], (x) => parseInt(x, 16)); };
62
+ // secp256k1
63
+ const P = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;
64
+ const N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
65
+ const GX = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n;
66
+ const GY = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;
67
+ const mod = (a, m) => { const r = a % m; return r < 0n ? r + m : r; };
68
+ function pow(b, e, m) { let r = 1n; b = mod(b, m); while (e > 0n) {
69
+ if (e & 1n)
70
+ r = (r * b) % m;
71
+ b = (b * b) % m;
72
+ e >>= 1n;
73
+ } return r; }
74
+ const inv = (a, m) => pow(a, m - 2n, m);
75
+ function add(p, q) {
76
+ if (!p)
77
+ return q;
78
+ if (!q)
79
+ return p;
80
+ if (p[0] === q[0] && mod(p[1] + q[1], P) === 0n)
81
+ return null;
82
+ const l = p[0] === q[0] && p[1] === q[1] ? mod(3n * p[0] * p[0] * inv(2n * p[1], P), P) : mod((q[1] - p[1]) * inv(mod(q[0] - p[0], P), P), P);
83
+ const x = mod(l * l - p[0] - q[0], P);
84
+ return [x, mod(l * (p[0] - x) - p[1], P)];
85
+ }
86
+ function mul(p, k) { let r = null, q = p; k = mod(k, N); while (k > 0n) {
87
+ if (k & 1n)
88
+ r = add(r, q);
89
+ q = add(q, q);
90
+ k >>= 1n;
91
+ } return r; }
92
+ /** Recover the uncompressed public key (64 bytes, x||y) from a message hash and an (r, s, recovery id) signature. */
93
+ export function recoverPublicKey(hash, r, s, recId) {
94
+ if (r <= 0n || r >= N || s <= 0n || s >= N || recId < 0 || recId > 3)
95
+ return null;
96
+ const x = recId >= 2 ? r + N : r;
97
+ if (x >= P)
98
+ return null;
99
+ const y2 = mod(x * x * x + 7n, P);
100
+ let y = pow(y2, (P + 1n) / 4n, P);
101
+ if (mod(y * y, P) !== y2)
102
+ return null;
103
+ if ((y & 1n) !== BigInt(recId & 1))
104
+ y = P - y;
105
+ const e = BigInt('0x' + toHex(hash)) % N;
106
+ const rInv = inv(r, N);
107
+ const Q = add(mul([x, y], mod(s * rInv, N)), mul([GX, GY], mod(-e * rInv, N)));
108
+ if (!Q)
109
+ return null;
110
+ const out = new Uint8Array(64);
111
+ out.set(fromHex(Q[0].toString(16).padStart(64, '0')), 0);
112
+ out.set(fromHex(Q[1].toString(16).padStart(64, '0')), 32);
113
+ return out;
114
+ }
115
+ export const addressOf = (pub64) => '0x' + toHex(keccak256(pub64).slice(12));
116
+ /** The address of a private key (used by tests to build signatures). */
117
+ export function addressFromPrivateKey(priv) {
118
+ const Q = mul([GX, GY], priv);
119
+ const pub = new Uint8Array(64);
120
+ pub.set(fromHex(Q[0].toString(16).padStart(64, '0')), 0);
121
+ pub.set(fromHex(Q[1].toString(16).padStart(64, '0')), 32);
122
+ return addressOf(pub);
123
+ }
124
+ /** A 65-byte Ethereum signature (r, s, v) over a 32-byte hash, low-s. `k` must be a fresh random nonce. Tests use it; Oculon never holds keys. */
125
+ export function signHash(hash, priv, k) {
126
+ const R = mul([GX, GY], k);
127
+ const r = mod(R[0], N);
128
+ const e = BigInt('0x' + toHex(hash)) % N;
129
+ let s = mod(inv(k, N) * (e + r * priv), N);
130
+ let recId = Number(R[1] & 1n) | (R[0] >= N ? 2 : 0);
131
+ if (s > N / 2n) {
132
+ s = N - s;
133
+ recId ^= 1;
134
+ }
135
+ return '0x' + r.toString(16).padStart(64, '0') + s.toString(16).padStart(64, '0') + (27 + recId).toString(16).padStart(2, '0');
136
+ }
137
+ /** The hash Ethereum wallets sign for personal_sign: keccak256("\x19Ethereum Signed Message:\n" + length + message). */
138
+ export function personalHash(message) {
139
+ const msg = new TextEncoder().encode(message);
140
+ const prefix = new TextEncoder().encode(`\x19Ethereum Signed Message:\n${msg.length}`);
141
+ const all = new Uint8Array(prefix.length + msg.length);
142
+ all.set(prefix);
143
+ all.set(msg, prefix.length);
144
+ return keccak256(all);
145
+ }
146
+ /** The lower-case address that signed a personal_sign message, or null if the signature is malformed. */
147
+ export function recoverPersonalSigner(message, signature) {
148
+ let sig;
149
+ try {
150
+ sig = fromHex(signature);
151
+ }
152
+ catch {
153
+ return null;
154
+ }
155
+ if (sig.length !== 65)
156
+ return null;
157
+ const r = BigInt('0x' + toHex(sig.slice(0, 32))), s = BigInt('0x' + toHex(sig.slice(32, 64)));
158
+ let v = sig[64];
159
+ if (v >= 27)
160
+ v -= 27;
161
+ if (s > N / 2n)
162
+ return null; // wallets produce low-s signatures; reject malleated ones
163
+ const pub = recoverPublicKey(personalHash(message), r, s, v);
164
+ return pub ? addressOf(pub) : null;
165
+ }
@@ -18,6 +18,8 @@ export interface HttpConfig {
18
18
  fetch?: typeof fetch;
19
19
  throttle?: boolean;
20
20
  retryDelayMs?: number;
21
+ /** Skip a host for a few minutes after it fails several times in a row (default on). */
22
+ breaker?: boolean;
21
23
  }
22
24
  export declare class Http {
23
25
  private readonly store;
@@ -31,6 +33,7 @@ export declare class Http {
31
33
  timeoutMs?: number;
32
34
  retries?: number;
33
35
  }): Promise<Sourced<Buffer>>;
36
+ private postBytesRaw;
34
37
  /** Uncached binary GET; 404 is reported as UNAVAILABLE. Network errors and 5xx are retried once. */
35
38
  getBytes(url: string, o: {
36
39
  source: string;
@@ -38,5 +41,13 @@ export declare class Http {
38
41
  timeoutMs?: number;
39
42
  retries?: number;
40
43
  }): Promise<Sourced<Buffer>>;
44
+ private getBytesRaw;
45
+ /** Record a finished call: the running check's replay log, and (for live calls) the /status stats. */
46
+ private note;
47
+ /**
48
+ * One live request with retries. `hostDown` is true when the failure says the host is unhealthy (network error,
49
+ * timeout, 5xx, 429), which feeds the breaker; a 4xx answer means the host is up.
50
+ */
51
+ private live;
41
52
  get<T = unknown>(url: string, o: GetOptions): Promise<Sourced<T>>;
42
53
  }
package/dist/core/http.js CHANGED
@@ -1,8 +1,12 @@
1
+ import { breakerOpenUntil, breakerResult, logCall, MIRRORS, recordSourceCall } from './calls.js';
1
2
  import { scrubSecrets } from './keys.js';
2
3
  import { takeQuota } from './quota.js';
3
4
  /** Minimum gap between requests per host, following each provider's published guidance. */
4
5
  const HOST_GAP_MS = {
5
6
  'crt.sh': 2000,
7
+ 'api.honeypot.is': 600,
8
+ 'mempool.space': 300,
9
+ 'api.mainnet-beta.solana.com': 300,
6
10
  'api.gdeltproject.org': 5500,
7
11
  'export.arxiv.org': 3100,
8
12
  'api.github.com': 1500,
@@ -127,6 +131,12 @@ export class Http {
127
131
  }
128
132
  /** Uncached binary POST (used for timestamp calendars). Returns the raw response bytes. */
129
133
  async postBytes(url, body, o) {
134
+ const t0 = Date.now();
135
+ const r = await this.postBytesRaw(url, body, o);
136
+ this.note(o.source, url, r.prov.status, Date.now() - t0, r.prov.note, undefined, r.prov.note !== 'daily quota reached');
137
+ return r;
138
+ }
139
+ async postBytesRaw(url, body, o) {
130
140
  if (!takeQuota(this.store, o.source))
131
141
  return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'daily quota reached') };
132
142
  const doFetch = this.cfg.fetch ?? fetch;
@@ -158,6 +168,12 @@ export class Http {
158
168
  }
159
169
  /** Uncached binary GET; 404 is reported as UNAVAILABLE. Network errors and 5xx are retried once. */
160
170
  async getBytes(url, o) {
171
+ const t0 = Date.now();
172
+ const r = await this.getBytesRaw(url, o);
173
+ this.note(o.source, url, r.prov.status, Date.now() - t0, r.prov.note);
174
+ return r;
175
+ }
176
+ async getBytesRaw(url, o) {
161
177
  const doFetch = this.cfg.fetch ?? fetch;
162
178
  const retries = o.retries ?? 1;
163
179
  let lastErr = 'unknown error';
@@ -182,41 +198,40 @@ export class Http {
182
198
  }
183
199
  return { data: null, prov: prov(o.source, url, 'ERROR', Date.now(), lastErr) };
184
200
  }
185
- async get(url, o) {
186
- const as = o.as ?? 'json';
187
- const ttl = (o.ttlSec ?? 900) * 1000;
188
- const retries = o.retries ?? 2;
189
- const cached = this.store.cacheGet(url);
190
- const now = Date.now();
191
- if (cached && now - cached.fetchedAt < ttl) {
192
- return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt) };
193
- }
194
- if (!takeQuota(this.store, o.source)) {
195
- if (cached)
196
- return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt, 'daily quota reached; showing last cached result') };
197
- return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'daily quota reached') };
201
+ /** Record a finished call: the running check's replay log, and (for live calls) the /status stats. */
202
+ note(source, url, status, ms, note, via, live = true) {
203
+ let host = '';
204
+ try {
205
+ host = new URL(url).host;
198
206
  }
207
+ catch { }
208
+ logCall({ source, host, status, ms: Math.round(ms), at: new Date().toISOString(), ...(note ? { note: scrubSecrets(note).slice(0, 200) } : {}), ...(via ? { via } : {}) });
209
+ if (live)
210
+ recordSourceCall(this.store, source, via ?? host, status === 'LIVE' || (status === 'UNAVAILABLE' && note === 'HTTP 404'), ms, note ? scrubSecrets(note) : undefined);
211
+ }
212
+ /**
213
+ * One live request with retries. `hostDown` is true when the failure says the host is unhealthy (network error,
214
+ * timeout, 5xx, 429), which feeds the breaker; a 4xx answer means the host is up.
215
+ */
216
+ async live(url, o, as, retries, extraHeaders = {}) {
199
217
  const doFetch = this.cfg.fetch ?? fetch;
200
218
  const host = new URL(url).host;
201
219
  const baseDelay = this.cfg.retryDelayMs ?? 1500;
202
220
  let lastErr = 'unknown error';
221
+ let hostDown = false;
203
222
  for (let attempt = 0; attempt <= retries; attempt++) {
204
223
  if (this.cfg.throttle !== false)
205
224
  await throttle(host);
206
225
  try {
207
226
  const res = await doFetch(url, {
208
- headers: {
209
- 'user-agent': userAgent(url),
210
- accept: as === 'json' ? 'application/json' : '*/*',
211
- ...o.headers,
212
- },
227
+ headers: { 'user-agent': userAgent(url), accept: as === 'json' ? 'application/json' : '*/*', ...o.headers, ...extraHeaders },
213
228
  signal: AbortSignal.timeout(o.timeoutMs ?? 20_000),
214
229
  });
215
- if (res.status === 404) {
216
- return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'HTTP 404') };
217
- }
230
+ if (res.status === 404)
231
+ return { ok: false, notFound: true, err: 'HTTP 404', hostDown: false };
218
232
  if (res.status === 429 || res.status >= 500) {
219
233
  lastErr = `HTTP ${res.status}`;
234
+ hostDown = true;
220
235
  const retryAfter = Number(res.headers.get('retry-after'));
221
236
  const wait = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, 30_000) : baseDelay * 2 ** attempt;
222
237
  if (attempt < retries)
@@ -226,6 +241,7 @@ export class Http {
226
241
  if (!res.ok) {
227
242
  const text = await res.text().catch(() => '');
228
243
  lastErr = `HTTP ${res.status}${errorReason(text)}`;
244
+ hostDown = false;
229
245
  // GitHub signals (secondary) rate limits with 403.
230
246
  if (res.status === 403 && (res.headers.get('x-ratelimit-remaining') === '0' || /rate limit/i.test(text))) {
231
247
  lastErr = 'HTTP 403 rate limited';
@@ -238,27 +254,94 @@ export class Http {
238
254
  const body = await res.text();
239
255
  if (o.rateLimitText?.test(body.slice(0, 300))) {
240
256
  lastErr = 'rate limited';
257
+ hostDown = false;
241
258
  if (attempt < retries)
242
259
  await sleep(Math.max(baseDelay, 6000) * 2 ** attempt);
243
260
  continue;
244
261
  }
245
- let data = this.parse(body, as);
246
- let stored = body;
247
- if (o.keep && as === 'json' && data != null) {
248
- data = o.keep(data);
249
- stored = JSON.stringify(data);
250
- }
251
- this.store.cachePut(url, stored);
252
- return { data, prov: prov(o.source, url, 'LIVE', Date.now()) };
262
+ this.parse(body, as); // throws ParseError on a broken body
263
+ return { ok: true, body };
253
264
  }
254
265
  catch (e) {
255
266
  lastErr = errMsg(e);
256
- if (e instanceof ParseError)
267
+ if (e instanceof ParseError) {
268
+ hostDown = false;
257
269
  break;
270
+ }
271
+ hostDown = true;
258
272
  if (attempt < retries)
259
273
  await sleep(baseDelay * 2 ** attempt);
260
274
  }
261
275
  }
276
+ return { ok: false, notFound: false, err: lastErr, hostDown };
277
+ }
278
+ async get(url, o) {
279
+ const as = o.as ?? 'json';
280
+ const ttl = (o.ttlSec ?? 900) * 1000;
281
+ const retries = o.retries ?? 2;
282
+ const cached = this.store.cacheGet(url);
283
+ const now = Date.now();
284
+ if (cached && now - cached.fetchedAt < ttl) {
285
+ this.note(o.source, url, 'CACHED', 0, undefined, undefined, false);
286
+ return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt) };
287
+ }
288
+ if (!takeQuota(this.store, o.source)) {
289
+ this.note(o.source, url, cached ? 'CACHED' : 'UNAVAILABLE', 0, 'daily quota reached', undefined, false);
290
+ if (cached)
291
+ return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt, 'daily quota reached; showing last cached result') };
292
+ return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'daily quota reached') };
293
+ }
294
+ const host = new URL(url).host;
295
+ const useBreaker = this.cfg.breaker !== false;
296
+ const keep = (body) => {
297
+ let data = this.parse(body, as);
298
+ let stored = body;
299
+ if (o.keep && as === 'json' && data != null) {
300
+ data = o.keep(data);
301
+ stored = JSON.stringify(data);
302
+ }
303
+ return { data, stored };
304
+ };
305
+ let lastErr;
306
+ const skipped = useBreaker ? breakerOpenUntil(host) : null;
307
+ if (skipped) {
308
+ lastErr = `skipped: ${host} kept failing, retrying it after ${new Date(skipped).toISOString().slice(11, 16)} UTC`;
309
+ }
310
+ else {
311
+ const t0 = Date.now();
312
+ const r = await this.live(url, o, as, retries);
313
+ if (useBreaker)
314
+ breakerResult(host, r.ok || !r.hostDown);
315
+ if (r.ok) {
316
+ const { data, stored } = keep(r.body);
317
+ this.store.cachePut(url, stored);
318
+ this.note(o.source, url, 'LIVE', Date.now() - t0);
319
+ return { data, prov: prov(o.source, url, 'LIVE', Date.now()) };
320
+ }
321
+ if (r.notFound) {
322
+ this.note(o.source, url, 'UNAVAILABLE', Date.now() - t0, 'HTTP 404');
323
+ return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'HTTP 404') };
324
+ }
325
+ lastErr = r.err;
326
+ this.note(o.source, url, 'ERROR', Date.now() - t0, r.err);
327
+ }
328
+ // Auto fallback: the same request on a mirror host, when there is one.
329
+ const mirror = MIRRORS[host];
330
+ const alt = mirror?.rewrite(new URL(url));
331
+ if (mirror && alt && !(useBreaker && breakerOpenUntil(mirror.host))) {
332
+ const t0 = Date.now();
333
+ const r = await this.live(alt.url, o, as, 1, alt.headers);
334
+ if (useBreaker)
335
+ breakerResult(mirror.host, r.ok || !r.hostDown);
336
+ if (r.ok) {
337
+ const { data, stored } = keep(r.body);
338
+ this.store.cachePut(url, stored);
339
+ const why = `${host} failed (${lastErr}); answered by ${mirror.host}`;
340
+ this.note(o.source, alt.url, 'LIVE', Date.now() - t0, why, mirror.host);
341
+ return { data, prov: prov(o.source, url, 'LIVE', Date.now(), why) };
342
+ }
343
+ this.note(o.source, alt.url, 'ERROR', Date.now() - t0, r.err, mirror.host);
344
+ }
262
345
  if (cached) {
263
346
  return {
264
347
  data: this.parse(cached.body, as),
@@ -0,0 +1,51 @@
1
+ /**
2
+ * A small PDF writer for reports, no dependencies: A4 pages, the standard Helvetica and Courier fonts
3
+ * (WinAnsi), headings, paragraphs with word wrap, bullet lists, key-value rows, coloured verdict bars and links.
4
+ * Characters outside WinAnsi are replaced, so any input gives a valid file.
5
+ */
6
+ type RGB = [number, number, number];
7
+ export type Block = {
8
+ t: 'title';
9
+ text: string;
10
+ } | {
11
+ t: 'h';
12
+ text: string;
13
+ } | {
14
+ t: 'p';
15
+ text: string;
16
+ size?: number;
17
+ color?: RGB;
18
+ } | {
19
+ t: 'mono';
20
+ text: string;
21
+ } | {
22
+ t: 'bullets';
23
+ items: string[];
24
+ color?: RGB;
25
+ } | {
26
+ t: 'kv';
27
+ rows: [string, string][];
28
+ } | {
29
+ t: 'bar';
30
+ label: string;
31
+ text: string;
32
+ color: RGB;
33
+ } | {
34
+ t: 'link';
35
+ text: string;
36
+ url: string;
37
+ } | {
38
+ t: 'table';
39
+ head: string[];
40
+ rows: string[][];
41
+ widths: number[];
42
+ } | {
43
+ t: 'gap';
44
+ h?: number;
45
+ };
46
+ /** WinAnsi-safe text: common punctuation mapped, anything else outside Latin-1 becomes '?'. */
47
+ export declare function ansi(s: string): string;
48
+ /** Render blocks to a PDF file. `footer` is printed on every page. */
49
+ export declare function renderPdf(blocks: Block[], footer: string): Buffer;
50
+ export declare const TONE_RGB: Record<string, RGB>;
51
+ export {};
@@ -0,0 +1,211 @@
1
+ /**
2
+ * A small PDF writer for reports, no dependencies: A4 pages, the standard Helvetica and Courier fonts
3
+ * (WinAnsi), headings, paragraphs with word wrap, bullet lists, key-value rows, coloured verdict bars and links.
4
+ * Characters outside WinAnsi are replaced, so any input gives a valid file.
5
+ */
6
+ const W = 595, H = 842, M = 50, CW = W - 2 * M;
7
+ const INK = [0.08, 0.1, 0.11], MUTE = [0.42, 0.47, 0.49], ACCENT = [0, 0.48, 0.53];
8
+ // Helvetica widths (per 1000 em) for ASCII 32-126; other characters use 556.
9
+ const HELV = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584];
10
+ const BOLD_EXTRA = 1.06;
11
+ function width(s, size, font) {
12
+ if (font === 'F3')
13
+ return s.length * 600 * size / 1000;
14
+ let w = 0;
15
+ for (const ch of s) {
16
+ const c = ch.charCodeAt(0);
17
+ w += c >= 32 && c <= 126 ? HELV[c - 32] : 556;
18
+ }
19
+ return (w * size / 1000) * (font === 'F2' ? BOLD_EXTRA : 1);
20
+ }
21
+ /** WinAnsi-safe text: common punctuation mapped, anything else outside Latin-1 becomes '?'. */
22
+ export function ansi(s) {
23
+ return s
24
+ .replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/[–—]/g, '-').replace(/…/g, '...').replace(/→/g, '->').replace(/•/g, '-')
25
+ .replace(/[\r\t]/g, ' ')
26
+ .replace(/[^\n\x20-\x7e\xa0-\xff]/g, '?');
27
+ }
28
+ const esc = (s) => s.replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
29
+ function wrap(text, size, font, max) {
30
+ const out = [];
31
+ for (const para of ansi(text).split('\n')) {
32
+ let line = '';
33
+ for (const word of para.split(/ +/)) {
34
+ const tryLine = line ? `${line} ${word}` : word;
35
+ if (width(tryLine, size, font) <= max) {
36
+ line = tryLine;
37
+ continue;
38
+ }
39
+ if (line)
40
+ out.push(line);
41
+ // A single word wider than the line (a hash, a URL) is cut into pieces.
42
+ let w = word;
43
+ while (width(w, size, font) > max) {
44
+ let n = w.length;
45
+ while (n > 1 && width(w.slice(0, n), size, font) > max)
46
+ n--;
47
+ out.push(w.slice(0, n));
48
+ w = w.slice(n);
49
+ }
50
+ line = w;
51
+ }
52
+ out.push(line);
53
+ }
54
+ return out;
55
+ }
56
+ class Doc {
57
+ footer;
58
+ pages = [];
59
+ links = [];
60
+ y = 0;
61
+ constructor(footer) {
62
+ this.footer = footer;
63
+ this.page();
64
+ }
65
+ get ops() { return this.pages[this.pages.length - 1]; }
66
+ page() {
67
+ this.pages.push([]);
68
+ this.links.push([]);
69
+ this.y = H - M;
70
+ }
71
+ need(h) { if (this.y - h < M + 24)
72
+ this.page(); }
73
+ text(x, y, s, size, font, color = INK) {
74
+ this.ops.push(`BT /${font} ${size} Tf ${color.map((c) => c.toFixed(3)).join(' ')} rg ${x.toFixed(1)} ${y.toFixed(1)} Td (${esc(s)}) Tj ET`);
75
+ }
76
+ rect(x, y, w, h, color) {
77
+ this.ops.push(`${color.map((c) => c.toFixed(3)).join(' ')} rg ${x.toFixed(1)} ${y.toFixed(1)} ${w.toFixed(1)} ${h.toFixed(1)} re f`);
78
+ }
79
+ line(y, color = [0.85, 0.87, 0.88]) {
80
+ this.ops.push(`${color.map((c) => c.toFixed(3)).join(' ')} RG 0.8 w ${M} ${y.toFixed(1)} m ${W - M} ${y.toFixed(1)} l S`);
81
+ }
82
+ para(s, size, font, color = INK, indent = 0, lead = 1.45) {
83
+ for (const l of wrap(s, size, font, CW - indent)) {
84
+ this.need(size * lead);
85
+ this.y -= size * lead;
86
+ this.text(M + indent, this.y, l, size, font, color);
87
+ }
88
+ }
89
+ build() {
90
+ const objs = [];
91
+ const add = (s) => { objs.push(s); return objs.length; };
92
+ add('<< /Type /Catalog /Pages 2 0 R >>');
93
+ add('PAGES');
94
+ const f1 = add('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>');
95
+ const f2 = add('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>');
96
+ const f3 = add('<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>');
97
+ const kids = [];
98
+ this.pages.forEach((ops, i) => {
99
+ const foot = `BT /F1 8 Tf ${MUTE.join(' ')} rg ${M} 28 Td (${esc(ansi(this.footer))}) Tj ET BT /F1 8 Tf ${MUTE.join(' ')} rg ${W - M - 40} 28 Td (Page ${i + 1} of ${this.pages.length}) Tj ET`;
100
+ const content = [...ops, foot].join('\n');
101
+ const c = add(`<< /Length ${Buffer.byteLength(content, 'latin1')} >>\nstream\n${content}\nendstream`);
102
+ const annots = this.links[i].map((l) => add(`<< /Type /Annot /Subtype /Link /Rect [${l.rect.map((n) => n.toFixed(1)).join(' ')}] /Border [0 0 0] /A << /S /URI /URI (${esc(ansi(l.url))}) >> >>`));
103
+ kids.push(add(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${W} ${H}] /Resources << /Font << /F1 ${f1} 0 R /F2 ${f2} 0 R /F3 ${f3} 0 R >> >> /Contents ${c} 0 R${annots.length ? ` /Annots [${annots.map((a) => `${a} 0 R`).join(' ')}]` : ''} >>`));
104
+ });
105
+ objs[1] = `<< /Type /Pages /Kids [${kids.map((k) => `${k} 0 R`).join(' ')}] /Count ${kids.length} >>`;
106
+ add('<< /Producer (Oculon) /Title (Oculon report) >>');
107
+ return Buffer.from(rebuild(objs), 'latin1');
108
+ }
109
+ }
110
+ function rebuild(objs) {
111
+ let out = '%PDF-1.4\n%\xe2\xe3\xcf\xd3\n';
112
+ const offsets = [];
113
+ objs.forEach((o, i) => {
114
+ offsets.push(Buffer.byteLength(out, 'latin1'));
115
+ out += `${i + 1} 0 obj\n${o}\nendobj\n`;
116
+ });
117
+ const xref = Buffer.byteLength(out, 'latin1');
118
+ out += `xref\n0 ${objs.length + 1}\n0000000000 65535 f \n${offsets.map((o) => `${String(o).padStart(10, '0')} 00000 n \n`).join('')}`;
119
+ out += `trailer\n<< /Size ${objs.length + 1} /Root 1 0 R /Info ${objs.length} 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
120
+ return out;
121
+ }
122
+ /** Render blocks to a PDF file. `footer` is printed on every page. */
123
+ export function renderPdf(blocks, footer) {
124
+ const d = new Doc(footer);
125
+ for (const b of blocks) {
126
+ switch (b.t) {
127
+ case 'title':
128
+ d.text(M, d.y - 10, 'OCULON', 9, 'F2', ACCENT);
129
+ d.y -= 22;
130
+ d.para(b.text, 20, 'F2', INK, 0, 1.25);
131
+ d.y -= 8;
132
+ d.line(d.y);
133
+ d.y -= 6;
134
+ break;
135
+ case 'h':
136
+ d.need(40);
137
+ d.y -= 14;
138
+ d.para(b.text.toUpperCase(), 9.5, 'F2', ACCENT, 0, 1.6);
139
+ d.y -= 2;
140
+ break;
141
+ case 'p':
142
+ d.para(b.text, b.size ?? 10.5, 'F1', b.color ?? INK);
143
+ break;
144
+ case 'mono':
145
+ d.para(b.text, 8.5, 'F3', INK, 0, 1.4);
146
+ break;
147
+ case 'bullets':
148
+ for (const it of b.items) {
149
+ const lines = wrap(it, 10.5, 'F1', CW - 14);
150
+ lines.forEach((l, i) => {
151
+ d.need(15);
152
+ d.y -= 15;
153
+ if (i === 0)
154
+ d.text(M, d.y, '-', 10.5, 'F2', b.color ?? ACCENT);
155
+ d.text(M + 14, d.y, l, 10.5, 'F1');
156
+ });
157
+ }
158
+ break;
159
+ case 'kv':
160
+ for (const [k, v] of b.rows) {
161
+ const lines = wrap(v, 10, 'F1', CW - 150);
162
+ lines.forEach((l, i) => {
163
+ d.need(15);
164
+ d.y -= 15;
165
+ if (i === 0)
166
+ d.text(M, d.y, ansi(k), 9, 'F2', MUTE);
167
+ d.text(M + 150, d.y, l, 10, 'F1');
168
+ });
169
+ d.y -= 3;
170
+ }
171
+ break;
172
+ case 'bar': {
173
+ d.need(48);
174
+ d.y -= 42;
175
+ d.rect(M, d.y, CW, 36, b.color);
176
+ d.text(M + 14, d.y + 22, ansi(b.label), 8, 'F2', [1, 1, 1]);
177
+ d.text(M + 14, d.y + 8, ansi(b.text).slice(0, 70), 14, 'F2', [1, 1, 1]);
178
+ d.y -= 4;
179
+ break;
180
+ }
181
+ case 'link': {
182
+ d.need(15);
183
+ d.y -= 15;
184
+ const s = ansi(b.text);
185
+ d.text(M, d.y, s, 10, 'F1', ACCENT);
186
+ d.links[d.pages.length - 1].push({ page: d.pages.length - 1, rect: [M, d.y - 2, M + width(s, 10, 'F1'), d.y + 10], url: b.url });
187
+ break;
188
+ }
189
+ case 'table': {
190
+ const xs = b.widths.reduce((a, w, i) => [...a, (a[i - 1] ?? M) + (i ? b.widths[i - 1] : 0)], []).map((x, i) => (i === 0 ? M : x));
191
+ const row = (cells, font, color) => {
192
+ const wrapped = cells.map((c, i) => wrap(c, 8.5, font, b.widths[i] - 6));
193
+ const h = Math.max(...wrapped.map((w) => w.length)) * 11 + 4;
194
+ d.need(h);
195
+ wrapped.forEach((ls, i) => ls.forEach((l, j) => d.text(xs[i], d.y - 11 - j * 11, l, 8.5, font, color)));
196
+ d.y -= h;
197
+ d.line(d.y + 1);
198
+ };
199
+ row(b.head, 'F2', MUTE);
200
+ for (const r of b.rows)
201
+ row(r, 'F1', INK);
202
+ break;
203
+ }
204
+ case 'gap':
205
+ d.y -= b.h ?? 8;
206
+ break;
207
+ }
208
+ }
209
+ return d.build();
210
+ }
211
+ export const TONE_RGB = { bad: [0.78, 0.18, 0.24], warn: [0.79, 0.52, 0.06], ok: [0.1, 0.55, 0.35], info: [0.25, 0.32, 0.36] };