@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.
- package/CHANGELOG.md +9 -0
- package/LICENSE +21 -0
- package/README.md +40 -2
- package/build/configure.d.ts +3 -0
- package/build/configure.js +43 -0
- package/build/index.d.ts +20 -0
- package/build/index.js +18 -0
- package/build/src/augmentations.d.ts +1 -0
- package/build/src/augmentations.js +1 -0
- package/build/src/client_registry.d.ts +50 -0
- package/build/src/client_registry.js +260 -0
- package/build/src/config.d.ts +396 -0
- package/build/src/config.js +228 -0
- package/build/src/controllers/poppy_consent_controller.d.ts +19 -0
- package/build/src/controllers/poppy_consent_controller.js +194 -0
- package/build/src/controllers/poppy_controller.d.ts +33 -0
- package/build/src/controllers/poppy_controller.js +219 -0
- package/build/src/dpop.d.ts +61 -0
- package/build/src/dpop.js +158 -0
- package/build/src/email_code_sign_in.d.ts +40 -0
- package/build/src/email_code_sign_in.js +142 -0
- package/build/src/errors.d.ts +25 -0
- package/build/src/errors.js +25 -0
- package/build/src/extension.d.ts +37 -0
- package/build/src/extension.js +167 -0
- package/build/src/messages.d.ts +20 -0
- package/build/src/messages.js +22 -0
- package/build/src/redirect_exact.d.ts +6 -0
- package/build/src/redirect_exact.js +11 -0
- package/build/src/replay.d.ts +25 -0
- package/build/src/replay.js +106 -0
- package/build/src/resource.d.ts +100 -0
- package/build/src/resource.js +122 -0
- package/build/src/runtime.d.ts +8 -0
- package/build/src/runtime.js +15 -0
- package/build/src/safe_fetch.d.ts +48 -0
- package/build/src/safe_fetch.js +262 -0
- package/build/src/service.d.ts +301 -0
- package/build/src/service.js +1488 -0
- package/build/src/session_jwt.d.ts +30 -0
- package/build/src/session_jwt.js +133 -0
- package/build/src/store.d.ts +106 -0
- package/build/src/store.js +261 -0
- package/build/src/tables.d.ts +27 -0
- package/build/src/tables.js +156 -0
- package/build/src/web_session.d.ts +43 -0
- package/build/src/web_session.js +120 -0
- package/package.json +70 -3
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type AuthAccount } from '@adonis-agora/authkit-server';
|
|
2
|
+
import type { PoppyMediatedConfigInput } from './config.js';
|
|
3
|
+
/** O que {@link PoppyEmailCodeSignInOptions.sendCode} recebe. */
|
|
4
|
+
export interface PoppySignInCodeEmail {
|
|
5
|
+
email: string;
|
|
6
|
+
code: string;
|
|
7
|
+
/** Nome do agente (metadata dele, ou o host do `client_id`). */
|
|
8
|
+
agentName: string;
|
|
9
|
+
expiresInMinutes: number;
|
|
10
|
+
}
|
|
11
|
+
export interface PoppyEmailCodeSignInOptions {
|
|
12
|
+
/** Scopes que este sign-in pode conceder. */
|
|
13
|
+
scopes: string[];
|
|
14
|
+
/** Validade do código, em segundos. Default: 600. */
|
|
15
|
+
codeTtl?: number;
|
|
16
|
+
/** Tentativas de código antes de `invalid_grant`. Default: 5. */
|
|
17
|
+
maxCodeAttempts?: number;
|
|
18
|
+
/**
|
|
19
|
+
* Quem pode entrar por aqui (ex.: só pacientes, não profissionais). `false` = recebe a
|
|
20
|
+
* resposta de conta inexistente. Default: toda conta ativa.
|
|
21
|
+
*/
|
|
22
|
+
eligible?: (account: AuthAccount) => boolean | Promise<boolean>;
|
|
23
|
+
/**
|
|
24
|
+
* Códigos por e-mail por hora, nesta instância — impede um agente de lotar a caixa de
|
|
25
|
+
* alguém. Acima disso a resposta é a mesma, sem e-mail. Default: 5.
|
|
26
|
+
*/
|
|
27
|
+
maxPerHour?: number;
|
|
28
|
+
/** Rótulo do campo que o agente mostra ao usuário. Default: `'Email address'`. */
|
|
29
|
+
label?: string;
|
|
30
|
+
/** Texto de `sentTo` a partir do e-mail mascarado. Default: `` `Email to ${masked}` ``. */
|
|
31
|
+
sentTo?: (masked: string) => string;
|
|
32
|
+
/**
|
|
33
|
+
* Envia o código você mesmo (era `mail.onPoppySignInCode` no `config/authkit.ts`). Sem ele, sai
|
|
34
|
+
* pelo mailer default do authkit, com o branding e o i18n dele (chaves `mail.poppy_sign_in.*`).
|
|
35
|
+
*/
|
|
36
|
+
sendCode?: (data: PoppySignInCodeEmail) => Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
/** `ana.souza@gmail.com` → `a***@gmail.com`: o bastante para a pessoa reconhecer. */
|
|
39
|
+
export declare function maskEmail(email: string): string;
|
|
40
|
+
export declare function poppyEmailCodeSignIn(options: PoppyEmailCodeSignInOptions): PoppyMediatedConfigInput;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @experimental Poppy (Personal Agent Protocol) Draft 0.3 — pode mudar de forma incompatível enquanto a spec for draft.
|
|
3
|
+
*
|
|
4
|
+
* Mediated Sign-In pronto (extensão `mediated-sign-in`): o agente pede o e-mail da conta, o authkit manda
|
|
5
|
+
* um código de 6 dígitos para ele e o agente devolve o código. Usa as contas
|
|
6
|
+
* (`accountStore`) e o e-mail (o mailer default do authkit, ou `sendCode`) — o app só liga:
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* personalAgents: {
|
|
10
|
+
* extensions: [poppy({ signIn: { mediated: poppyEmailCodeSignIn({ scopes: ['orders:read'] }) } })],
|
|
11
|
+
* }
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* Sem enumeração de contas: e-mail sem conta, conta desativada, conta recusada
|
|
15
|
+
* por `eligible` ou e-mail acima do limite recebem a MESMA resposta, sem código
|
|
16
|
+
* (`accountId: null`) — a lib recusa qualquer código como errado. O envio não é
|
|
17
|
+
* esperado, então o tempo de resposta também não denuncia.
|
|
18
|
+
*/
|
|
19
|
+
import { randomInt } from 'node:crypto';
|
|
20
|
+
import { sendAuthkitCodeEmail, supportsAccountStatus, } from '@adonis-agora/authkit-server';
|
|
21
|
+
import { poppyFor } from './runtime.js';
|
|
22
|
+
/** `ana.souza@gmail.com` → `a***@gmail.com`: o bastante para a pessoa reconhecer. */
|
|
23
|
+
export function maskEmail(email) {
|
|
24
|
+
const at = email.lastIndexOf('@');
|
|
25
|
+
const user = at > 0 ? email.slice(0, at) : '';
|
|
26
|
+
const domain = at > 0 ? email.slice(at + 1) : '';
|
|
27
|
+
if (!user || !domain)
|
|
28
|
+
return '***';
|
|
29
|
+
return `${user[0]}***@${domain}`;
|
|
30
|
+
}
|
|
31
|
+
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
32
|
+
const HOUR_MS = 3600 * 1000;
|
|
33
|
+
const MAX_TRACKED = 10_000;
|
|
34
|
+
export function poppyEmailCodeSignIn(options) {
|
|
35
|
+
const positive = (value, fallback, what) => {
|
|
36
|
+
if (value === undefined)
|
|
37
|
+
return fallback;
|
|
38
|
+
if (!Number.isFinite(value) || value < 1) {
|
|
39
|
+
throw new Error(`authkit-poppy: poppyEmailCodeSignIn ${what} precisa ser um número >= 1.`);
|
|
40
|
+
}
|
|
41
|
+
return Math.floor(value);
|
|
42
|
+
};
|
|
43
|
+
const codeTtl = positive(options.codeTtl, 600, 'codeTtl');
|
|
44
|
+
const maxPerHour = positive(options.maxPerHour, 5, 'maxPerHour');
|
|
45
|
+
const maxCodeAttempts = positive(options.maxCodeAttempts, 5, 'maxCodeAttempts');
|
|
46
|
+
const sentToText = options.sentTo ?? ((masked) => `Email to ${masked}`);
|
|
47
|
+
const sends = new Map();
|
|
48
|
+
/** `true` = ainda cabe um envio para este e-mail na última hora (e conta este). */
|
|
49
|
+
const claim = (email) => {
|
|
50
|
+
const now = Date.now();
|
|
51
|
+
const recent = (sends.get(email) ?? []).filter((t) => now - t < HOUR_MS);
|
|
52
|
+
if (recent.length >= maxPerHour) {
|
|
53
|
+
sends.set(email, recent);
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
recent.push(now);
|
|
57
|
+
sends.delete(email);
|
|
58
|
+
sends.set(email, recent);
|
|
59
|
+
if (sends.size > MAX_TRACKED)
|
|
60
|
+
sends.delete(sends.keys().next().value);
|
|
61
|
+
return true;
|
|
62
|
+
};
|
|
63
|
+
const eligibleAccount = async (ctx, email) => {
|
|
64
|
+
const service = await ctx.containerResolver.make('authkit.server');
|
|
65
|
+
const store = service.config.accountStore;
|
|
66
|
+
const account = await store.findByEmail(email);
|
|
67
|
+
if (!account)
|
|
68
|
+
return null;
|
|
69
|
+
if (supportsAccountStatus(store) && (await store.isDisabled(account.id)))
|
|
70
|
+
return null;
|
|
71
|
+
if (options.eligible) {
|
|
72
|
+
// Um `eligible` que lança vira "não elegível": um 500 só para algumas contas as denunciaria.
|
|
73
|
+
try {
|
|
74
|
+
if (!(await options.eligible(account)))
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
ctx.logger.error({ err: error }, 'authkit-poppy: poppyEmailCodeSignIn eligible lançou');
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return account;
|
|
83
|
+
};
|
|
84
|
+
return {
|
|
85
|
+
fields: [{ name: 'email', label: options.label ?? 'Email address', secret: false }],
|
|
86
|
+
scopes: options.scopes,
|
|
87
|
+
codeTtl,
|
|
88
|
+
maxCodeAttempts,
|
|
89
|
+
async verify({ credentials, clientId, ctx }) {
|
|
90
|
+
const email = (credentials.email ?? '').trim().toLowerCase();
|
|
91
|
+
if (!EMAIL.test(email))
|
|
92
|
+
return { status: 'failed' };
|
|
93
|
+
const sentTo = sentToText(maskEmail(email));
|
|
94
|
+
const decoy = { status: 'code_required', accountId: null, sentTo };
|
|
95
|
+
// O limite conta para qualquer e-mail — com ou sem conta, a resposta não muda.
|
|
96
|
+
if (!claim(email))
|
|
97
|
+
return decoy;
|
|
98
|
+
const account = await eligibleAccount(ctx, email);
|
|
99
|
+
if (!account)
|
|
100
|
+
return decoy;
|
|
101
|
+
const code = String(randomInt(0, 1_000_000)).padStart(6, '0');
|
|
102
|
+
// Sem `await`: o caminho com conta não pode demorar mais que o sem conta.
|
|
103
|
+
void deliver(ctx, { email, code, clientId, expiresInMinutes: Math.ceil(codeTtl / 60) }, options.sendCode);
|
|
104
|
+
return { status: 'code_required', accountId: account.id, sentTo, code };
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function hostOf(clientId) {
|
|
109
|
+
try {
|
|
110
|
+
return new URL(clientId).host;
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return clientId;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function deliver(ctx, data, hook) {
|
|
117
|
+
try {
|
|
118
|
+
const poppy = await poppyFor(ctx);
|
|
119
|
+
const agentName = poppy
|
|
120
|
+
? await poppy.registry.displayName(data.clientId)
|
|
121
|
+
: hostOf(data.clientId);
|
|
122
|
+
const input = {
|
|
123
|
+
email: data.email,
|
|
124
|
+
code: data.code,
|
|
125
|
+
agentName,
|
|
126
|
+
expiresInMinutes: data.expiresInMinutes,
|
|
127
|
+
};
|
|
128
|
+
if (hook)
|
|
129
|
+
await hook(input);
|
|
130
|
+
else {
|
|
131
|
+
await sendAuthkitCodeEmail(ctx, {
|
|
132
|
+
email: input.email,
|
|
133
|
+
code: input.code,
|
|
134
|
+
messages: 'mail.poppy_sign_in',
|
|
135
|
+
params: { agent: input.agentName, minutes: input.expiresInMinutes },
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
ctx.logger.error({ err: error }, 'authkit-poppy: o código do Mediated Sign-In não saiu');
|
|
141
|
+
}
|
|
142
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Erros OAuth do Poppy (§4.7, RFC 6749 §5.2, RFC 8628 §3.5, RFC 9449, extensão Mediated Sign-In)
|
|
3
|
+
* — viram `{ error, error_description }` com o status da spec.
|
|
4
|
+
*/
|
|
5
|
+
export type PoppyErrorCode = 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'invalid_session' | 'invalid_dpop_proof' | 'use_dpop_nonce'
|
|
6
|
+
/** Interno: HTTP 429 com `Retry-After`, sem corpo (§5.6). */
|
|
7
|
+
| 'too_many_requests' | 'code_required' | 'invalid_scope' | 'invalid_target' | 'unsupported_grant_type' | 'unsupported_token_type' | 'unauthorized_client' | 'authorization_pending' | 'slow_down' | 'access_denied' | 'expired_token';
|
|
8
|
+
export declare class PoppyError extends Error {
|
|
9
|
+
readonly code: PoppyErrorCode;
|
|
10
|
+
readonly description: string;
|
|
11
|
+
readonly status: number;
|
|
12
|
+
/** Headers extras da resposta (`DPoP-Nonce`, `Retry-After`). */
|
|
13
|
+
readonly headers: Record<string, string>;
|
|
14
|
+
/** Campos extras do corpo (`sign_in_id`, `sent_to`, `expires_in` do `code_required`). */
|
|
15
|
+
readonly extra: Record<string, unknown>;
|
|
16
|
+
constructor(code: PoppyErrorCode, description: string, options?: {
|
|
17
|
+
status?: number;
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
extra?: Record<string, unknown>;
|
|
20
|
+
});
|
|
21
|
+
toJSON(): {
|
|
22
|
+
error: PoppyErrorCode;
|
|
23
|
+
error_description: string;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
const STATUS = {
|
|
2
|
+
invalid_client: 401,
|
|
3
|
+
too_many_requests: 429,
|
|
4
|
+
};
|
|
5
|
+
export class PoppyError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
description;
|
|
8
|
+
status;
|
|
9
|
+
/** Headers extras da resposta (`DPoP-Nonce`, `Retry-After`). */
|
|
10
|
+
headers;
|
|
11
|
+
/** Campos extras do corpo (`sign_in_id`, `sent_to`, `expires_in` do `code_required`). */
|
|
12
|
+
extra;
|
|
13
|
+
constructor(code, description, options = {}) {
|
|
14
|
+
super(description);
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.description = description;
|
|
17
|
+
this.name = 'PoppyError';
|
|
18
|
+
this.status = options.status ?? STATUS[code] ?? 400;
|
|
19
|
+
this.headers = options.headers ?? {};
|
|
20
|
+
this.extra = options.extra ?? {};
|
|
21
|
+
}
|
|
22
|
+
toJSON() {
|
|
23
|
+
return { error: this.code, error_description: this.description, ...this.extra };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `poppy()` — o Personal Agent Protocol como uma `personalAgents.extensions` do authkit-server:
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* // config/authkit.ts
|
|
6
|
+
* import { poppy } from '@adonis-agora/authkit-poppy'
|
|
7
|
+
*
|
|
8
|
+
* export default defineConfig({
|
|
9
|
+
* // ...
|
|
10
|
+
* personalAgents: {
|
|
11
|
+
* extensions: [poppy({ organization: { name: 'Shop', domain: 'shop.example' }, scopes: { … } })],
|
|
12
|
+
* },
|
|
13
|
+
* })
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* Mesmas rotas, tabelas, tokens e slots globais de quando o Poppy morava dentro do authkit-server.
|
|
17
|
+
*/
|
|
18
|
+
import type { PersonalAgentExtension } from '@adonis-agora/authkit-server';
|
|
19
|
+
import { type PoppyConfigInput } from './config.js';
|
|
20
|
+
import type { JsonFetcher } from './safe_fetch.js';
|
|
21
|
+
import { PoppyService } from './service.js';
|
|
22
|
+
/** Prefixo dos ids dos grants (refresh tokens) do Poppy no ledger do authkit. */
|
|
23
|
+
export declare const POPPY_GRANT_PREFIX = "pgrant_";
|
|
24
|
+
/** Opções da extension além do config do protocolo. */
|
|
25
|
+
export interface PoppyExtensionOptions {
|
|
26
|
+
/**
|
|
27
|
+
* SÓ TESTES: busca de JSON (metadata/JWKS dos agentes) no lugar da busca com guarda de SSRF.
|
|
28
|
+
*/
|
|
29
|
+
fetchJson?: JsonFetcher;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* O Personal Agent Protocol ("Poppy", Draft 0.3) para `personalAgents.extensions`.
|
|
33
|
+
*
|
|
34
|
+
* @experimental Acompanha uma spec em draft: este pacote fica no 0.x e pode quebrar em qualquer
|
|
35
|
+
* minor.
|
|
36
|
+
*/
|
|
37
|
+
export declare function poppy(config: PoppyConfigInput, options?: PoppyExtensionOptions): PersonalAgentExtension<PoppyService>;
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { PoppyClientRegistry } from './client_registry.js';
|
|
2
|
+
import { resolvePoppyConfig, } from './config.js';
|
|
3
|
+
import { hmacNonceSource } from './dpop.js';
|
|
4
|
+
import { POPPY_MESSAGES } from './messages.js';
|
|
5
|
+
import { databaseReplayStore, memoryLimiter, memoryReplayStore, redisReplayStore, } from './replay.js';
|
|
6
|
+
import { installPoppySlots } from './resource.js';
|
|
7
|
+
import { POPPY_PROTOCOL_ID } from './runtime.js';
|
|
8
|
+
import { PoppyService, poppyUrls } from './service.js';
|
|
9
|
+
import { PoppyStore } from './store.js';
|
|
10
|
+
import { POPPY_TABLES } from './tables.js';
|
|
11
|
+
import { isPoppyBrowser } from './web_session.js';
|
|
12
|
+
/** Prefixo dos ids dos grants (refresh tokens) do Poppy no ledger do authkit. */
|
|
13
|
+
export const POPPY_GRANT_PREFIX = 'pgrant_';
|
|
14
|
+
const PoppyController = () => import('./controllers/poppy_controller.js');
|
|
15
|
+
const PoppyConsentController = () => import('./controllers/poppy_consent_controller.js');
|
|
16
|
+
/**
|
|
17
|
+
* Discovery, authorization server (token, revogação, device authorization), Mediated Sign-In e
|
|
18
|
+
* sessão de navegador — server-to-server ou POST cross-site do navegador do agente (sem CSRF, ver
|
|
19
|
+
* `csrfExemptPaths`). As telas do usuário (authorize/device) exigem a sessão de conta e mantêm o
|
|
20
|
+
* CSRF.
|
|
21
|
+
*/
|
|
22
|
+
function registerRoutes(router, prefix, kit) {
|
|
23
|
+
// Nomes explícitos: o Router nomeia pela dupla controller.método, e as duas URLs da metadata
|
|
24
|
+
// (RFC 8414 na raiz e debaixo do issuer) usam o mesmo — "poppy.metadata already exists" no boot.
|
|
25
|
+
router
|
|
26
|
+
.get('/.well-known/poppy.json', [PoppyController, 'discovery'])
|
|
27
|
+
.as('authkit.poppy.discovery');
|
|
28
|
+
router
|
|
29
|
+
.get('/.well-known/oauth-protected-resource', [PoppyController, 'protectedResource'])
|
|
30
|
+
.as('authkit.poppy.protected_resource');
|
|
31
|
+
router
|
|
32
|
+
.get(`/.well-known/oauth-authorization-server${prefix}`, [PoppyController, 'metadata'])
|
|
33
|
+
.as('authkit.poppy.metadata');
|
|
34
|
+
router
|
|
35
|
+
.get(`${prefix}/.well-known/oauth-authorization-server`, [PoppyController, 'metadata'])
|
|
36
|
+
.as('authkit.poppy.metadata_under_issuer');
|
|
37
|
+
router.post(`${prefix}/oauth/token`, [PoppyController, 'token']).as('authkit.poppy.token');
|
|
38
|
+
router.post(`${prefix}/oauth/revoke`, [PoppyController, 'revoke']).as('authkit.poppy.revoke');
|
|
39
|
+
router
|
|
40
|
+
.post(`${prefix}/oauth/device`, [PoppyController, 'deviceAuthorization'])
|
|
41
|
+
.as('authkit.poppy.device_authorization');
|
|
42
|
+
// A página grava um pedido sem autenticação: throttle por IP.
|
|
43
|
+
kit.throttle.login(router
|
|
44
|
+
.get(`${prefix}/browser-session`, [PoppyController, 'browserSessionPage'])
|
|
45
|
+
.as('authkit.poppy.browser_session_page'));
|
|
46
|
+
router
|
|
47
|
+
.post(`${prefix}/browser-session`, [PoppyController, 'browserSession'])
|
|
48
|
+
.as('authkit.poppy.browser_session');
|
|
49
|
+
router
|
|
50
|
+
.post(`${prefix}/browser-session/authorize`, [PoppyController, 'browserSessionAuthorize'])
|
|
51
|
+
.as('authkit.poppy.browser_session_authorize');
|
|
52
|
+
router
|
|
53
|
+
.group(() => {
|
|
54
|
+
router
|
|
55
|
+
.get(`${prefix}/oauth/authorize`, [PoppyConsentController, 'authorize'])
|
|
56
|
+
.as('authkit.poppy.authorize');
|
|
57
|
+
router
|
|
58
|
+
.post(`${prefix}/oauth/authorize`, [PoppyConsentController, 'decideAuthorization'])
|
|
59
|
+
.as('authkit.poppy.authorize_decide');
|
|
60
|
+
kit.throttle.otp(router
|
|
61
|
+
.get(`${prefix}/device`, [PoppyConsentController, 'device'])
|
|
62
|
+
.as('authkit.poppy.device'));
|
|
63
|
+
kit.throttle.otp(router
|
|
64
|
+
.post(`${prefix}/device`, [PoppyConsentController, 'decideDevice'])
|
|
65
|
+
.as('authkit.poppy.device_decide'));
|
|
66
|
+
})
|
|
67
|
+
.use([kit.accountGuard]);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* O registro do console admin por cima do config: um agente BLOQUEADO no console é recusado mesmo
|
|
71
|
+
* que o config o registre; um LIBERADO entra mesmo fora da lista. O que o config bloqueia continua
|
|
72
|
+
* bloqueado.
|
|
73
|
+
*/
|
|
74
|
+
function withRegistry(cfg, host) {
|
|
75
|
+
return {
|
|
76
|
+
...cfg,
|
|
77
|
+
clients: {
|
|
78
|
+
...cfg.clients,
|
|
79
|
+
isBlocked: async (id) => (await cfg.clients.isBlocked(id)) || (await host.registryStatus(id)) === 'blocked',
|
|
80
|
+
isRegistered: async (id) => (await cfg.clients.isRegistered(id)) || (await host.registryStatus(id)) === 'allowed',
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
async function resolveReplay(replay, host) {
|
|
85
|
+
if (replay === 'memory')
|
|
86
|
+
return memoryReplayStore();
|
|
87
|
+
if (replay === 'database')
|
|
88
|
+
return databaseReplayStore(() => host.db());
|
|
89
|
+
if (typeof replay.claim === 'function')
|
|
90
|
+
return replay;
|
|
91
|
+
const redis = await host.make('redis');
|
|
92
|
+
return redisReplayStore(redis.connection(replay.redis));
|
|
93
|
+
}
|
|
94
|
+
/** Bearer de MCP de Sessions logadas viram access tokens do oidc-provider (§7). */
|
|
95
|
+
function mcpBridge(cfg, host) {
|
|
96
|
+
const tokens = host.accessTokens;
|
|
97
|
+
const trim = (url) => url.replace(/\/+$/, '');
|
|
98
|
+
return {
|
|
99
|
+
isMcpResource: (url) => tokens.isMcpResource(url),
|
|
100
|
+
async mint(input) {
|
|
101
|
+
// Só com a integração MCP do authkit ligada, ou um MCP declarado em `apis`.
|
|
102
|
+
if (!tokens.mcpEnabled &&
|
|
103
|
+
!cfg.apis.some((a) => a.type === 'mcp' && trim(a.url) === trim(input.resource))) {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
return tokens.mint({ ...input, grantType: POPPY_PROTOCOL_ID });
|
|
107
|
+
},
|
|
108
|
+
revoke: (grantId) => tokens.revokeGrant(grantId),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* O Personal Agent Protocol ("Poppy", Draft 0.3) para `personalAgents.extensions`.
|
|
113
|
+
*
|
|
114
|
+
* @experimental Acompanha uma spec em draft: este pacote fica no 0.x e pode quebrar em qualquer
|
|
115
|
+
* minor.
|
|
116
|
+
*/
|
|
117
|
+
export function poppy(config, options = {}) {
|
|
118
|
+
return {
|
|
119
|
+
id: POPPY_PROTOCOL_ID,
|
|
120
|
+
resolve(context) {
|
|
121
|
+
const resolved = resolvePoppyConfig(config, context.delegationScopes ?? undefined);
|
|
122
|
+
const csrfExemptPaths = [
|
|
123
|
+
`${resolved.prefix}/oauth/token`,
|
|
124
|
+
`${resolved.prefix}/oauth/revoke`,
|
|
125
|
+
`${resolved.prefix}/oauth/device`,
|
|
126
|
+
`${resolved.prefix}/browser-session`,
|
|
127
|
+
`${resolved.prefix}/browser-session/authorize`,
|
|
128
|
+
];
|
|
129
|
+
return {
|
|
130
|
+
label: 'Poppy',
|
|
131
|
+
grantIdPrefix: POPPY_GRANT_PREFIX,
|
|
132
|
+
prefix: resolved.prefix,
|
|
133
|
+
csrfExemptPaths,
|
|
134
|
+
tables: POPPY_TABLES,
|
|
135
|
+
messages: POPPY_MESSAGES,
|
|
136
|
+
isAgentBrowser: (ctx) => isPoppyBrowser(ctx),
|
|
137
|
+
boot() {
|
|
138
|
+
// O slot global que o `@adonis-agora/agent` usa para autenticar o endpoint de conversas
|
|
139
|
+
// (e o MCP) sem importar este pacote — o contrato é o símbolo.
|
|
140
|
+
installPoppySlots(poppyUrls(context.issuer, resolved.prefix).issuer);
|
|
141
|
+
},
|
|
142
|
+
routes: (router, kit) => registerRoutes(router, resolved.prefix, kit),
|
|
143
|
+
async setup(host) {
|
|
144
|
+
const cfg = withRegistry(resolved, host);
|
|
145
|
+
const limiter = cfg.rateLimit === false
|
|
146
|
+
? null
|
|
147
|
+
: typeof cfg.rateLimit === 'function'
|
|
148
|
+
? cfg.rateLimit
|
|
149
|
+
: memoryLimiter(cfg.rateLimit);
|
|
150
|
+
return new PoppyService({
|
|
151
|
+
cfg,
|
|
152
|
+
urls: poppyUrls(host.issuer, cfg.prefix),
|
|
153
|
+
store: new PoppyStore(() => host.db()),
|
|
154
|
+
grants: host.grants,
|
|
155
|
+
registry: new PoppyClientRegistry(cfg, { fetchJson: options.fetchJson }),
|
|
156
|
+
replay: await resolveReplay(cfg.replay, host),
|
|
157
|
+
limiter,
|
|
158
|
+
nonces: hmacNonceSource(host.deriveSecret('poppy-dpop-nonce')),
|
|
159
|
+
isAccountActive: (accountId) => host.isAccountActive(accountId),
|
|
160
|
+
mcp: mcpBridge(cfg, host),
|
|
161
|
+
now: () => host.now(),
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Textos do Poppy somados ao i18n do authkit (`messages` da extension). O host troca qualquer um
|
|
3
|
+
* em `i18n.messages` do `config/authkit.ts`, como os do próprio authkit.
|
|
4
|
+
*/
|
|
5
|
+
export declare const POPPY_MESSAGES: {
|
|
6
|
+
readonly en: {
|
|
7
|
+
readonly 'mail.poppy_sign_in.subject': 'Your code to connect {agent}';
|
|
8
|
+
readonly 'mail.poppy_sign_in.heading': 'Connect {agent} to your account';
|
|
9
|
+
readonly 'mail.poppy_sign_in.intro': '{agent} asked to sign in to your account. If that was you, give it the code below. It expires in {minutes} minutes and works once.';
|
|
10
|
+
readonly 'mail.poppy_sign_in.code_label': 'Your code:';
|
|
11
|
+
readonly 'mail.poppy_sign_in.fallback': 'If you did not ask for this, ignore this email — nobody gets in without the code. Never share it with anyone else.';
|
|
12
|
+
};
|
|
13
|
+
readonly 'pt-BR': {
|
|
14
|
+
readonly 'mail.poppy_sign_in.subject': 'Seu código para conectar {agent}';
|
|
15
|
+
readonly 'mail.poppy_sign_in.heading': 'Conecte {agent} à sua conta';
|
|
16
|
+
readonly 'mail.poppy_sign_in.intro': '{agent} pediu para entrar na sua conta. Se foi você, informe o código abaixo. Ele expira em {minutes} minutos e serve uma única vez.';
|
|
17
|
+
readonly 'mail.poppy_sign_in.code_label': 'Seu código:';
|
|
18
|
+
readonly 'mail.poppy_sign_in.fallback': 'Se não foi você, ignore este e-mail — ninguém entra sem o código. Nunca o compartilhe com outra pessoa.';
|
|
19
|
+
};
|
|
20
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Textos do Poppy somados ao i18n do authkit (`messages` da extension). O host troca qualquer um
|
|
3
|
+
* em `i18n.messages` do `config/authkit.ts`, como os do próprio authkit.
|
|
4
|
+
*/
|
|
5
|
+
export const POPPY_MESSAGES = {
|
|
6
|
+
en: {
|
|
7
|
+
// Código do Mediated Sign-In pronto (`poppyEmailCodeSignIn`): um personal agent pede para
|
|
8
|
+
// entrar na conta.
|
|
9
|
+
'mail.poppy_sign_in.subject': 'Your code to connect {agent}',
|
|
10
|
+
'mail.poppy_sign_in.heading': 'Connect {agent} to your account',
|
|
11
|
+
'mail.poppy_sign_in.intro': '{agent} asked to sign in to your account. If that was you, give it the code below. It expires in {minutes} minutes and works once.',
|
|
12
|
+
'mail.poppy_sign_in.code_label': 'Your code:',
|
|
13
|
+
'mail.poppy_sign_in.fallback': 'If you did not ask for this, ignore this email — nobody gets in without the code. Never share it with anyone else.',
|
|
14
|
+
},
|
|
15
|
+
'pt-BR': {
|
|
16
|
+
'mail.poppy_sign_in.subject': 'Seu código para conectar {agent}',
|
|
17
|
+
'mail.poppy_sign_in.heading': 'Conecte {agent} à sua conta',
|
|
18
|
+
'mail.poppy_sign_in.intro': '{agent} pediu para entrar na sua conta. Se foi você, informe o código abaixo. Ele expira em {minutes} minutos e serve uma única vez.',
|
|
19
|
+
'mail.poppy_sign_in.code_label': 'Seu código:',
|
|
20
|
+
'mail.poppy_sign_in.fallback': 'Se não foi você, ignore este e-mail — ninguém entra sem o código. Nunca o compartilhe com outra pessoa.',
|
|
21
|
+
},
|
|
22
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Redireciona para `url` EXATAMENTE como montada: o `redirect.forwardQueryString: true` do starter
|
|
3
|
+
* do AdonisJS colaria a query da request atual no fim. Fora de uma Response do AdonisJS (dublês de
|
|
4
|
+
* teste), cai no `redirect(url)` de sempre. (O mesmo do authkit-server.)
|
|
5
|
+
*/
|
|
6
|
+
export declare function redirectExact(response: any, url: string): unknown;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Redireciona para `url` EXATAMENTE como montada: o `redirect.forwardQueryString: true` do starter
|
|
3
|
+
* do AdonisJS colaria a query da request atual no fim. Fora de uma Response do AdonisJS (dublês de
|
|
4
|
+
* teste), cai no `redirect(url)` de sempre. (O mesmo do authkit-server.)
|
|
5
|
+
*/
|
|
6
|
+
export function redirectExact(response, url) {
|
|
7
|
+
if (typeof response?.getStatus === 'function') {
|
|
8
|
+
return response.redirect().clearQs().toPath(url);
|
|
9
|
+
}
|
|
10
|
+
return response.redirect(url);
|
|
11
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { PoppyLimiter, PoppyReplayStore } from './config.js';
|
|
2
|
+
export declare const JTI_TABLE = "auth_poppy_jtis";
|
|
3
|
+
/** Chave curta e de tamanho fixo para um `jti` de um tipo/agente. */
|
|
4
|
+
export declare function replayKey(kind: string, ...parts: string[]): string;
|
|
5
|
+
/** Em memória, por processo. Só serve com uma instância. */
|
|
6
|
+
export declare function memoryReplayStore(options?: {
|
|
7
|
+
max?: number;
|
|
8
|
+
now?: () => number;
|
|
9
|
+
}): PoppyReplayStore;
|
|
10
|
+
/**
|
|
11
|
+
* Na tabela lib-owned `auth_poppy_jtis` (PK = chave): o INSERT de uma chave que
|
|
12
|
+
* já existe falha — atômico entre instâncias. Linhas vencidas saem aos poucos.
|
|
13
|
+
*/
|
|
14
|
+
export declare function databaseReplayStore(conn: () => any, options?: {
|
|
15
|
+
now?: () => Date;
|
|
16
|
+
}): PoppyReplayStore;
|
|
17
|
+
/** Numa conexão Redis (`SET key 1 PX ttl NX`). */
|
|
18
|
+
export declare function redisReplayStore(redis: {
|
|
19
|
+
set: (...args: any[]) => Promise<unknown>;
|
|
20
|
+
}): PoppyReplayStore;
|
|
21
|
+
/** Janelas fixas em memória, por processo: `sessionsPerMinute` por agente, `mediatedPerHour` por (agente, usuário). */
|
|
22
|
+
export declare function memoryLimiter(limits: {
|
|
23
|
+
sessionsPerMinute: number;
|
|
24
|
+
mediatedPerHour: number;
|
|
25
|
+
}, now?: () => number): PoppyLimiter;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proteção contra replay (`jti` de asserções, client assertions, provas DPoP e
|
|
3
|
+
* asserções de navegador) e limites de taxa do Poppy.
|
|
4
|
+
*/
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
export const JTI_TABLE = 'auth_poppy_jtis';
|
|
7
|
+
/** Chave curta e de tamanho fixo para um `jti` de um tipo/agente. */
|
|
8
|
+
export function replayKey(kind, ...parts) {
|
|
9
|
+
return `${kind}:${createHash('sha256').update(parts.join('\u0000')).digest('base64url')}`;
|
|
10
|
+
}
|
|
11
|
+
/** Em memória, por processo. Só serve com uma instância. */
|
|
12
|
+
export function memoryReplayStore(options = {}) {
|
|
13
|
+
const seen = new Map();
|
|
14
|
+
const max = options.max ?? 100_000;
|
|
15
|
+
const now = options.now ?? Date.now;
|
|
16
|
+
let claims = 0;
|
|
17
|
+
return {
|
|
18
|
+
async claim(key, expiresAt) {
|
|
19
|
+
const t = now();
|
|
20
|
+
if (++claims % 1000 === 0 || seen.size >= max) {
|
|
21
|
+
for (const [k, exp] of seen)
|
|
22
|
+
if (exp <= t)
|
|
23
|
+
seen.delete(k);
|
|
24
|
+
}
|
|
25
|
+
const existing = seen.get(key);
|
|
26
|
+
if (existing !== undefined && existing > t)
|
|
27
|
+
return false;
|
|
28
|
+
if (seen.size >= max)
|
|
29
|
+
seen.delete(seen.keys().next().value);
|
|
30
|
+
seen.set(key, expiresAt.getTime());
|
|
31
|
+
return true;
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Na tabela lib-owned `auth_poppy_jtis` (PK = chave): o INSERT de uma chave que
|
|
37
|
+
* já existe falha — atômico entre instâncias. Linhas vencidas saem aos poucos.
|
|
38
|
+
*/
|
|
39
|
+
export function databaseReplayStore(conn, options = {}) {
|
|
40
|
+
const now = options.now ?? (() => new Date());
|
|
41
|
+
let claims = 0;
|
|
42
|
+
return {
|
|
43
|
+
async claim(key, expiresAt) {
|
|
44
|
+
const t = now();
|
|
45
|
+
if (++claims % 200 === 1) {
|
|
46
|
+
await conn().from(JTI_TABLE).where('expires_at', '<', t).delete();
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
await conn().table(JTI_TABLE).insert({ key, expires_at: expiresAt });
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
// 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();
|
|
55
|
+
if (!row)
|
|
56
|
+
throw error;
|
|
57
|
+
const exp = row.expires_at instanceof Date
|
|
58
|
+
? row.expires_at
|
|
59
|
+
: new Date(Number(row.expires_at) || row.expires_at);
|
|
60
|
+
if (exp.getTime() > t.getTime())
|
|
61
|
+
return false;
|
|
62
|
+
const updated = await conn()
|
|
63
|
+
.from(JTI_TABLE)
|
|
64
|
+
.where('key', key)
|
|
65
|
+
.where('expires_at', '<=', t)
|
|
66
|
+
.update({ expires_at: expiresAt });
|
|
67
|
+
return ((typeof updated === 'number' ? updated : Array.isArray(updated) ? updated.length : 0) > 0);
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** Numa conexão Redis (`SET key 1 PX ttl NX`). */
|
|
73
|
+
export function redisReplayStore(redis) {
|
|
74
|
+
return {
|
|
75
|
+
async claim(key, expiresAt) {
|
|
76
|
+
const ttl = Math.max(1000, expiresAt.getTime() - Date.now());
|
|
77
|
+
const result = await redis.set(`authkit:poppy:jti:${key}`, '1', 'PX', ttl, 'NX');
|
|
78
|
+
return result === 'OK';
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/** Janelas fixas em memória, por processo: `sessionsPerMinute` por agente, `mediatedPerHour` por (agente, usuário). */
|
|
83
|
+
export function memoryLimiter(limits, now = Date.now) {
|
|
84
|
+
const windows = new Map();
|
|
85
|
+
return async ({ action, key }) => {
|
|
86
|
+
const [limit, windowMs] = action === 'session'
|
|
87
|
+
? [limits.sessionsPerMinute, 60_000]
|
|
88
|
+
: [limits.mediatedPerHour, 3_600_000];
|
|
89
|
+
const t = now();
|
|
90
|
+
const id = `${action}:${key}`;
|
|
91
|
+
let w = windows.get(id);
|
|
92
|
+
if (!w || t - w.start >= windowMs) {
|
|
93
|
+
w = { start: t, count: 0 };
|
|
94
|
+
windows.set(id, w);
|
|
95
|
+
if (windows.size > 50_000) {
|
|
96
|
+
for (const [k, v] of windows)
|
|
97
|
+
if (t - v.start >= 3_600_000)
|
|
98
|
+
windows.delete(k);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (w.count >= limit)
|
|
102
|
+
return Math.ceil((w.start + windowMs - t) / 1000);
|
|
103
|
+
w.count++;
|
|
104
|
+
return null;
|
|
105
|
+
};
|
|
106
|
+
}
|