@adonis-agora/authkit-poppy 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +21 -0
  3. package/README.md +40 -2
  4. package/build/configure.d.ts +3 -0
  5. package/build/configure.js +43 -0
  6. package/build/index.d.ts +20 -0
  7. package/build/index.js +18 -0
  8. package/build/src/augmentations.d.ts +1 -0
  9. package/build/src/augmentations.js +1 -0
  10. package/build/src/client_registry.d.ts +50 -0
  11. package/build/src/client_registry.js +260 -0
  12. package/build/src/config.d.ts +396 -0
  13. package/build/src/config.js +228 -0
  14. package/build/src/controllers/poppy_consent_controller.d.ts +19 -0
  15. package/build/src/controllers/poppy_consent_controller.js +194 -0
  16. package/build/src/controllers/poppy_controller.d.ts +33 -0
  17. package/build/src/controllers/poppy_controller.js +219 -0
  18. package/build/src/dpop.d.ts +61 -0
  19. package/build/src/dpop.js +158 -0
  20. package/build/src/email_code_sign_in.d.ts +40 -0
  21. package/build/src/email_code_sign_in.js +142 -0
  22. package/build/src/errors.d.ts +25 -0
  23. package/build/src/errors.js +25 -0
  24. package/build/src/extension.d.ts +37 -0
  25. package/build/src/extension.js +167 -0
  26. package/build/src/messages.d.ts +20 -0
  27. package/build/src/messages.js +22 -0
  28. package/build/src/redirect_exact.d.ts +6 -0
  29. package/build/src/redirect_exact.js +11 -0
  30. package/build/src/replay.d.ts +25 -0
  31. package/build/src/replay.js +106 -0
  32. package/build/src/resource.d.ts +100 -0
  33. package/build/src/resource.js +122 -0
  34. package/build/src/runtime.d.ts +8 -0
  35. package/build/src/runtime.js +15 -0
  36. package/build/src/safe_fetch.d.ts +48 -0
  37. package/build/src/safe_fetch.js +262 -0
  38. package/build/src/service.d.ts +301 -0
  39. package/build/src/service.js +1488 -0
  40. package/build/src/session_jwt.d.ts +30 -0
  41. package/build/src/session_jwt.js +133 -0
  42. package/build/src/store.d.ts +106 -0
  43. package/build/src/store.js +261 -0
  44. package/build/src/tables.d.ts +27 -0
  45. package/build/src/tables.js +156 -0
  46. package/build/src/web_session.d.ts +43 -0
  47. package/build/src/web_session.js +120 -0
  48. package/package.json +70 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # @adonis-agora/authkit-poppy
2
+
3
+ ## 0.3.0
4
+
5
+ The package version follows the Poppy spec draft it implements: 0.3.x is Draft 0.3.
6
+
7
+ ### Minor Changes
8
+
9
+ - [#456](https://github.com/DavideCarvalho/adonis-agora-authkit/pull/456) [`9c12ef9`](https://github.com/DavideCarvalho/adonis-agora-authkit/commit/9c12ef9c1c49db9d54a7da6d241264499ad76e18) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - First release: the Personal Agent Protocol ("Poppy", Draft 0.3) as an extension of `@adonis-agora/authkit-server` 1.x — `personalAgents: { extensions: [poppy({ ... })] }`. Same options, routes, tables, tokens and global slots as the Poppy that was built into authkit-server 0.x; `poppyEmailCodeSignIn` takes `sendCode` in place of the old `mail.onPoppySignInCode` hook, `ensurePoppySchema()` creates its tables in a migration, and `node ace configure @adonis-agora/authkit-poppy` checks the install and shows the config change. Experimental: this package stays on 0.x while the spec is a draft.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Davi de Carvalho
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # @adonis-agora/authkit-poppy
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The [Personal Agent Protocol ("Poppy")](https://personalagentprotocol.org/docs/spec) for
4
+ [AuthKit](https://davidecarvalho.github.io/agora/docs/authkit): discovery (`poppy.json`), signed
5
+ `Poppy-Session` agent sessions, Direct / Device / Mediated sign-in, DPoP, MCP tokens and browser
6
+ sessions — as an extension of `@adonis-agora/authkit-server`.
7
+
8
+ > **Experimental.** Poppy is a draft spec. The package version follows the draft it implements:
9
+ > `0.3.x` is Draft 0.3, and the next draft ships as a new minor. Pin it with `~0.3.0`.
10
+
11
+ ```sh
12
+ node ace add @adonis-agora/authkit-poppy
13
+ ```
14
+
15
+ ```ts
16
+ // config/authkit.ts
17
+ import { poppy } from '@adonis-agora/authkit-poppy'
18
+
19
+ export default defineConfig({
20
+ // ...
21
+ personalAgents: {
22
+ extensions: [
23
+ poppy({
24
+ organization: { name: 'Acme', domain: 'acme.com' },
25
+ scopes: { 'orders:read': 'See your orders' },
26
+ }),
27
+ ],
28
+ },
29
+ })
30
+ ```
31
+
32
+ ```ts
33
+ // start/routes.ts
34
+ import { poppyAuth, poppyOf } from '@adonis-agora/authkit-poppy'
35
+
36
+ router
37
+ .get('/orders', async (ctx) => listOrders(poppyOf(ctx)!.accountId))
38
+ .use(poppyAuth({ scopes: ['orders:read'] }))
39
+ ```
40
+
41
+ Guide: [Personal agents — Poppy](https://davidecarvalho.github.io/agora/docs/authkit/personal-agents-poppy).
@@ -0,0 +1,3 @@
1
+ import type Configure from '@adonisjs/core/commands/configure';
2
+ export declare const POPPY_CONFIG_SNIPPET = "import { poppy } from '@adonis-agora/authkit-poppy'\n\nexport default defineConfig({\n // ...\n personalAgents: {\n extensions: [\n poppy({\n organization: { name: 'Shop', domain: 'shop.example' },\n scopes: { 'orders:read': 'See your orders' },\n }),\n ],\n },\n})";
3
+ export declare function configure(command: Configure): Promise<void>;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * `node ace configure @adonis-agora/authkit-poppy` (ou `node ace add`). O Poppy não tem provider
3
+ * próprio nem env: liga-se em `personalAgents.extensions` do `config/authkit.ts`, então o comando
4
+ * confere o que precisa existir e mostra a mudança — editar o `defineConfig` do host
5
+ * automaticamente seria frágil demais.
6
+ */
7
+ import { existsSync, readFileSync } from 'node:fs';
8
+ export const POPPY_CONFIG_SNIPPET = `import { poppy } from '@adonis-agora/authkit-poppy'
9
+
10
+ export default defineConfig({
11
+ // ...
12
+ personalAgents: {
13
+ extensions: [
14
+ poppy({
15
+ organization: { name: 'Shop', domain: 'shop.example' },
16
+ scopes: { 'orders:read': 'See your orders' },
17
+ }),
18
+ ],
19
+ },
20
+ })`;
21
+ export async function configure(command) {
22
+ const logger = command.logger;
23
+ const pkgPath = command.app.makePath('package.json');
24
+ const pkg = existsSync(pkgPath) ? JSON.parse(readFileSync(pkgPath, 'utf8')) : {};
25
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
26
+ if (!deps['@adonis-agora/authkit-server']) {
27
+ logger.error('@adonis-agora/authkit-poppy plugs into @adonis-agora/authkit-server. Run `node ace add @adonis-agora/authkit-server` first.');
28
+ command.exitCode = 1;
29
+ return;
30
+ }
31
+ const configPath = command.app.configPath('authkit.ts');
32
+ const source = existsSync(configPath) ? readFileSync(configPath, 'utf8') : '';
33
+ if (source.includes('@adonis-agora/authkit-poppy')) {
34
+ logger.success('config/authkit.ts already imports @adonis-agora/authkit-poppy');
35
+ return;
36
+ }
37
+ if (/personalAgents\s*:\s*\{[^}]*\bpoppy\s*:/s.test(source)) {
38
+ logger.warning('config/authkit.ts still has `personalAgents.poppy` (authkit-server 0.x). Move it into `personalAgents.extensions: [poppy({ ... })]` — same options.');
39
+ }
40
+ logger.info('Add the Poppy extension to config/authkit.ts:');
41
+ command.ui.instructions().heading('config/authkit.ts').add(POPPY_CONFIG_SNIPPET).render();
42
+ logger.info("Tables (auth_poppy_*) are created at boot with AuthKit's own (`schema.autoManage`); with it off, call `ensurePoppySchema(this.db)` in a migration.");
43
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @adonis-agora/authkit-poppy — the Personal Agent Protocol ("Poppy", Draft 0.3) for AuthKit, as a
3
+ * `personalAgents.extensions` entry of `@adonis-agora/authkit-server`.
4
+ *
5
+ * Experimental: this package stays on 0.x and follows the draft spec, so any minor may break.
6
+ */
7
+ export { configure, POPPY_CONFIG_SNIPPET } from './configure.js';
8
+ export type { PoppyAgentProtocolEntry, PoppyApiEntry, PoppyBrowserLogin, PoppyClientsConfigInput, PoppyConfigInput, PoppyLimiter, PoppyMediatedConfigInput, PoppyMediatedField, PoppyMediatedResult, PoppyMediatedVerifyInput, PoppyPrincipalBase, PoppyReplayStore, PoppyScopeHint, PoppySignInType, ResolvedPoppyConfig, } from './src/config.js';
9
+ export { accessTokenHash, type DpopNonceSource, type DpopResult, hmacNonceSource, type VerifyDpopInput, verifyDpopProof, } from './src/dpop.js';
10
+ export { maskEmail, type PoppyEmailCodeSignInOptions, type PoppySignInCodeEmail, poppyEmailCodeSignIn, } from './src/email_code_sign_in.js';
11
+ export { PoppyError, type PoppyErrorCode } from './src/errors.js';
12
+ export { POPPY_GRANT_PREFIX, type PoppyExtensionOptions, poppy, } from './src/extension.js';
13
+ export { POPPY_MESSAGES } from './src/messages.js';
14
+ export { databaseReplayStore, memoryReplayStore, redisReplayStore, } from './src/replay.js';
15
+ export { installPoppySlots, POPPY_AUTHENTICATE_SLOT, type PoppyAuthenticate, type PoppyAuthResult, type PoppyPrincipal, type PoppySlotRequest, poppyAuth, poppyOf, verifyPoppyRequest, writePoppyAuthError, } from './src/resource.js';
16
+ export { POPPY_PROTOCOL_ID, poppyFor, poppyFromApp } from './src/runtime.js';
17
+ export { isBlockedAddress, SafeFetchError, safeFetchJson, } from './src/safe_fetch.js';
18
+ export type { PoppyAuthError, PoppyGrantSummary, PoppyService, PoppySessionState, PoppyTokenResponse, PoppyVerifyOptions, } from './src/service.js';
19
+ export { ensurePoppySchema, POPPY_TABLES } from './src/tables.js';
20
+ export { isPoppyBrowser, POPPY_WEB_SESSION_KEY, type PoppyWebSessionMarker, poppyWebSession, poppyWebSessionOf, } from './src/web_session.js';
package/build/index.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @adonis-agora/authkit-poppy — the Personal Agent Protocol ("Poppy", Draft 0.3) for AuthKit, as a
3
+ * `personalAgents.extensions` entry of `@adonis-agora/authkit-server`.
4
+ *
5
+ * Experimental: this package stays on 0.x and follows the draft spec, so any minor may break.
6
+ */
7
+ export { configure, POPPY_CONFIG_SNIPPET } from './configure.js';
8
+ export { accessTokenHash, hmacNonceSource, verifyDpopProof, } from './src/dpop.js';
9
+ export { maskEmail, poppyEmailCodeSignIn, } from './src/email_code_sign_in.js';
10
+ export { PoppyError } from './src/errors.js';
11
+ export { POPPY_GRANT_PREFIX, poppy, } from './src/extension.js';
12
+ export { POPPY_MESSAGES } from './src/messages.js';
13
+ export { databaseReplayStore, memoryReplayStore, redisReplayStore, } from './src/replay.js';
14
+ export { installPoppySlots, POPPY_AUTHENTICATE_SLOT, poppyAuth, poppyOf, verifyPoppyRequest, writePoppyAuthError, } from './src/resource.js';
15
+ export { POPPY_PROTOCOL_ID, poppyFor, poppyFromApp } from './src/runtime.js';
16
+ export { isBlockedAddress, SafeFetchError, safeFetchJson, } from './src/safe_fetch.js';
17
+ export { ensurePoppySchema, POPPY_TABLES } from './src/tables.js';
18
+ export { isPoppyBrowser, POPPY_WEB_SESSION_KEY, poppyWebSession, poppyWebSessionOf, } from './src/web_session.js';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Identidade do personal agent no Poppy (§4.1): o `client_id` é uma URL HTTPS
3
+ * que devolve o documento de metadata do agente (OAuth Client ID Metadata
4
+ * Document). Buscamos (à prova de SSRF), validamos, guardamos em cache e
5
+ * importamos as chaves públicas do `jwks_uri`.
6
+ */
7
+ import { type JWTVerifyGetKey } from 'jose';
8
+ import type { ResolvedPoppyConfig } from './config.js';
9
+ import { type JsonFetcher } from './safe_fetch.js';
10
+ export interface PoppyClient {
11
+ clientId: string;
12
+ /** `client_name`, ou o host do `client_id`. */
13
+ name: string;
14
+ logoUri: string | null;
15
+ jwksUri: string;
16
+ redirectUris: string[];
17
+ extensions: Record<string, unknown>;
18
+ /** Chaves públicas do `jwks_uri`. */
19
+ keys: JWTVerifyGetKey;
20
+ }
21
+ /**
22
+ * `redirect_uri` igual a uma entrada de `redirect_uris`; numa loopback redirect URI a porta não
23
+ * conta (§4.2, RFC 8252 §7.3).
24
+ */
25
+ export declare function redirectUriAllowed(registered: string[], redirectUri: string): boolean;
26
+ /** Valida um documento de metadata e devolve os campos usados. Lança `invalid_client`. */
27
+ export declare function validateClientMetadata(fetchedFrom: string, doc: unknown, options?: {
28
+ allowHttp?: boolean;
29
+ }): Omit<PoppyClient, 'keys'>;
30
+ export interface PoppyClientRegistryOptions {
31
+ /** Busca de JSON. Default: {@link safeFetchJson}. */
32
+ fetchJson?: JsonFetcher;
33
+ now?: () => number;
34
+ }
35
+ /**
36
+ * Resolve e valida agentes pelo `client_id`, com cache (respeita `max-age`,
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).
39
+ */
40
+ export declare class PoppyClientRegistry {
41
+ #private;
42
+ constructor(cfg: ResolvedPoppyConfig, options?: PoppyClientRegistryOptions);
43
+ /**
44
+ * O agente, ou `invalid_client`: `client_id` não é HTTPS, bloqueado, não
45
+ * registrado (quando o app exige registro), metadata inválida/inalcançável.
46
+ */
47
+ resolve(clientId: unknown): Promise<PoppyClient>;
48
+ /** Nome de exibição sem falhar (console de conta): metadata em cache/buscada, ou o host. */
49
+ displayName(clientId: string): Promise<string>;
50
+ }
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Identidade do personal agent no Poppy (§4.1): o `client_id` é uma URL HTTPS
3
+ * que devolve o documento de metadata do agente (OAuth Client ID Metadata
4
+ * Document). Buscamos (à prova de SSRF), validamos, guardamos em cache e
5
+ * importamos as chaves públicas do `jwks_uri`.
6
+ */
7
+ import { createLocalJWKSet } from 'jose';
8
+ 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
+ function hostOf(url) {
18
+ try {
19
+ return new URL(url).host.toLowerCase();
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
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
+ /** Loopback redirect URI (RFC 8252 §7.3): `http`, IP de loopback literal, sem fragmento. */
38
+ function isLoopbackRedirect(value) {
39
+ if (typeof value !== 'string')
40
+ return false;
41
+ try {
42
+ const url = new URL(value);
43
+ return (url.protocol === 'http:' &&
44
+ (url.hostname === '127.0.0.1' || url.hostname === '[::1]') &&
45
+ !url.username &&
46
+ !url.password &&
47
+ !url.hash);
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ }
53
+ /**
54
+ * `redirect_uri` igual a uma entrada de `redirect_uris`; numa loopback redirect URI a porta não
55
+ * conta (§4.2, RFC 8252 §7.3).
56
+ */
57
+ export function redirectUriAllowed(registered, redirectUri) {
58
+ if (registered.includes(redirectUri))
59
+ return true;
60
+ if (!isLoopbackRedirect(redirectUri))
61
+ return false;
62
+ const withoutPort = (value) => {
63
+ const url = new URL(value);
64
+ url.port = '';
65
+ return url.toString();
66
+ };
67
+ return registered.some((r) => isLoopbackRedirect(r) && withoutPort(r) === withoutPort(redirectUri));
68
+ }
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
+ /** Valida um documento de metadata e devolve os campos usados. Lança `invalid_client`. */
81
+ export function validateClientMetadata(fetchedFrom, doc, options = {}) {
82
+ const allowHttp = options.allowHttp === true;
83
+ const bad = (why) => new PoppyError('invalid_client', `client metadata: ${why}`);
84
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc))
85
+ throw bad('not a JSON object');
86
+ const d = doc;
87
+ if (d.client_id !== fetchedFrom)
88
+ throw bad('client_id must equal the URL it was fetched from');
89
+ const host = hostOf(fetchedFrom);
90
+ if (!isHttpsUrl(d.jwks_uri, allowHttp) || hostOf(d.jwks_uri) !== host) {
91
+ throw bad('jwks_uri must be an HTTPS URL on the same domain as client_id');
92
+ }
93
+ const redirects = d.redirect_uris ?? [];
94
+ if (!Array.isArray(redirects))
95
+ throw bad('redirect_uris must be an array');
96
+ for (const uri of redirects) {
97
+ if (isLoopbackRedirect(uri))
98
+ continue;
99
+ if (!isHttpsUrl(uri, allowHttp) || hostOf(uri) !== host) {
100
+ throw bad('every redirect_uri must be an HTTPS URL on the same domain as client_id, or a loopback URI');
101
+ }
102
+ }
103
+ if (d.token_endpoint_auth_method !== 'private_key_jwt') {
104
+ throw bad('token_endpoint_auth_method must be private_key_jwt');
105
+ }
106
+ if (d.jwks !== undefined)
107
+ throw bad('keys are published at jwks_uri only');
108
+ const name = typeof d.client_name === 'string' && d.client_name.trim() ? d.client_name : host;
109
+ const extensions = d.extensions && typeof d.extensions === 'object' && !Array.isArray(d.extensions)
110
+ ? d.extensions
111
+ : {};
112
+ return {
113
+ clientId: fetchedFrom,
114
+ name: name.slice(0, 200),
115
+ logoUri: isHttpsUrl(d.logo_uri, allowHttp) ? d.logo_uri : null,
116
+ jwksUri: d.jwks_uri,
117
+ redirectUris: redirects,
118
+ extensions,
119
+ };
120
+ }
121
+ /** Só chaves públicas (§4.1) e pelo menos uma. */
122
+ function validateJwks(doc) {
123
+ const keys = doc?.keys;
124
+ if (!Array.isArray(keys) || keys.length === 0) {
125
+ throw new PoppyError('invalid_client', 'jwks_uri must serve a non-empty JWK set');
126
+ }
127
+ for (const key of keys) {
128
+ if (!key || typeof key !== 'object')
129
+ throw new PoppyError('invalid_client', 'invalid JWK');
130
+ const k = key;
131
+ if ('d' in k || 'p' in k || 'q' in k || k.kty === 'oct') {
132
+ throw new PoppyError('invalid_client', 'jwks_uri must contain only public keys');
133
+ }
134
+ }
135
+ return { keys: keys };
136
+ }
137
+ /**
138
+ * Resolve e valida agentes pelo `client_id`, com cache (respeita `max-age`,
139
+ * 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).
141
+ */
142
+ export class PoppyClientRegistry {
143
+ #cfg;
144
+ #fetch;
145
+ #now;
146
+ #clients = new Map();
147
+ #jwks = new Map();
148
+ constructor(cfg, options = {}) {
149
+ 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;
156
+ }
157
+ /**
158
+ * O agente, ou `invalid_client`: `client_id` não é HTTPS, bloqueado, não
159
+ * registrado (quando o app exige registro), metadata inválida/inalcançável.
160
+ */
161
+ async resolve(clientId) {
162
+ if (!isHttpsUrl(clientId, this.#cfg.allowInsecureClientIds)) {
163
+ throw new PoppyError('invalid_client', 'client_id must be an HTTPS URL');
164
+ }
165
+ if (await this.#cfg.clients.isBlocked(clientId)) {
166
+ throw new PoppyError('invalid_client', 'client_id is blocked');
167
+ }
168
+ if (this.#cfg.clients.requireRegistration &&
169
+ !(await this.#cfg.clients.isRegistered(clientId))) {
170
+ throw new PoppyError('invalid_client', 'client_id is not registered');
171
+ }
172
+ const meta = await this.#metadata(clientId);
173
+ return { ...meta, keys: this.#keySet(meta.jwksUri) };
174
+ }
175
+ /** Nome de exibição sem falhar (console de conta): metadata em cache/buscada, ou o host. */
176
+ async displayName(clientId) {
177
+ try {
178
+ return (await this.#metadata(clientId)).name;
179
+ }
180
+ catch {
181
+ return hostOf(clientId) ?? clientId;
182
+ }
183
+ }
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
+ /** `JWTVerifyGetKey` que relê o JWKS uma vez quando o `kid` é desconhecido (rotação). */
246
+ #keySet(jwksUri) {
247
+ return async (header, token) => {
248
+ const jwks = await this.#fetchJwks(jwksUri, false);
249
+ try {
250
+ return await createLocalJWKSet(jwks)(header, token);
251
+ }
252
+ catch (error) {
253
+ const refreshed = await this.#fetchJwks(jwksUri, true);
254
+ if (refreshed === jwks)
255
+ throw error;
256
+ return createLocalJWKSet(refreshed)(header, token);
257
+ }
258
+ };
259
+ }
260
+ }