@adonis-agora/authkit-poppy 0.3.1-rc.1 → 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 +21 -0
- package/build/index.d.ts +1 -1
- package/build/index.js +2 -1
- package/build/src/client_registry.d.ts +4 -3
- package/build/src/client_registry.js +26 -107
- package/build/src/extension.d.ts +1 -2
- package/build/src/extension.js +9 -2
- package/build/src/replay.d.ts +3 -1
- package/build/src/replay.js +7 -5
- package/build/src/store.d.ts +5 -1
- package/build/src/store.js +23 -19
- package/build/src/tables.d.ts +5 -1
- package/build/src/tables.js +4 -1
- package/package.json +3 -3
- package/build/src/safe_fetch.d.ts +0 -48
- package/build/src/safe_fetch.js +0 -262
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
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
|
+
|
|
9
|
+
## 0.3.1-rc.2
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- [#474](https://github.com/DavideCarvalho/adonis-agora-authkit/pull/474) [`df9e49d`](https://github.com/DavideCarvalho/adonis-agora-authkit/commit/df9e49d7817c03a7cce4cac1df709c7788d6307c) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - AuthKit's tables can live in their own database schema: `schema: { name: 'auth' }` in `defineConfig` puts every table AuthKit owns in `auth` (`"auth"."auth_settings"`) while the app stays in `public`. The schema is written into every statement, so it works on any connection and inside the app's own transaction, with no `searchPath` (which leaks across clients behind PgBouncer in transaction mode).
|
|
14
|
+
|
|
15
|
+
- The boot creates the schema (`CREATE SCHEMA IF NOT EXISTS`; MySQL: `CREATE DATABASE IF NOT EXISTS`) when `autoManage` is on, and fails with a message naming the schema and the grant when the role cannot create it. `ensureAuthkitSchema(db, { schema })` does the same from a migration.
|
|
16
|
+
- Covers the OIDC adapter table (`adapters.database({ schema })` overrides), the Lucid keystore (`jwks.store: { driver: 'lucid', schema }` overrides), the account store's tables (MFA, password history, organizations), runtime settings, session revocations, the personal-agent tables and agent extensions (`PersonalAgentHost.table(name)`, `AuthkitTable.create(table, { table })`, `ensureAuthkitTables(db, tables, { schema })`; Poppy uses them and `ensurePoppySchema(db, { schema })`).
|
|
17
|
+
- authkit-client: `lucidRevocationStore({ schema })`.
|
|
18
|
+
- SQLite with `schema.name` fails the boot instead of ignoring the option.
|
|
19
|
+
- `agora:doctor` gains `authkit.db-schema`: the schema exists, the tables are in it, the connection can write there. Silent without `schema.name`.
|
|
20
|
+
- The key-rotation lock key includes the schema, so two installs in two schemas of one database do not share it.
|
|
21
|
+
|
|
22
|
+
Without `schema.name` nothing changes.
|
|
23
|
+
|
|
3
24
|
## 0.3.1-rc.1
|
|
4
25
|
|
|
5
26
|
### 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:
|
|
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
|
-
#
|
|
145
|
-
#
|
|
146
|
-
#clients = new Map();
|
|
147
|
-
#jwks = new Map();
|
|
115
|
+
#clients;
|
|
116
|
+
#jwks;
|
|
148
117
|
constructor(cfg, options = {}) {
|
|
149
118
|
this.#cfg = cfg;
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
(
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
this.#
|
|
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.#
|
|
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.#
|
|
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.#
|
|
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.#
|
|
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);
|
package/build/src/extension.d.ts
CHANGED
|
@@ -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/build/src/extension.js
CHANGED
|
@@ -81,11 +81,18 @@ function withRegistry(cfg, host) {
|
|
|
81
81
|
},
|
|
82
82
|
};
|
|
83
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* How the host names AuthKit's tables (with `schema.name`, `schema.table`). A host from before
|
|
86
|
+
* `table()` existed has no schema option, so the bare name is right there.
|
|
87
|
+
*/
|
|
88
|
+
function tableOf(host) {
|
|
89
|
+
return (name) => (typeof host.table === 'function' ? host.table(name) : name);
|
|
90
|
+
}
|
|
84
91
|
async function resolveReplay(replay, host) {
|
|
85
92
|
if (replay === 'memory')
|
|
86
93
|
return memoryReplayStore();
|
|
87
94
|
if (replay === 'database')
|
|
88
|
-
return databaseReplayStore(() => host.db());
|
|
95
|
+
return databaseReplayStore(() => host.db(), tableOf(host));
|
|
89
96
|
if (typeof replay.claim === 'function')
|
|
90
97
|
return replay;
|
|
91
98
|
const redis = await host.make('redis');
|
|
@@ -163,7 +170,7 @@ export function poppy(config, options = {}) {
|
|
|
163
170
|
return new PoppyService({
|
|
164
171
|
cfg,
|
|
165
172
|
urls: poppyUrls(host.issuer, cfg.prefix),
|
|
166
|
-
store: new PoppyStore(() => host.db()),
|
|
173
|
+
store: new PoppyStore(() => host.db(), tableOf(host)),
|
|
167
174
|
grants: host.grants,
|
|
168
175
|
registry: new PoppyClientRegistry(cfg, { fetchJson: options.fetchJson }),
|
|
169
176
|
replay: await resolveReplay(cfg.replay, host),
|
package/build/src/replay.d.ts
CHANGED
|
@@ -11,7 +11,9 @@ export declare function memoryReplayStore(options?: {
|
|
|
11
11
|
* Na tabela lib-owned `auth_poppy_jtis` (PK = chave): o INSERT de uma chave que
|
|
12
12
|
* já existe falha — atômico entre instâncias. Linhas vencidas saem aos poucos.
|
|
13
13
|
*/
|
|
14
|
-
export declare function databaseReplayStore(conn: () => any,
|
|
14
|
+
export declare function databaseReplayStore(conn: () => any,
|
|
15
|
+
/** Nome da tabela como os statements o escrevem (`schema.tabela` quando o app usa um schema). */
|
|
16
|
+
table?: (name: string) => string, options?: {
|
|
15
17
|
now?: () => Date;
|
|
16
18
|
}): PoppyReplayStore;
|
|
17
19
|
/** Numa conexão Redis (`SET key 1 PX ttl NX`). */
|
package/build/src/replay.js
CHANGED
|
@@ -36,22 +36,24 @@ export function memoryReplayStore(options = {}) {
|
|
|
36
36
|
* Na tabela lib-owned `auth_poppy_jtis` (PK = chave): o INSERT de uma chave que
|
|
37
37
|
* já existe falha — atômico entre instâncias. Linhas vencidas saem aos poucos.
|
|
38
38
|
*/
|
|
39
|
-
export function databaseReplayStore(conn,
|
|
39
|
+
export function databaseReplayStore(conn,
|
|
40
|
+
/** Nome da tabela como os statements o escrevem (`schema.tabela` quando o app usa um schema). */
|
|
41
|
+
table = (name) => name, options = {}) {
|
|
40
42
|
const now = options.now ?? (() => new Date());
|
|
41
43
|
let claims = 0;
|
|
42
44
|
return {
|
|
43
45
|
async claim(key, expiresAt) {
|
|
44
46
|
const t = now();
|
|
45
47
|
if (++claims % 200 === 1) {
|
|
46
|
-
await conn().from(JTI_TABLE).where('expires_at', '<', t).delete();
|
|
48
|
+
await conn().from(table(JTI_TABLE)).where('expires_at', '<', t).delete();
|
|
47
49
|
}
|
|
48
50
|
try {
|
|
49
|
-
await conn().table(JTI_TABLE).insert({ key, expires_at: expiresAt });
|
|
51
|
+
await conn().table(table(JTI_TABLE)).insert({ key, expires_at: expiresAt });
|
|
50
52
|
return true;
|
|
51
53
|
}
|
|
52
54
|
catch (error) {
|
|
53
55
|
// Chave já usada — a não ser que a linha vencida ainda não tenha saído.
|
|
54
|
-
const row = await conn().from(JTI_TABLE).where('key', key).first();
|
|
56
|
+
const row = await conn().from(table(JTI_TABLE)).where('key', key).first();
|
|
55
57
|
if (!row)
|
|
56
58
|
throw error;
|
|
57
59
|
const exp = row.expires_at instanceof Date
|
|
@@ -60,7 +62,7 @@ export function databaseReplayStore(conn, options = {}) {
|
|
|
60
62
|
if (exp.getTime() > t.getTime())
|
|
61
63
|
return false;
|
|
62
64
|
const updated = await conn()
|
|
63
|
-
.from(JTI_TABLE)
|
|
65
|
+
.from(table(JTI_TABLE))
|
|
64
66
|
.where('key', key)
|
|
65
67
|
.where('expires_at', '<=', t)
|
|
66
68
|
.update({ expires_at: expiresAt });
|
package/build/src/store.d.ts
CHANGED
|
@@ -64,7 +64,11 @@ export interface RequestRow {
|
|
|
64
64
|
}
|
|
65
65
|
export declare class PoppyStore {
|
|
66
66
|
private conn;
|
|
67
|
-
|
|
67
|
+
/** Nome da tabela como os statements o escrevem (`schema.tabela` quando o app usa um schema). */
|
|
68
|
+
private t;
|
|
69
|
+
constructor(conn: () => any,
|
|
70
|
+
/** Nome da tabela como os statements o escrevem (`schema.tabela` quando o app usa um schema). */
|
|
71
|
+
t?: (name: string) => string);
|
|
68
72
|
insertSession(row: Omit<SessionRow, 'endedAt'>): Promise<void>;
|
|
69
73
|
findSession(id: string): Promise<SessionRow | null>;
|
|
70
74
|
/** Estende a vida da Session (uso). */
|
package/build/src/store.js
CHANGED
|
@@ -92,12 +92,16 @@ function toRequest(row) {
|
|
|
92
92
|
}
|
|
93
93
|
export class PoppyStore {
|
|
94
94
|
conn;
|
|
95
|
-
|
|
95
|
+
t;
|
|
96
|
+
constructor(conn,
|
|
97
|
+
/** Nome da tabela como os statements o escrevem (`schema.tabela` quando o app usa um schema). */
|
|
98
|
+
t = (name) => name) {
|
|
96
99
|
this.conn = conn;
|
|
100
|
+
this.t = t;
|
|
97
101
|
}
|
|
98
102
|
// ─── sessions ─────────────────────────────────────────────────────────────
|
|
99
103
|
async insertSession(row) {
|
|
100
|
-
await this.conn().table(SESSION_TABLE).insert({
|
|
104
|
+
await this.conn().table(this.t(SESSION_TABLE)).insert({
|
|
101
105
|
id: row.id,
|
|
102
106
|
client_id: row.clientId,
|
|
103
107
|
user_id: row.userId,
|
|
@@ -113,13 +117,13 @@ export class PoppyStore {
|
|
|
113
117
|
async findSession(id) {
|
|
114
118
|
if (typeof id !== 'string' || !id)
|
|
115
119
|
return null;
|
|
116
|
-
const row = await this.conn().from(SESSION_TABLE).where('id', id).first();
|
|
120
|
+
const row = await this.conn().from(this.t(SESSION_TABLE)).where('id', id).first();
|
|
117
121
|
return row ? toSession(row) : null;
|
|
118
122
|
}
|
|
119
123
|
/** Estende a vida da Session (uso). */
|
|
120
124
|
async touchSession(id, expiresAt, at) {
|
|
121
125
|
await this.conn()
|
|
122
|
-
.from(SESSION_TABLE)
|
|
126
|
+
.from(this.t(SESSION_TABLE))
|
|
123
127
|
.where('id', id)
|
|
124
128
|
.whereNull('ended_at')
|
|
125
129
|
.update({ expires_at: expiresAt, updated_at: at });
|
|
@@ -130,7 +134,7 @@ export class PoppyStore {
|
|
|
130
134
|
*/
|
|
131
135
|
async bindSessionAccount(id, accountId, at) {
|
|
132
136
|
const result = await this.conn()
|
|
133
|
-
.from(SESSION_TABLE)
|
|
137
|
+
.from(this.t(SESSION_TABLE))
|
|
134
138
|
.where('id', id)
|
|
135
139
|
.where((q) => q.whereNull('account_id').orWhere('account_id', accountId))
|
|
136
140
|
.update({ account_id: accountId, updated_at: at });
|
|
@@ -139,7 +143,7 @@ export class PoppyStore {
|
|
|
139
143
|
/** Encerra todas as Sessions de um agente (bloqueio no console): param na hora. */
|
|
140
144
|
async endSessionsOfClient(clientId, at) {
|
|
141
145
|
const result = await this.conn()
|
|
142
|
-
.from(SESSION_TABLE)
|
|
146
|
+
.from(this.t(SESSION_TABLE))
|
|
143
147
|
.where('client_id', clientId)
|
|
144
148
|
.whereNull('ended_at')
|
|
145
149
|
.update({ ended_at: at, grant_id: null, scope: '', updated_at: at });
|
|
@@ -147,7 +151,7 @@ export class PoppyStore {
|
|
|
147
151
|
}
|
|
148
152
|
// ─── access tokens ────────────────────────────────────────────────────────
|
|
149
153
|
async insertToken(row) {
|
|
150
|
-
await this.conn().table(TOKEN_TABLE).insert({
|
|
154
|
+
await this.conn().table(this.t(TOKEN_TABLE)).insert({
|
|
151
155
|
token_hash: row.tokenHash,
|
|
152
156
|
// `session_id`/`user_id` são NOT NULL desde a Draft 0.1 e o schema só é aditivo; o sign-in
|
|
153
157
|
// não conhece a Session nem o User ID (§4.4).
|
|
@@ -164,19 +168,19 @@ export class PoppyStore {
|
|
|
164
168
|
});
|
|
165
169
|
}
|
|
166
170
|
async findToken(hash) {
|
|
167
|
-
const row = await this.conn().from(TOKEN_TABLE).where('token_hash', hash).first();
|
|
171
|
+
const row = await this.conn().from(this.t(TOKEN_TABLE)).where('token_hash', hash).first();
|
|
168
172
|
return row ? toToken(row) : null;
|
|
169
173
|
}
|
|
170
174
|
async deleteToken(hash) {
|
|
171
|
-
return affected(await this.conn().from(TOKEN_TABLE).where('token_hash', hash).delete()) > 0;
|
|
175
|
+
return (affected(await this.conn().from(this.t(TOKEN_TABLE)).where('token_hash', hash).delete()) > 0);
|
|
172
176
|
}
|
|
173
177
|
async deleteTokensExpiredBefore(before) {
|
|
174
|
-
await this.conn().from(TOKEN_TABLE).where('expires_at', '<', before).delete();
|
|
178
|
+
await this.conn().from(this.t(TOKEN_TABLE)).where('expires_at', '<', before).delete();
|
|
175
179
|
}
|
|
176
180
|
// ─── sign-in requests ─────────────────────────────────────────────────────
|
|
177
181
|
async insertRequest(row) {
|
|
178
182
|
await this.conn()
|
|
179
|
-
.table(REQUEST_TABLE)
|
|
183
|
+
.table(this.t(REQUEST_TABLE))
|
|
180
184
|
.insert({
|
|
181
185
|
id: row.id,
|
|
182
186
|
kind: row.kind,
|
|
@@ -200,15 +204,15 @@ export class PoppyStore {
|
|
|
200
204
|
async findRequest(id) {
|
|
201
205
|
if (typeof id !== 'string' || !id)
|
|
202
206
|
return null;
|
|
203
|
-
const row = await this.conn().from(REQUEST_TABLE).where('id', id).first();
|
|
207
|
+
const row = await this.conn().from(this.t(REQUEST_TABLE)).where('id', id).first();
|
|
204
208
|
return row ? toRequest(row) : null;
|
|
205
209
|
}
|
|
206
210
|
async findRequestByCodeHash(hash) {
|
|
207
|
-
const row = await this.conn().from(REQUEST_TABLE).where('code_hash', hash).first();
|
|
211
|
+
const row = await this.conn().from(this.t(REQUEST_TABLE)).where('code_hash', hash).first();
|
|
208
212
|
return row ? toRequest(row) : null;
|
|
209
213
|
}
|
|
210
214
|
async findRequestByUserCode(userCode) {
|
|
211
|
-
const row = await this.conn().from(REQUEST_TABLE).where('user_code', userCode).first();
|
|
215
|
+
const row = await this.conn().from(this.t(REQUEST_TABLE)).where('user_code', userCode).first();
|
|
212
216
|
return row ? toRequest(row) : null;
|
|
213
217
|
}
|
|
214
218
|
/** Transição atômica — só se o pedido ainda está em `from`. */
|
|
@@ -231,7 +235,7 @@ export class PoppyStore {
|
|
|
231
235
|
if (patch.data !== undefined)
|
|
232
236
|
update.data = JSON.stringify(patch.data);
|
|
233
237
|
const result = await this.conn()
|
|
234
|
-
.from(REQUEST_TABLE)
|
|
238
|
+
.from(this.t(REQUEST_TABLE))
|
|
235
239
|
.where('id', id)
|
|
236
240
|
.where('status', from)
|
|
237
241
|
.update(update);
|
|
@@ -240,7 +244,7 @@ export class PoppyStore {
|
|
|
240
244
|
/** Conta uma tentativa errada (atômico sobre o valor lido). */
|
|
241
245
|
async bumpAttempts(id, from) {
|
|
242
246
|
const result = await this.conn()
|
|
243
|
-
.from(REQUEST_TABLE)
|
|
247
|
+
.from(this.t(REQUEST_TABLE))
|
|
244
248
|
.where('id', id)
|
|
245
249
|
.where('attempts', from)
|
|
246
250
|
.update({ attempts: from + 1 });
|
|
@@ -248,14 +252,14 @@ export class PoppyStore {
|
|
|
248
252
|
}
|
|
249
253
|
async setRequestData(id, data) {
|
|
250
254
|
await this.conn()
|
|
251
|
-
.from(REQUEST_TABLE)
|
|
255
|
+
.from(this.t(REQUEST_TABLE))
|
|
252
256
|
.where('id', id)
|
|
253
257
|
.update({ data: JSON.stringify(data) });
|
|
254
258
|
}
|
|
255
259
|
async markPolled(id, at) {
|
|
256
|
-
await this.conn().from(REQUEST_TABLE).where('id', id).update({ last_polled_at: at });
|
|
260
|
+
await this.conn().from(this.t(REQUEST_TABLE)).where('id', id).update({ last_polled_at: at });
|
|
257
261
|
}
|
|
258
262
|
async deleteRequestsExpiredBefore(before) {
|
|
259
|
-
await this.conn().from(REQUEST_TABLE).where('expires_at', '<', before).delete();
|
|
263
|
+
await this.conn().from(this.t(REQUEST_TABLE)).where('expires_at', '<', before).delete();
|
|
260
264
|
}
|
|
261
265
|
}
|
package/build/src/tables.d.ts
CHANGED
|
@@ -18,10 +18,14 @@ export declare const POPPY_TABLES: readonly AuthkitTable[];
|
|
|
18
18
|
* async up() {
|
|
19
19
|
* await ensureAuthkitSchema(this.db)
|
|
20
20
|
* await ensurePoppySchema(this.db)
|
|
21
|
+
* // with `schema.name: 'auth'`: pass `{ schema: 'auth' }` to both
|
|
21
22
|
* }
|
|
22
23
|
* }
|
|
23
24
|
* ```
|
|
24
25
|
*/
|
|
25
|
-
export declare function ensurePoppySchema(db: unknown,
|
|
26
|
+
export declare function ensurePoppySchema(db: unknown,
|
|
27
|
+
/** The same `connection` and `schema` (`schema.name`) as AuthKit's tables. */
|
|
28
|
+
options?: {
|
|
26
29
|
connection?: string;
|
|
30
|
+
schema?: string;
|
|
27
31
|
}): Promise<Pick<import("@adonis-agora/authkit-server").EnsureSchemaReport, "altered" | "created" | "indexed">>;
|
package/build/src/tables.js
CHANGED
|
@@ -147,10 +147,13 @@ export const POPPY_TABLES = [
|
|
|
147
147
|
* async up() {
|
|
148
148
|
* await ensureAuthkitSchema(this.db)
|
|
149
149
|
* await ensurePoppySchema(this.db)
|
|
150
|
+
* // with `schema.name: 'auth'`: pass `{ schema: 'auth' }` to both
|
|
150
151
|
* }
|
|
151
152
|
* }
|
|
152
153
|
* ```
|
|
153
154
|
*/
|
|
154
|
-
export function ensurePoppySchema(db,
|
|
155
|
+
export function ensurePoppySchema(db,
|
|
156
|
+
/** The same `connection` and `schema` (`schema.name`) as AuthKit's tables. */
|
|
157
|
+
options = {}) {
|
|
155
158
|
return ensureAuthkitTables(db, POPPY_TABLES, options);
|
|
156
159
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adonis-agora/authkit-poppy",
|
|
3
|
-
"version": "0.3.1-rc.
|
|
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.
|
|
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.
|
|
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>;
|
package/build/src/safe_fetch.js
DELETED
|
@@ -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
|
-
}
|