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

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,29 @@
1
1
  # @adonis-agora/authkit-poppy
2
2
 
3
+ ## 1.0.0-rc.5
4
+
5
+ ### Major Changes
6
+
7
+ - [#544](https://github.com/DavideCarvalho/adonis-agora-authkit/pull/544) [`ccc5b61`](https://github.com/DavideCarvalho/adonis-agora-authkit/commit/ccc5b61ffc27bf38ada188b557eed0764bd1153c) Thanks [@DavideCarvalho](https://github.com/DavideCarvalho)! - Poppy 1.0. The package now implements the published Personal Agent Protocol 1.0 and serves version `1.0` only; its version follows the spec version.
8
+
9
+ Breaking changes for apps:
10
+
11
+ - `agent.protocols[]` entries need a `description` (what the agent there can help with). An endpoint announced through the `@adonis-agora/poppy:endpoints` slot is published only with a `description` next to `conversations`.
12
+ - `feedback` and `excludedTasks` moved into `tasks` (`tasks.feedback`, `tasks.excludedTasks`, plus `tasks.skillIndex` and `tasks.resolve`); the package serves `GET /poppy/tasks` and lists it as `tasks.endpoint`. Pass `tasks: { endpoint }` to serve your own.
13
+ - `extensions` takes a list with one entry per version: `{ name: [{ version: '1', … }] }`.
14
+ - `poppy:browser-sign-in` is added to the scopes when browser join and sign-in are on; joining a browser with an access token needs it. `web.unscoped` (default `true`) and `web.disabled` are new.
15
+ - Requests verified with the Session header need `Poppy-Version: 1.x` (`version_unsupported` otherwise). Ended Sessions and account changes answer `session_ended`. Sessions are keyed by `client_id` + `sid` + User ID. Failures carry a `body` to send as JSON.
16
+ - Delegations are `poppy-delegation+jwt` in the `poppy_dlg` header.
17
+ - `assertionMaxLifetime` can't be lower than 300.
18
+
19
+ New: Pushed Authorization Requests (`POST /poppy/oauth/par`, `par: { required }`), refresh tokens bound to the sign-in's DPoP key (`dpop.bindRefreshTokens`), `auth.disabled` when no sign-in type is on, `organization.domain` with its port, `scopes_supported` in the protected resource metadata, `resource=https://{domain}` for the default token, `protocolVersion` and `extensions` on the principal, and `verifyPoppyRequest(…, { extension })`. A new table, `auth_poppy_grant_keys`, is created with the others.
20
+
21
+ ## 0.3.1-rc.4
22
+
23
+ ### Patch Changes
24
+
25
+ - fix(deps): update dependency jose to v6.2.18 ([#535](https://github.com/DavideCarvalho/adonis-agora-authkit/issues/535))
26
+
3
27
  ## 0.3.1-rc.3
4
28
 
5
29
  ### Patch Changes
package/README.md CHANGED
@@ -1,12 +1,11 @@
1
1
  # @adonis-agora/authkit-poppy
2
2
 
3
- The [Personal Agent Protocol ("Poppy")](https://personalagentprotocol.org/docs/spec) for
3
+ The [Personal Agent Protocol ("Poppy") 1.0](https://personalagentprotocol.org/docs/1.0/spec) for
4
4
  [AuthKit](https://davidecarvalho.github.io/agora/docs/authkit): discovery (`poppy.json`), signed
5
5
  `Poppy-Session` agent sessions, Direct / Device / Mediated sign-in, DPoP, MCP tokens and browser
6
6
  sessions — as an extension of `@adonis-agora/authkit-server`.
7
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`.
8
+ > The package version follows the spec version it implements: `1.x` is Poppy `1.x`.
10
9
 
11
10
  ```sh
12
11
  node ace add @adonis-agora/authkit-poppy
package/build/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @adonis-agora/authkit-poppy — the Personal Agent Protocol ("Poppy", Draft 0.3) for AuthKit, as a
2
+ * @adonis-agora/authkit-poppy — the Personal Agent Protocol ("Poppy", version 1.0) for AuthKit, as a
3
3
  * `personalAgents.extensions` entry of `@adonis-agora/authkit-server`.
4
4
  *
5
- * Experimental: this package stays on 0.x and follows the draft spec, so any minor may break.
5
+ * The package version follows the spec version: 1.x implements Poppy 1.x.
6
6
  */
7
7
  export { isBlockedAddress, SafeFetchError, safeFetchJson } from '@adonis-agora/authkit-server';
8
8
  export { configure, POPPY_CONFIG_SNIPPET } from './configure.js';
package/build/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @adonis-agora/authkit-poppy — the Personal Agent Protocol ("Poppy", Draft 0.3) for AuthKit, as a
2
+ * @adonis-agora/authkit-poppy — the Personal Agent Protocol ("Poppy", version 1.0) for AuthKit, as a
3
3
  * `personalAgents.extensions` entry of `@adonis-agora/authkit-server`.
4
4
  *
5
- * Experimental: this package stays on 0.x and follows the draft spec, so any minor may break.
5
+ * The package version follows the spec version: 1.x implements Poppy 1.x.
6
6
  */
7
7
  // A busca à prova de SSRF mora no `@adonis-agora/authkit-server` (Client ID Metadata Documents).
8
8
  export { isBlockedAddress, SafeFetchError, safeFetchJson } from '@adonis-agora/authkit-server';
@@ -14,7 +14,6 @@ export interface PoppyClient {
14
14
  logoUri: string | null;
15
15
  jwksUri: string;
16
16
  redirectUris: string[];
17
- extensions: Record<string, unknown>;
18
17
  /** Chaves públicas do `jwks_uri`. */
19
18
  keys: JWTVerifyGetKey;
20
19
  }
@@ -76,16 +76,12 @@ export function validateClientMetadata(fetchedFrom, doc, options = {}) {
76
76
  if (d.jwks !== undefined)
77
77
  throw bad('keys are published at jwks_uri only');
78
78
  const name = typeof d.client_name === 'string' && d.client_name.trim() ? d.client_name : host;
79
- const extensions = d.extensions && typeof d.extensions === 'object' && !Array.isArray(d.extensions)
80
- ? d.extensions
81
- : {};
82
79
  return {
83
80
  clientId: fetchedFrom,
84
81
  name: name.slice(0, 200),
85
82
  logoUri: isHttpsUrl(d.logo_uri, allowHttp) ? d.logo_uri : null,
86
83
  jwksUri: d.jwks_uri,
87
84
  redirectUris: redirects,
88
- extensions,
89
85
  };
90
86
  }
91
87
  /** Só chaves públicas (§4.1) e pelo menos uma. */
@@ -118,8 +114,8 @@ export class PoppyClientRegistry {
118
114
  this.#cfg = cfg;
119
115
  const fetchJson = options.fetchJson ??
120
116
  (cfg.allowInsecureClientIds
121
- ? (url) => insecureDevFetchJson(url, { userAgent: 'authkit-poppy/0.3' })
122
- : (url) => safeFetchJson(url, { userAgent: 'authkit-poppy/0.3' }));
117
+ ? (url) => insecureDevFetchJson(url, { userAgent: 'authkit-poppy/1.0' })
118
+ : (url) => safeFetchJson(url, { userAgent: 'authkit-poppy/1.0' }));
123
119
  const common = { fetchJson, now: options.now, ttl: { min: 60, max: 86_400, fallback: 3600 } };
124
120
  this.#clients = new MetadataDocumentCache({
125
121
  ...common,
@@ -1,8 +1,6 @@
1
1
  /**
2
- * @experimental Draft 0.3 da spec (https://personalagentprotocol.org/docs/spec) — pode mudar de forma
3
- * incompatível fora de majors enquanto a spec for draft.
4
- *
5
- * Personal Agent Protocol ("Poppy", Draft 0.3 — https://personalagentprotocol.org) — config.
2
+ * Personal Agent Protocol ("Poppy", versão 1.0 — https://personalagentprotocol.org/docs/1.0/spec) —
3
+ * config.
6
4
  *
7
5
  * Poppy é o segundo protocolo de personal agents ao lado do PACT. O agente se identifica pelo
8
6
  * `client_id` (uma URL HTTPS com o documento de metadata dele) e declara a Session em cada request
@@ -71,9 +69,6 @@ export type PoppyMediatedResult = {
71
69
  } | {
72
70
  status: 'denied';
73
71
  };
74
- /**
75
- * @experimental Poppy (Personal Agent Protocol) Draft 0.3 — pode mudar de forma incompatível enquanto a spec for draft.
76
- */
77
72
  export interface PoppyMediatedConfigInput {
78
73
  /** Campos pedidos (extensão Mediated Sign-In). Ex.: `[{ name: 'email', … }, { name: 'password', secret: true, … }]`. */
79
74
  fields: PoppyMediatedField[];
@@ -102,6 +97,11 @@ export interface PoppyAgentProtocolEntry {
102
97
  type: string;
103
98
  /** URL HTTPS do endpoint de conversas. */
104
99
  endpoint: string;
100
+ /**
101
+ * O que o agente deste endpoint ajuda a fazer (§3.1, §8.1) — o personal agent usa para decidir se
102
+ * uma conversa serve à tarefa. Pode dizer que ajuda com qualquer coisa. Obrigatório.
103
+ */
104
+ description: string;
105
105
  /** A interface precisa da conta desde o início (§3.2). Default: `session`. */
106
106
  access?: 'session' | 'signed_in';
107
107
  /**
@@ -123,6 +123,62 @@ export interface PoppyApiEntry {
123
123
  /** Como em `agent.protocols`. MCP sempre exige o próprio `url` (§7). */
124
124
  resource?: string;
125
125
  }
126
+ /** Uma tarefa que a empresa escolheu não oferecer pelo protocolo (§9.1). */
127
+ export interface PoppyExcludedTask {
128
+ /** A tarefa, numa frase curta: "Send a wire transfer". */
129
+ task: string;
130
+ /** Outro jeito de fazer a tarefa (§9.2). */
131
+ alternative?: PoppyAlternative;
132
+ }
133
+ /** Outro jeito de fazer uma tarefa (§9.2): `instructions`, `references` ou os dois. */
134
+ export interface PoppyAlternative {
135
+ instructions?: string;
136
+ references?: ({
137
+ type: 'openapi';
138
+ url: string;
139
+ operation_id: string;
140
+ } | {
141
+ type: 'mcp';
142
+ url: string;
143
+ tool: string;
144
+ } | {
145
+ type: 'web';
146
+ url: string;
147
+ })[];
148
+ }
149
+ /** A resposta do `tasks.endpoint` (§9). */
150
+ export interface PoppyTasksResponse {
151
+ excluded_tasks?: PoppyExcludedTask[];
152
+ /** Índice do Agent Skills discovery (schema 0.2.0) — §9.4. */
153
+ skill_index?: Record<string, unknown>;
154
+ feedback?: {
155
+ endpoint: string;
156
+ };
157
+ }
158
+ /** Cobertura de tarefas (§9): o que sai no `tasks.endpoint`. */
159
+ export interface PoppyTasksConfigInput {
160
+ /**
161
+ * Um `tasks.endpoint` que o próprio app serve, publicado como está. Sem ele, a lib serve
162
+ * `{prefix}/tasks` com os campos abaixo.
163
+ */
164
+ endpoint?: string;
165
+ /** Tarefas não oferecidas (§9.1). */
166
+ excludedTasks?: PoppyExcludedTask[];
167
+ /** Índice de skills (§9.4), no formato do Agent Skills discovery 0.2.0. */
168
+ skillIndex?: Record<string, unknown>;
169
+ /** Endpoint de feedback que o app implementa (§9.3). */
170
+ feedback?: {
171
+ endpoint: string;
172
+ };
173
+ /**
174
+ * Resposta por Session (ex.: testar uma skill com parte dos usuários). Recebe a Session já
175
+ * verificada e a resposta montada dos campos acima; a resposta sai `Cache-Control: no-store`.
176
+ */
177
+ resolve?: (input: {
178
+ principal: PoppyPrincipalBase;
179
+ response: PoppyTasksResponse;
180
+ }) => PoppyTasksResponse | Promise<PoppyTasksResponse>;
181
+ }
126
182
  /** Hook de login do navegador do agente (§6) para apps com sessão de login própria. */
127
183
  export type PoppyBrowserLogin = (ctx: HttpContext, input: {
128
184
  sessionId: string;
@@ -136,9 +192,6 @@ export type PoppyBrowserLogin = (ctx: HttpContext, input: {
136
192
  * Onde o protocolo guarda os `jti` já vistos (client assertions, Session JWTs,
137
193
  * provas DPoP) até expirarem. `claim` devolve `true` na
138
194
  * primeira vez que vê a chave e `false` num replay.
139
- *
140
- * @experimental Poppy (Personal Agent Protocol) Draft 0.3 — acompanha a spec em desenvolvimento e PODE MUDAR
141
- * de forma incompatível fora de majors enquanto ela for draft.
142
195
  */
143
196
  export interface PoppyReplayStore {
144
197
  claim(key: string, expiresAt: Date): Promise<boolean>;
@@ -160,9 +213,6 @@ export interface PoppyClientsConfigInput {
160
213
  /** `client_id`s bloqueados (revogados por mau uso). */
161
214
  blocked?: string[] | ((clientId: string) => boolean | Promise<boolean>);
162
215
  }
163
- /**
164
- * @experimental Poppy (Personal Agent Protocol) Draft 0.3 — pode mudar de forma incompatível enquanto a spec for draft.
165
- */
166
216
  export interface PoppyConfigInput {
167
217
  /** Nome exibido e domínio (`organization` do poppy.json). */
168
218
  organization: {
@@ -201,28 +251,40 @@ export interface PoppyConfigInput {
201
251
  };
202
252
  /** APIs do app que aceitam o header da Session (§7). */
203
253
  apis?: PoppyApiEntry[];
204
- /** Endpoint de feedback que o app implementa (§9.3). */
205
- feedback?: {
206
- endpoint: string;
207
- };
208
- /** Documento público das tarefas que a empresa não oferece (§9.1). */
209
- excludedTasks?: {
210
- url: string;
211
- };
254
+ /** Cobertura de tarefas (§9): tarefas excluídas, skills e feedback, no `tasks.endpoint`. */
255
+ tasks?: PoppyTasksConfigInput;
212
256
  /**
213
- * Site (§6). Default: liga o `browser_session_endpoint`. `false` desliga. `login`
257
+ * Site (§6). Default: liga o `browser_session_endpoint`. `false` não publica `web`. `login`
214
258
  * substitui o login default (sessão de conta do authkit + `adonisAuth.guard`). `redirectTo` é
215
259
  * a página do site para onde o navegador vai depois de entrar (path). Default: `/`.
260
+ *
261
+ * - `disabled: true` pede aos personal agents que não naveguem o site num navegador
262
+ * (`web.disabled`); desliga o `browser_session_endpoint`. Liste `agent` ou `apis`.
263
+ * - `unscoped` (`web.unscoped`): o site não aplica os scopes do cookie, então
264
+ * `poppy:browser-sign-in` dá todo o acesso da conta no site. Default: `true` — o login default
265
+ * entra na conta inteira. Passe `false` só com um `login` que aplica os scopes.
216
266
  */
217
267
  web?: false | {
218
268
  browserSession?: boolean;
269
+ disabled?: boolean;
270
+ unscoped?: boolean;
219
271
  login?: PoppyBrowserLogin;
220
272
  redirectTo?: string;
221
273
  };
222
- /** Extensões suportadas (§3.3), publicadas como estão. */
223
- extensions?: Record<string, {
274
+ /**
275
+ * Extensões suportadas (§3.3), publicadas como estão: uma entrada por versão.
276
+ * Ex.: `{ 'example.com/gift-wrap': [{ version: '1', endpoint: 'https://…' }] }`.
277
+ */
278
+ extensions?: Record<string, ({
224
279
  version: string;
225
- } & Record<string, unknown>>;
280
+ } & Record<string, unknown>)[]>;
281
+ /**
282
+ * Pushed Authorization Requests (RFC 9126, §4.2) no Direct Sign-In. Default: oferecido.
283
+ * `{ required: true }` exige (`require_pushed_authorization_requests`). `false` não oferece.
284
+ */
285
+ par?: boolean | {
286
+ required?: boolean;
287
+ };
226
288
  /** Registro/allowlist/blocklist de agentes. */
227
289
  clients?: PoppyClientsConfigInput;
228
290
  /**
@@ -245,7 +307,10 @@ export interface PoppyConfigInput {
245
307
  deviceCodeTtl?: number;
246
308
  /** Intervalo mínimo de polling do device flow, em segundos. Default: 5. */
247
309
  pollInterval?: number;
248
- /** Vida máxima das client assertions (`exp - iat`), em segundos. Default: 300. */
310
+ /**
311
+ * Vida máxima das client assertions (`exp - iat`), em segundos. Default: 300. Nunca menos que 300:
312
+ * a spec proíbe recusar uma assertion de até 5 minutos (§4.1).
313
+ */
249
314
  assertionMaxLifetime?: number;
250
315
  /** Session JWT (§5.3). */
251
316
  sessionJwt?: {
@@ -262,6 +327,11 @@ export interface PoppyConfigInput {
262
327
  maxAge?: number;
263
328
  /** Algoritmos aceitos na prova. Default: `['ES256']`. */
264
329
  algorithms?: string[];
330
+ /**
331
+ * Prende o refresh token à chave DPoP do sign-in (§4.4): um refresh sem prova ou com outra
332
+ * chave leva `invalid_grant`. Só vale para sign-ins feitos com prova. Default: true.
333
+ */
334
+ bindRefreshTokens?: boolean;
265
335
  };
266
336
  /**
267
337
  * Onde guardar os `jti` vistos. Default: `'database'` (tabela lib-owned
@@ -296,9 +366,6 @@ export interface PoppyConfigInput {
296
366
  }
297
367
  /**
298
368
  * O que uma request verificada autoriza — sem o `actor`.
299
- *
300
- * @experimental Poppy (Personal Agent Protocol) Draft 0.3 — acompanha a spec em desenvolvimento e PODE MUDAR
301
- * de forma incompatível fora de majors enquanto ela for draft.
302
369
  */
303
370
  export interface PoppyPrincipalBase {
304
371
  /** User ID que o personal agent deu ao usuário NESTE app (opaco, estável). */
@@ -311,8 +378,15 @@ export interface PoppyPrincipalBase {
311
378
  clientId: string;
312
379
  /** Scopes do access token. Vazio deslogado. */
313
380
  scopes: string[];
314
- /** A Session, única por `client_id` + `sid`. */
381
+ /** A Session, única por `client_id` + `sid` + User ID (§5.3). */
315
382
  sessionId: string;
383
+ /** A versão do protocolo que a request declarou em `Poppy-Version` (`'1.0'`, `'1.1'`…). */
384
+ protocolVersion: string;
385
+ /**
386
+ * As extensões que a request declarou em `Poppy-Extensions` e que este app lista, `nome → versão`
387
+ * (§3.3, §3.4).
388
+ */
389
+ extensions: Record<string, string>;
316
390
  signedIn: boolean;
317
391
  /** `resource` para o qual o token foi emitido (RFC 8707), ou `null`. */
318
392
  resource: string | null;
@@ -350,20 +424,27 @@ export interface ResolvedPoppyConfig {
350
424
  protocols: PoppyAgentProtocolEntry[];
351
425
  } | null;
352
426
  apis: PoppyApiEntry[];
353
- feedback: {
354
- endpoint: string;
355
- } | null;
356
- excludedTasks: {
357
- url: string;
427
+ /** `null` = sem `tasks` no poppy.json. */
428
+ tasks: {
429
+ /** Endpoint do próprio app; `null` = a lib serve `{prefix}/tasks`. */
430
+ endpoint: string | null;
431
+ response: PoppyTasksResponse;
432
+ resolve?: PoppyTasksConfigInput['resolve'];
358
433
  } | null;
359
434
  web: {
360
435
  browserSession: boolean;
436
+ disabled: boolean;
437
+ unscoped: boolean;
361
438
  login?: PoppyBrowserLogin;
362
439
  redirectTo: string;
363
440
  } | null;
364
- extensions: Record<string, {
441
+ extensions: Record<string, ({
365
442
  version: string;
366
- } & Record<string, unknown>>;
443
+ } & Record<string, unknown>)[]>;
444
+ /** `null` = sem PAR. */
445
+ par: {
446
+ required: boolean;
447
+ } | null;
367
448
  clients: {
368
449
  requireRegistration: boolean;
369
450
  isRegistered: (clientId: string) => Promise<boolean>;
@@ -389,6 +470,7 @@ export interface ResolvedPoppyConfig {
389
470
  requireNonce: boolean;
390
471
  maxAge: number;
391
472
  algorithms: string[];
473
+ bindRefreshTokens: boolean;
392
474
  };
393
475
  replay: 'database' | 'memory' | {
394
476
  redis: string;
@@ -403,6 +485,14 @@ export interface ResolvedPoppyConfig {
403
485
  }
404
486
  export declare function normalizePoppyPrefix(prefix: string | undefined): string;
405
487
  export declare function resolvePoppyConfig(input: PoppyConfigInput | undefined, fallbackScopes: Record<string, string> | undefined): ResolvedPoppyConfig | undefined;
488
+ /** O único scope que o protocolo define: o navegador do agente entra logado no site (§6). */
489
+ export declare const BROWSER_SIGN_IN_SCOPE = "poppy:browser-sign-in";
490
+ /** A descrição quando o site aplica os scopes do cookie. */
491
+ export declare const BROWSER_SIGN_IN_SCOPED_DESCRIPTION = "Use the website signed in, with the other access you approve";
492
+ /** A descrição quando o site dá a conta inteira (`web.unscoped`, §6). */
493
+ export declare const BROWSER_SIGN_IN_UNSCOPED_DESCRIPTION = "Browse the website, and see and do anything your account can do there";
494
+ /** O nome da extensão Mediated Sign-In em `extensions`. */
495
+ export declare const MEDIATED_SIGN_IN_EXTENSION = "mediated-sign-in";
406
496
  /** The scope that lets a personal agent use the app's Agora developer tools over MCP. */
407
497
  export declare const AGORA_DEV_SCOPE = "agora:dev";
408
498
  /** The catalog description of {@link AGORA_DEV_SCOPE} (the consent screen shows a translated text). */
@@ -129,10 +129,21 @@ export function resolvePoppyConfig(input, fallbackScopes) {
129
129
  if (all.length === 0 && (signInInput.direct !== false || signInInput.device !== false)) {
130
130
  fail('nenhum scope: declare `scopes` ou desligue signIn.direct e signIn.device.');
131
131
  }
132
+ const legacy = input;
133
+ if (legacy.feedback !== undefined || legacy.excludedTasks !== undefined) {
134
+ fail('feedback e excludedTasks foram para `tasks` (tasks.feedback, tasks.excludedTasks).');
135
+ }
136
+ const offersSignIn = signInInput.direct !== false || signInInput.device !== false || !!signInInput.mediated;
132
137
  for (const entry of input.agent?.protocols ?? []) {
133
138
  if (!entry.type)
134
139
  fail('agent.protocols[].type é obrigatório.');
135
140
  absoluteUrl(entry.endpoint, 'agent.protocols[].endpoint');
141
+ if (typeof entry.description !== 'string' || !entry.description.trim()) {
142
+ fail('agent.protocols[].description é obrigatório (o que o agente ajuda a fazer).');
143
+ }
144
+ if (entry.access === 'signed_in' && !offersSignIn) {
145
+ fail('agent.protocols[].access signed_in exige um tipo de sign-in.');
146
+ }
136
147
  if (entry.resource)
137
148
  absoluteUrl(entry.resource, 'agent.protocols[].resource');
138
149
  if (entry.access && entry.access !== 'session' && entry.access !== 'signed_in') {
@@ -148,18 +159,61 @@ export function resolvePoppyConfig(input, fallbackScopes) {
148
159
  if (typeof api.description !== 'string')
149
160
  fail('apis[].description é obrigatório.');
150
161
  }
151
- if (input.feedback)
152
- absoluteUrl(input.feedback.endpoint, 'feedback.endpoint');
153
- if (input.excludedTasks)
154
- absoluteUrl(input.excludedTasks.url, 'excludedTasks.url');
162
+ const tasks = resolveTasks(input.tasks, input.apis ?? []);
155
163
  const redirectTo = input.web ? (input.web.redirectTo ?? '/') : '/';
156
164
  if (!redirectTo.startsWith('/') || redirectTo.startsWith('//')) {
157
165
  fail('web.redirectTo precisa ser um path do site.');
158
166
  }
159
- for (const name of Object.keys(input.extensions ?? {})) {
160
- if (typeof input.extensions[name]?.version !== 'string') {
161
- fail(`extensions.${name}.version é obrigatório (string).`);
167
+ let web = null;
168
+ if (input.web !== false) {
169
+ const disabled = input.web?.disabled === true;
170
+ if (disabled && input.web?.browserSession === true) {
171
+ fail('web.disabled não combina com web.browserSession: não liste o browser_session_endpoint.');
162
172
  }
173
+ const browserSession = !disabled && input.web?.browserSession !== false;
174
+ if (input.web?.unscoped === true && !browserSession) {
175
+ fail('web.unscoped exige o browser_session_endpoint (web.browserSession).');
176
+ }
177
+ web = {
178
+ browserSession,
179
+ disabled,
180
+ unscoped: browserSession && input.web?.unscoped !== false,
181
+ login: input.web?.login,
182
+ redirectTo,
183
+ };
184
+ }
185
+ const extensions = {};
186
+ for (const [name, entries] of Object.entries(input.extensions ?? {})) {
187
+ if (name === MEDIATED_SIGN_IN_EXTENSION) {
188
+ fail(`extensions.${name} é publicada por signIn.mediated.`);
189
+ }
190
+ if (!Array.isArray(entries) || entries.length === 0) {
191
+ fail(`extensions.${name} precisa ser uma lista, uma entrada por versão (§3.3).`);
192
+ }
193
+ for (const entry of entries) {
194
+ if (typeof entry?.version !== 'string' || !entry.version) {
195
+ fail(`extensions.${name}[].version é obrigatório (string).`);
196
+ }
197
+ }
198
+ extensions[name] = entries.map((e) => ({ ...e }));
199
+ }
200
+ // `poppy:browser-sign-in` (§4.7, §6): quem lista o browser_session_endpoint e oferece sign-in
201
+ // precisa suportá-lo. No site que não aplica os scopes, ele dá a conta inteira — e diz isso.
202
+ if (web?.browserSession && offersSignIn && !(BROWSER_SIGN_IN_SCOPE in scopes)) {
203
+ scopes[BROWSER_SIGN_IN_SCOPE] = web.unscoped
204
+ ? BROWSER_SIGN_IN_UNSCOPED_DESCRIPTION
205
+ : BROWSER_SIGN_IN_SCOPED_DESCRIPTION;
206
+ if (web.unscoped && !(BROWSER_SIGN_IN_SCOPE in scopeHints)) {
207
+ scopeHints[BROWSER_SIGN_IN_SCOPE] = { changes: 'irreversible', personal_data: true };
208
+ }
209
+ }
210
+ const catalog = Object.keys(scopes);
211
+ const withBrowserScope = (type) => type && BROWSER_SIGN_IN_SCOPE in scopes && !type.scopes.includes(BROWSER_SIGN_IN_SCOPE)
212
+ ? { scopes: [...type.scopes, BROWSER_SIGN_IN_SCOPE] }
213
+ : type;
214
+ const assertionMaxLifetime = positive(input.assertionMaxLifetime, 300, 'assertionMaxLifetime');
215
+ if (assertionMaxLifetime < 300) {
216
+ fail('assertionMaxLifetime precisa ser >= 300: a spec proíbe recusar assertions de até 5 min.');
163
217
  }
164
218
  const dpopAlgs = input.dpop?.algorithms ?? ['ES256'];
165
219
  if (dpopAlgs.length === 0 || dpopAlgs.some((a) => a === 'none' || a.startsWith('HS'))) {
@@ -186,22 +240,18 @@ export function resolvePoppyConfig(input, fallbackScopes) {
186
240
  scopes,
187
241
  scopeHints,
188
242
  signIn: {
189
- direct: typeScopes(signInInput.direct, all, 'direct'),
190
- device: typeScopes(signInInput.device, all, 'device'),
243
+ direct: withBrowserScope(typeScopes(signInInput.direct, catalog, 'direct')),
244
+ device: withBrowserScope(typeScopes(signInInput.device, catalog, 'device')),
191
245
  mediated,
192
246
  },
193
247
  agent: input.agent?.protocols?.length ? { protocols: [...input.agent.protocols] } : null,
194
248
  apis: [...(input.apis ?? [])],
195
- feedback: input.feedback ?? null,
196
- excludedTasks: input.excludedTasks ?? null,
197
- web: input.web === false
249
+ tasks,
250
+ web,
251
+ extensions,
252
+ par: input.par === false || signInInput.direct === false
198
253
  ? null
199
- : {
200
- browserSession: input.web?.browserSession !== false,
201
- login: input.web?.login,
202
- redirectTo,
203
- },
204
- extensions: { ...(input.extensions ?? {}) },
254
+ : { required: typeof input.par === 'object' && input.par.required === true },
205
255
  clients: {
206
256
  requireRegistration: input.clients?.requireRegistration === true,
207
257
  isRegistered: membership(input.clients?.registered),
@@ -216,13 +266,14 @@ export function resolvePoppyConfig(input, fallbackScopes) {
216
266
  authorizationCodeTtl: positive(input.authorizationCodeTtl, 60, 'authorizationCodeTtl'),
217
267
  deviceCodeTtl: positive(input.deviceCodeTtl, 600, 'deviceCodeTtl'),
218
268
  pollInterval: positive(input.pollInterval, 5, 'pollInterval'),
219
- assertionMaxLifetime: positive(input.assertionMaxLifetime, 300, 'assertionMaxLifetime'),
269
+ assertionMaxLifetime,
220
270
  sessionJwt: { maxAge: positive(input.sessionJwt?.maxAge, 60, 'sessionJwt.maxAge') },
221
271
  dpop: {
222
272
  required: input.dpop?.required === true,
223
273
  requireNonce: input.dpop?.requireNonce === true,
224
274
  maxAge: positive(input.dpop?.maxAge, 60, 'dpop.maxAge'),
225
275
  algorithms: [...dpopAlgs],
276
+ bindRefreshTokens: input.dpop?.bindRefreshTokens !== false,
226
277
  },
227
278
  replay: input.replay ?? 'database',
228
279
  rateLimit,
@@ -232,6 +283,76 @@ export function resolvePoppyConfig(input, fallbackScopes) {
232
283
  resolved.devTools = input.devTools ?? null;
233
284
  return input.devTools === true ? withAgoraDevScope(resolved, input) : resolved;
234
285
  }
286
+ /** O único scope que o protocolo define: o navegador do agente entra logado no site (§6). */
287
+ export const BROWSER_SIGN_IN_SCOPE = 'poppy:browser-sign-in';
288
+ /** A descrição quando o site aplica os scopes do cookie. */
289
+ export const BROWSER_SIGN_IN_SCOPED_DESCRIPTION = 'Use the website signed in, with the other access you approve';
290
+ /** A descrição quando o site dá a conta inteira (`web.unscoped`, §6). */
291
+ export const BROWSER_SIGN_IN_UNSCOPED_DESCRIPTION = 'Browse the website, and see and do anything your account can do there';
292
+ /** O nome da extensão Mediated Sign-In em `extensions`. */
293
+ export const MEDIATED_SIGN_IN_EXTENSION = 'mediated-sign-in';
294
+ const SKILL_DIGEST = /^sha256:[0-9a-f]{64}$/;
295
+ function resolveTasks(input, apis) {
296
+ if (!input)
297
+ return null;
298
+ if (input.endpoint !== undefined) {
299
+ absoluteUrl(input.endpoint, 'tasks.endpoint');
300
+ if (input.excludedTasks || input.skillIndex || input.feedback || input.resolve) {
301
+ fail('tasks.endpoint é um endpoint do app: os demais campos de tasks ficam nele.');
302
+ }
303
+ return { endpoint: input.endpoint, response: {} };
304
+ }
305
+ const response = {};
306
+ if (input.excludedTasks) {
307
+ for (const item of input.excludedTasks) {
308
+ if (typeof item?.task !== 'string' || !item.task.trim()) {
309
+ fail('tasks.excludedTasks[].task é obrigatório.');
310
+ }
311
+ if (item.alternative)
312
+ validateAlternative(item.alternative, apis);
313
+ }
314
+ response.excluded_tasks = input.excludedTasks.map((t) => ({ ...t }));
315
+ }
316
+ if (input.skillIndex) {
317
+ const index = input.skillIndex;
318
+ if (typeof index.$schema !== 'string' || !Array.isArray(index.skills)) {
319
+ fail('tasks.skillIndex precisa de $schema e skills (Agent Skills discovery 0.2.0).');
320
+ }
321
+ for (const skill of index.skills) {
322
+ for (const field of ['name', 'description', 'type', 'url']) {
323
+ if (typeof skill?.[field] !== 'string' || !skill[field]) {
324
+ fail(`tasks.skillIndex.skills[].${field} é obrigatório.`);
325
+ }
326
+ }
327
+ if (typeof skill.digest !== 'string' || !SKILL_DIGEST.test(skill.digest)) {
328
+ fail('tasks.skillIndex.skills[].digest precisa ser sha256: + 64 hex minúsculos.');
329
+ }
330
+ }
331
+ response.skill_index = index;
332
+ }
333
+ if (input.feedback) {
334
+ absoluteUrl(input.feedback.endpoint, 'tasks.feedback.endpoint');
335
+ response.feedback = { endpoint: input.feedback.endpoint };
336
+ }
337
+ if (input.resolve !== undefined && typeof input.resolve !== 'function') {
338
+ fail('tasks.resolve precisa ser uma função.');
339
+ }
340
+ return { endpoint: null, response, resolve: input.resolve };
341
+ }
342
+ function validateAlternative(alternative, apis) {
343
+ const refs = alternative.references ?? [];
344
+ if (!alternative.instructions && refs.length === 0) {
345
+ fail('tasks.excludedTasks[].alternative precisa de instructions ou references (§9.2).');
346
+ }
347
+ for (const ref of refs) {
348
+ absoluteUrl(ref.url, 'tasks alternative references[].url');
349
+ if (ref.type === 'openapi' || ref.type === 'mcp') {
350
+ if (!apis.some((a) => a.type === ref.type && a.url === ref.url)) {
351
+ fail(`references[] ${ref.type} precisa apontar uma entrada de apis (${ref.url}).`);
352
+ }
353
+ }
354
+ }
355
+ }
235
356
  /** The scope that lets a personal agent use the app's Agora developer tools over MCP. */
236
357
  export const AGORA_DEV_SCOPE = 'agora:dev';
237
358
  /** The catalog description of {@link AGORA_DEV_SCOPE} (the consent screen shows a translated text). */
@@ -1,7 +1,8 @@
1
1
  import type { HttpContext } from '@adonisjs/core/http';
2
2
  /**
3
- * Endpoints do Poppy (§3, §4, §6): descoberta, protected resource metadata, metadata RFC 8414,
4
- * token, revogação, device authorization e a entrada do navegador na Session. Os POSTs são isentos
3
+ * Endpoints do Poppy (§3, §4, §6, §9): descoberta, protected resource metadata, metadata RFC 8414,
4
+ * token, PAR, revogação, device authorization, a entrada do navegador na Session e o
5
+ * `tasks.endpoint`. Os POSTs são isentos
5
6
  * de CSRF — `csrfExemptPaths` da extension, que o `authkitCsrfExceptions` do authkit lê.
6
7
  */
7
8
  export default class PoppyController {
@@ -12,6 +13,13 @@ export default class PoppyController {
12
13
  /** `GET /.well-known/oauth-authorization-server{prefix}` (RFC 8414 + `protected_resources`). */
13
14
  metadata(ctx: HttpContext): Promise<void>;
14
15
  token(ctx: HttpContext): Promise<void>;
16
+ /** `POST pushed_authorization_request_endpoint` (RFC 9126, §4.2): 201 com o `request_uri`. */
17
+ pushedAuthorization(ctx: HttpContext): Promise<void>;
18
+ /**
19
+ * `GET tasks.endpoint` (§9): com o header da Session, sem access token. Resposta por Session
20
+ * (`tasks.resolve`) sai `no-store`; a mesma para todos, `private`.
21
+ */
22
+ tasks(ctx: HttpContext): Promise<void>;
15
23
  deviceAuthorization(ctx: HttpContext): Promise<void>;
16
24
  /** RFC 7009: 200 também para token desconhecido. */
17
25
  revoke(ctx: HttpContext): Promise<void>;