@adonis-agora/authkit-server 1.0.0-rc.1 → 1.0.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +4 -5
  3. package/build/commands/clients_create.d.ts +4 -0
  4. package/build/commands/clients_create.js +97 -0
  5. package/build/commands/commands.json +14 -0
  6. package/build/index.d.ts +8 -11
  7. package/build/index.js +5 -9
  8. package/build/providers/authkit_server_provider.js +6 -8
  9. package/build/src/agents/config.d.ts +9 -13
  10. package/build/src/agents/config.js +17 -11
  11. package/build/src/agents/delegation_service.js +3 -3
  12. package/build/src/agents/delegation_store.d.ts +3 -2
  13. package/build/src/agents/delegation_store.js +6 -5
  14. package/build/src/agents/extension.d.ts +261 -0
  15. package/build/src/agents/extension.js +40 -0
  16. package/build/src/agents/middleware.js +1 -1
  17. package/build/src/agents/protocol.d.ts +4 -4
  18. package/build/src/agents/registry_store.d.ts +3 -2
  19. package/build/src/agents/registry_store.js +1 -1
  20. package/build/src/agents/runtime.d.ts +26 -7
  21. package/build/src/agents/runtime.js +110 -75
  22. package/build/src/audit/audit_sink.d.ts +1 -1
  23. package/build/src/audit/audit_sink.js +6 -1
  24. package/build/src/define_config.d.ts +16 -12
  25. package/build/src/define_config.js +11 -7
  26. package/build/src/host/access_token_verifier.js +7 -0
  27. package/build/src/host/account_api/account_api_controller.js +8 -6
  28. package/build/src/host/account_session_sign_in.d.ts +12 -0
  29. package/build/src/host/account_session_sign_in.js +19 -0
  30. package/build/src/host/admin_api/api_clients_controller.d.ts +37 -0
  31. package/build/src/host/admin_api/api_clients_controller.js +31 -1
  32. package/build/src/host/admin_api/dto.d.ts +3 -1
  33. package/build/src/host/admin_api/dto.js +2 -0
  34. package/build/src/host/admin_clients_service.d.ts +20 -0
  35. package/build/src/host/admin_clients_service.js +55 -0
  36. package/build/src/host/admin_console/console_clients_controller.d.ts +41 -0
  37. package/build/src/host/admin_console/console_clients_controller.js +34 -1
  38. package/build/src/host/admin_console/console_personal_agents_controller.d.ts +1 -6
  39. package/build/src/host/admin_console/console_personal_agents_controller.js +50 -30
  40. package/build/src/host/admin_sessions_service.js +8 -5
  41. package/build/src/host/admin_validators.d.ts +29 -0
  42. package/build/src/host/admin_validators.js +30 -0
  43. package/build/src/host/auth_host_config.d.ts +6 -2
  44. package/build/src/host/controllers/account_apps_controller.js +15 -11
  45. package/build/src/host/csrf.d.ts +3 -3
  46. package/build/src/host/csrf.js +3 -13
  47. package/build/src/host/default_mailer.d.ts +11 -6
  48. package/build/src/host/default_mailer.js +16 -12
  49. package/build/src/host/i18n.d.ts +3 -14
  50. package/build/src/host/i18n.js +15 -13
  51. package/build/src/host/register_auth_host.js +30 -61
  52. package/build/src/host/ui-dist/assets/index-u0bMxkLg.js +67 -0
  53. package/build/src/host/ui-dist/index.html +1 -1
  54. package/build/src/provider/build_provider.js +37 -6
  55. package/build/src/provider/oidc_service.d.ts +1 -1
  56. package/build/src/provider/oidc_service.js +1 -1
  57. package/build/src/schema/ensure.d.ts +14 -0
  58. package/build/src/schema/ensure.js +43 -150
  59. package/build/src/service_tenants/client_metadata.d.ts +39 -0
  60. package/build/src/service_tenants/client_metadata.js +80 -0
  61. package/build/src/service_tenants/config.d.ts +44 -0
  62. package/build/src/service_tenants/config.js +44 -0
  63. package/build/src/service_tenants/provider_hooks.d.ts +52 -0
  64. package/build/src/service_tenants/provider_hooks.js +124 -0
  65. package/build/src/service_tenants/tenant_verifier.d.ts +73 -0
  66. package/build/src/service_tenants/tenant_verifier.js +104 -0
  67. package/package.json +2 -2
  68. package/build/src/agents/poppy/client_registry.d.ts +0 -50
  69. package/build/src/agents/poppy/client_registry.js +0 -260
  70. package/build/src/agents/poppy/config.d.ts +0 -396
  71. package/build/src/agents/poppy/config.js +0 -228
  72. package/build/src/agents/poppy/dpop.d.ts +0 -61
  73. package/build/src/agents/poppy/dpop.js +0 -158
  74. package/build/src/agents/poppy/email_code_sign_in.d.ts +0 -27
  75. package/build/src/agents/poppy/email_code_sign_in.js +0 -140
  76. package/build/src/agents/poppy/errors.d.ts +0 -25
  77. package/build/src/agents/poppy/errors.js +0 -25
  78. package/build/src/agents/poppy/replay.d.ts +0 -25
  79. package/build/src/agents/poppy/replay.js +0 -106
  80. package/build/src/agents/poppy/resource.d.ts +0 -100
  81. package/build/src/agents/poppy/resource.js +0 -129
  82. package/build/src/agents/poppy/safe_fetch.d.ts +0 -48
  83. package/build/src/agents/poppy/safe_fetch.js +0 -262
  84. package/build/src/agents/poppy/service.d.ts +0 -293
  85. package/build/src/agents/poppy/service.js +0 -1458
  86. package/build/src/agents/poppy/session_jwt.d.ts +0 -30
  87. package/build/src/agents/poppy/session_jwt.js +0 -133
  88. package/build/src/agents/poppy/store.d.ts +0 -106
  89. package/build/src/agents/poppy/store.js +0 -261
  90. package/build/src/agents/poppy/web_session.d.ts +0 -39
  91. package/build/src/agents/poppy/web_session.js +0 -122
  92. package/build/src/host/controllers/poppy_consent_controller.d.ts +0 -19
  93. package/build/src/host/controllers/poppy_consent_controller.js +0 -199
  94. package/build/src/host/controllers/poppy_controller.d.ts +0 -33
  95. package/build/src/host/controllers/poppy_controller.js +0 -219
  96. package/build/src/host/poppy_session_key.d.ts +0 -9
  97. package/build/src/host/poppy_session_key.js +0 -9
  98. package/build/src/host/ui-dist/assets/index-D0EIeyKK.js +0 -67
@@ -8,7 +8,7 @@
8
8
  <link rel="preconnect" href="https://fonts.googleapis.com">
9
9
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
10
  <link href="https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700&family=JetBrains+Mono:ital,wght@0,400;0,500;0,600;1,400&display=swap" rel="stylesheet">
11
- <script type="module" crossorigin src="/__AUTHKIT_BASE__/assets/index-D0EIeyKK.js"></script>
11
+ <script type="module" crossorigin src="/__AUTHKIT_BASE__/assets/index-u0bMxkLg.js"></script>
12
12
  <link rel="stylesheet" crossorigin href="/__AUTHKIT_BASE__/assets/index-DTSmD4RU.css">
13
13
  </head>
14
14
  <body>
@@ -3,6 +3,8 @@ import { pickModelAdapterClass } from '../adapters/factory.js';
3
3
  import { normalizeActiveOrg, readActiveOrgFromKoaCtx } from '../host/active_org_cookie.js';
4
4
  import { consoleSsoClientMetadata } from '../host/console_sso.js';
5
5
  import { findMcpResource, mcpAuthorizeMiddleware } from '../mcp/mcp_oauth.js';
6
+ import { hideDisabledClients } from '../service_tenants/client_metadata.js';
7
+ import { createServiceTenantHooks } from '../service_tenants/provider_hooks.js';
6
8
  import { createDeviceSources } from './device_sources.js';
7
9
  import { createLogoutSources } from './logout_sources.js';
8
10
  import { registrationPolicyMiddleware } from './registration_policy.js';
@@ -79,21 +81,35 @@ export function buildProvider(config, options, sessionTtlHolder, tokenTtlHolder)
79
81
  return key ? { key, rc: at.resources[key] } : null;
80
82
  };
81
83
  const mcp = config.mcp;
82
- const resourceIndicatorFeatures = at.anyJwt || declaredResources.length > 0 || mcp.enabled
84
+ // Service tenants (`serviceTenants`): `client_credentials` clients with a partition,
85
+ // whose tokens are JWTs for a service-tenant resource. See `service_tenants/`.
86
+ const serviceTenants = createServiceTenantHooks({
87
+ serviceTenants: config.serviceTenants ?? { enabled: false, resources: {} },
88
+ AdapterClass: config.AdapterClass,
89
+ audit: config.audit,
90
+ });
91
+ const signAlg = config.jwks.keys[0]?.alg ?? 'RS256';
92
+ const resourceIndicatorFeatures = at.anyJwt || declaredResources.length > 0 || mcp.enabled || serviceTenants.enabled
83
93
  ? {
84
94
  resourceIndicators: {
85
95
  enabled: true,
86
- defaultResource: async (_ctx, _client, oneOf) => {
96
+ defaultResource: async (ctx, client, oneOf) => {
87
97
  // Nas trocas (code/refresh/device), o provider passa `oneOf` com as
88
98
  // resources já concedidas — devolvemos para não falhar a request.
89
99
  if (oneOf)
90
100
  return oneOf;
101
+ const serviceResource = await serviceTenants.defaultResource(ctx, client);
102
+ if (serviceResource)
103
+ return serviceResource;
91
104
  // Authorize/sem resource explícito: no modo JWT, liga ao resource
92
105
  // default (modo simples). Só opaco: sem resource (AT de sempre).
93
106
  return at.anyJwt ? at.audience : undefined;
94
107
  },
95
108
  useGrantedResource: async () => true,
96
- getResourceServerInfo: (_ctx, resourceIndicator, _client) => {
109
+ getResourceServerInfo: async (ctx, resourceIndicator, client) => {
110
+ const serviceInfo = await serviceTenants.resourceServerInfo(ctx, resourceIndicator, client, signAlg);
111
+ if (serviceInfo)
112
+ return serviceInfo;
97
113
  const found = findResource(resourceIndicator);
98
114
  const isDefault = at.anyJwt && resourceIndicator === at.audience;
99
115
  // Servidores MCP (`mcp`): os declarados e os registrados em runtime.
@@ -122,7 +138,7 @@ export function buildProvider(config, options, sessionTtlHolder, tokenTtlHolder)
122
138
  info.accessTokenTTL = ttl;
123
139
  if (format === 'jwt') {
124
140
  // Assina com a chave de assinatura corrente do keystore (mesma do JWKS).
125
- info.jwt = { sign: { alg: config.jwks.keys[0]?.alg ?? 'RS256' } };
141
+ info.jwt = { sign: { alg: signAlg } };
126
142
  }
127
143
  return info;
128
144
  },
@@ -138,13 +154,23 @@ export function buildProvider(config, options, sessionTtlHolder, tokenTtlHolder)
138
154
  // O ator (`act`, RFC 8693) dos access tokens de impersonation — ver
139
155
  // `impersonationExtraClaims` em `token_exchange.ts`. Sem isto o token trocado
140
156
  // não se distingue de um token do próprio alvo no resource server.
141
- extraTokenClaims: async (_ctx, token) => impersonationExtraClaims(token),
157
+ // Service tenants add `partition`/`capabilities` (see `service_tenants/`).
158
+ extraTokenClaims: async (ctx, token) => {
159
+ const actor = impersonationExtraClaims(token);
160
+ const tenant = await serviceTenants.extraClaims(ctx, token);
161
+ return actor || tenant ? { ...tenant, ...actor } : undefined;
162
+ },
142
163
  // Dispatcher por modelo (suportado pelo oidc-provider: `Adapter` aceita
143
164
  // função `(name) => adapter` além de classe). Session-scoped vai pro
144
165
  // `SessionAdapterClass`, o resto pro `AdapterClass` — mesma regra de
145
166
  // `pickModelAdapterClass`, usada também pelos serviços que instanciam
146
167
  // adapter na mão. Sem `session.adapter`, as duas classes são a mesma.
147
- adapter: ((name) => new (pickModelAdapterClass(name, config.AdapterClass, config.SessionAdapterClass))(name)),
168
+ // A disabled client (`authkit_disabled`) is "not found" for the provider: every
169
+ // endpoint answers `invalid_client` on the next request.
170
+ adapter: ((name) => {
171
+ const instance = new (pickModelAdapterClass(name, config.AdapterClass, config.SessionAdapterClass))(name);
172
+ return name === 'Client' ? hideDisabledClients(instance) : instance;
173
+ }),
148
174
  findAccount: options.findAccount,
149
175
  // Grant REAPROVEITADO (consent já lembrado): o org capturado no primeiro
150
176
  // consent ficaria VELHO se o usuário trocasse de org no console e voltasse a
@@ -244,6 +270,7 @@ export function buildProvider(config, options, sessionTtlHolder, tokenTtlHolder)
244
270
  backchannelLogout: { enabled: true },
245
271
  revocation: { enabled: true },
246
272
  introspection: { enabled: true },
273
+ ...(serviceTenants.enabled ? { clientCredentials: { enabled: true } } : {}),
247
274
  ...registrationFeatures,
248
275
  ...deviceFlowFeatures,
249
276
  ...dpopFeatures,
@@ -279,6 +306,10 @@ export function buildProvider(config, options, sessionTtlHolder, tokenTtlHolder)
279
306
  ? sessionTtlHolder.transientSec
280
307
  : sessionTtlHolder.rememberSec
281
308
  : config.ttl.session,
309
+ // `client_credentials` tokens: the resource's lifetime (a service-tenant resource
310
+ // always sets one), else the access-token TTL.
311
+ ClientCredentials: (_ctx, token) => token?.resourceServer?.accessTokenTTL ??
312
+ (tokenTtlHolder ? tokenTtlHolder.accessTokenSec : config.ttl.accessToken),
282
313
  Interaction: 3600,
283
314
  Grant: tokenTtlHolder
284
315
  ? () => tokenTtlHolder.refreshTokenSec
@@ -28,7 +28,7 @@ export declare class OidcService {
28
28
  };
29
29
  /**
30
30
  * @internal Segredo derivado da app key para um uso (`label`) — HMAC dos nonces
31
- * DPoP do Poppy, por exemplo. Igual em todas as instâncias, sem expor a chave.
31
+ * DPoP de uma extension de personal agents, por exemplo. Igual em todas as instâncias, sem expor a chave.
32
32
  */
33
33
  deriveSecret(label: string): Buffer;
34
34
  /** Pathname do issuer sem barra final (ex.: `/oidc`). Vazio quando montado na raiz. */
@@ -44,7 +44,7 @@ export class OidcService {
44
44
  }
45
45
  /**
46
46
  * @internal Segredo derivado da app key para um uso (`label`) — HMAC dos nonces
47
- * DPoP do Poppy, por exemplo. Igual em todas as instâncias, sem expor a chave.
47
+ * DPoP de uma extension de personal agents, por exemplo. Igual em todas as instâncias, sem expor a chave.
48
48
  */
49
49
  deriveSecret(label) {
50
50
  return createHmac('sha256', this.#appKey).update(`authkit:${label}`).digest();
@@ -23,9 +23,15 @@
23
23
  * }
24
24
  * ```
25
25
  */
26
+ import type { AuthkitTable } from '../agents/extension.js';
26
27
  export interface EnsureSchemaOptions {
27
28
  /** Conexão Lucid a usar. Default: conexão primária. */
28
29
  connection?: string;
30
+ /**
31
+ * Tabelas de `personalAgents.extensions` (`tables` de cada uma), garantidas junto. O provider
32
+ * passa as do config no boot.
33
+ */
34
+ tables?: readonly AuthkitTable[];
29
35
  /**
30
36
  * Tabela da conta, onde a coluna opcional `login_methods` pertence. Vem do
31
37
  * metadado `accountStore.accountTable` (o provider repassa no boot). Undefined
@@ -51,6 +57,14 @@ export interface EnsureSchemaReport {
51
57
  ensured: boolean;
52
58
  };
53
59
  }
60
+ /**
61
+ * Garante tabelas lib-owned no formato {@link AuthkitTable} — o que `ensureAuthkitSchema` faz com as
62
+ * do authkit: cria as que faltam, adiciona colunas e índices novos, nunca dropa nem altera. Para
63
+ * uma extension expor o próprio `ensure*Schema()` para migrations do host. Estável no 1.x.
64
+ */
65
+ export declare function ensureAuthkitTables(db: any, tables: readonly AuthkitTable[], options?: {
66
+ connection?: string;
67
+ }): Promise<Pick<EnsureSchemaReport, 'created' | 'altered' | 'indexed'>>;
54
68
  /**
55
69
  * Garante que as tabelas do authkit existem e têm todas as colunas que esta
56
70
  * versão da lib espera. Aditivo e idempotente — seguro de rodar em todo boot
@@ -309,7 +309,7 @@ const TABLES = [
309
309
  name: 'auth_agent_registry',
310
310
  /**
311
311
  * Agentes liberados (`allowed`) ou bloqueados (`blocked`) pelo console admin,
312
- * somados ao `defineConfig` — PACT pelo `iss`, Poppy pelo `client_id`.
312
+ * somados ao `defineConfig` — PACT pelo `iss`; uma extension pelo identificador dela.
313
313
  */
314
314
  create: (t) => {
315
315
  t.string('id').primary();
@@ -333,135 +333,6 @@ const TABLES = [
333
333
  updated_at: (t) => t.dateTime('updated_at', { useTz: true, precision: 3 }).nullable(),
334
334
  },
335
335
  },
336
- /*
337
- * Personal Agent Protocol (Poppy). Os refresh tokens são grants de
338
- * `auth_agent_grants` (prefixo `pgrant_`) com o hash em
339
- * `auth_agent_refresh_tokens`; aqui ficam Sessions, access tokens, pedidos de
340
- * sign-in e os `jti` vistos. Mesmas regras de data das tabelas acima.
341
- */
342
- {
343
- name: 'auth_poppy_sessions',
344
- /**
345
- * Uma Session: um usuário do agente (`user_id`, opaco) num agente (`client_id`), com o
346
- * `agent_id` opcional. `account_id` é a conta que já usou. `grant_id` e `scope` ficaram da
347
- * Draft 0.1, sem uso (o schema só é aditivo).
348
- */
349
- create: (t) => {
350
- t.string('id').primary();
351
- t.string('client_id', 2048).notNullable();
352
- t.string('user_id').notNullable();
353
- t.string('agent_id').nullable();
354
- t.string('account_id').nullable().index();
355
- t.string('grant_id').nullable().index();
356
- t.text('scope').notNullable();
357
- t.dateTime('expires_at', { useTz: true, precision: 3 }).notNullable();
358
- t.dateTime('ended_at', { useTz: true, precision: 3 }).nullable();
359
- t.dateTime('created_at', { useTz: true, precision: 3 }).notNullable();
360
- t.dateTime('updated_at', { useTz: true, precision: 3 }).notNullable();
361
- },
362
- columns: {
363
- client_id: (t) => t.string('client_id', 2048),
364
- user_id: (t) => t.string('user_id'),
365
- agent_id: (t) => t.string('agent_id').nullable(),
366
- account_id: (t) => t.string('account_id').nullable().index(),
367
- grant_id: (t) => t.string('grant_id').nullable().index(),
368
- scope: (t) => t.text('scope'),
369
- expires_at: (t) => t.dateTime('expires_at', { useTz: true, precision: 3 }).nullable(),
370
- ended_at: (t) => t.dateTime('ended_at', { useTz: true, precision: 3 }).nullable(),
371
- created_at: (t) => t.dateTime('created_at', { useTz: true, precision: 3 }).nullable(),
372
- updated_at: (t) => t.dateTime('updated_at', { useTz: true, precision: 3 }).nullable(),
373
- },
374
- },
375
- {
376
- name: 'auth_poppy_tokens',
377
- /**
378
- * Access tokens — só o hash. `jkt` = chave DPoP; `null` = Bearer. `session_id` e `user_id`
379
- * ficaram da Draft 0.1 e saem vazios: o sign-in não conhece a Session.
380
- */
381
- create: (t) => {
382
- t.string('token_hash', 64).primary();
383
- t.string('session_id').notNullable().index();
384
- t.string('client_id', 2048).notNullable();
385
- t.string('user_id').notNullable();
386
- t.string('account_id').nullable();
387
- t.string('grant_id').nullable().index();
388
- t.text('scope').notNullable();
389
- t.string('resource', 2048).nullable();
390
- t.string('jkt', 64).nullable();
391
- t.dateTime('expires_at', { useTz: true, precision: 3 }).notNullable().index();
392
- t.dateTime('created_at', { useTz: true, precision: 3 }).notNullable();
393
- },
394
- columns: {
395
- session_id: (t) => t.string('session_id').index(),
396
- client_id: (t) => t.string('client_id', 2048),
397
- user_id: (t) => t.string('user_id'),
398
- account_id: (t) => t.string('account_id').nullable(),
399
- grant_id: (t) => t.string('grant_id').nullable().index(),
400
- scope: (t) => t.text('scope'),
401
- resource: (t) => t.string('resource', 2048).nullable(),
402
- jkt: (t) => t.string('jkt', 64).nullable(),
403
- expires_at: (t) => t.dateTime('expires_at', { useTz: true, precision: 3 }).nullable(),
404
- created_at: (t) => t.dateTime('created_at', { useTz: true, precision: 3 }).nullable(),
405
- },
406
- },
407
- {
408
- name: 'auth_poppy_requests',
409
- /**
410
- * Pedidos: `authorize` (Direct — vira código após o consentimento), `device` (RFC 8628),
411
- * `mediated` (aguardando o código de uso único) e `browser` (entrada de um navegador, §6).
412
- * Códigos só como hash. Linhas expiradas são apagadas no próximo pedido.
413
- */
414
- create: (t) => {
415
- t.string('id').primary();
416
- t.string('kind', 16).notNullable();
417
- t.string('code_hash', 64).nullable().unique();
418
- t.string('user_code', 16).nullable().unique();
419
- t.string('client_id', 2048).notNullable();
420
- t.string('session_id').nullable();
421
- t.string('account_id').nullable();
422
- t.text('requested_scope').notNullable();
423
- t.text('granted_scope').nullable();
424
- t.string('redirect_uri', 2048).nullable();
425
- t.string('code_challenge', 128).nullable();
426
- t.string('status', 16).notNullable();
427
- t.integer('attempts').notNullable().defaultTo(0);
428
- t.integer('interval_seconds').nullable();
429
- t.dateTime('last_polled_at', { useTz: true, precision: 3 }).nullable();
430
- t.text('data').nullable();
431
- t.dateTime('expires_at', { useTz: true, precision: 3 }).notNullable().index();
432
- t.dateTime('created_at', { useTz: true, precision: 3 }).notNullable();
433
- },
434
- columns: {
435
- kind: (t) => t.string('kind', 16),
436
- code_hash: (t) => t.string('code_hash', 64).nullable(),
437
- user_code: (t) => t.string('user_code', 16).nullable(),
438
- client_id: (t) => t.string('client_id', 2048),
439
- session_id: (t) => t.string('session_id').nullable(),
440
- account_id: (t) => t.string('account_id').nullable(),
441
- requested_scope: (t) => t.text('requested_scope'),
442
- granted_scope: (t) => t.text('granted_scope').nullable(),
443
- redirect_uri: (t) => t.string('redirect_uri', 2048).nullable(),
444
- code_challenge: (t) => t.string('code_challenge', 128).nullable(),
445
- status: (t) => t.string('status', 16),
446
- attempts: (t) => t.integer('attempts').defaultTo(0),
447
- interval_seconds: (t) => t.integer('interval_seconds').nullable(),
448
- last_polled_at: (t) => t.dateTime('last_polled_at', { useTz: true, precision: 3 }).nullable(),
449
- data: (t) => t.text('data').nullable(),
450
- expires_at: (t) => t.dateTime('expires_at', { useTz: true, precision: 3 }).nullable(),
451
- created_at: (t) => t.dateTime('created_at', { useTz: true, precision: 3 }).nullable(),
452
- },
453
- },
454
- {
455
- name: 'auth_poppy_jtis',
456
- /** `jti` já aceitos (client assertions, Session JWTs, provas DPoP), até expirarem — anti-replay entre instâncias. */
457
- create: (t) => {
458
- t.string('key', 100).primary();
459
- t.dateTime('expires_at', { useTz: true, precision: 3 }).notNullable().index();
460
- },
461
- columns: {
462
- expires_at: (t) => t.dateTime('expires_at', { useTz: true, precision: 3 }).nullable(),
463
- },
464
- },
465
336
  ];
466
337
  /** Linhas de um `rawQuery`, no formato de cada driver (pg, mysql2, sqlite). */
467
338
  function catalogRows(result) {
@@ -586,26 +457,9 @@ async function ensureIndex(conn, table, index) {
586
457
  throw error;
587
458
  }
588
459
  }
589
- /**
590
- * Garante que as tabelas do authkit existem e têm todas as colunas que esta
591
- * versão da lib espera. Aditivo e idempotente — seguro de rodar em todo boot
592
- * e dentro de migrations.
593
- *
594
- * `db` é o manager (`Database`, no boot) ou o client da própria migration
595
- * (`this.db`, um `QueryClient`/`TransactionClient`, usado como está).
596
- */
597
- export async function ensureAuthkitSchema(db, options = {}) {
598
- const conn = typeof db.connection !== 'function'
599
- ? db
600
- : options.connection
601
- ? db.connection(options.connection)
602
- : db.connection();
603
- const report = {
604
- created: [],
605
- altered: {},
606
- loginMethods: { table: options.accountTable ?? 'users', ensured: false },
607
- };
608
- for (const def of TABLES) {
460
+ /** Cria/completa as tabelas (o miolo de {@link ensureAuthkitSchema}). */
461
+ async function ensureTables(conn, tables, report) {
462
+ for (const def of tables) {
609
463
  if (!(await tableExists(conn, def.name))) {
610
464
  try {
611
465
  await conn.schema.createTable(def.name, def.create);
@@ -639,6 +493,45 @@ export async function ensureAuthkitSchema(db, options = {}) {
639
493
  report.indexed[def.name].push(index.name);
640
494
  }
641
495
  }
496
+ }
497
+ /**
498
+ * Garante tabelas lib-owned no formato {@link AuthkitTable} — o que `ensureAuthkitSchema` faz com as
499
+ * do authkit: cria as que faltam, adiciona colunas e índices novos, nunca dropa nem altera. Para
500
+ * uma extension expor o próprio `ensure*Schema()` para migrations do host. Estável no 1.x.
501
+ */
502
+ export async function ensureAuthkitTables(db, tables, options = {}) {
503
+ const conn = typeof db.connection !== 'function'
504
+ ? db
505
+ : options.connection
506
+ ? db.connection(options.connection)
507
+ : db.connection();
508
+ const report = {
509
+ created: [],
510
+ altered: {},
511
+ };
512
+ await ensureTables(conn, tables, report);
513
+ return report;
514
+ }
515
+ /**
516
+ * Garante que as tabelas do authkit existem e têm todas as colunas que esta
517
+ * versão da lib espera. Aditivo e idempotente — seguro de rodar em todo boot
518
+ * e dentro de migrations.
519
+ *
520
+ * `db` é o manager (`Database`, no boot) ou o client da própria migration
521
+ * (`this.db`, um `QueryClient`/`TransactionClient`, usado como está).
522
+ */
523
+ export async function ensureAuthkitSchema(db, options = {}) {
524
+ const conn = typeof db.connection !== 'function'
525
+ ? db
526
+ : options.connection
527
+ ? db.connection(options.connection)
528
+ : db.connection();
529
+ const report = {
530
+ created: [],
531
+ altered: {},
532
+ loginMethods: { table: options.accountTable ?? 'users', ensured: false },
533
+ };
534
+ await ensureTables(conn, [...TABLES, ...(options.tables ?? [])], report);
642
535
  // Coluna `login_methods` na tabela da CONTA — a tabela é HOST-owned (não está
643
536
  // em TABLES porque o nome/shape são decisão do app), mas a LIB consome a
644
537
  // coluna (LoginMethodsPreferenceCapability). Alguns deploys de host só migram
@@ -0,0 +1,39 @@
1
+ import type { OidcAdapter } from '../adapters/adapter_contract.js';
2
+ /**
3
+ * authkit-owned keys in a persisted `Client` payload. oidc-provider strips unknown
4
+ * metadata when it builds a `Client` (and when dynamic registration persists one), so
5
+ * these keys can only be written by authkit itself (console, Admin API, CLI) and are
6
+ * read straight from the adapter.
7
+ */
8
+ export declare const SERVICE_TENANT_KEY = "authkit_service_tenant";
9
+ export declare const CLIENT_DISABLED_KEY = "authkit_disabled";
10
+ /** The service-tenant part of a client. */
11
+ export interface ServiceTenantInfo {
12
+ /** Partition (tenant) the client acts as. Emitted as the `partition` claim. */
13
+ partition: string;
14
+ /** Granted capabilities. Emitted as the `capabilities` claim when non-empty. */
15
+ capabilities: string[];
16
+ }
17
+ /** Letters, digits, `.`, `_`, `:` and `-`; starts with a letter or digit; up to 128 chars. */
18
+ export declare const PARTITION_PATTERN: RegExp;
19
+ /** Like {@link PARTITION_PATTERN}, plus `*` and `/`. */
20
+ export declare const CAPABILITY_PATTERN: RegExp;
21
+ export declare const MAX_CAPABILITIES = 64;
22
+ /** Reads the service-tenant metadata from a raw client payload, or `null`. */
23
+ export declare function serviceTenantOf(payload: Record<string, unknown> | undefined | null): ServiceTenantInfo | null;
24
+ /** `true` when the raw client payload is disabled. */
25
+ export declare function isClientDisabled(payload: Record<string, unknown> | undefined | null): boolean;
26
+ /**
27
+ * Validates and normalizes service-tenant input. Returns an error message or the
28
+ * normalized value (trimmed, de-duplicated capabilities).
29
+ */
30
+ export declare function normalizeServiceTenant(input: {
31
+ partition: string;
32
+ capabilities?: string[];
33
+ }): ServiceTenantInfo | string;
34
+ /**
35
+ * Wraps the provider's `Client` adapter so a disabled client is "not found": every
36
+ * endpoint answers `invalid_client` from the next request on, on every instance that
37
+ * shares the adapter. Writes are untouched.
38
+ */
39
+ export declare function hideDisabledClients<T extends OidcAdapter>(adapter: T): T;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * authkit-owned keys in a persisted `Client` payload. oidc-provider strips unknown
3
+ * metadata when it builds a `Client` (and when dynamic registration persists one), so
4
+ * these keys can only be written by authkit itself (console, Admin API, CLI) and are
5
+ * read straight from the adapter.
6
+ */
7
+ export const SERVICE_TENANT_KEY = 'authkit_service_tenant';
8
+ export const CLIENT_DISABLED_KEY = 'authkit_disabled';
9
+ /** Letters, digits, `.`, `_`, `:` and `-`; starts with a letter or digit; up to 128 chars. */
10
+ export const PARTITION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
11
+ /** Like {@link PARTITION_PATTERN}, plus `*` and `/`. */
12
+ export const CAPABILITY_PATTERN = /^[A-Za-z0-9*][A-Za-z0-9._:*/-]{0,127}$/;
13
+ export const MAX_CAPABILITIES = 64;
14
+ /** Reads the service-tenant metadata from a raw client payload, or `null`. */
15
+ export function serviceTenantOf(payload) {
16
+ const raw = payload?.[SERVICE_TENANT_KEY];
17
+ if (!raw || typeof raw !== 'object')
18
+ return null;
19
+ if (typeof raw.partition !== 'string' || !PARTITION_PATTERN.test(raw.partition))
20
+ return null;
21
+ const capabilities = Array.isArray(raw.capabilities)
22
+ ? raw.capabilities.filter((c) => typeof c === 'string' && c.length > 0)
23
+ : [];
24
+ return { partition: raw.partition, capabilities };
25
+ }
26
+ /** `true` when the raw client payload is disabled. */
27
+ export function isClientDisabled(payload) {
28
+ return payload?.[CLIENT_DISABLED_KEY] === true;
29
+ }
30
+ /**
31
+ * Validates and normalizes service-tenant input. Returns an error message or the
32
+ * normalized value (trimmed, de-duplicated capabilities).
33
+ */
34
+ export function normalizeServiceTenant(input) {
35
+ // Called directly too (not only behind the HTTP validators): check the types here.
36
+ const rawPartition = input?.partition;
37
+ const partition = typeof rawPartition === 'string' ? rawPartition.trim() : '';
38
+ if (!PARTITION_PATTERN.test(partition)) {
39
+ return `partition "${partition}" is invalid: use letters, digits, ".", "_", ":" or "-" (max 128 chars)`;
40
+ }
41
+ const rawCapabilities = input.capabilities ?? [];
42
+ if (!Array.isArray(rawCapabilities))
43
+ return 'capabilities must be an array of strings';
44
+ const capabilities = [];
45
+ for (const raw of rawCapabilities) {
46
+ if (typeof raw !== 'string')
47
+ return 'capabilities must be an array of strings';
48
+ const cap = raw.trim();
49
+ if (!CAPABILITY_PATTERN.test(cap)) {
50
+ return `capability "${cap}" is invalid: use letters, digits, ".", "_", ":", "*", "/" or "-" (max 128 chars)`;
51
+ }
52
+ if (!capabilities.includes(cap))
53
+ capabilities.push(cap);
54
+ }
55
+ if (capabilities.length > MAX_CAPABILITIES) {
56
+ return `at most ${MAX_CAPABILITIES} capabilities per client`;
57
+ }
58
+ return { partition, capabilities };
59
+ }
60
+ /**
61
+ * Wraps the provider's `Client` adapter so a disabled client is "not found": every
62
+ * endpoint answers `invalid_client` from the next request on, on every instance that
63
+ * shares the adapter. Writes are untouched.
64
+ */
65
+ export function hideDisabledClients(adapter) {
66
+ return new Proxy(adapter, {
67
+ get(target, prop, receiver) {
68
+ if (prop === 'find') {
69
+ return async (id) => {
70
+ const payload = await target.find(id);
71
+ return isClientDisabled(payload)
72
+ ? undefined
73
+ : payload;
74
+ };
75
+ }
76
+ const value = Reflect.get(target, prop, receiver);
77
+ return typeof value === 'function' ? value.bind(target) : value;
78
+ },
79
+ });
80
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Service tenants: confidential `client_credentials` clients that act as a partition
3
+ * (`partition` claim) of a resource server (e.g. a durable control plane). Their tokens
4
+ * are JWT access tokens (RFC 9068) whose `aud` is the resource (RFC 8707).
5
+ */
6
+ /** One resource that issues service-tenant tokens. */
7
+ export interface ServiceTenantResourceInput {
8
+ /** `aud` of the token. Default: the resource indicator itself. */
9
+ audience?: string;
10
+ /** Token lifetime in seconds. Default: 600 (10 minutes). */
11
+ expiresIn?: number;
12
+ /** Scopes a service tenant may request for this resource. Default: none. */
13
+ scopes?: string[];
14
+ }
15
+ export interface ServiceTenantsConfigInput {
16
+ /**
17
+ * Resource indicators (RFC 8707) that issue service-tenant tokens, e.g.
18
+ * `{ 'urn:agora:durable': {} }`. Only service-tenant clients can get tokens for them.
19
+ */
20
+ resources: Record<string, ServiceTenantResourceInput>;
21
+ }
22
+ export interface ResolvedServiceTenantResource {
23
+ audience: string;
24
+ expiresIn: number;
25
+ scopes: string[];
26
+ }
27
+ export interface ResolvedServiceTenantsConfig {
28
+ /** `true` when at least one resource is declared. */
29
+ enabled: boolean;
30
+ resources: Record<string, ResolvedServiceTenantResource>;
31
+ }
32
+ /** Default token lifetime: 10 minutes. */
33
+ export declare const DEFAULT_SERVICE_TENANT_TTL = 600;
34
+ /**
35
+ * Resolves `serviceTenants`. Throws on an invalid resource indicator, a non-positive
36
+ * `expiresIn`, or a resource also declared in `accessTokens.resources` (a resource is
37
+ * either for users or for service tenants, never both).
38
+ */
39
+ export declare function resolveServiceTenants(input: ServiceTenantsConfigInput | undefined, accessTokenResources?: Record<string, unknown>): ResolvedServiceTenantsConfig;
40
+ /** Finds a declared service-tenant resource, tolerating a trailing slash. */
41
+ export declare function findServiceTenantResource(config: ResolvedServiceTenantsConfig, indicator: string): {
42
+ key: string;
43
+ resource: ResolvedServiceTenantResource;
44
+ } | null;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Service tenants: confidential `client_credentials` clients that act as a partition
3
+ * (`partition` claim) of a resource server (e.g. a durable control plane). Their tokens
4
+ * are JWT access tokens (RFC 9068) whose `aud` is the resource (RFC 8707).
5
+ */
6
+ /** Default token lifetime: 10 minutes. */
7
+ export const DEFAULT_SERVICE_TENANT_TTL = 600;
8
+ const trimSlash = (s) => s.replace(/\/+$/, '');
9
+ /**
10
+ * Resolves `serviceTenants`. Throws on an invalid resource indicator, a non-positive
11
+ * `expiresIn`, or a resource also declared in `accessTokens.resources` (a resource is
12
+ * either for users or for service tenants, never both).
13
+ */
14
+ export function resolveServiceTenants(input, accessTokenResources = {}) {
15
+ const resources = {};
16
+ const userResources = new Set(Object.keys(accessTokenResources).map(trimSlash));
17
+ for (const [indicator, rc] of Object.entries(input?.resources ?? {})) {
18
+ const parsed = URL.parse(indicator);
19
+ if (!parsed || indicator.includes('#')) {
20
+ throw new Error(`authkit: serviceTenants.resources["${indicator}"] must be an absolute URI without a fragment (e.g. "urn:agora:durable").`);
21
+ }
22
+ if (userResources.has(trimSlash(indicator))) {
23
+ throw new Error(`authkit: "${indicator}" is declared in both accessTokens.resources and serviceTenants.resources. Pick one.`);
24
+ }
25
+ const expiresIn = rc?.expiresIn ?? DEFAULT_SERVICE_TENANT_TTL;
26
+ if (!Number.isInteger(expiresIn) || expiresIn <= 0) {
27
+ throw new Error(`authkit: serviceTenants.resources["${indicator}"].expiresIn must be a positive integer (seconds).`);
28
+ }
29
+ resources[indicator] = {
30
+ audience: rc?.audience ?? indicator,
31
+ expiresIn,
32
+ scopes: [...(rc?.scopes ?? [])],
33
+ };
34
+ }
35
+ return { enabled: Object.keys(resources).length > 0, resources };
36
+ }
37
+ /** Finds a declared service-tenant resource, tolerating a trailing slash. */
38
+ export function findServiceTenantResource(config, indicator) {
39
+ if (config.resources[indicator])
40
+ return { key: indicator, resource: config.resources[indicator] };
41
+ const trimmed = trimSlash(indicator);
42
+ const key = Object.keys(config.resources).find((k) => trimSlash(k) === trimmed);
43
+ return key ? { key, resource: config.resources[key] } : null;
44
+ }
@@ -0,0 +1,52 @@
1
+ import type { OidcAdapterClass } from '../adapters/factory.js';
2
+ import type { AuditSink } from '../audit/audit_sink.js';
3
+ import { type ResolvedServiceTenantsConfig } from './config.js';
4
+ export interface ServiceTenantHooksDeps {
5
+ serviceTenants: ResolvedServiceTenantsConfig;
6
+ /** Adapter class of the `Client` model (raw: sees authkit's own keys). */
7
+ AdapterClass: OidcAdapterClass;
8
+ audit?: AuditSink;
9
+ }
10
+ /** Resource server info for a service-tenant resource, in oidc-provider's shape. */
11
+ export interface ServiceTenantResourceServerInfo {
12
+ scope: string;
13
+ audience: string;
14
+ accessTokenFormat: 'jwt';
15
+ accessTokenTTL: number;
16
+ jwt: {
17
+ sign: {
18
+ alg: string;
19
+ };
20
+ };
21
+ }
22
+ /**
23
+ * The provider hooks behind service tenants:
24
+ *
25
+ * - a service-tenant resource is granted only to a service-tenant client, only on the
26
+ * `client_credentials` grant, always as a JWT access token (RFC 9068);
27
+ * - a service-tenant client can only get tokens for a service-tenant resource (when
28
+ * it sends no `resource` and exactly one is declared, that one is used);
29
+ * - its tokens carry the `partition` (and `capabilities`) claims read from the client
30
+ * at issuance time, so an edit applies to the next token.
31
+ */
32
+ export declare function createServiceTenantHooks(deps: ServiceTenantHooksDeps): {
33
+ enabled: boolean;
34
+ /**
35
+ * `defaultResource` for a service-tenant client: the only declared resource, or
36
+ * `invalid_target` when several are declared. `undefined` for any other client.
37
+ */
38
+ defaultResource(ctx: any, client: any): Promise<string | undefined>;
39
+ /**
40
+ * `getResourceServerInfo` for service tenants. Returns the info for a
41
+ * service-tenant resource, `undefined` when neither the resource nor the client is
42
+ * a service-tenant one (the caller handles it), and throws `invalid_target` for a
43
+ * mismatch.
44
+ */
45
+ resourceServerInfo(ctx: any, indicator: string, client: any, signAlg: string): Promise<ServiceTenantResourceServerInfo | undefined>;
46
+ /** `extraTokenClaims` for a service-tenant token; audits the issuance. */
47
+ extraClaims(ctx: any, token: any): Promise<{
48
+ partition: string;
49
+ capabilities?: string[];
50
+ } | undefined>;
51
+ };
52
+ export type ServiceTenantHooks = ReturnType<typeof createServiceTenantHooks>;