@adonis-agora/authkit-poppy 0.3.1-rc.2 → 0.3.1-rc.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @adonis-agora/authkit-poppy
2
2
 
3
+ ## 0.3.1-rc.3
4
+
5
+ ### Patch Changes
6
+
7
+ - [#489](https://github.com/DavideCarvalho/adonis-agora-authkit/pull/489) [`3c650b1`](https://github.com/DavideCarvalho/adonis-agora-authkit/commit/3c650b1fe176752ad68df7fc061fa8a6dc1a475a) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - The SSRF-safe fetch and the agent metadata/JWKS cache now come from `@adonis-agora/authkit-server`, which uses the same code for MCP Client ID Metadata Documents. Behaviour is unchanged. `isBlockedAddress`, `SafeFetchError` and `safeFetchJson` are still exported from this package.
8
+
3
9
  ## 0.3.1-rc.2
4
10
 
5
11
  ### Patch Changes
package/build/index.d.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  *
5
5
  * Experimental: this package stays on 0.x and follows the draft spec, so any minor may break.
6
6
  */
7
+ export { isBlockedAddress, SafeFetchError, safeFetchJson } from '@adonis-agora/authkit-server';
7
8
  export { configure, POPPY_CONFIG_SNIPPET } from './configure.js';
8
9
  export type { PoppyAgentProtocolEntry, PoppyApiEntry, PoppyBrowserLogin, PoppyClientsConfigInput, PoppyConfigInput, PoppyLimiter, PoppyMediatedConfigInput, PoppyMediatedField, PoppyMediatedResult, PoppyMediatedVerifyInput, PoppyPrincipalBase, PoppyReplayStore, PoppyScopeHint, PoppySignInType, ResolvedPoppyConfig, } from './src/config.js';
9
10
  export { AGORA_DEV_SCOPE } from './src/config.js';
@@ -15,7 +16,6 @@ export { POPPY_MESSAGES } from './src/messages.js';
15
16
  export { databaseReplayStore, memoryReplayStore, redisReplayStore, } from './src/replay.js';
16
17
  export { installPoppySlots, POPPY_AUTHENTICATE_SLOT, type PoppyAuthenticate, type PoppyAuthResult, type PoppyPrincipal, type PoppySlotRequest, poppyAuth, poppyOf, verifyPoppyRequest, writePoppyAuthError, } from './src/resource.js';
17
18
  export { POPPY_PROTOCOL_ID, poppyFor, poppyFromApp } from './src/runtime.js';
18
- export { isBlockedAddress, SafeFetchError, safeFetchJson, } from './src/safe_fetch.js';
19
19
  export type { PoppyAuthError, PoppyGrantSummary, PoppyScopeDescription, PoppyService, PoppySessionState, PoppyTokenResponse, PoppyVerifyOptions, } from './src/service.js';
20
20
  export { ensurePoppySchema, POPPY_TABLES } from './src/tables.js';
21
21
  export { isPoppyBrowser, POPPY_WEB_SESSION_KEY, type PoppyWebSessionMarker, poppyWebSession, poppyWebSessionOf, } from './src/web_session.js';
package/build/index.js CHANGED
@@ -4,6 +4,8 @@
4
4
  *
5
5
  * Experimental: this package stays on 0.x and follows the draft spec, so any minor may break.
6
6
  */
7
+ // A busca à prova de SSRF mora no `@adonis-agora/authkit-server` (Client ID Metadata Documents).
8
+ export { isBlockedAddress, SafeFetchError, safeFetchJson } from '@adonis-agora/authkit-server';
7
9
  export { configure, POPPY_CONFIG_SNIPPET } from './configure.js';
8
10
  export { AGORA_DEV_SCOPE } from './src/config.js';
9
11
  export { accessTokenHash, hmacNonceSource, verifyDpopProof, } from './src/dpop.js';
@@ -14,6 +16,5 @@ export { POPPY_MESSAGES } from './src/messages.js';
14
16
  export { databaseReplayStore, memoryReplayStore, redisReplayStore, } from './src/replay.js';
15
17
  export { installPoppySlots, POPPY_AUTHENTICATE_SLOT, poppyAuth, poppyOf, verifyPoppyRequest, writePoppyAuthError, } from './src/resource.js';
16
18
  export { POPPY_PROTOCOL_ID, poppyFor, poppyFromApp } from './src/runtime.js';
17
- export { isBlockedAddress, SafeFetchError, safeFetchJson, } from './src/safe_fetch.js';
18
19
  export { ensurePoppySchema, POPPY_TABLES } from './src/tables.js';
19
20
  export { isPoppyBrowser, POPPY_WEB_SESSION_KEY, poppyWebSession, poppyWebSessionOf, } from './src/web_session.js';
@@ -4,9 +4,9 @@
4
4
  * Document). Buscamos (à prova de SSRF), validamos, guardamos em cache e
5
5
  * importamos as chaves públicas do `jwks_uri`.
6
6
  */
7
+ import { type JsonFetcher } from '@adonis-agora/authkit-server';
7
8
  import { type JWTVerifyGetKey } from 'jose';
8
9
  import type { ResolvedPoppyConfig } from './config.js';
9
- import { type JsonFetcher } from './safe_fetch.js';
10
10
  export interface PoppyClient {
11
11
  clientId: string;
12
12
  /** `client_name`, ou o host do `client_id`. */
@@ -28,14 +28,15 @@ export declare function validateClientMetadata(fetchedFrom: string, doc: unknown
28
28
  allowHttp?: boolean;
29
29
  }): Omit<PoppyClient, 'keys'>;
30
30
  export interface PoppyClientRegistryOptions {
31
- /** Busca de JSON. Default: {@link safeFetchJson}. */
31
+ /** Busca de JSON. Default: `safeFetchJson` do `@adonis-agora/authkit-server`. */
32
32
  fetchJson?: JsonFetcher;
33
33
  now?: () => number;
34
34
  }
35
35
  /**
36
36
  * Resolve e valida agentes pelo `client_id`, com cache (respeita `max-age`,
37
37
  * entre 1 min e 24 h; falhas ficam 1 min em cache para que o mesmo `client_id`
38
- * não vire uma busca de saída por request).
38
+ * não vire uma busca de saída por request). A busca à prova de SSRF e o cache de
39
+ * documentos são os do `@adonis-agora/authkit-server` (Client ID Metadata Documents).
39
40
  */
40
41
  export declare class PoppyClientRegistry {
41
42
  #private;
@@ -4,16 +4,9 @@
4
4
  * Document). Buscamos (à prova de SSRF), validamos, guardamos em cache e
5
5
  * importamos as chaves públicas do `jwks_uri`.
6
6
  */
7
+ import { insecureDevFetchJson, isHttpsUrl, MetadataDocumentCache, safeFetchJson, } from '@adonis-agora/authkit-server';
7
8
  import { createLocalJWKSet } from 'jose';
8
9
  import { PoppyError } from './errors.js';
9
- import { insecureDevFetchJson, SafeFetchError, safeFetchJson, } from './safe_fetch.js';
10
- const MIN_TTL_MS = 60 * 1000;
11
- const MAX_TTL_MS = 24 * 3600 * 1000;
12
- const DEFAULT_TTL_MS = 3600 * 1000;
13
- const FAILURE_TTL_MS = 60 * 1000;
14
- const MAX_CACHED = 1000;
15
- /** Releitura do JWKS quando o `kid` não está no conjunto em cache — no máximo a cada 30 s. */
16
- const JWKS_REFRESH_COOLDOWN_MS = 30 * 1000;
17
10
  function hostOf(url) {
18
11
  try {
19
12
  return new URL(url).host.toLowerCase();
@@ -22,18 +15,6 @@ function hostOf(url) {
22
15
  return null;
23
16
  }
24
17
  }
25
- function isHttpsUrl(value, allowHttp = false) {
26
- if (typeof value !== 'string')
27
- return false;
28
- try {
29
- const url = new URL(value);
30
- const schemeOk = url.protocol === 'https:' || (allowHttp && url.protocol === 'http:');
31
- return schemeOk && !url.username && !url.password && !url.hash;
32
- }
33
- catch {
34
- return false;
35
- }
36
- }
37
18
  /** Loopback redirect URI (RFC 8252 §7.3): `http`, IP de loopback literal, sem fragmento. */
38
19
  function isLoopbackRedirect(value) {
39
20
  if (typeof value !== 'string')
@@ -66,17 +47,6 @@ export function redirectUriAllowed(registered, redirectUri) {
66
47
  };
67
48
  return registered.some((r) => isLoopbackRedirect(r) && withoutPort(r) === withoutPort(redirectUri));
68
49
  }
69
- function ttlFrom(maxAge) {
70
- if (maxAge === null)
71
- return DEFAULT_TTL_MS;
72
- return Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, maxAge * 1000));
73
- }
74
- function setBounded(map, key, value) {
75
- map.delete(key);
76
- map.set(key, value);
77
- if (map.size > MAX_CACHED)
78
- map.delete(map.keys().next().value);
79
- }
80
50
  /** Valida um documento de metadata e devolve os campos usados. Lança `invalid_client`. */
81
51
  export function validateClientMetadata(fetchedFrom, doc, options = {}) {
82
52
  const allowHttp = options.allowHttp === true;
@@ -137,22 +107,32 @@ function validateJwks(doc) {
137
107
  /**
138
108
  * Resolve e valida agentes pelo `client_id`, com cache (respeita `max-age`,
139
109
  * entre 1 min e 24 h; falhas ficam 1 min em cache para que o mesmo `client_id`
140
- * não vire uma busca de saída por request).
110
+ * não vire uma busca de saída por request). A busca à prova de SSRF e o cache de
111
+ * documentos são os do `@adonis-agora/authkit-server` (Client ID Metadata Documents).
141
112
  */
142
113
  export class PoppyClientRegistry {
143
114
  #cfg;
144
- #fetch;
145
- #now;
146
- #clients = new Map();
147
- #jwks = new Map();
115
+ #clients;
116
+ #jwks;
148
117
  constructor(cfg, options = {}) {
149
118
  this.#cfg = cfg;
150
- this.#fetch =
151
- options.fetchJson ??
152
- (cfg.allowInsecureClientIds
153
- ? (url) => insecureDevFetchJson(url)
154
- : (url) => safeFetchJson(url));
155
- this.#now = options.now ?? Date.now;
119
+ const fetchJson = options.fetchJson ??
120
+ (cfg.allowInsecureClientIds
121
+ ? (url) => insecureDevFetchJson(url, { userAgent: 'authkit-poppy/0.3' })
122
+ : (url) => safeFetchJson(url, { userAgent: 'authkit-poppy/0.3' }));
123
+ const common = { fetchJson, now: options.now, ttl: { min: 60, max: 86_400, fallback: 3600 } };
124
+ this.#clients = new MetadataDocumentCache({
125
+ ...common,
126
+ validate: (url, body) => validateClientMetadata(url, body, { allowHttp: this.#cfg.allowInsecureClientIds }),
127
+ fetchError: (_url, why) => new PoppyError('invalid_client', `client metadata: ${why}`),
128
+ });
129
+ this.#jwks = new MetadataDocumentCache({
130
+ ...common,
131
+ validate: (_url, body) => validateJwks(body),
132
+ fetchError: (_url, why) => new PoppyError('invalid_client', `jwks_uri: ${why}`),
133
+ // Releitura do JWKS quando o `kid` não está no conjunto em cache — no máximo a cada 30 s.
134
+ refreshCooldown: 30,
135
+ });
156
136
  }
157
137
  /**
158
138
  * O agente, ou `invalid_client`: `client_id` não é HTTPS, bloqueado, não
@@ -169,88 +149,27 @@ export class PoppyClientRegistry {
169
149
  !(await this.#cfg.clients.isRegistered(clientId))) {
170
150
  throw new PoppyError('invalid_client', 'client_id is not registered');
171
151
  }
172
- const meta = await this.#metadata(clientId);
152
+ const meta = await this.#clients.get(clientId);
173
153
  return { ...meta, keys: this.#keySet(meta.jwksUri) };
174
154
  }
175
155
  /** Nome de exibição sem falhar (console de conta): metadata em cache/buscada, ou o host. */
176
156
  async displayName(clientId) {
177
157
  try {
178
- return (await this.#metadata(clientId)).name;
158
+ return (await this.#clients.get(clientId)).name;
179
159
  }
180
160
  catch {
181
161
  return hostOf(clientId) ?? clientId;
182
162
  }
183
163
  }
184
- #metadata(clientId) {
185
- const now = this.#now();
186
- const cached = this.#clients.get(clientId);
187
- if (cached && cached.expiresAt > now)
188
- return cached.value;
189
- const entry = {
190
- value: Promise.resolve(null),
191
- expiresAt: now + FAILURE_TTL_MS,
192
- };
193
- entry.value = (async () => {
194
- let fetched;
195
- try {
196
- fetched = await this.#fetch(clientId);
197
- }
198
- catch (error) {
199
- const why = error instanceof SafeFetchError ? error.message : 'unreachable';
200
- throw new PoppyError('invalid_client', `client metadata: ${why}`);
201
- }
202
- const meta = validateClientMetadata(clientId, fetched.body, {
203
- allowHttp: this.#cfg.allowInsecureClientIds,
204
- });
205
- entry.expiresAt = this.#now() + ttlFrom(fetched.maxAge);
206
- return meta;
207
- })();
208
- entry.value.catch(() => {
209
- entry.expiresAt = this.#now() + FAILURE_TTL_MS;
210
- });
211
- setBounded(this.#clients, clientId, entry);
212
- return entry.value;
213
- }
214
- #fetchJwks(jwksUri, force) {
215
- const now = this.#now();
216
- const cached = this.#jwks.get(jwksUri);
217
- if (cached && cached.expiresAt > now && !force)
218
- return cached.value;
219
- if (cached && force && now - cached.fetchedAt < JWKS_REFRESH_COOLDOWN_MS)
220
- return cached.value;
221
- const entry = {
222
- value: Promise.resolve({ keys: [] }),
223
- expiresAt: now + FAILURE_TTL_MS,
224
- fetchedAt: now,
225
- };
226
- entry.value = (async () => {
227
- let fetched;
228
- try {
229
- fetched = await this.#fetch(jwksUri);
230
- }
231
- catch (error) {
232
- const why = error instanceof SafeFetchError ? error.message : 'unreachable';
233
- throw new PoppyError('invalid_client', `jwks_uri: ${why}`);
234
- }
235
- const jwks = validateJwks(fetched.body);
236
- entry.expiresAt = this.#now() + ttlFrom(fetched.maxAge);
237
- return jwks;
238
- })();
239
- entry.value.catch(() => {
240
- entry.expiresAt = this.#now() + FAILURE_TTL_MS;
241
- });
242
- setBounded(this.#jwks, jwksUri, entry);
243
- return entry.value;
244
- }
245
164
  /** `JWTVerifyGetKey` que relê o JWKS uma vez quando o `kid` é desconhecido (rotação). */
246
165
  #keySet(jwksUri) {
247
166
  return async (header, token) => {
248
- const jwks = await this.#fetchJwks(jwksUri, false);
167
+ const jwks = await this.#jwks.get(jwksUri);
249
168
  try {
250
169
  return await createLocalJWKSet(jwks)(header, token);
251
170
  }
252
171
  catch (error) {
253
- const refreshed = await this.#fetchJwks(jwksUri, true);
172
+ const refreshed = await this.#jwks.get(jwksUri, { force: true });
254
173
  if (refreshed === jwks)
255
174
  throw error;
256
175
  return createLocalJWKSet(refreshed)(header, token);
@@ -15,9 +15,8 @@
15
15
  *
16
16
  * Mesmas rotas, tabelas, tokens e slots globais de quando o Poppy morava dentro do authkit-server.
17
17
  */
18
- import type { PersonalAgentExtension } from '@adonis-agora/authkit-server';
18
+ import type { JsonFetcher, PersonalAgentExtension } from '@adonis-agora/authkit-server';
19
19
  import { type PoppyConfigInput } from './config.js';
20
- import type { JsonFetcher } from './safe_fetch.js';
21
20
  import { PoppyService } from './service.js';
22
21
  /** Prefixo dos ids dos grants (refresh tokens) do Poppy no ledger do authkit. */
23
22
  export declare const POPPY_GRANT_PREFIX = "pgrant_";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adonis-agora/authkit-poppy",
3
- "version": "0.3.1-rc.2",
3
+ "version": "0.3.1-rc.3",
4
4
  "description": "Personal Agent Protocol (\"Poppy\") for AuthKit: discovery, signed Poppy-Session agent sessions, Direct/Device/Mediated sign-in, MCP and browser sessions — an optional extension of @adonis-agora/authkit-server.",
5
5
  "license": "MIT",
6
6
  "author": "dudousxd",
@@ -40,7 +40,7 @@
40
40
  "node": ">=24"
41
41
  },
42
42
  "peerDependencies": {
43
- "@adonis-agora/authkit-server": "^1.0.0-rc.12",
43
+ "@adonis-agora/authkit-server": "^1.0.0-rc.20",
44
44
  "@adonisjs/core": "^7.5.0",
45
45
  "@adonisjs/session": "^8.1.0",
46
46
  "@adonisjs/shield": "^9.0.0"
@@ -49,7 +49,7 @@
49
49
  "jose": "6.2.16"
50
50
  },
51
51
  "devDependencies": {
52
- "@adonis-agora/authkit-server": "1.0.0-rc.12",
52
+ "@adonis-agora/authkit-server": "1.0.0-rc.20",
53
53
  "@adonisjs/core": "7.6.0",
54
54
  "@adonisjs/lucid": "22.4.2",
55
55
  "@adonisjs/session": "8.3.0",
@@ -1,48 +0,0 @@
1
- /**
2
- * `fetch` de documentos JSON de terceiros à prova de SSRF.
3
- *
4
- * O `client_id` de um agente Poppy é uma URL que QUALQUER um escolhe — buscá-la
5
- * sem cuidado faria deste app um proxy para a rede interna. Regras:
6
- * - só `https:`; sem credenciais na URL; porta qualquer;
7
- * - o IP é conferido NA CONEXÃO (o `lookup` do socket), não num DNS separado —
8
- * sem janela para DNS rebinding; loopback, privados, link-local, CGNAT,
9
- * multicast, reservados e os equivalentes IPv6 são recusados;
10
- * - IP literal na URL passa pela mesma regra;
11
- * - sem redirects (o `client_id` tem de ser exatamente a URL buscada);
12
- * - teto de tempo e de bytes.
13
- */
14
- import { type LookupAddress } from 'node:dns';
15
- export declare class SafeFetchError extends Error {
16
- constructor(message: string);
17
- }
18
- export interface FetchedJson {
19
- status: number;
20
- body: unknown;
21
- /** `max-age` do `Cache-Control`, em segundos, quando há. */
22
- maxAge: number | null;
23
- }
24
- /** Busca um JSON (GET). Lança {@link SafeFetchError} em qualquer recusa. */
25
- export type JsonFetcher = (url: string) => Promise<FetchedJson>;
26
- export type LookupFn = (hostname: string, options: {
27
- all: true;
28
- }, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void) => void;
29
- export interface SafeFetchOptions {
30
- timeoutMs?: number;
31
- maxBytes?: number;
32
- /** Resolução de nomes — injetável nos testes. Default: `dns.lookup`. */
33
- lookup?: LookupFn;
34
- }
35
- /** `true` quando o IP não pode ser alvo de uma busca de saída. */
36
- export declare function isBlockedAddress(ip: string): boolean;
37
- /**
38
- * Busca `url` e devolve o JSON. Só HTTPS, sem redirect, IP público conferido na
39
- * conexão, `timeoutMs` (default 5 s) e `maxBytes` (default 64 KiB).
40
- */
41
- export declare function safeFetchJson(url: string, options?: SafeFetchOptions): Promise<FetchedJson>;
42
- /**
43
- * SÓ DEV/TESTE (`poppy({ allowInsecureClientIds })`): busca um JSON por
44
- * `http:` ou `https:` SEM a guarda de SSRF — loopback e rede privada liberados,
45
- * para um agente local (`http://localhost:7777/agent.json`). Mantém sem redirect,
46
- * teto de tempo e de bytes. Nunca use em produção (a config recusa).
47
- */
48
- export declare function insecureDevFetchJson(url: string, options?: Omit<SafeFetchOptions, 'lookup'>): Promise<FetchedJson>;
@@ -1,262 +0,0 @@
1
- /**
2
- * `fetch` de documentos JSON de terceiros à prova de SSRF.
3
- *
4
- * O `client_id` de um agente Poppy é uma URL que QUALQUER um escolhe — buscá-la
5
- * sem cuidado faria deste app um proxy para a rede interna. Regras:
6
- * - só `https:`; sem credenciais na URL; porta qualquer;
7
- * - o IP é conferido NA CONEXÃO (o `lookup` do socket), não num DNS separado —
8
- * sem janela para DNS rebinding; loopback, privados, link-local, CGNAT,
9
- * multicast, reservados e os equivalentes IPv6 são recusados;
10
- * - IP literal na URL passa pela mesma regra;
11
- * - sem redirects (o `client_id` tem de ser exatamente a URL buscada);
12
- * - teto de tempo e de bytes.
13
- */
14
- import { lookup as dnsLookup } from 'node:dns';
15
- import { request as httpsRequest } from 'node:https';
16
- import { isIP } from 'node:net';
17
- export class SafeFetchError extends Error {
18
- constructor(message) {
19
- super(message);
20
- this.name = 'SafeFetchError';
21
- }
22
- }
23
- function ipv4ToInt(ip) {
24
- return ip.split('.').reduce((acc, part) => (acc << 8) + Number(part), 0) >>> 0;
25
- }
26
- function inV4(ip, cidr) {
27
- const [base, bits] = cidr.split('/');
28
- const mask = Number(bits) === 0 ? 0 : (~0 << (32 - Number(bits))) >>> 0;
29
- return (ip & mask) === (ipv4ToInt(base) & mask);
30
- }
31
- const BLOCKED_V4 = [
32
- '0.0.0.0/8',
33
- '10.0.0.0/8',
34
- '100.64.0.0/10',
35
- '127.0.0.0/8',
36
- '169.254.0.0/16',
37
- '172.16.0.0/12',
38
- '192.0.0.0/24',
39
- '192.0.2.0/24',
40
- '192.88.99.0/24',
41
- '192.168.0.0/16',
42
- '198.18.0.0/15',
43
- '198.51.100.0/24',
44
- '203.0.113.0/24',
45
- '224.0.0.0/4',
46
- '240.0.0.0/4',
47
- ];
48
- /** Expande um IPv6 em 8 grupos de 16 bits. */
49
- function ipv6Groups(ip) {
50
- let addr = ip.toLowerCase().split('%')[0];
51
- // Sufixo IPv4 (::ffff:1.2.3.4).
52
- const v4 = /(\d+\.\d+\.\d+\.\d+)$/.exec(addr);
53
- if (v4) {
54
- const n = ipv4ToInt(v4[1]);
55
- addr = `${addr.slice(0, -v4[1].length)}${(n >>> 16).toString(16)}:${(n & 0xffff).toString(16)}`;
56
- }
57
- const [head, tail] = addr.split('::');
58
- const h = head ? head.split(':') : [];
59
- const t = tail !== undefined ? (tail ? tail.split(':') : []) : [];
60
- const fill = addr.includes('::') ? 8 - h.length - t.length : 0;
61
- const groups = [...h, ...Array(fill).fill('0'), ...t].map((g) => Number.parseInt(g || '0', 16));
62
- return groups.length === 8 && groups.every((g) => g >= 0 && g <= 0xffff) ? groups : null;
63
- }
64
- /** `true` quando o IP não pode ser alvo de uma busca de saída. */
65
- export function isBlockedAddress(ip) {
66
- const family = isIP(ip);
67
- if (family === 4) {
68
- const n = ipv4ToInt(ip);
69
- return BLOCKED_V4.some((cidr) => inV4(n, cidr));
70
- }
71
- if (family !== 6)
72
- return true;
73
- const g = ipv6Groups(ip);
74
- if (!g)
75
- return true;
76
- if (g.every((x) => x === 0))
77
- return true; // ::
78
- if (g.slice(0, 7).every((x) => x === 0) && g[7] === 1)
79
- return true; // ::1
80
- // IPv4-translated (::ffff:0:a.b.c.d) e NAT64 (64:ff9b::a.b.c.d) também chegam a um IPv4.
81
- const translated = g.slice(0, 4).every((x) => x === 0) && g[4] === 0xffff && g[5] === 0;
82
- const nat64 = g[0] === 0x64 && g[1] === 0xff9b && g.slice(2, 6).every((x) => x === 0);
83
- if (translated || nat64) {
84
- return isBlockedAddress(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
85
- }
86
- // IPv4-mapped (::ffff:a.b.c.d) e IPv4-compatible: decide pelo IPv4.
87
- if (g.slice(0, 5).every((x) => x === 0) && (g[5] === 0xffff || g[5] === 0)) {
88
- const v4 = `${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`;
89
- return isBlockedAddress(v4);
90
- }
91
- if ((g[0] & 0xfe00) === 0xfc00)
92
- return true; // fc00::/7 (ULA)
93
- if ((g[0] & 0xffc0) === 0xfe80)
94
- return true; // fe80::/10 (link-local)
95
- if ((g[0] & 0xffc0) === 0xfec0)
96
- return true; // fec0::/10 (site-local)
97
- if ((g[0] & 0xff00) === 0xff00)
98
- return true; // ff00::/8 (multicast)
99
- if (g[0] === 0x2001 && g[1] === 0x0db8)
100
- return true; // 2001:db8::/32 (doc)
101
- if (g[0] === 0x64 && g[1] === 0xff9b)
102
- return true; // 64:ff9b::/96 (NAT64)
103
- if (g[0] === 0x2002) {
104
- // 6to4: o IPv4 embutido.
105
- return isBlockedAddress(`${g[1] >> 8}.${g[1] & 255}.${g[2] >> 8}.${g[2] & 255}`);
106
- }
107
- return false;
108
- }
109
- function parseMaxAge(header) {
110
- const value = Array.isArray(header) ? header.join(',') : header;
111
- if (!value)
112
- return null;
113
- if (/\bno-store\b|\bno-cache\b/i.test(value))
114
- return 0;
115
- const match = /\bmax-age=(\d+)/i.exec(value);
116
- return match ? Number(match[1]) : null;
117
- }
118
- /**
119
- * Busca `url` e devolve o JSON. Só HTTPS, sem redirect, IP público conferido na
120
- * conexão, `timeoutMs` (default 5 s) e `maxBytes` (default 64 KiB).
121
- */
122
- export function safeFetchJson(url, options = {}) {
123
- const timeoutMs = options.timeoutMs ?? 5000;
124
- const maxBytes = options.maxBytes ?? 64 * 1024;
125
- const resolve = options.lookup ?? dnsLookup;
126
- let parsed;
127
- try {
128
- parsed = new URL(url);
129
- }
130
- catch {
131
- return Promise.reject(new SafeFetchError('invalid URL'));
132
- }
133
- if (parsed.protocol !== 'https:')
134
- return Promise.reject(new SafeFetchError('only https URLs'));
135
- if (parsed.username || parsed.password) {
136
- return Promise.reject(new SafeFetchError('credentials in URL'));
137
- }
138
- const host = parsed.hostname.replace(/^\[|\]$/g, '');
139
- if (isIP(host) && isBlockedAddress(host)) {
140
- return Promise.reject(new SafeFetchError('blocked address'));
141
- }
142
- // `lookup` do socket: resolve e recusa se QUALQUER endereço for interno.
143
- const guardedLookup = (hostname, opts, callback) => {
144
- resolve(hostname, { all: true }, (err, addresses) => {
145
- if (err)
146
- return callback(err);
147
- const list = addresses ?? [];
148
- if (list.length === 0)
149
- return callback(new SafeFetchError('no address'));
150
- if (list.some((a) => isBlockedAddress(a.address))) {
151
- return callback(new SafeFetchError('blocked address'));
152
- }
153
- if (opts?.all)
154
- return callback(null, list);
155
- return callback(null, list[0].address, list[0].family);
156
- });
157
- };
158
- return new Promise((done, reject) => {
159
- let settled = false;
160
- const finish = (fn) => {
161
- if (settled)
162
- return;
163
- settled = true;
164
- clearTimeout(timer);
165
- fn();
166
- };
167
- const req = httpsRequest(parsed, {
168
- method: 'GET',
169
- headers: { accept: 'application/json', 'user-agent': 'authkit-poppy/0.3' },
170
- lookup: guardedLookup,
171
- // IP literal: o `lookup` não roda — já conferido acima.
172
- }, (res) => {
173
- const status = res.statusCode ?? 0;
174
- if (status >= 300 && status < 400) {
175
- res.resume();
176
- return finish(() => reject(new SafeFetchError('redirects are not followed')));
177
- }
178
- const chunks = [];
179
- let size = 0;
180
- res.on('data', (chunk) => {
181
- size += chunk.length;
182
- if (size > maxBytes) {
183
- req.destroy();
184
- finish(() => reject(new SafeFetchError('response too large')));
185
- return;
186
- }
187
- chunks.push(chunk);
188
- });
189
- res.on('end', () => finish(() => {
190
- if (status !== 200)
191
- return reject(new SafeFetchError(`HTTP ${status}`));
192
- try {
193
- done({
194
- status,
195
- body: JSON.parse(Buffer.concat(chunks).toString('utf8')),
196
- maxAge: parseMaxAge(res.headers['cache-control']),
197
- });
198
- }
199
- catch {
200
- reject(new SafeFetchError('invalid JSON'));
201
- }
202
- }));
203
- res.on('error', (e) => finish(() => reject(new SafeFetchError(e.message))));
204
- });
205
- const timer = setTimeout(() => {
206
- req.destroy();
207
- finish(() => reject(new SafeFetchError('timeout')));
208
- }, timeoutMs);
209
- req.on('error', (e) => finish(() => reject(e instanceof SafeFetchError ? e : new SafeFetchError(e.message))));
210
- req.end();
211
- });
212
- }
213
- /**
214
- * SÓ DEV/TESTE (`poppy({ allowInsecureClientIds })`): busca um JSON por
215
- * `http:` ou `https:` SEM a guarda de SSRF — loopback e rede privada liberados,
216
- * para um agente local (`http://localhost:7777/agent.json`). Mantém sem redirect,
217
- * teto de tempo e de bytes. Nunca use em produção (a config recusa).
218
- */
219
- export async function insecureDevFetchJson(url, options = {}) {
220
- const timeoutMs = options.timeoutMs ?? 5000;
221
- const maxBytes = options.maxBytes ?? 64 * 1024;
222
- let parsed;
223
- try {
224
- parsed = new URL(url);
225
- }
226
- catch {
227
- throw new SafeFetchError('invalid URL');
228
- }
229
- if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
230
- throw new SafeFetchError('only http(s) URLs');
231
- }
232
- if (parsed.username || parsed.password)
233
- throw new SafeFetchError('credentials in URL');
234
- let res;
235
- try {
236
- res = await fetch(parsed, {
237
- redirect: 'manual',
238
- headers: { accept: 'application/json', 'user-agent': 'authkit-poppy/0.3 (insecure-dev)' },
239
- signal: AbortSignal.timeout(timeoutMs),
240
- });
241
- }
242
- catch (error) {
243
- throw new SafeFetchError(error.name === 'TimeoutError' ? 'timeout' : 'unreachable');
244
- }
245
- if (res.status >= 300 && res.status < 400)
246
- throw new SafeFetchError('redirects are not followed');
247
- const buf = Buffer.from(await res.arrayBuffer());
248
- if (buf.length > maxBytes)
249
- throw new SafeFetchError('response too large');
250
- if (res.status !== 200)
251
- throw new SafeFetchError(`HTTP ${res.status}`);
252
- try {
253
- return {
254
- status: res.status,
255
- body: JSON.parse(buf.toString('utf8')),
256
- maxAge: parseMaxAge(res.headers.get('cache-control') ?? undefined),
257
- };
258
- }
259
- catch {
260
- throw new SafeFetchError('invalid JSON');
261
- }
262
- }