@adonis-agora/authkit-sdk 0.6.1 → 0.6.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.
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # @adonis-agora/authkit-sdk
2
+
3
+ Backend SDK for the [AuthKit](https://github.com/DavideCarvalho/adonis-agora-authkit) Admin API:
4
+ manage users, sessions, OIDC clients, organizations, settings, signing keys, and the audit
5
+ log from server-side code — with **one typed interface** and **two interchangeable drivers**.
6
+
7
+ - **`remote`** — HTTP against the Admin REST API (`/api/authkit/v1`), authenticated with a
8
+ Bearer API key. Use it from any backend service.
9
+ - **`embedded`** — in-process calls that resolve the server services straight from the
10
+ AdonisJS container. Use it when the IdP runs in the **same** app: zero HTTP, zero API key.
11
+
12
+ Both drivers return the **exact same shapes**, so you can start embedded and split out to
13
+ remote later without touching call sites.
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ pnpm add @adonis-agora/authkit-sdk
19
+ ```
20
+
21
+ `@adonis-agora/authkit-server` is an **optional** peer dependency — only the `embedded`
22
+ driver needs it (imported lazily). Remote-only consumers can skip it entirely.
23
+
24
+ ## Usage
25
+
26
+ `createAuthkit` always returns a `Promise<Authkit>`.
27
+
28
+ ### Remote
29
+
30
+ ```ts
31
+ import { createAuthkit } from '@adonis-agora/authkit-sdk'
32
+
33
+ const authkit = await createAuthkit({
34
+ mode: 'remote',
35
+ baseUrl: 'https://idp.example.com',
36
+ apiKey: process.env.AUTHKIT_ADMIN_KEY!,
37
+ // apiPrefix: '/api/authkit/v1', // default; must match registerAuthHost
38
+ })
39
+ ```
40
+
41
+ ### Embedded (same app)
42
+
43
+ ```ts
44
+ import app from '@adonisjs/core/services/app'
45
+ import { createAuthkit } from '@adonis-agora/authkit-sdk'
46
+
47
+ const authkit = await createAuthkit({ mode: 'embedded', app })
48
+ ```
49
+
50
+ ### The interface
51
+
52
+ ```ts
53
+ // Users
54
+ await authkit.users.list({ search: 'jane' })
55
+ const user = await authkit.users.create({ email: 'jane@acme.dev' })
56
+ await authkit.users.delete(user.id) // cascades sessions, grants, tokens (LGPD/GDPR)
57
+
58
+ // Sessions
59
+ await authkit.sessions.list(user.id)
60
+ await authkit.sessions.revokeAll(user.id)
61
+
62
+ // OIDC clients
63
+ await authkit.clients.create({ /* client input */ })
64
+ await authkit.clients.regenerateSecret(clientId)
65
+
66
+ // Organizations, members & invitations
67
+ await authkit.organizations.create({ name: 'Acme' })
68
+ await authkit.organizations.members.add(orgId, { accountId, role: 'admin' })
69
+
70
+ // Audit log, stats, settings, signing keys
71
+ await authkit.audit.list({ action: 'user.login' })
72
+ await authkit.stats()
73
+ await authkit.settings.set('branding.name', 'Acme')
74
+ await authkit.keys.rotate({ retire: false })
75
+
76
+ // Token verification
77
+ const result = await authkit.tokens.verify(bearerToken)
78
+ ```
79
+
80
+ Errors surface as `AuthkitApiError`:
81
+
82
+ ```ts
83
+ import { AuthkitApiError } from '@adonis-agora/authkit-sdk'
84
+
85
+ try {
86
+ await authkit.users.get('missing')
87
+ } catch (err) {
88
+ if (err instanceof AuthkitApiError) {
89
+ console.error(err.status, err.message)
90
+ }
91
+ }
92
+ ```
93
+
94
+ ## Documentation
95
+
96
+ Full guide and the Admin REST API reference live in the
97
+ [AuthKit docs](https://github.com/DavideCarvalho/adonis-agora-authkit) (`apps/docs` → Backend SDK
98
+ and Admin API).
99
+
100
+ ## License
101
+
102
+ MIT
@@ -5,6 +5,12 @@ const ACTOR = { actorId: null, ip: null, source: 'admin-api' };
5
5
  * services that only touch `request.protocol()`/`request.host()` (used when
6
6
  * composing the password-reset URL) and `request.ip()`. We deliberately do NOT
7
7
  * import `@adonisjs/core/http` here — out-of-band SDK calls have no real request.
8
+ *
9
+ * It also carries `containerResolver.app` and `logger`, which is all the server's
10
+ * default mailer reads (host config for the sender, branding and locale; the
11
+ * logger for the dev fallback). Without them, an SDK-created organization
12
+ * invitation reached the database and no inbox — the same silent failure the
13
+ * missing `onOrgInvitation` fallback caused on the HTTP path.
8
14
  */
9
15
  function fakeCtx(app) {
10
16
  const origin = (app.config.get('authkit.issuer', '') || '').replace(/\/+$/, '');
@@ -26,6 +32,16 @@ function fakeCtx(app) {
26
32
  host: () => host,
27
33
  ip: () => null,
28
34
  },
35
+ containerResolver: { app },
36
+ // Pino-shaped shim. `ApplicationService` exposes no logger synchronously (it
37
+ // is a container binding), and the only thing the server's default mailer
38
+ // does with it is the dev-time "no @adonisjs/mail installed, here is the
39
+ // link" notice. Dropping the field would make that notice vanish, which is
40
+ // the one case where an SDK caller most needs to be told nothing was sent.
41
+ logger: {
42
+ info: (...args) => console.info(...args),
43
+ error: (...args) => console.error(...args),
44
+ },
29
45
  };
30
46
  }
31
47
  /**
@@ -190,7 +206,11 @@ export async function createEmbeddedAuthkit(opts) {
190
206
  const admin = new AdminSessionsService(service);
191
207
  const sessions = await enrichSessionsWithContext(cfg, userId, await admin.listSessions(userId));
192
208
  const grants = await admin.listGrants(userId);
193
- return { canList: admin.canList, sessions: sessions.map(sessionDto), grants: grants.map(grantDto) };
209
+ return {
210
+ canList: admin.canList,
211
+ sessions: sessions.map(sessionDto),
212
+ grants: grants.map(grantDto),
213
+ };
194
214
  },
195
215
  async revokeAll(userId) {
196
216
  const result = await new AdminSessionsService(service).revokeAll(userId);
@@ -290,7 +310,7 @@ export async function createEmbeddedAuthkit(opts) {
290
310
  return verifier.verify(token);
291
311
  },
292
312
  },
293
- organizations: (function () {
313
+ organizations: (() => {
294
314
  const orgsService = new AdminOrgsService(cfg);
295
315
  const ACTOR = { actorId: null, ip: null, source: 'admin-api' };
296
316
  const origin = (cfg.issuer ?? '').replace(/\/+$/, '');
@@ -306,7 +326,12 @@ export async function createEmbeddedAuthkit(opts) {
306
326
  };
307
327
  }
308
328
  function memberDto(m) {
309
- return { accountId: m.accountId, email: m.email ?? null, role: m.role, joinedAt: m.joinedAt };
329
+ return {
330
+ accountId: m.accountId,
331
+ email: m.email ?? null,
332
+ role: m.role,
333
+ joinedAt: m.joinedAt,
334
+ };
310
335
  }
311
336
  function invitationDto(inv) {
312
337
  return {
@@ -330,17 +355,25 @@ export async function createEmbeddedAuthkit(opts) {
330
355
  async create(input) {
331
356
  const result = await orgsService.createOrg(input, ACTOR);
332
357
  if ('ok' in result && result.ok === false) {
333
- throw new Error(result.reason === 'not_supported' ? 'Organizations não suportado.' : 'Slug já em uso.');
358
+ throw new Error(result.reason === 'not_supported'
359
+ ? 'Organizations não suportado.'
360
+ : 'Slug já em uso.');
334
361
  }
335
362
  return orgDto(result);
336
363
  },
337
364
  async get(id) {
338
365
  const result = await orgsService.getOrg(id);
339
366
  if ('ok' in result && result.ok === false) {
340
- throw new Error(result.reason === 'not_supported' ? 'Organizations não suportado.' : 'Organização não encontrada.');
367
+ throw new Error(result.reason === 'not_supported'
368
+ ? 'Organizations não suportado.'
369
+ : 'Organização não encontrada.');
341
370
  }
342
371
  const detail = result;
343
- return { ...orgDto(detail), members: detail.members.map(memberDto), pendingInvitations: detail.pendingInvitations.map(invitationDto) };
372
+ return {
373
+ ...orgDto(detail),
374
+ members: detail.members.map(memberDto),
375
+ pendingInvitations: detail.pendingInvitations.map(invitationDto),
376
+ };
344
377
  },
345
378
  async update(id, input) {
346
379
  const result = await orgsService.updateOrg(id, input, ACTOR);
@@ -389,7 +422,9 @@ export async function createEmbeddedAuthkit(opts) {
389
422
  },
390
423
  invitations: {
391
424
  async create(orgId, input) {
392
- const result = await orgsService.createInvitation(orgId, input, ACTOR, origin);
425
+ // `ctx` is what lets the server fall back to its own invitation email
426
+ // when the host defines no `mail.onOrgInvitation` hook.
427
+ const result = await orgsService.createInvitation(orgId, input, ACTOR, origin, null, ctx);
393
428
  if (!result.ok)
394
429
  throw new Error('Organização não encontrada.');
395
430
  return invitationDto(result.invitation);
@@ -405,7 +440,7 @@ export async function createEmbeddedAuthkit(opts) {
405
440
  })(),
406
441
  settings: {
407
442
  async list() {
408
- const { RuntimeSettings } = await import('@adonis-agora/authkit-server');
443
+ const { RuntimeSettings } = (await import('@adonis-agora/authkit-server'));
409
444
  let db;
410
445
  try {
411
446
  db = await app.container.make('lucid.db');
@@ -426,7 +461,7 @@ export async function createEmbeddedAuthkit(opts) {
426
461
  };
427
462
  },
428
463
  async get(key) {
429
- const { RuntimeSettings } = await import('@adonis-agora/authkit-server');
464
+ const { RuntimeSettings } = (await import('@adonis-agora/authkit-server'));
430
465
  let db;
431
466
  try {
432
467
  db = await app.container.make('lucid.db');
@@ -442,7 +477,7 @@ export async function createEmbeddedAuthkit(opts) {
442
477
  return { key, value, updatedAt: null, updatedBy: null };
443
478
  },
444
479
  async set(key, value) {
445
- const { RuntimeSettings } = await import('@adonis-agora/authkit-server');
480
+ const { RuntimeSettings } = (await import('@adonis-agora/authkit-server'));
446
481
  let db;
447
482
  try {
448
483
  db = await app.container.make('lucid.db');
@@ -463,7 +498,7 @@ export async function createEmbeddedAuthkit(opts) {
463
498
  return { key, value: saved, updatedAt: new Date().toISOString(), updatedBy: null };
464
499
  },
465
500
  async delete(key) {
466
- const { RuntimeSettings } = await import('@adonis-agora/authkit-server');
501
+ const { RuntimeSettings } = (await import('@adonis-agora/authkit-server'));
467
502
  let db;
468
503
  try {
469
504
  db = await app.container.make('lucid.db');
@@ -486,7 +521,7 @@ export async function createEmbeddedAuthkit(opts) {
486
521
  keys: {
487
522
  async status() {
488
523
  // Build a settings capability for the policy (optional; falls back to defaults when absent).
489
- const { RuntimeSettings } = await import('@adonis-agora/authkit-server');
524
+ const { RuntimeSettings } = (await import('@adonis-agora/authkit-server'));
490
525
  let settingsSvc = null;
491
526
  try {
492
527
  const db = await app.container.make('lucid.db');
@@ -21,7 +21,7 @@ export function createRemoteAuthkit(opts) {
21
21
  const baseUrl = opts.baseUrl.replace(/\/+$/, '');
22
22
  const rawApiPrefix = (opts.apiPrefix ?? '/api/authkit/v1').trim();
23
23
  // Normalize: ensure leading slash, strip trailing slash.
24
- const normalizedApiPrefix = (rawApiPrefix.startsWith('/') ? rawApiPrefix : '/' + rawApiPrefix).replace(/\/+$/, '') || '/';
24
+ const normalizedApiPrefix = (rawApiPrefix.startsWith('/') ? rawApiPrefix : `/${rawApiPrefix}`).replace(/\/+$/, '') || '/';
25
25
  const root = `${baseUrl}${normalizedApiPrefix}`;
26
26
  const doFetch = opts.fetchImpl ?? globalThis.fetch;
27
27
  if (typeof doFetch !== 'function') {
@@ -47,7 +47,8 @@ export function createRemoteAuthkit(opts) {
47
47
  const text = await res.text();
48
48
  const payload = text ? safeJson(text) : undefined;
49
49
  if (!res.ok) {
50
- const envelope = payload?.error;
50
+ const envelope = payload
51
+ ?.error;
51
52
  throw new AuthkitApiError(res.status, envelope?.code ?? 'http_error', envelope?.message ?? `Request failed with status ${res.status}.`);
52
53
  }
53
54
  return payload;
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@adonis-agora/authkit-sdk",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "description": "Backend SDK for the AuthKit Admin API with one typed interface and two drivers: remote (HTTP/Bearer) and embedded (in-process when the IdP runs in the same AdonisJS app).",
5
5
  "license": "MIT",
6
6
  "author": "dudousxd",
7
- "homepage": "https://github.com/DavideCarvalho/adonis-authkit/tree/main/packages/authkit-sdk#readme",
7
+ "homepage": "https://github.com/DavideCarvalho/adonis-agora-authkit/tree/main/packages/authkit-sdk#readme",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "https://github.com/DavideCarvalho/adonis-authkit.git",
10
+ "url": "https://github.com/DavideCarvalho/adonis-agora-authkit.git",
11
11
  "directory": "packages/authkit-sdk"
12
12
  },
13
13
  "bugs": {
14
- "url": "https://github.com/DavideCarvalho/adonis-authkit/issues"
14
+ "url": "https://github.com/DavideCarvalho/adonis-agora-authkit/issues"
15
15
  },
16
16
  "keywords": [
17
17
  "adonisjs",
@@ -47,18 +47,18 @@
47
47
  }
48
48
  },
49
49
  "devDependencies": {
50
- "@adonisjs/core": "7.3.5",
50
+ "@adonisjs/core": "7.4.0",
51
51
  "@adonisjs/tsconfig": "2.0.0",
52
52
  "@japa/assert": "4.2.0",
53
53
  "@japa/runner": "5.3.0",
54
54
  "@poppinss/ts-exec": "1.4.4",
55
55
  "@types/node": "25.9.1",
56
56
  "typescript": "6.0.3",
57
- "@adonis-agora/authkit-server": "0.35.0"
57
+ "@adonis-agora/authkit-server": "0.58.0"
58
58
  },
59
59
  "scripts": {
60
60
  "build": "tsc",
61
- "typecheck": "tsc --noEmit",
61
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.tests.json",
62
62
  "test": "node --import=@poppinss/ts-exec bin/test.ts"
63
63
  }
64
64
  }