@adonis-agora/authkit-server 0.78.0 → 0.80.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/build/index.d.ts +1 -0
- package/build/index.js +1 -0
- package/build/src/agents/config.d.ts +2 -0
- package/build/src/agents/config.js +3 -0
- package/build/src/agents/delegation_store.d.ts +16 -0
- package/build/src/agents/delegation_store.js +44 -0
- package/build/src/agents/poppy/config.d.ts +3 -0
- package/build/src/agents/poppy/config.js +7 -0
- package/build/src/agents/poppy/email_code_sign_in.d.ts +27 -0
- package/build/src/agents/poppy/email_code_sign_in.js +140 -0
- package/build/src/agents/poppy/service.d.ts +6 -0
- package/build/src/agents/poppy/service.js +12 -0
- package/build/src/agents/poppy/store.d.ts +2 -0
- package/build/src/agents/poppy/store.js +9 -0
- package/build/src/agents/registry_store.d.ts +41 -0
- package/build/src/agents/registry_store.js +138 -0
- package/build/src/agents/runtime.d.ts +13 -0
- package/build/src/agents/runtime.js +87 -5
- package/build/src/audit/audit_sink.d.ts +1 -1
- package/build/src/audit/audit_sink.js +6 -0
- package/build/src/define_config.d.ts +12 -0
- package/build/src/host/admin_api/dto.d.ts +1 -1
- package/build/src/host/admin_console/admin_shell_controller.js +7 -0
- package/build/src/host/admin_console/console_personal_agents_controller.d.ts +83 -0
- package/build/src/host/admin_console/console_personal_agents_controller.js +337 -0
- package/build/src/host/default_mailer.d.ts +11 -0
- package/build/src/host/default_mailer.js +29 -0
- package/build/src/host/i18n.d.ts +10 -0
- package/build/src/host/i18n.js +12 -0
- package/build/src/host/register_auth_host.js +16 -0
- package/build/src/host/ui-dist/assets/index-LrScaR9C.js +155 -0
- package/build/src/host/ui-dist/index.html +1 -1
- package/build/src/schema/ensure.js +28 -0
- package/package.json +2 -2
- package/build/src/host/ui-dist/assets/index-CIqtoNcO.js +0 -155
package/build/index.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ export { personalAgentAuth, personalAgentOf, personalAgentReceipt, personalAgent
|
|
|
19
19
|
export type { PoppyAgentProtocolEntry, PoppyApiEntry, PoppyBrowserLogin, PoppyClientsConfigInput, PoppyConfigInput, PoppyLimiter, PoppyMediatedConfigInput, PoppyMediatedField, PoppyMediatedResult, PoppyMediatedVerifyInput, PoppyPrincipalBase, PoppyReplayStore, ResolvedPoppyConfig, } from './src/agents/poppy/config.js';
|
|
20
20
|
export { POPPY_READ, POPPY_WRITE } from './src/agents/poppy/config.js';
|
|
21
21
|
export { accessTokenHash, type DpopNonceSource, type DpopResult, hmacNonceSource, type VerifyDpopInput, verifyDpopProof, } from './src/agents/poppy/dpop.js';
|
|
22
|
+
export { maskEmail, type PoppyEmailCodeSignInOptions, poppyEmailCodeSignIn, } from './src/agents/poppy/email_code_sign_in.js';
|
|
22
23
|
export { PoppyError, type PoppyErrorCode } from './src/agents/poppy/errors.js';
|
|
23
24
|
export { databaseReplayStore, memoryReplayStore, redisReplayStore, } from './src/agents/poppy/replay.js';
|
|
24
25
|
export { installPoppySlots, POPPY_AUTHENTICATE_SLOT, type PoppyAuthenticate, type PoppyAuthResult, type PoppyPrincipal, type PoppySlotRequest, poppyAuth, poppyOf, verifyPoppyRequest, writePoppyAuthError, } from './src/agents/poppy/resource.js';
|
package/build/index.js
CHANGED
|
@@ -11,6 +11,7 @@ export { PersonalAgentVerifier } from './src/agents/agent_identity.js';
|
|
|
11
11
|
export { personalAgentAuth, personalAgentOf, personalAgentReceipt, personalAgentSecurity, personalAgentStepUp, } from './src/agents/middleware.js';
|
|
12
12
|
export { POPPY_READ, POPPY_WRITE } from './src/agents/poppy/config.js';
|
|
13
13
|
export { accessTokenHash, hmacNonceSource, verifyDpopProof, } from './src/agents/poppy/dpop.js';
|
|
14
|
+
export { maskEmail, poppyEmailCodeSignIn, } from './src/agents/poppy/email_code_sign_in.js';
|
|
14
15
|
export { PoppyError } from './src/agents/poppy/errors.js';
|
|
15
16
|
export { databaseReplayStore, memoryReplayStore, redisReplayStore, } from './src/agents/poppy/replay.js';
|
|
16
17
|
export { installPoppySlots, POPPY_AUTHENTICATE_SLOT, poppyAuth, poppyOf, verifyPoppyRequest, writePoppyAuthError, } from './src/agents/poppy/resource.js';
|
|
@@ -103,6 +103,8 @@ export interface ResolvedPersonalAgentsConfig {
|
|
|
103
103
|
/** `''` quando o PACT está desligado. */
|
|
104
104
|
audience: string;
|
|
105
105
|
resolveAgent: PersonalAgentResolver;
|
|
106
|
+
/** A lista `agents` do config quando é um array (o console mostra); `null` = resolver do host. */
|
|
107
|
+
staticAgents: PersonalAgentRegistration[] | null;
|
|
106
108
|
open: boolean;
|
|
107
109
|
delegation?: ResolvedPersonalAgentDelegationConfig;
|
|
108
110
|
prefix: string;
|
|
@@ -51,10 +51,12 @@ export function resolvePersonalAgentsConfig(input) {
|
|
|
51
51
|
throw new Error('authkit: o Poppy não é um `protocol` do PACT — configure-o em `personalAgents.poppy` (os dois convivem).');
|
|
52
52
|
}
|
|
53
53
|
let resolveAgent;
|
|
54
|
+
let staticAgents = null;
|
|
54
55
|
if (typeof input.agents === 'function') {
|
|
55
56
|
resolveAgent = input.agents;
|
|
56
57
|
}
|
|
57
58
|
else {
|
|
59
|
+
staticAgents = [...(input.agents ?? [])];
|
|
58
60
|
const byIssuer = new Map();
|
|
59
61
|
for (const agent of input.agents ?? []) {
|
|
60
62
|
assertUrl(agent.issuer, `agents[].issuer`);
|
|
@@ -101,6 +103,7 @@ export function resolvePersonalAgentsConfig(input) {
|
|
|
101
103
|
protocol,
|
|
102
104
|
audience: pact ? input.audience : '',
|
|
103
105
|
resolveAgent,
|
|
106
|
+
staticAgents,
|
|
104
107
|
open: input.open === true,
|
|
105
108
|
delegation,
|
|
106
109
|
prefix,
|
|
@@ -37,7 +37,13 @@ export interface GrantRow {
|
|
|
37
37
|
createdAt: Date;
|
|
38
38
|
updatedAt: Date;
|
|
39
39
|
}
|
|
40
|
+
export interface LiveGrantFilter {
|
|
41
|
+
protocol?: 'pact' | 'poppy';
|
|
42
|
+
clientId?: string;
|
|
43
|
+
accountId?: string;
|
|
44
|
+
}
|
|
40
45
|
export declare class DelegationStore {
|
|
46
|
+
#private;
|
|
41
47
|
private conn;
|
|
42
48
|
/** `conn` = uma conexão Lucid (`db.connection(name?)`) — ou uma transação. */
|
|
43
49
|
constructor(conn: () => any);
|
|
@@ -75,6 +81,16 @@ export declare class DelegationStore {
|
|
|
75
81
|
/** Revoga um grant DA CONTA. `false` = não existe, é de outra conta ou já revogado. */
|
|
76
82
|
revokeGrant(accountId: string, id: string, at: Date): Promise<boolean>;
|
|
77
83
|
revokeAllGrants(accountId: string, at: Date): Promise<number>;
|
|
84
|
+
listLiveGrants(input: LiveGrantFilter & {
|
|
85
|
+
now: Date;
|
|
86
|
+
offset: number;
|
|
87
|
+
limit: number;
|
|
88
|
+
}): Promise<GrantRow[]>;
|
|
89
|
+
countLiveGrants(now: Date, filter?: LiveGrantFilter): Promise<number>;
|
|
90
|
+
/** Conexões vivas de um protocolo por agente: `client_id` → número de grants. */
|
|
91
|
+
countLiveGrantsByClient(now: Date, protocol: 'pact' | 'poppy'): Promise<Map<string, number>>;
|
|
92
|
+
/** Ids dos grants não revogados de um agente (vivos ou não) — para revogar todos. */
|
|
93
|
+
unrevokedGrantIdsOfClient(clientId: string): Promise<string[]>;
|
|
78
94
|
/** Revoga um grant sem checar a conta — reação a reuso de refresh token. */
|
|
79
95
|
revokeGrantById(id: string, at: Date): Promise<void>;
|
|
80
96
|
insertRefreshToken(row: {
|
|
@@ -183,6 +183,50 @@ export class DelegationStore {
|
|
|
183
183
|
.update({ revoked_at: at, updated_at: at });
|
|
184
184
|
return affected(result);
|
|
185
185
|
}
|
|
186
|
+
// ─── console admin (todas as contas) ──────────────────────────────────────
|
|
187
|
+
/**
|
|
188
|
+
* Grants vivos (não revogados nem expirados em `now`), de todas as contas. O
|
|
189
|
+
* protocolo sai do prefixo do id: `agrant_` (PACT) ou `pgrant_` (Poppy).
|
|
190
|
+
*/
|
|
191
|
+
#live(now, filter = {}) {
|
|
192
|
+
let q = this.conn().from(GRANT_TABLE).whereNull('revoked_at').where('expires_at', '>', now);
|
|
193
|
+
if (filter.protocol)
|
|
194
|
+
q = q.where('id', 'like', filter.protocol === 'poppy' ? 'pgrant_%' : 'agrant_%');
|
|
195
|
+
if (filter.clientId)
|
|
196
|
+
q = q.where('client_id', filter.clientId);
|
|
197
|
+
if (filter.accountId)
|
|
198
|
+
q = q.where('account_id', filter.accountId);
|
|
199
|
+
return q;
|
|
200
|
+
}
|
|
201
|
+
async listLiveGrants(input) {
|
|
202
|
+
const rows = await this.#live(input.now, input)
|
|
203
|
+
.orderBy('created_at', 'desc')
|
|
204
|
+
.orderBy('id', 'asc')
|
|
205
|
+
.offset(input.offset)
|
|
206
|
+
.limit(input.limit);
|
|
207
|
+
return rows.map(toGrant);
|
|
208
|
+
}
|
|
209
|
+
async countLiveGrants(now, filter = {}) {
|
|
210
|
+
const row = await this.#live(now, filter).count('* as total').first();
|
|
211
|
+
return Number(row?.total ?? 0);
|
|
212
|
+
}
|
|
213
|
+
/** Conexões vivas de um protocolo por agente: `client_id` → número de grants. */
|
|
214
|
+
async countLiveGrantsByClient(now, protocol) {
|
|
215
|
+
const rows = await this.#live(now, { protocol })
|
|
216
|
+
.select('client_id')
|
|
217
|
+
.count('* as total')
|
|
218
|
+
.groupBy('client_id');
|
|
219
|
+
return new Map(rows.map((r) => [r.client_id, Number(r.total)]));
|
|
220
|
+
}
|
|
221
|
+
/** Ids dos grants não revogados de um agente (vivos ou não) — para revogar todos. */
|
|
222
|
+
async unrevokedGrantIdsOfClient(clientId) {
|
|
223
|
+
const rows = await this.conn()
|
|
224
|
+
.from(GRANT_TABLE)
|
|
225
|
+
.where('client_id', clientId)
|
|
226
|
+
.whereNull('revoked_at')
|
|
227
|
+
.select('id');
|
|
228
|
+
return rows.map((r) => r.id);
|
|
229
|
+
}
|
|
186
230
|
/** Revoga um grant sem checar a conta — reação a reuso de refresh token. */
|
|
187
231
|
async revokeGrantById(id, at) {
|
|
188
232
|
await this.conn()
|
|
@@ -332,6 +332,9 @@ export interface ResolvedPoppyConfig {
|
|
|
332
332
|
requireRegistration: boolean;
|
|
333
333
|
isRegistered: (clientId: string) => Promise<boolean>;
|
|
334
334
|
isBlocked: (clientId: string) => Promise<boolean>;
|
|
335
|
+
/** As listas do config quando são arrays (o console mostra); `null` = função do host. */
|
|
336
|
+
registeredList: string[] | null;
|
|
337
|
+
blockedList: string[] | null;
|
|
335
338
|
};
|
|
336
339
|
/** Dev/teste: `client_id` http e busca sem guarda de SSRF (ver o input). */
|
|
337
340
|
allowInsecureClientIds: boolean;
|
|
@@ -47,6 +47,11 @@ function membership(value) {
|
|
|
47
47
|
const set = new Set(value ?? []);
|
|
48
48
|
return async (id) => set.has(id);
|
|
49
49
|
}
|
|
50
|
+
function listOf(value) {
|
|
51
|
+
if (typeof value === 'function')
|
|
52
|
+
return null;
|
|
53
|
+
return [...new Set(value ?? [])];
|
|
54
|
+
}
|
|
50
55
|
function typeScopes(input, all, what) {
|
|
51
56
|
if (input === false)
|
|
52
57
|
return null;
|
|
@@ -180,6 +185,8 @@ export function resolvePoppyConfig(input, fallbackScopes) {
|
|
|
180
185
|
requireRegistration: input.clients?.requireRegistration === true,
|
|
181
186
|
isRegistered: membership(input.clients?.registered),
|
|
182
187
|
isBlocked: membership(input.clients?.blocked),
|
|
188
|
+
registeredList: listOf(input.clients?.registered),
|
|
189
|
+
blockedList: listOf(input.clients?.blocked),
|
|
183
190
|
},
|
|
184
191
|
allowInsecureClientIds,
|
|
185
192
|
sessionTokenTtl: positive(input.sessionTokenTtl, 3600, 'sessionTokenTtl'),
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type AuthAccount } from '../../accounts/account_store.js';
|
|
2
|
+
import type { PoppyMediatedConfigInput } from './config.js';
|
|
3
|
+
export interface PoppyEmailCodeSignInOptions {
|
|
4
|
+
/** Scopes que este sign-in pode conceder. Default: `['poppy:read']` (o default do Mediated). */
|
|
5
|
+
scopes?: string[];
|
|
6
|
+
/** Validade do código, em segundos. Default: 600. */
|
|
7
|
+
codeTtl?: number;
|
|
8
|
+
/** Tentativas de código antes de `failed`. Default: 5. */
|
|
9
|
+
maxCodeAttempts?: number;
|
|
10
|
+
/**
|
|
11
|
+
* Quem pode entrar por aqui (ex.: só pacientes, não profissionais). `false` = recebe a
|
|
12
|
+
* resposta de conta inexistente. Default: toda conta ativa.
|
|
13
|
+
*/
|
|
14
|
+
eligible?: (account: AuthAccount) => boolean | Promise<boolean>;
|
|
15
|
+
/**
|
|
16
|
+
* Códigos por e-mail por hora, nesta instância — impede um agente de lotar a caixa de
|
|
17
|
+
* alguém. Acima disso a resposta é a mesma, sem e-mail. Default: 5.
|
|
18
|
+
*/
|
|
19
|
+
maxPerHour?: number;
|
|
20
|
+
/** Rótulo do campo que o agente mostra ao usuário. Default: `'Email address'`. */
|
|
21
|
+
label?: string;
|
|
22
|
+
/** Texto de `sentTo` a partir do e-mail mascarado. Default: `` `Email to ${masked}` ``. */
|
|
23
|
+
sentTo?: (masked: string) => string;
|
|
24
|
+
}
|
|
25
|
+
/** `ana.souza@gmail.com` → `a***@gmail.com`: o bastante para a pessoa reconhecer. */
|
|
26
|
+
export declare function maskEmail(email: string): string;
|
|
27
|
+
export declare function poppyEmailCodeSignIn(options?: PoppyEmailCodeSignInOptions): PoppyMediatedConfigInput;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @experimental Poppy (Personal Agent Protocol) Draft 0.1 — pode mudar de forma incompatível enquanto a spec for draft.
|
|
3
|
+
*
|
|
4
|
+
* Mediated Sign-In pronto (§4.7): 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 (hook `mail.onPoppySignInCode` ou o mailer default)
|
|
7
|
+
* do próprio authkit — o app só liga:
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* personalAgents: {
|
|
11
|
+
* poppy: { signIn: { mediated: poppyEmailCodeSignIn() } },
|
|
12
|
+
* }
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* Sem enumeração de contas: e-mail sem conta, conta desativada, conta recusada
|
|
16
|
+
* por `eligible` ou e-mail acima do limite recebem a MESMA resposta, sem código
|
|
17
|
+
* (`accountId: null`) — a lib recusa qualquer código como errado. O envio não é
|
|
18
|
+
* esperado, então o tempo de resposta também não denuncia.
|
|
19
|
+
*/
|
|
20
|
+
import { randomInt } from 'node:crypto';
|
|
21
|
+
import { supportsAccountStatus } from '../../accounts/account_store.js';
|
|
22
|
+
import { sendPoppySignInCodeEmail } from '../../host/default_mailer.js';
|
|
23
|
+
import { personalAgentsFor } from '../runtime.js';
|
|
24
|
+
/** `ana.souza@gmail.com` → `a***@gmail.com`: o bastante para a pessoa reconhecer. */
|
|
25
|
+
export function maskEmail(email) {
|
|
26
|
+
const at = email.lastIndexOf('@');
|
|
27
|
+
const user = at > 0 ? email.slice(0, at) : '';
|
|
28
|
+
const domain = at > 0 ? email.slice(at + 1) : '';
|
|
29
|
+
if (!user || !domain)
|
|
30
|
+
return '***';
|
|
31
|
+
return `${user[0]}***@${domain}`;
|
|
32
|
+
}
|
|
33
|
+
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
34
|
+
const HOUR_MS = 3600 * 1000;
|
|
35
|
+
const MAX_TRACKED = 10_000;
|
|
36
|
+
export function poppyEmailCodeSignIn(options = {}) {
|
|
37
|
+
const positive = (value, fallback, what) => {
|
|
38
|
+
if (value === undefined)
|
|
39
|
+
return fallback;
|
|
40
|
+
if (!Number.isFinite(value) || value < 1) {
|
|
41
|
+
throw new Error(`authkit: poppyEmailCodeSignIn ${what} precisa ser um número >= 1.`);
|
|
42
|
+
}
|
|
43
|
+
return Math.floor(value);
|
|
44
|
+
};
|
|
45
|
+
const codeTtl = positive(options.codeTtl, 600, 'codeTtl');
|
|
46
|
+
const maxPerHour = positive(options.maxPerHour, 5, 'maxPerHour');
|
|
47
|
+
const maxCodeAttempts = positive(options.maxCodeAttempts, 5, 'maxCodeAttempts');
|
|
48
|
+
const sentToText = options.sentTo ?? ((masked) => `Email to ${masked}`);
|
|
49
|
+
const sends = new Map();
|
|
50
|
+
/** `true` = ainda cabe um envio para este e-mail na última hora (e conta este). */
|
|
51
|
+
const claim = (email) => {
|
|
52
|
+
const now = Date.now();
|
|
53
|
+
const recent = (sends.get(email) ?? []).filter((t) => now - t < HOUR_MS);
|
|
54
|
+
if (recent.length >= maxPerHour) {
|
|
55
|
+
sends.set(email, recent);
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
recent.push(now);
|
|
59
|
+
sends.delete(email);
|
|
60
|
+
sends.set(email, recent);
|
|
61
|
+
if (sends.size > MAX_TRACKED)
|
|
62
|
+
sends.delete(sends.keys().next().value);
|
|
63
|
+
return true;
|
|
64
|
+
};
|
|
65
|
+
const eligibleAccount = async (ctx, email) => {
|
|
66
|
+
const service = await ctx.containerResolver.make('authkit.server');
|
|
67
|
+
const store = service.config.accountStore;
|
|
68
|
+
const account = await store.findByEmail(email);
|
|
69
|
+
if (!account)
|
|
70
|
+
return null;
|
|
71
|
+
if (supportsAccountStatus(store) && (await store.isDisabled(account.id)))
|
|
72
|
+
return null;
|
|
73
|
+
if (options.eligible) {
|
|
74
|
+
// Um `eligible` que lança vira "não elegível": um 500 só para algumas contas as denunciaria.
|
|
75
|
+
try {
|
|
76
|
+
if (!(await options.eligible(account)))
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
ctx.logger.error({ err: error }, 'authkit: poppyEmailCodeSignIn eligible lançou');
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return account;
|
|
85
|
+
};
|
|
86
|
+
return {
|
|
87
|
+
fields: [{ name: 'email', label: options.label ?? 'Email address', secret: false }],
|
|
88
|
+
...(options.scopes ? { scopes: options.scopes } : {}),
|
|
89
|
+
codeTtl,
|
|
90
|
+
maxCodeAttempts,
|
|
91
|
+
async verify({ credentials, clientId, ctx }) {
|
|
92
|
+
const email = (credentials.email ?? '').trim().toLowerCase();
|
|
93
|
+
if (!EMAIL.test(email))
|
|
94
|
+
return { status: 'failed' };
|
|
95
|
+
const sentTo = sentToText(maskEmail(email));
|
|
96
|
+
const decoy = { status: 'code_required', accountId: null, sentTo };
|
|
97
|
+
// O limite conta para qualquer e-mail — com ou sem conta, a resposta não muda.
|
|
98
|
+
if (!claim(email))
|
|
99
|
+
return decoy;
|
|
100
|
+
const account = await eligibleAccount(ctx, email);
|
|
101
|
+
if (!account)
|
|
102
|
+
return decoy;
|
|
103
|
+
const code = String(randomInt(0, 1_000_000)).padStart(6, '0');
|
|
104
|
+
// Sem `await`: o caminho com conta não pode demorar mais que o sem conta.
|
|
105
|
+
void deliver(ctx, { email, code, clientId, expiresInMinutes: Math.ceil(codeTtl / 60) });
|
|
106
|
+
return { status: 'code_required', accountId: account.id, sentTo, code };
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function hostOf(clientId) {
|
|
111
|
+
try {
|
|
112
|
+
return new URL(clientId).host;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return clientId;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function deliver(ctx, data) {
|
|
119
|
+
try {
|
|
120
|
+
const runtime = await personalAgentsFor(ctx);
|
|
121
|
+
const agentName = runtime?.poppy
|
|
122
|
+
? await runtime.poppy.registry.displayName(data.clientId)
|
|
123
|
+
: hostOf(data.clientId);
|
|
124
|
+
const service = await ctx.containerResolver.make('authkit.server');
|
|
125
|
+
const hook = service.config.mail?.onPoppySignInCode;
|
|
126
|
+
const input = {
|
|
127
|
+
email: data.email,
|
|
128
|
+
code: data.code,
|
|
129
|
+
agentName,
|
|
130
|
+
expiresInMinutes: data.expiresInMinutes,
|
|
131
|
+
};
|
|
132
|
+
if (hook)
|
|
133
|
+
await hook(input);
|
|
134
|
+
else
|
|
135
|
+
await sendPoppySignInCodeEmail(ctx, input);
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
ctx.logger.error({ err: error }, 'authkit: o código do Poppy Mediated Sign-In não saiu');
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -276,5 +276,11 @@ export declare class PoppyService {
|
|
|
276
276
|
revokeAccountGrant(accountId: string, grantId: string): Promise<boolean>;
|
|
277
277
|
/** Revoga todos os Account Tokens da conta (sair de tudo, conta suspensa…). */
|
|
278
278
|
revokeAllAccountGrants(accountId: string): Promise<number>;
|
|
279
|
+
/**
|
|
280
|
+
* Bloqueio pelo console admin: revoga todos os Account Tokens do agente (todas as
|
|
281
|
+
* contas) e encerra as Sessions dele — os Session Tokens param na próxima request.
|
|
282
|
+
* Devolve quantos Account Tokens estavam vivos.
|
|
283
|
+
*/
|
|
284
|
+
disconnectClient(clientId: string): Promise<number>;
|
|
279
285
|
}
|
|
280
286
|
export type { RequestRow };
|
|
@@ -1277,6 +1277,18 @@ export class PoppyService {
|
|
|
1277
1277
|
await this.revokeGrant(g.id);
|
|
1278
1278
|
return live.length;
|
|
1279
1279
|
}
|
|
1280
|
+
/**
|
|
1281
|
+
* Bloqueio pelo console admin: revoga todos os Account Tokens do agente (todas as
|
|
1282
|
+
* contas) e encerra as Sessions dele — os Session Tokens param na próxima request.
|
|
1283
|
+
* Devolve quantos Account Tokens estavam vivos.
|
|
1284
|
+
*/
|
|
1285
|
+
async disconnectClient(clientId) {
|
|
1286
|
+
const ids = (await this.#grants.unrevokedGrantIdsOfClient(clientId)).filter((id) => id.startsWith('pgrant_'));
|
|
1287
|
+
for (const id of ids)
|
|
1288
|
+
await this.revokeGrant(id);
|
|
1289
|
+
await this.#store.endSessionsOfClient(clientId, this.#now());
|
|
1290
|
+
return ids.length;
|
|
1291
|
+
}
|
|
1280
1292
|
// ─── internos ─────────────────────────────────────────────────────────────
|
|
1281
1293
|
/** Scopes de um pedido de sign-in: obrigatórios, conhecidos e do tipo (§4.4). */
|
|
1282
1294
|
#signInScopes(raw, type) {
|
|
@@ -82,6 +82,8 @@ export declare class PoppyStore {
|
|
|
82
82
|
}): Promise<boolean>;
|
|
83
83
|
/** Sign-out (§4.9): as Sessions logadas com o grant continuam, deslogadas. */
|
|
84
84
|
signOutSessionsOfGrant(grantId: string, at: Date): Promise<number>;
|
|
85
|
+
/** Encerra todas as Sessions de um agente (bloqueio no console): os tokens param na hora. */
|
|
86
|
+
endSessionsOfClient(clientId: string, at: Date): Promise<number>;
|
|
85
87
|
insertToken(row: TokenRow): Promise<void>;
|
|
86
88
|
findToken(hash: string): Promise<TokenRow | null>;
|
|
87
89
|
deleteToken(hash: string): Promise<boolean>;
|
|
@@ -152,6 +152,15 @@ export class PoppyStore {
|
|
|
152
152
|
.update({ grant_id: null, scope: '', updated_at: at });
|
|
153
153
|
return affected(result);
|
|
154
154
|
}
|
|
155
|
+
/** Encerra todas as Sessions de um agente (bloqueio no console): os tokens param na hora. */
|
|
156
|
+
async endSessionsOfClient(clientId, at) {
|
|
157
|
+
const result = await this.conn()
|
|
158
|
+
.from(SESSION_TABLE)
|
|
159
|
+
.where('client_id', clientId)
|
|
160
|
+
.whereNull('ended_at')
|
|
161
|
+
.update({ ended_at: at, grant_id: null, scope: '', updated_at: at });
|
|
162
|
+
return affected(result);
|
|
163
|
+
}
|
|
155
164
|
// ─── session tokens ───────────────────────────────────────────────────────
|
|
156
165
|
async insertToken(row) {
|
|
157
166
|
await this.conn().table(TOKEN_TABLE).insert({
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export declare const REGISTRY_TABLE = "auth_agent_registry";
|
|
2
|
+
export type AgentProtocolId = 'pact' | 'poppy';
|
|
3
|
+
export type AgentRegistryStatus = 'allowed' | 'blocked';
|
|
4
|
+
export interface AgentRegistryRow {
|
|
5
|
+
id: string;
|
|
6
|
+
protocol: AgentProtocolId;
|
|
7
|
+
/** PACT: o `iss` do agente. Poppy: o `client_id` (URL do documento de metadata). */
|
|
8
|
+
identifier: string;
|
|
9
|
+
status: AgentRegistryStatus;
|
|
10
|
+
name: string | null;
|
|
11
|
+
/** JWKS do agente PACT (obrigatório num `allowed` PACT). */
|
|
12
|
+
jwksUri: string | null;
|
|
13
|
+
/** Conta do admin que fez a mudança. */
|
|
14
|
+
updatedBy: string | null;
|
|
15
|
+
createdAt: Date;
|
|
16
|
+
updatedAt: Date;
|
|
17
|
+
}
|
|
18
|
+
/** Quanto tempo o snapshot vale antes de reler a tabela. */
|
|
19
|
+
export declare const SNAPSHOT_TTL_MS: number;
|
|
20
|
+
export declare class AgentRegistryStore {
|
|
21
|
+
#private;
|
|
22
|
+
constructor(conn: () => any, options?: {
|
|
23
|
+
now?: () => number;
|
|
24
|
+
});
|
|
25
|
+
/** Todas as linhas, mais recentes primeiro. Lê do banco (console). */
|
|
26
|
+
list(): Promise<AgentRegistryRow[]>;
|
|
27
|
+
/** A linha do agente, pelo snapshot. `null` = o console não diz nada sobre ele. */
|
|
28
|
+
find(protocol: AgentProtocolId, identifier: string): Promise<AgentRegistryRow | null>;
|
|
29
|
+
findById(id: string): Promise<AgentRegistryRow | null>;
|
|
30
|
+
/** Cria ou troca a linha de (protocolo, identificador). */
|
|
31
|
+
upsert(input: {
|
|
32
|
+
protocol: AgentProtocolId;
|
|
33
|
+
identifier: string;
|
|
34
|
+
status: AgentRegistryStatus;
|
|
35
|
+
name?: string | null;
|
|
36
|
+
jwksUri?: string | null;
|
|
37
|
+
updatedBy?: string | null;
|
|
38
|
+
}): Promise<AgentRegistryRow>;
|
|
39
|
+
delete(id: string): Promise<boolean>;
|
|
40
|
+
invalidate(): void;
|
|
41
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registro de personal agents feito pelo console admin — tabela LIB-OWNED
|
|
3
|
+
* `auth_agent_registry` (ver `schema/ensure.ts`). SOMA ao `defineConfig`:
|
|
4
|
+
*
|
|
5
|
+
* - `allowed`: o agente entra mesmo fora da lista do config (PACT: issuer + JWKS;
|
|
6
|
+
* Poppy: `client_id` registrado quando `clients.requireRegistration`).
|
|
7
|
+
* - `blocked`: o agente é recusado mesmo que o config o liste — bloquear é a
|
|
8
|
+
* ação de emergência, e precisa valer sem deploy.
|
|
9
|
+
*
|
|
10
|
+
* O que o config bloqueia continua bloqueado: o console não desfaz o config.
|
|
11
|
+
*
|
|
12
|
+
* A tabela é pequena e lida em TODA verificação de agente PACT, então as linhas
|
|
13
|
+
* ficam num snapshot em memória por {@link SNAPSHOT_TTL_MS}. Escritas por este
|
|
14
|
+
* processo invalidam na hora; em outras instâncias o efeito chega no próximo
|
|
15
|
+
* refresh — o bloqueio corta os tokens já emitidos pelo banco (grants revogados,
|
|
16
|
+
* Sessions encerradas), então o atraso só vale para um agente começando do zero.
|
|
17
|
+
*/
|
|
18
|
+
import { randomBytes } from 'node:crypto';
|
|
19
|
+
export const REGISTRY_TABLE = 'auth_agent_registry';
|
|
20
|
+
/** Quanto tempo o snapshot vale antes de reler a tabela. */
|
|
21
|
+
export const SNAPSHOT_TTL_MS = 15 * 1000;
|
|
22
|
+
function toDate(value) {
|
|
23
|
+
if (value instanceof Date)
|
|
24
|
+
return value;
|
|
25
|
+
if (typeof value === 'number')
|
|
26
|
+
return new Date(value);
|
|
27
|
+
if (typeof value === 'string' && /^\d+$/.test(value))
|
|
28
|
+
return new Date(Number(value));
|
|
29
|
+
return new Date(String(value));
|
|
30
|
+
}
|
|
31
|
+
function toRow(row) {
|
|
32
|
+
return {
|
|
33
|
+
id: row.id,
|
|
34
|
+
protocol: row.protocol,
|
|
35
|
+
identifier: row.identifier,
|
|
36
|
+
status: row.status,
|
|
37
|
+
name: row.name ?? null,
|
|
38
|
+
jwksUri: row.jwks_uri ?? null,
|
|
39
|
+
updatedBy: row.updated_by ?? null,
|
|
40
|
+
createdAt: toDate(row.created_at),
|
|
41
|
+
updatedAt: toDate(row.updated_at),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const key = (protocol, identifier) => `${protocol} ${identifier}`;
|
|
45
|
+
export class AgentRegistryStore {
|
|
46
|
+
#conn;
|
|
47
|
+
#now;
|
|
48
|
+
#snapshot = null;
|
|
49
|
+
#loading = null;
|
|
50
|
+
constructor(conn, options = {}) {
|
|
51
|
+
this.#conn = conn;
|
|
52
|
+
this.#now = options.now ?? Date.now;
|
|
53
|
+
}
|
|
54
|
+
/** Todas as linhas, mais recentes primeiro. Lê do banco (console). */
|
|
55
|
+
async list() {
|
|
56
|
+
const rows = await this.#conn().from(REGISTRY_TABLE).orderBy('updated_at', 'desc');
|
|
57
|
+
return rows.map(toRow);
|
|
58
|
+
}
|
|
59
|
+
/** A linha do agente, pelo snapshot. `null` = o console não diz nada sobre ele. */
|
|
60
|
+
async find(protocol, identifier) {
|
|
61
|
+
return (await this.#rows()).get(key(protocol, identifier)) ?? null;
|
|
62
|
+
}
|
|
63
|
+
async findById(id) {
|
|
64
|
+
const row = await this.#conn().from(REGISTRY_TABLE).where('id', id).first();
|
|
65
|
+
return row ? toRow(row) : null;
|
|
66
|
+
}
|
|
67
|
+
/** Cria ou troca a linha de (protocolo, identificador). */
|
|
68
|
+
async upsert(input) {
|
|
69
|
+
const now = new Date(this.#now());
|
|
70
|
+
const existing = await this.#conn()
|
|
71
|
+
.from(REGISTRY_TABLE)
|
|
72
|
+
.where('protocol', input.protocol)
|
|
73
|
+
.where('identifier', input.identifier)
|
|
74
|
+
.first();
|
|
75
|
+
const values = {
|
|
76
|
+
status: input.status,
|
|
77
|
+
name: input.name ?? null,
|
|
78
|
+
jwks_uri: input.jwksUri ?? null,
|
|
79
|
+
updated_by: input.updatedBy ?? null,
|
|
80
|
+
updated_at: now,
|
|
81
|
+
};
|
|
82
|
+
if (existing) {
|
|
83
|
+
await this.#conn().from(REGISTRY_TABLE).where('id', existing.id).update(values);
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
await this.#conn()
|
|
87
|
+
.table(REGISTRY_TABLE)
|
|
88
|
+
.insert({
|
|
89
|
+
id: `areg_${randomBytes(12).toString('base64url')}`,
|
|
90
|
+
protocol: input.protocol,
|
|
91
|
+
identifier: input.identifier,
|
|
92
|
+
created_at: now,
|
|
93
|
+
...values,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
this.invalidate();
|
|
97
|
+
const row = await this.#conn()
|
|
98
|
+
.from(REGISTRY_TABLE)
|
|
99
|
+
.where('protocol', input.protocol)
|
|
100
|
+
.where('identifier', input.identifier)
|
|
101
|
+
.first();
|
|
102
|
+
return toRow(row);
|
|
103
|
+
}
|
|
104
|
+
async delete(id) {
|
|
105
|
+
const result = await this.#conn().from(REGISTRY_TABLE).where('id', id).delete();
|
|
106
|
+
this.invalidate();
|
|
107
|
+
return (typeof result === 'number' ? result : Array.isArray(result) ? result.length : 0) > 0;
|
|
108
|
+
}
|
|
109
|
+
invalidate() {
|
|
110
|
+
this.#snapshot = null;
|
|
111
|
+
}
|
|
112
|
+
async #rows() {
|
|
113
|
+
const now = this.#now();
|
|
114
|
+
if (this.#snapshot && this.#snapshot.expiresAt > now)
|
|
115
|
+
return this.#snapshot.rows;
|
|
116
|
+
if (!this.#loading) {
|
|
117
|
+
this.#loading = (async () => {
|
|
118
|
+
try {
|
|
119
|
+
const rows = (await this.#conn().from(REGISTRY_TABLE)).map(toRow);
|
|
120
|
+
const map = new Map(rows.map((r) => [key(r.protocol, r.identifier), r]));
|
|
121
|
+
this.#snapshot = { rows: map, expiresAt: this.#now() + SNAPSHOT_TTL_MS };
|
|
122
|
+
return map;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
// Banco fora (ou tabela ainda não criada): fica com o último snapshot, ou
|
|
126
|
+
// nenhum — o config continua valendo sozinho. Tenta de novo logo.
|
|
127
|
+
const rows = this.#snapshot?.rows ?? new Map();
|
|
128
|
+
this.#snapshot = { rows, expiresAt: this.#now() + 1000 };
|
|
129
|
+
return rows;
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
this.#loading = null;
|
|
133
|
+
}
|
|
134
|
+
})();
|
|
135
|
+
}
|
|
136
|
+
return this.#loading;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
@@ -3,8 +3,10 @@ import type { OidcService } from '../provider/oidc_service.js';
|
|
|
3
3
|
import { PersonalAgentVerifier } from './agent_identity.js';
|
|
4
4
|
import type { ResolvedPersonalAgentsConfig } from './config.js';
|
|
5
5
|
import { PersonalAgentDelegation } from './delegation_service.js';
|
|
6
|
+
import { DelegationStore, type GrantRow } from './delegation_store.js';
|
|
6
7
|
import type { JsonFetcher } from './poppy/safe_fetch.js';
|
|
7
8
|
import { PoppyService } from './poppy/service.js';
|
|
9
|
+
import { type AgentProtocolId, AgentRegistryStore } from './registry_store.js';
|
|
8
10
|
/** URLs públicas do authorization server de delegação. */
|
|
9
11
|
export interface PersonalAgentUrls {
|
|
10
12
|
/** `issuer` (RFC 8414) — também o `iss` dos tokens de delegação. */
|
|
@@ -35,6 +37,17 @@ export interface PersonalAgentsRuntime {
|
|
|
35
37
|
revokeAgentGrant(accountId: string, grantId: string): Promise<boolean>;
|
|
36
38
|
/** Revoga todos os grants de personal agents da conta. Devolve quantos estavam vivos. */
|
|
37
39
|
revokeAllAgentGrants(accountId: string): Promise<number>;
|
|
40
|
+
/**
|
|
41
|
+
* Registro do console admin (agentes liberados/bloqueados além do config).
|
|
42
|
+
* `null` sem banco (PACT só de identidade sem `lucid.db`).
|
|
43
|
+
*/
|
|
44
|
+
registry: AgentRegistryStore | null;
|
|
45
|
+
/** Grants de todas as contas (console admin). `null` sem banco. */
|
|
46
|
+
grants: DelegationStore | null;
|
|
47
|
+
/** Revoga um grant de QUALQUER conta (console admin). Devolve o grant, ou `null` se já não valia. */
|
|
48
|
+
revokeGrantById(grantId: string): Promise<GrantRow | null>;
|
|
49
|
+
/** Desconecta um agente de todas as contas (bloqueio). Devolve quantos grants estavam vivos. */
|
|
50
|
+
disconnectAgent(protocol: AgentProtocolId, identifier: string): Promise<number>;
|
|
38
51
|
}
|
|
39
52
|
export interface BuildPersonalAgentsOptions {
|
|
40
53
|
/** Resolve serviços do container (redis do replay store). */
|