@adonis-agora/authkit-sdk 0.6.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/LICENSE +21 -0
- package/build/index.d.ts +8 -0
- package/build/index.js +4 -0
- package/build/src/embedded_driver.d.ts +16 -0
- package/build/src/embedded_driver.js +509 -0
- package/build/src/errors.d.ts +9 -0
- package/build/src/errors.js +14 -0
- package/build/src/factory.d.ts +18 -0
- package/build/src/factory.js +17 -0
- package/build/src/remote_driver.d.ts +27 -0
- package/build/src/remote_driver.js +193 -0
- package/build/src/types.d.ts +381 -0
- package/build/src/types.js +9 -0
- package/package.json +64 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Davi de Carvalho
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/build/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createAuthkit } from './src/factory.js';
|
|
2
|
+
export type { CreateAuthkitOptions } from './src/factory.js';
|
|
3
|
+
export { createRemoteAuthkit } from './src/remote_driver.js';
|
|
4
|
+
export type { RemoteOptions } from './src/remote_driver.js';
|
|
5
|
+
export { createEmbeddedAuthkit } from './src/embedded_driver.js';
|
|
6
|
+
export type { EmbeddedOptions } from './src/embedded_driver.js';
|
|
7
|
+
export { AuthkitApiError } from './src/errors.js';
|
|
8
|
+
export type * from './src/types.js';
|
package/build/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ApplicationService } from '@adonisjs/core/types';
|
|
2
|
+
import type { Authkit } from './types.js';
|
|
3
|
+
export interface EmbeddedOptions {
|
|
4
|
+
/** The AdonisJS application service (e.g. injected `app`). */
|
|
5
|
+
app: ApplicationService;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Embedded driver: when the IdP runs IN-PROCESS in the same AdonisJS app, this
|
|
9
|
+
* resolves the server services from the container (`authkit.server`) and calls
|
|
10
|
+
* the SAME underlying services the Admin API controllers use
|
|
11
|
+
* (`AdminUsersService`, `AdminClientsService`, `AdminSessionsService`,
|
|
12
|
+
* `TokenVerifyService`), producing identical return shapes. The
|
|
13
|
+
* `@adonis-agora/authkit-server` package is imported LAZILY so remote-mode
|
|
14
|
+
* users never need it installed (it's an optional peer dependency).
|
|
15
|
+
*/
|
|
16
|
+
export declare function createEmbeddedAuthkit(opts: EmbeddedOptions): Promise<Authkit>;
|
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
/** Audit actor used for SDK-originated writes — mirrors the REST `admin-api` source. */
|
|
2
|
+
const ACTOR = { actorId: null, ip: null, source: 'admin-api' };
|
|
3
|
+
/**
|
|
4
|
+
* Builds a minimal HttpContext-shaped object good enough for the server
|
|
5
|
+
* services that only touch `request.protocol()`/`request.host()` (used when
|
|
6
|
+
* composing the password-reset URL) and `request.ip()`. We deliberately do NOT
|
|
7
|
+
* import `@adonisjs/core/http` here — out-of-band SDK calls have no real request.
|
|
8
|
+
*/
|
|
9
|
+
function fakeCtx(app) {
|
|
10
|
+
const origin = (app.config.get('authkit.issuer', '') || '').replace(/\/+$/, '');
|
|
11
|
+
let protocol = 'https';
|
|
12
|
+
let host = 'localhost';
|
|
13
|
+
if (origin) {
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(origin);
|
|
16
|
+
protocol = url.protocol.replace(/:$/, '');
|
|
17
|
+
host = url.host;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
/* keep defaults */
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
request: {
|
|
25
|
+
protocol: () => protocol,
|
|
26
|
+
host: () => host,
|
|
27
|
+
ip: () => null,
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Embedded driver: when the IdP runs IN-PROCESS in the same AdonisJS app, this
|
|
33
|
+
* resolves the server services from the container (`authkit.server`) and calls
|
|
34
|
+
* the SAME underlying services the Admin API controllers use
|
|
35
|
+
* (`AdminUsersService`, `AdminClientsService`, `AdminSessionsService`,
|
|
36
|
+
* `TokenVerifyService`), producing identical return shapes. The
|
|
37
|
+
* `@adonis-agora/authkit-server` package is imported LAZILY so remote-mode
|
|
38
|
+
* users never need it installed (it's an optional peer dependency).
|
|
39
|
+
*/
|
|
40
|
+
export async function createEmbeddedAuthkit(opts) {
|
|
41
|
+
const { app } = opts;
|
|
42
|
+
// Lazy import: only remote-mode consumers may not have the server installed.
|
|
43
|
+
const server = await import('@adonis-agora/authkit-server');
|
|
44
|
+
const { AdminUsersService, AdminClientsService, AdminSessionsService, AdminOrgsService, TokenVerifyService, enrichSessionsWithContext, computeAdminStats, buildKeysStatus, rotateNow, } = server;
|
|
45
|
+
const service = await app.container.make('authkit.server');
|
|
46
|
+
const cfg = service.config;
|
|
47
|
+
const ctx = fakeCtx(app);
|
|
48
|
+
// ---- DTO projections (mirror admin_api/dto.ts) ----
|
|
49
|
+
const usersService = new AdminUsersService(cfg);
|
|
50
|
+
async function userDto(account) {
|
|
51
|
+
return {
|
|
52
|
+
id: account.id,
|
|
53
|
+
email: account.email,
|
|
54
|
+
name: account.name ?? null,
|
|
55
|
+
avatarUrl: account.avatarUrl ?? null,
|
|
56
|
+
globalRoles: account.globalRoles ?? [],
|
|
57
|
+
disabled: await usersService.isDisabled(account.id),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function clientDto(client) {
|
|
61
|
+
return {
|
|
62
|
+
clientId: client.clientId,
|
|
63
|
+
confidential: client.confidential,
|
|
64
|
+
grants: client.grants,
|
|
65
|
+
redirectUris: client.redirectUris,
|
|
66
|
+
postLogoutRedirectUris: client.postLogoutRedirectUris,
|
|
67
|
+
tokenEndpointAuthMethod: client.tokenEndpointAuthMethod,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function sessionDto(s) {
|
|
71
|
+
return {
|
|
72
|
+
id: s.id,
|
|
73
|
+
accountId: s.accountId,
|
|
74
|
+
loginTs: s.loginTs ?? null,
|
|
75
|
+
amr: s.amr ?? [],
|
|
76
|
+
userAgent: s.userAgent ?? null,
|
|
77
|
+
browser: s.browser ?? null,
|
|
78
|
+
os: s.os ?? null,
|
|
79
|
+
ip: s.ip ?? null,
|
|
80
|
+
location: s.location ?? null,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function grantDto(g) {
|
|
84
|
+
return {
|
|
85
|
+
id: g.id,
|
|
86
|
+
accountId: g.accountId,
|
|
87
|
+
clientId: g.clientId ?? null,
|
|
88
|
+
accessTokens: g.accessTokens,
|
|
89
|
+
refreshTokens: g.refreshTokens,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
function auditDto(e) {
|
|
93
|
+
return {
|
|
94
|
+
id: e.id,
|
|
95
|
+
type: e.type,
|
|
96
|
+
accountId: e.accountId ?? null,
|
|
97
|
+
email: e.email ?? null,
|
|
98
|
+
clientId: e.clientId ?? null,
|
|
99
|
+
actorId: e.actorId ?? null,
|
|
100
|
+
ip: e.ip ?? null,
|
|
101
|
+
metadata: e.metadata ?? null,
|
|
102
|
+
createdAt: e.createdAt instanceof Date ? e.createdAt.toISOString() : e.createdAt,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function normalizeClientInput(input) {
|
|
106
|
+
return {
|
|
107
|
+
clientId: input.clientId?.trim() || undefined,
|
|
108
|
+
redirectUris: input.redirectUris ?? [],
|
|
109
|
+
postLogoutRedirectUris: input.postLogoutRedirectUris ?? [],
|
|
110
|
+
grantTypes: input.grantTypes ?? [],
|
|
111
|
+
tokenEndpointAuthMethod: input.tokenEndpointAuthMethod ?? 'client_secret_basic',
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
return {
|
|
115
|
+
users: {
|
|
116
|
+
async list(params = {}) {
|
|
117
|
+
const search = (params.search ?? '').trim();
|
|
118
|
+
const page = Math.max(1, params.page ?? 1);
|
|
119
|
+
const limit = Math.max(1, Math.min(100, params.limit ?? 20));
|
|
120
|
+
const result = await cfg.accountStore.listAccounts({ search, page, limit });
|
|
121
|
+
const data = await Promise.all(result.data.map((u) => userDto(u)));
|
|
122
|
+
return { data, total: result.total, page, limit };
|
|
123
|
+
},
|
|
124
|
+
async get(id) {
|
|
125
|
+
const account = await cfg.accountStore.findById(id);
|
|
126
|
+
if (!account)
|
|
127
|
+
throw new Error('Usuário não encontrado.');
|
|
128
|
+
return userDto(account);
|
|
129
|
+
},
|
|
130
|
+
async create(input) {
|
|
131
|
+
const result = await usersService.create(ctx, {
|
|
132
|
+
email: input.email.trim(),
|
|
133
|
+
name: input.name ?? null,
|
|
134
|
+
password: input.password ?? null,
|
|
135
|
+
invite: input.invite === true,
|
|
136
|
+
}, ACTOR);
|
|
137
|
+
if (!result.ok)
|
|
138
|
+
throw new Error('Já existe uma conta com este e-mail.');
|
|
139
|
+
return { ...(await userDto(result.account)), invited: result.invited };
|
|
140
|
+
},
|
|
141
|
+
async update(id, input) {
|
|
142
|
+
const account = await cfg.accountStore.findById(id);
|
|
143
|
+
if (!account)
|
|
144
|
+
throw new Error('Usuário não encontrado.');
|
|
145
|
+
if (Array.isArray(input.globalRoles)) {
|
|
146
|
+
const normalized = Array.from(new Set(input.globalRoles.map((r) => String(r).trim()).filter(Boolean)));
|
|
147
|
+
await usersService.setGlobalRoles(id, normalized);
|
|
148
|
+
}
|
|
149
|
+
if (input.name !== undefined || input.avatarUrl !== undefined) {
|
|
150
|
+
const patch = {};
|
|
151
|
+
if (input.name !== undefined)
|
|
152
|
+
patch.name = input.name;
|
|
153
|
+
if (input.avatarUrl !== undefined)
|
|
154
|
+
patch.avatarUrl = input.avatarUrl;
|
|
155
|
+
await usersService.updateProfile(id, patch);
|
|
156
|
+
}
|
|
157
|
+
const updated = await cfg.accountStore.findById(id);
|
|
158
|
+
return userDto(updated);
|
|
159
|
+
},
|
|
160
|
+
async disable(id) {
|
|
161
|
+
const applied = await usersService.setStatus(id, true, ACTOR);
|
|
162
|
+
if (!applied)
|
|
163
|
+
throw new Error('O store de contas não suporta habilitar/desabilitar.');
|
|
164
|
+
return { id, disabled: true };
|
|
165
|
+
},
|
|
166
|
+
async enable(id) {
|
|
167
|
+
const applied = await usersService.setStatus(id, false, ACTOR);
|
|
168
|
+
if (!applied)
|
|
169
|
+
throw new Error('O store de contas não suporta habilitar/desabilitar.');
|
|
170
|
+
return { id, disabled: false };
|
|
171
|
+
},
|
|
172
|
+
async resetPassword(id) {
|
|
173
|
+
const account = await usersService.resetPassword(ctx, id, ACTOR);
|
|
174
|
+
if (!account)
|
|
175
|
+
throw new Error('Usuário não encontrado.');
|
|
176
|
+
return { id, sent: true };
|
|
177
|
+
},
|
|
178
|
+
async delete(id) {
|
|
179
|
+
const outcome = await usersService.delete(service, id, ACTOR);
|
|
180
|
+
if (!outcome.ok) {
|
|
181
|
+
throw new Error(outcome.reason === 'not_found'
|
|
182
|
+
? 'Usuário não encontrado.'
|
|
183
|
+
: 'O store de contas não suporta deletar usuários.');
|
|
184
|
+
}
|
|
185
|
+
return { id, deleted: true, ...outcome.result };
|
|
186
|
+
},
|
|
187
|
+
},
|
|
188
|
+
sessions: {
|
|
189
|
+
async list(userId) {
|
|
190
|
+
const admin = new AdminSessionsService(service);
|
|
191
|
+
const sessions = await enrichSessionsWithContext(cfg, userId, await admin.listSessions(userId));
|
|
192
|
+
const grants = await admin.listGrants(userId);
|
|
193
|
+
return { canList: admin.canList, sessions: sessions.map(sessionDto), grants: grants.map(grantDto) };
|
|
194
|
+
},
|
|
195
|
+
async revokeAll(userId) {
|
|
196
|
+
const result = await new AdminSessionsService(service).revokeAll(userId);
|
|
197
|
+
await cfg.audit?.record({
|
|
198
|
+
type: 'session.revoked_all',
|
|
199
|
+
accountId: userId,
|
|
200
|
+
actorId: ACTOR.actorId,
|
|
201
|
+
ip: ACTOR.ip,
|
|
202
|
+
metadata: { actor: ACTOR.source, ...result },
|
|
203
|
+
});
|
|
204
|
+
return result;
|
|
205
|
+
},
|
|
206
|
+
},
|
|
207
|
+
clients: {
|
|
208
|
+
async list() {
|
|
209
|
+
const svc = new AdminClientsService(service);
|
|
210
|
+
if (!svc.canList)
|
|
211
|
+
return { data: [], canList: false };
|
|
212
|
+
const clients = await svc.list();
|
|
213
|
+
return { data: clients.map(clientDto), canList: true };
|
|
214
|
+
},
|
|
215
|
+
async get(id) {
|
|
216
|
+
const client = await new AdminClientsService(service).find(id);
|
|
217
|
+
if (!client)
|
|
218
|
+
throw new Error('Client não encontrado.');
|
|
219
|
+
return clientDto(client);
|
|
220
|
+
},
|
|
221
|
+
async create(input) {
|
|
222
|
+
const svc = new AdminClientsService(service);
|
|
223
|
+
const created = await svc.create(normalizeClientInput(input));
|
|
224
|
+
await cfg.audit?.record({
|
|
225
|
+
type: 'client.created',
|
|
226
|
+
clientId: created.clientId,
|
|
227
|
+
ip: null,
|
|
228
|
+
metadata: { actor: 'admin-api' },
|
|
229
|
+
});
|
|
230
|
+
return { clientId: created.clientId, clientSecret: created.clientSecret ?? null };
|
|
231
|
+
},
|
|
232
|
+
async update(id, input) {
|
|
233
|
+
const svc = new AdminClientsService(service);
|
|
234
|
+
const existing = await svc.find(id);
|
|
235
|
+
if (!existing)
|
|
236
|
+
throw new Error('Client não encontrado.');
|
|
237
|
+
await svc.update(id, normalizeClientInput(input));
|
|
238
|
+
await cfg.audit?.record({
|
|
239
|
+
type: 'client.updated',
|
|
240
|
+
clientId: id,
|
|
241
|
+
ip: null,
|
|
242
|
+
metadata: { actor: 'admin-api' },
|
|
243
|
+
});
|
|
244
|
+
return clientDto(await svc.find(id));
|
|
245
|
+
},
|
|
246
|
+
async regenerateSecret(id) {
|
|
247
|
+
const svc = new AdminClientsService(service);
|
|
248
|
+
const secret = await svc.regenerateSecret(id);
|
|
249
|
+
await cfg.audit?.record({
|
|
250
|
+
type: 'client.updated',
|
|
251
|
+
clientId: id,
|
|
252
|
+
ip: null,
|
|
253
|
+
metadata: { actor: 'admin-api', action: 'regenerate_secret' },
|
|
254
|
+
});
|
|
255
|
+
return { clientId: id, clientSecret: secret };
|
|
256
|
+
},
|
|
257
|
+
async delete(id) {
|
|
258
|
+
const svc = new AdminClientsService(service);
|
|
259
|
+
await svc.delete(id);
|
|
260
|
+
await cfg.audit?.record({
|
|
261
|
+
type: 'client.deleted',
|
|
262
|
+
clientId: id,
|
|
263
|
+
ip: null,
|
|
264
|
+
metadata: { actor: 'admin-api' },
|
|
265
|
+
});
|
|
266
|
+
return { clientId: id, deleted: true };
|
|
267
|
+
},
|
|
268
|
+
},
|
|
269
|
+
audit: {
|
|
270
|
+
async list(params = {}) {
|
|
271
|
+
const sink = cfg.audit;
|
|
272
|
+
if (!sink || typeof sink.list !== 'function') {
|
|
273
|
+
throw new Error('O sink de auditoria configurado não suporta consulta.');
|
|
274
|
+
}
|
|
275
|
+
const page = Math.max(1, params.page ?? 1);
|
|
276
|
+
const limit = Math.max(1, Math.min(100, params.limit ?? 20));
|
|
277
|
+
const type = params.type?.trim() || undefined;
|
|
278
|
+
const subject = params.subject?.trim() || undefined;
|
|
279
|
+
const result = await sink.list({ page, limit, type, subject });
|
|
280
|
+
return { data: result.data.map(auditDto), total: result.total, page, limit };
|
|
281
|
+
},
|
|
282
|
+
},
|
|
283
|
+
async stats() {
|
|
284
|
+
const sessions = new AdminSessionsService(service);
|
|
285
|
+
return computeAdminStats(cfg, sessions);
|
|
286
|
+
},
|
|
287
|
+
tokens: {
|
|
288
|
+
async verify(token) {
|
|
289
|
+
const verifier = new TokenVerifyService(cfg, service.provider);
|
|
290
|
+
return verifier.verify(token);
|
|
291
|
+
},
|
|
292
|
+
},
|
|
293
|
+
organizations: (function () {
|
|
294
|
+
const orgsService = new AdminOrgsService(cfg);
|
|
295
|
+
const ACTOR = { actorId: null, ip: null, source: 'admin-api' };
|
|
296
|
+
const origin = (cfg.issuer ?? '').replace(/\/+$/, '');
|
|
297
|
+
function orgDto(org) {
|
|
298
|
+
return {
|
|
299
|
+
id: org.id,
|
|
300
|
+
name: org.name,
|
|
301
|
+
slug: org.slug,
|
|
302
|
+
logoUrl: org.logoUrl ?? null,
|
|
303
|
+
metadata: org.metadata ?? null,
|
|
304
|
+
createdAt: org.createdAt,
|
|
305
|
+
memberCount: org.memberCount,
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
function memberDto(m) {
|
|
309
|
+
return { accountId: m.accountId, email: m.email ?? null, role: m.role, joinedAt: m.joinedAt };
|
|
310
|
+
}
|
|
311
|
+
function invitationDto(inv) {
|
|
312
|
+
return {
|
|
313
|
+
id: inv.id,
|
|
314
|
+
organizationId: inv.organizationId,
|
|
315
|
+
email: inv.email,
|
|
316
|
+
role: inv.role,
|
|
317
|
+
invitedBy: inv.invitedBy,
|
|
318
|
+
expiresAt: inv.expiresAt,
|
|
319
|
+
acceptedAt: inv.acceptedAt ?? null,
|
|
320
|
+
createdAt: inv.createdAt,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
return {
|
|
324
|
+
async list() {
|
|
325
|
+
const result = await orgsService.listOrgs();
|
|
326
|
+
if (!Array.isArray(result))
|
|
327
|
+
throw new Error('Organizations não é suportado nesta instalação.');
|
|
328
|
+
return { data: result.map(orgDto) };
|
|
329
|
+
},
|
|
330
|
+
async create(input) {
|
|
331
|
+
const result = await orgsService.createOrg(input, ACTOR);
|
|
332
|
+
if ('ok' in result && result.ok === false) {
|
|
333
|
+
throw new Error(result.reason === 'not_supported' ? 'Organizations não suportado.' : 'Slug já em uso.');
|
|
334
|
+
}
|
|
335
|
+
return orgDto(result);
|
|
336
|
+
},
|
|
337
|
+
async get(id) {
|
|
338
|
+
const result = await orgsService.getOrg(id);
|
|
339
|
+
if ('ok' in result && result.ok === false) {
|
|
340
|
+
throw new Error(result.reason === 'not_supported' ? 'Organizations não suportado.' : 'Organização não encontrada.');
|
|
341
|
+
}
|
|
342
|
+
const detail = result;
|
|
343
|
+
return { ...orgDto(detail), members: detail.members.map(memberDto), pendingInvitations: detail.pendingInvitations.map(invitationDto) };
|
|
344
|
+
},
|
|
345
|
+
async update(id, input) {
|
|
346
|
+
const result = await orgsService.updateOrg(id, input, ACTOR);
|
|
347
|
+
if ('ok' in result && result.ok === false) {
|
|
348
|
+
throw new Error('Organização não encontrada ou slug já em uso.');
|
|
349
|
+
}
|
|
350
|
+
return orgDto(result);
|
|
351
|
+
},
|
|
352
|
+
async delete(id) {
|
|
353
|
+
const result = await orgsService.deleteOrg(id, ACTOR);
|
|
354
|
+
if (!result.ok)
|
|
355
|
+
throw new Error('Organização não encontrada.');
|
|
356
|
+
return { id, deleted: true };
|
|
357
|
+
},
|
|
358
|
+
members: {
|
|
359
|
+
async list(orgId) {
|
|
360
|
+
const result = await orgsService.getOrg(orgId);
|
|
361
|
+
if ('ok' in result && result.ok === false)
|
|
362
|
+
throw new Error('Organização não encontrada.');
|
|
363
|
+
return result.members.map(memberDto);
|
|
364
|
+
},
|
|
365
|
+
async add(orgId, input) {
|
|
366
|
+
const result = await orgsService.addMember(orgId, input, ACTOR);
|
|
367
|
+
if (!result.ok)
|
|
368
|
+
throw new Error('Não foi possível adicionar membro.');
|
|
369
|
+
return { orgId, accountId: input.accountId, role: input.role, added: true };
|
|
370
|
+
},
|
|
371
|
+
async remove(orgId, accountId) {
|
|
372
|
+
const result = await orgsService.removeMember(orgId, accountId, ACTOR);
|
|
373
|
+
if (!result.ok) {
|
|
374
|
+
if (result.reason === 'last_owner')
|
|
375
|
+
throw new Error('Não é possível remover o último owner.');
|
|
376
|
+
throw new Error('Membro não encontrado.');
|
|
377
|
+
}
|
|
378
|
+
return { orgId, accountId, removed: true };
|
|
379
|
+
},
|
|
380
|
+
async updateRole(orgId, accountId, role) {
|
|
381
|
+
const result = await orgsService.updateMemberRole(orgId, accountId, role, ACTOR);
|
|
382
|
+
if (!result.ok) {
|
|
383
|
+
if (result.reason === 'last_owner')
|
|
384
|
+
throw new Error('Não é possível rebaixar o último owner.');
|
|
385
|
+
throw new Error('Membro não encontrado.');
|
|
386
|
+
}
|
|
387
|
+
return { orgId, accountId, role, updated: true };
|
|
388
|
+
},
|
|
389
|
+
},
|
|
390
|
+
invitations: {
|
|
391
|
+
async create(orgId, input) {
|
|
392
|
+
const result = await orgsService.createInvitation(orgId, input, ACTOR, origin);
|
|
393
|
+
if (!result.ok)
|
|
394
|
+
throw new Error('Organização não encontrada.');
|
|
395
|
+
return invitationDto(result.invitation);
|
|
396
|
+
},
|
|
397
|
+
async revoke(orgId, invitationId) {
|
|
398
|
+
const result = await orgsService.revokeInvitation(orgId, invitationId, ACTOR);
|
|
399
|
+
if (!result.ok)
|
|
400
|
+
throw new Error('Convite não encontrado.');
|
|
401
|
+
return { orgId, invitationId, revoked: true };
|
|
402
|
+
},
|
|
403
|
+
},
|
|
404
|
+
};
|
|
405
|
+
})(),
|
|
406
|
+
settings: {
|
|
407
|
+
async list() {
|
|
408
|
+
const { RuntimeSettings } = await import('@adonis-agora/authkit-server');
|
|
409
|
+
let db;
|
|
410
|
+
try {
|
|
411
|
+
db = await app.container.make('lucid.db');
|
|
412
|
+
}
|
|
413
|
+
catch {
|
|
414
|
+
return { data: [] };
|
|
415
|
+
}
|
|
416
|
+
const connection = cfg.accountStore?.connectionName;
|
|
417
|
+
const svc = new RuntimeSettings(db, connection ? { connection } : {});
|
|
418
|
+
const rows = await svc.listSettings();
|
|
419
|
+
return {
|
|
420
|
+
data: rows.map((r) => ({
|
|
421
|
+
key: r.key,
|
|
422
|
+
value: r.value,
|
|
423
|
+
updatedAt: r.updatedAt instanceof Date ? r.updatedAt.toISOString() : (r.updatedAt ?? null),
|
|
424
|
+
updatedBy: r.updatedBy ?? null,
|
|
425
|
+
})),
|
|
426
|
+
};
|
|
427
|
+
},
|
|
428
|
+
async get(key) {
|
|
429
|
+
const { RuntimeSettings } = await import('@adonis-agora/authkit-server');
|
|
430
|
+
let db;
|
|
431
|
+
try {
|
|
432
|
+
db = await app.container.make('lucid.db');
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
throw new Error('Runtime settings not available.');
|
|
436
|
+
}
|
|
437
|
+
const connection = cfg.accountStore?.connectionName;
|
|
438
|
+
const svc = new RuntimeSettings(db, connection ? { connection } : {});
|
|
439
|
+
const value = await svc.getSetting(key);
|
|
440
|
+
if (value === null)
|
|
441
|
+
throw new Error(`Setting '${key}' not found.`);
|
|
442
|
+
return { key, value, updatedAt: null, updatedBy: null };
|
|
443
|
+
},
|
|
444
|
+
async set(key, value) {
|
|
445
|
+
const { RuntimeSettings } = await import('@adonis-agora/authkit-server');
|
|
446
|
+
let db;
|
|
447
|
+
try {
|
|
448
|
+
db = await app.container.make('lucid.db');
|
|
449
|
+
}
|
|
450
|
+
catch {
|
|
451
|
+
throw new Error('Runtime settings not available.');
|
|
452
|
+
}
|
|
453
|
+
const connection = cfg.accountStore?.connectionName;
|
|
454
|
+
const svc = new RuntimeSettings(db, connection ? { connection } : {});
|
|
455
|
+
await svc.setSetting(key, value, null);
|
|
456
|
+
const saved = await svc.getSetting(key);
|
|
457
|
+
await cfg.audit?.record({
|
|
458
|
+
type: 'settings.updated',
|
|
459
|
+
actorId: null,
|
|
460
|
+
ip: null,
|
|
461
|
+
metadata: { key, value },
|
|
462
|
+
});
|
|
463
|
+
return { key, value: saved, updatedAt: new Date().toISOString(), updatedBy: null };
|
|
464
|
+
},
|
|
465
|
+
async delete(key) {
|
|
466
|
+
const { RuntimeSettings } = await import('@adonis-agora/authkit-server');
|
|
467
|
+
let db;
|
|
468
|
+
try {
|
|
469
|
+
db = await app.container.make('lucid.db');
|
|
470
|
+
}
|
|
471
|
+
catch {
|
|
472
|
+
throw new Error('Runtime settings not available.');
|
|
473
|
+
}
|
|
474
|
+
const connection = cfg.accountStore?.connectionName;
|
|
475
|
+
const svc = new RuntimeSettings(db, connection ? { connection } : {});
|
|
476
|
+
await svc.deleteSetting(key);
|
|
477
|
+
await cfg.audit?.record({
|
|
478
|
+
type: 'settings.updated',
|
|
479
|
+
actorId: null,
|
|
480
|
+
ip: null,
|
|
481
|
+
metadata: { key, action: 'deleted' },
|
|
482
|
+
});
|
|
483
|
+
return { key, deleted: true };
|
|
484
|
+
},
|
|
485
|
+
},
|
|
486
|
+
keys: {
|
|
487
|
+
async status() {
|
|
488
|
+
// Build a settings capability for the policy (optional; falls back to defaults when absent).
|
|
489
|
+
const { RuntimeSettings } = await import('@adonis-agora/authkit-server');
|
|
490
|
+
let settingsSvc = null;
|
|
491
|
+
try {
|
|
492
|
+
const db = await app.container.make('lucid.db');
|
|
493
|
+
const connection = cfg.accountStore?.connectionName;
|
|
494
|
+
settingsSvc = new RuntimeSettings(db, connection ? { connection } : {});
|
|
495
|
+
}
|
|
496
|
+
catch {
|
|
497
|
+
// RuntimeSettings unavailable — buildKeysStatus will fall back to defaults.
|
|
498
|
+
}
|
|
499
|
+
const status = await buildKeysStatus(service, settingsSvc);
|
|
500
|
+
if (!status)
|
|
501
|
+
throw new Error('jwks não é managed+store.');
|
|
502
|
+
return status;
|
|
503
|
+
},
|
|
504
|
+
async rotate(input) {
|
|
505
|
+
return rotateNow(service, input);
|
|
506
|
+
},
|
|
507
|
+
},
|
|
508
|
+
};
|
|
509
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error thrown by the remote driver when the Admin API responds with a non-2xx
|
|
3
|
+
* status. Parsed from the API's `{ error: { code, message } }` envelope.
|
|
4
|
+
*/
|
|
5
|
+
export declare class AuthkitApiError extends Error {
|
|
6
|
+
readonly status: number;
|
|
7
|
+
readonly code: string;
|
|
8
|
+
constructor(status: number, code: string, message: string);
|
|
9
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error thrown by the remote driver when the Admin API responds with a non-2xx
|
|
3
|
+
* status. Parsed from the API's `{ error: { code, message } }` envelope.
|
|
4
|
+
*/
|
|
5
|
+
export class AuthkitApiError extends Error {
|
|
6
|
+
status;
|
|
7
|
+
code;
|
|
8
|
+
constructor(status, code, message) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = 'AuthkitApiError';
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.code = code;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { EmbeddedOptions } from './embedded_driver.js';
|
|
2
|
+
import type { RemoteOptions } from './remote_driver.js';
|
|
3
|
+
import type { Authkit } from './types.js';
|
|
4
|
+
export type CreateAuthkitOptions = ({
|
|
5
|
+
mode: 'remote';
|
|
6
|
+
} & RemoteOptions) | ({
|
|
7
|
+
mode: 'embedded';
|
|
8
|
+
} & EmbeddedOptions);
|
|
9
|
+
/**
|
|
10
|
+
* Creates an AuthKit backend SDK over the Admin API. Pick a driver via `mode`:
|
|
11
|
+
*
|
|
12
|
+
* - `remote`: HTTP against `<baseUrl>/api/authkit/v1` with a Bearer API key.
|
|
13
|
+
* - `embedded`: in-process, resolving the server services from the AdonisJS
|
|
14
|
+
* container — use when the IdP runs in the SAME app.
|
|
15
|
+
*
|
|
16
|
+
* Always returns a Promise (the embedded driver lazy-imports the server kit).
|
|
17
|
+
*/
|
|
18
|
+
export declare function createAuthkit(options: CreateAuthkitOptions): Promise<Authkit>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { createEmbeddedAuthkit } from './embedded_driver.js';
|
|
2
|
+
import { createRemoteAuthkit } from './remote_driver.js';
|
|
3
|
+
/**
|
|
4
|
+
* Creates an AuthKit backend SDK over the Admin API. Pick a driver via `mode`:
|
|
5
|
+
*
|
|
6
|
+
* - `remote`: HTTP against `<baseUrl>/api/authkit/v1` with a Bearer API key.
|
|
7
|
+
* - `embedded`: in-process, resolving the server services from the AdonisJS
|
|
8
|
+
* container — use when the IdP runs in the SAME app.
|
|
9
|
+
*
|
|
10
|
+
* Always returns a Promise (the embedded driver lazy-imports the server kit).
|
|
11
|
+
*/
|
|
12
|
+
export function createAuthkit(options) {
|
|
13
|
+
if (options.mode === 'embedded') {
|
|
14
|
+
return createEmbeddedAuthkit(options);
|
|
15
|
+
}
|
|
16
|
+
return Promise.resolve(createRemoteAuthkit(options));
|
|
17
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Authkit } from './types.js';
|
|
2
|
+
export interface RemoteOptions {
|
|
3
|
+
/** Base URL of the IdP host, e.g. `https://idp.example.com`. */
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
/** Admin API key sent as `Authorization: Bearer <apiKey>`. */
|
|
6
|
+
apiKey: string;
|
|
7
|
+
/**
|
|
8
|
+
* Path prefix of the Admin REST API on the IdP host.
|
|
9
|
+
* Must match the `adminApi` prefix configured in `registerAuthHost`.
|
|
10
|
+
* Defaults to `'/api/authkit/v1'` (back-compat).
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* // Custom prefix
|
|
14
|
+
* createAuthkit({ mode: 'remote', baseUrl, apiKey, apiPrefix: '/authkit/api' })
|
|
15
|
+
*/
|
|
16
|
+
apiPrefix?: string;
|
|
17
|
+
/** Override the fetch implementation (defaults to global `fetch`). */
|
|
18
|
+
fetchImpl?: typeof fetch;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Remote driver: a thin typed fetch wrapper over the Admin REST API
|
|
22
|
+
* (`/api/authkit/v1/*`). Paths match the server route list EXACTLY. Non-2xx
|
|
23
|
+
* responses are mapped to {@link AuthkitApiError} (parsed from the
|
|
24
|
+
* `{ error: { code, message } }` envelope); network/parse failures are wrapped
|
|
25
|
+
* in an error with code `network_error`.
|
|
26
|
+
*/
|
|
27
|
+
export declare function createRemoteAuthkit(opts: RemoteOptions): Authkit;
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { AuthkitApiError } from './errors.js';
|
|
2
|
+
/** Drops `undefined` query params and stringifies the rest. */
|
|
3
|
+
function buildQuery(params) {
|
|
4
|
+
const search = new URLSearchParams();
|
|
5
|
+
for (const [key, value] of Object.entries(params)) {
|
|
6
|
+
if (value === undefined || value === null)
|
|
7
|
+
continue;
|
|
8
|
+
search.set(key, String(value));
|
|
9
|
+
}
|
|
10
|
+
const qs = search.toString();
|
|
11
|
+
return qs ? `?${qs}` : '';
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Remote driver: a thin typed fetch wrapper over the Admin REST API
|
|
15
|
+
* (`/api/authkit/v1/*`). Paths match the server route list EXACTLY. Non-2xx
|
|
16
|
+
* responses are mapped to {@link AuthkitApiError} (parsed from the
|
|
17
|
+
* `{ error: { code, message } }` envelope); network/parse failures are wrapped
|
|
18
|
+
* in an error with code `network_error`.
|
|
19
|
+
*/
|
|
20
|
+
export function createRemoteAuthkit(opts) {
|
|
21
|
+
const baseUrl = opts.baseUrl.replace(/\/+$/, '');
|
|
22
|
+
const rawApiPrefix = (opts.apiPrefix ?? '/api/authkit/v1').trim();
|
|
23
|
+
// Normalize: ensure leading slash, strip trailing slash.
|
|
24
|
+
const normalizedApiPrefix = (rawApiPrefix.startsWith('/') ? rawApiPrefix : '/' + rawApiPrefix).replace(/\/+$/, '') || '/';
|
|
25
|
+
const root = `${baseUrl}${normalizedApiPrefix}`;
|
|
26
|
+
const doFetch = opts.fetchImpl ?? globalThis.fetch;
|
|
27
|
+
if (typeof doFetch !== 'function') {
|
|
28
|
+
throw new Error('No fetch implementation available — pass `fetchImpl` to createAuthkit.');
|
|
29
|
+
}
|
|
30
|
+
async function request(method, path, body) {
|
|
31
|
+
const headers = {
|
|
32
|
+
authorization: `Bearer ${opts.apiKey}`,
|
|
33
|
+
accept: 'application/json',
|
|
34
|
+
};
|
|
35
|
+
const init = { method, headers };
|
|
36
|
+
if (body !== undefined) {
|
|
37
|
+
headers['content-type'] = 'application/json';
|
|
38
|
+
init.body = JSON.stringify(body);
|
|
39
|
+
}
|
|
40
|
+
let res;
|
|
41
|
+
try {
|
|
42
|
+
res = await doFetch(`${root}${path}`, init);
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
throw new AuthkitApiError(0, 'network_error', err.message || 'Network request failed.');
|
|
46
|
+
}
|
|
47
|
+
const text = await res.text();
|
|
48
|
+
const payload = text ? safeJson(text) : undefined;
|
|
49
|
+
if (!res.ok) {
|
|
50
|
+
const envelope = payload?.error;
|
|
51
|
+
throw new AuthkitApiError(res.status, envelope?.code ?? 'http_error', envelope?.message ?? `Request failed with status ${res.status}.`);
|
|
52
|
+
}
|
|
53
|
+
return payload;
|
|
54
|
+
}
|
|
55
|
+
function safeJson(text) {
|
|
56
|
+
try {
|
|
57
|
+
return JSON.parse(text);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
users: {
|
|
65
|
+
list(params = {}) {
|
|
66
|
+
return request('GET', `/users${buildQuery({ ...params })}`);
|
|
67
|
+
},
|
|
68
|
+
get(id) {
|
|
69
|
+
return request('GET', `/users/${encodeURIComponent(id)}`);
|
|
70
|
+
},
|
|
71
|
+
create(input) {
|
|
72
|
+
return request('POST', '/users', input);
|
|
73
|
+
},
|
|
74
|
+
update(id, input) {
|
|
75
|
+
return request('PATCH', `/users/${encodeURIComponent(id)}`, input);
|
|
76
|
+
},
|
|
77
|
+
disable(id) {
|
|
78
|
+
return request('POST', `/users/${encodeURIComponent(id)}/disable`);
|
|
79
|
+
},
|
|
80
|
+
enable(id) {
|
|
81
|
+
return request('POST', `/users/${encodeURIComponent(id)}/enable`);
|
|
82
|
+
},
|
|
83
|
+
resetPassword(id) {
|
|
84
|
+
return request('POST', `/users/${encodeURIComponent(id)}/reset-password`);
|
|
85
|
+
},
|
|
86
|
+
delete(id) {
|
|
87
|
+
return request('DELETE', `/users/${encodeURIComponent(id)}`);
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
sessions: {
|
|
91
|
+
list(userId) {
|
|
92
|
+
return request('GET', `/users/${encodeURIComponent(userId)}/sessions`);
|
|
93
|
+
},
|
|
94
|
+
revokeAll(userId) {
|
|
95
|
+
return request('POST', `/users/${encodeURIComponent(userId)}/revoke-sessions`);
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
clients: {
|
|
99
|
+
list() {
|
|
100
|
+
return request('GET', '/clients');
|
|
101
|
+
},
|
|
102
|
+
get(id) {
|
|
103
|
+
return request('GET', `/clients/${encodeURIComponent(id)}`);
|
|
104
|
+
},
|
|
105
|
+
create(input) {
|
|
106
|
+
return request('POST', '/clients', input);
|
|
107
|
+
},
|
|
108
|
+
update(id, input) {
|
|
109
|
+
return request('PATCH', `/clients/${encodeURIComponent(id)}`, input);
|
|
110
|
+
},
|
|
111
|
+
regenerateSecret(id) {
|
|
112
|
+
return request('POST', `/clients/${encodeURIComponent(id)}/regenerate-secret`);
|
|
113
|
+
},
|
|
114
|
+
delete(id) {
|
|
115
|
+
return request('DELETE', `/clients/${encodeURIComponent(id)}`);
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
audit: {
|
|
119
|
+
list(params = {}) {
|
|
120
|
+
return request('GET', `/audit${buildQuery({ ...params })}`);
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
stats() {
|
|
124
|
+
return request('GET', '/stats');
|
|
125
|
+
},
|
|
126
|
+
tokens: {
|
|
127
|
+
verify(token) {
|
|
128
|
+
return request('POST', '/tokens/verify', { token });
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
settings: {
|
|
132
|
+
list() {
|
|
133
|
+
return request('GET', '/settings');
|
|
134
|
+
},
|
|
135
|
+
get(key) {
|
|
136
|
+
return request('GET', `/settings/${encodeURIComponent(key)}`);
|
|
137
|
+
},
|
|
138
|
+
set(key, value) {
|
|
139
|
+
return request('PUT', `/settings/${encodeURIComponent(key)}`, { value });
|
|
140
|
+
},
|
|
141
|
+
delete(key) {
|
|
142
|
+
return request('DELETE', `/settings/${encodeURIComponent(key)}`);
|
|
143
|
+
},
|
|
144
|
+
},
|
|
145
|
+
organizations: {
|
|
146
|
+
list() {
|
|
147
|
+
return request('GET', '/organizations');
|
|
148
|
+
},
|
|
149
|
+
create(input) {
|
|
150
|
+
return request('POST', '/organizations', input);
|
|
151
|
+
},
|
|
152
|
+
get(id) {
|
|
153
|
+
return request('GET', `/organizations/${encodeURIComponent(id)}`);
|
|
154
|
+
},
|
|
155
|
+
update(id, input) {
|
|
156
|
+
return request('PATCH', `/organizations/${encodeURIComponent(id)}`, input);
|
|
157
|
+
},
|
|
158
|
+
delete(id) {
|
|
159
|
+
return request('DELETE', `/organizations/${encodeURIComponent(id)}`);
|
|
160
|
+
},
|
|
161
|
+
members: {
|
|
162
|
+
list(orgId) {
|
|
163
|
+
return request('GET', `/organizations/${encodeURIComponent(orgId)}`).then((d) => d.members);
|
|
164
|
+
},
|
|
165
|
+
add(orgId, input) {
|
|
166
|
+
return request('POST', `/organizations/${encodeURIComponent(orgId)}/members`, input);
|
|
167
|
+
},
|
|
168
|
+
remove(orgId, accountId) {
|
|
169
|
+
return request('DELETE', `/organizations/${encodeURIComponent(orgId)}/members/${encodeURIComponent(accountId)}`);
|
|
170
|
+
},
|
|
171
|
+
updateRole(orgId, accountId, role) {
|
|
172
|
+
return request('PATCH', `/organizations/${encodeURIComponent(orgId)}/members/${encodeURIComponent(accountId)}`, { role });
|
|
173
|
+
},
|
|
174
|
+
},
|
|
175
|
+
invitations: {
|
|
176
|
+
create(orgId, input) {
|
|
177
|
+
return request('POST', `/organizations/${encodeURIComponent(orgId)}/invitations`, input);
|
|
178
|
+
},
|
|
179
|
+
revoke(orgId, invitationId) {
|
|
180
|
+
return request('DELETE', `/organizations/${encodeURIComponent(orgId)}/invitations/${encodeURIComponent(invitationId)}`);
|
|
181
|
+
},
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
keys: {
|
|
185
|
+
status() {
|
|
186
|
+
return request('GET', '/keys');
|
|
187
|
+
},
|
|
188
|
+
rotate(input) {
|
|
189
|
+
return request('POST', '/keys/rotate', input ?? {});
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
};
|
|
193
|
+
}
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SDK-owned types. We DELIBERATELY duplicate the DTO shapes returned by the
|
|
3
|
+
* Admin REST API (`packages/authkit-server/.../admin_api/dto.ts`) rather than
|
|
4
|
+
* importing them from `@adonis-agora/authkit-server`, so that remote-only
|
|
5
|
+
* consumers can install JUST this package with ZERO dependency on the server
|
|
6
|
+
* kit. The embedded driver maps the server's runtime values into these exact
|
|
7
|
+
* shapes — keep them in sync with the server DTOs.
|
|
8
|
+
*/
|
|
9
|
+
/** A user/account as projected by the Admin API (`userDto`). */
|
|
10
|
+
export interface AuthkitUser {
|
|
11
|
+
id: string;
|
|
12
|
+
email: string;
|
|
13
|
+
name: string | null;
|
|
14
|
+
avatarUrl: string | null;
|
|
15
|
+
globalRoles: string[];
|
|
16
|
+
disabled: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** Result of `users.create` — the user plus whether an invite e-mail was sent. */
|
|
19
|
+
export interface AuthkitCreatedUser extends AuthkitUser {
|
|
20
|
+
invited: boolean;
|
|
21
|
+
}
|
|
22
|
+
export interface ListUsersParams {
|
|
23
|
+
search?: string;
|
|
24
|
+
page?: number;
|
|
25
|
+
limit?: number;
|
|
26
|
+
}
|
|
27
|
+
export interface ListUsersResult {
|
|
28
|
+
data: AuthkitUser[];
|
|
29
|
+
total: number;
|
|
30
|
+
page: number;
|
|
31
|
+
limit: number;
|
|
32
|
+
}
|
|
33
|
+
export interface CreateUserInput {
|
|
34
|
+
email: string;
|
|
35
|
+
name?: string | null;
|
|
36
|
+
password?: string | null;
|
|
37
|
+
/** When true (and no password), creates with a random password and sends an invite/reset e-mail. */
|
|
38
|
+
invite?: boolean;
|
|
39
|
+
}
|
|
40
|
+
export interface UpdateUserInput {
|
|
41
|
+
globalRoles?: string[];
|
|
42
|
+
name?: string | null;
|
|
43
|
+
avatarUrl?: string | null;
|
|
44
|
+
}
|
|
45
|
+
/** An active IdP session (`sessionDto`). */
|
|
46
|
+
export interface AuthkitSession {
|
|
47
|
+
id: string;
|
|
48
|
+
accountId: string;
|
|
49
|
+
loginTs: number | null;
|
|
50
|
+
amr: string[];
|
|
51
|
+
/** Raw user-agent of the login (joined from the audit log). */
|
|
52
|
+
userAgent: string | null;
|
|
53
|
+
/** Browser family parsed from the user-agent (e.g. 'Chrome'). */
|
|
54
|
+
browser: string | null;
|
|
55
|
+
/** Operating system parsed from the user-agent (e.g. 'macOS'). */
|
|
56
|
+
os: string | null;
|
|
57
|
+
/** IP address of the login. */
|
|
58
|
+
ip: string | null;
|
|
59
|
+
/** Human-readable location resolved via the host `resolveGeo` hook (null without one). */
|
|
60
|
+
location: string | null;
|
|
61
|
+
}
|
|
62
|
+
/** A grant with live token counts (`grantDto`). */
|
|
63
|
+
export interface AuthkitGrant {
|
|
64
|
+
id: string;
|
|
65
|
+
accountId: string;
|
|
66
|
+
clientId: string | null;
|
|
67
|
+
accessTokens: number;
|
|
68
|
+
refreshTokens: number;
|
|
69
|
+
}
|
|
70
|
+
export interface ListSessionsResult {
|
|
71
|
+
canList: boolean;
|
|
72
|
+
sessions: AuthkitSession[];
|
|
73
|
+
grants: AuthkitGrant[];
|
|
74
|
+
}
|
|
75
|
+
/** Counts returned by a bulk session/grant revocation. */
|
|
76
|
+
export interface RevokeSessionsResult {
|
|
77
|
+
sessions: number;
|
|
78
|
+
grants: number;
|
|
79
|
+
accessTokens: number;
|
|
80
|
+
refreshTokens: number;
|
|
81
|
+
}
|
|
82
|
+
/** An OIDC client as projected by the Admin API (`clientDto`). */
|
|
83
|
+
export interface AuthkitClient {
|
|
84
|
+
clientId: string;
|
|
85
|
+
confidential: boolean;
|
|
86
|
+
grants: string[];
|
|
87
|
+
redirectUris: string[];
|
|
88
|
+
postLogoutRedirectUris: string[];
|
|
89
|
+
tokenEndpointAuthMethod: string;
|
|
90
|
+
}
|
|
91
|
+
export interface ListClientsResult {
|
|
92
|
+
data: AuthkitClient[];
|
|
93
|
+
canList: boolean;
|
|
94
|
+
}
|
|
95
|
+
export type TokenEndpointAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none';
|
|
96
|
+
export interface ClientInput {
|
|
97
|
+
clientId?: string;
|
|
98
|
+
redirectUris?: string[];
|
|
99
|
+
postLogoutRedirectUris?: string[];
|
|
100
|
+
grantTypes?: string[];
|
|
101
|
+
tokenEndpointAuthMethod?: TokenEndpointAuthMethod;
|
|
102
|
+
}
|
|
103
|
+
/** Created/regenerated client — the secret is shown ONCE (`createdClientDto`). */
|
|
104
|
+
export interface AuthkitCreatedClient {
|
|
105
|
+
clientId: string;
|
|
106
|
+
clientSecret: string | null;
|
|
107
|
+
}
|
|
108
|
+
export interface RegeneratedSecret {
|
|
109
|
+
clientId: string;
|
|
110
|
+
clientSecret: string;
|
|
111
|
+
}
|
|
112
|
+
export interface DeletedClient {
|
|
113
|
+
clientId: string;
|
|
114
|
+
deleted: boolean;
|
|
115
|
+
}
|
|
116
|
+
/** An audit event (`auditDto`). */
|
|
117
|
+
export interface AuthkitAuditEvent {
|
|
118
|
+
id: string | number;
|
|
119
|
+
type: string;
|
|
120
|
+
accountId: string | null;
|
|
121
|
+
email: string | null;
|
|
122
|
+
clientId: string | null;
|
|
123
|
+
actorId: string | null;
|
|
124
|
+
ip: string | null;
|
|
125
|
+
metadata: Record<string, unknown> | null;
|
|
126
|
+
createdAt: string;
|
|
127
|
+
}
|
|
128
|
+
export interface ListAuditParams {
|
|
129
|
+
type?: string;
|
|
130
|
+
subject?: string;
|
|
131
|
+
page?: number;
|
|
132
|
+
limit?: number;
|
|
133
|
+
}
|
|
134
|
+
export interface ListAuditResult {
|
|
135
|
+
data: AuthkitAuditEvent[];
|
|
136
|
+
total: number;
|
|
137
|
+
page: number;
|
|
138
|
+
limit: number;
|
|
139
|
+
}
|
|
140
|
+
/** A daily series point (ISO `YYYY-MM-DD` day + count). */
|
|
141
|
+
export interface AuthkitDailyPoint {
|
|
142
|
+
date: string;
|
|
143
|
+
count: number;
|
|
144
|
+
}
|
|
145
|
+
/** IdP summary metrics (`computeAdminStats`). */
|
|
146
|
+
export interface AuthkitStats {
|
|
147
|
+
totalUsers: number;
|
|
148
|
+
/** Active sessions; null when the OIDC adapter does not enumerate. */
|
|
149
|
+
activeSessions: number | null;
|
|
150
|
+
/** Monthly Active Users: unique accounts with a login.success in the last 30 days. */
|
|
151
|
+
mau: number;
|
|
152
|
+
signInsPerDay: AuthkitDailyPoint[];
|
|
153
|
+
signUpsPerDay: AuthkitDailyPoint[];
|
|
154
|
+
signInsTotal: number;
|
|
155
|
+
signUpsTotal: number;
|
|
156
|
+
/** Whether the audit sink supports querying (series are empty when false). */
|
|
157
|
+
auditSupported: boolean;
|
|
158
|
+
windowDays: number;
|
|
159
|
+
}
|
|
160
|
+
/** Generic token introspection result (`VerifyResult`). */
|
|
161
|
+
export type VerifyTokenResult = {
|
|
162
|
+
active: false;
|
|
163
|
+
} | {
|
|
164
|
+
active: true;
|
|
165
|
+
tokenType: 'pat' | 'access_token';
|
|
166
|
+
sub: string;
|
|
167
|
+
email?: string | null;
|
|
168
|
+
name?: string | null;
|
|
169
|
+
roles?: string[];
|
|
170
|
+
scopes?: string[];
|
|
171
|
+
audience?: string | string[] | null;
|
|
172
|
+
clientId?: string | null;
|
|
173
|
+
exp?: number | null;
|
|
174
|
+
};
|
|
175
|
+
/** Result of `users.disable`/`users.enable`. */
|
|
176
|
+
export interface UserStatusResult {
|
|
177
|
+
id: string;
|
|
178
|
+
disabled: boolean;
|
|
179
|
+
}
|
|
180
|
+
/** Result of `users.resetPassword`. */
|
|
181
|
+
export interface ResetPasswordResult {
|
|
182
|
+
id: string;
|
|
183
|
+
sent: boolean;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Result of `users.delete` — the cascade counts of what was removed (sessions,
|
|
187
|
+
* grants, tokens, PATs, passkeys, linked identities) plus how many audit rows were
|
|
188
|
+
* anonymized (kept, not deleted) and whether the avatar was removed.
|
|
189
|
+
*/
|
|
190
|
+
export interface DeletedUser {
|
|
191
|
+
id: string;
|
|
192
|
+
deleted: boolean;
|
|
193
|
+
sessions: number;
|
|
194
|
+
grants: number;
|
|
195
|
+
accessTokens: number;
|
|
196
|
+
refreshTokens: number;
|
|
197
|
+
pats: number;
|
|
198
|
+
passkeys: number;
|
|
199
|
+
providerIdentities: number;
|
|
200
|
+
auditAnonymized: number;
|
|
201
|
+
avatarDeleted: boolean;
|
|
202
|
+
}
|
|
203
|
+
/** An organization as returned by the Admin API. */
|
|
204
|
+
export interface AuthkitOrganization {
|
|
205
|
+
id: string;
|
|
206
|
+
name: string;
|
|
207
|
+
slug: string;
|
|
208
|
+
logoUrl: string | null;
|
|
209
|
+
metadata: Record<string, unknown> | null;
|
|
210
|
+
createdAt: string;
|
|
211
|
+
memberCount?: number;
|
|
212
|
+
}
|
|
213
|
+
/** An organization with full members and pending invitations (GET /:id). */
|
|
214
|
+
export interface AuthkitOrganizationDetail extends AuthkitOrganization {
|
|
215
|
+
members: AuthkitOrgMember[];
|
|
216
|
+
pendingInvitations: AuthkitOrgInvitation[];
|
|
217
|
+
}
|
|
218
|
+
export interface AuthkitOrgMember {
|
|
219
|
+
accountId: string;
|
|
220
|
+
email: string | null;
|
|
221
|
+
role: string;
|
|
222
|
+
joinedAt: string;
|
|
223
|
+
}
|
|
224
|
+
export interface AuthkitOrgInvitation {
|
|
225
|
+
id: string;
|
|
226
|
+
organizationId: string;
|
|
227
|
+
email: string;
|
|
228
|
+
role: string;
|
|
229
|
+
invitedBy: string;
|
|
230
|
+
expiresAt: string;
|
|
231
|
+
acceptedAt: string | null;
|
|
232
|
+
createdAt: string;
|
|
233
|
+
}
|
|
234
|
+
export interface ListOrganizationsResult {
|
|
235
|
+
data: AuthkitOrganization[];
|
|
236
|
+
}
|
|
237
|
+
export interface CreateOrganizationInput {
|
|
238
|
+
name: string;
|
|
239
|
+
slug: string;
|
|
240
|
+
ownerAccountId: string;
|
|
241
|
+
logoUrl?: string | null;
|
|
242
|
+
}
|
|
243
|
+
export interface UpdateOrganizationInput {
|
|
244
|
+
name?: string;
|
|
245
|
+
logoUrl?: string | null;
|
|
246
|
+
}
|
|
247
|
+
export interface AddOrgMemberInput {
|
|
248
|
+
accountId: string;
|
|
249
|
+
role: string;
|
|
250
|
+
}
|
|
251
|
+
export interface CreateOrgInvitationInput {
|
|
252
|
+
email: string;
|
|
253
|
+
role: string;
|
|
254
|
+
}
|
|
255
|
+
export interface DeletedOrganization {
|
|
256
|
+
id: string;
|
|
257
|
+
deleted: boolean;
|
|
258
|
+
}
|
|
259
|
+
export interface AddedOrgMember {
|
|
260
|
+
orgId: string;
|
|
261
|
+
accountId: string;
|
|
262
|
+
role: string;
|
|
263
|
+
added: boolean;
|
|
264
|
+
}
|
|
265
|
+
export interface RemovedOrgMember {
|
|
266
|
+
orgId: string;
|
|
267
|
+
accountId: string;
|
|
268
|
+
removed: boolean;
|
|
269
|
+
}
|
|
270
|
+
export interface UpdatedOrgMemberRole {
|
|
271
|
+
orgId: string;
|
|
272
|
+
accountId: string;
|
|
273
|
+
role: string;
|
|
274
|
+
updated: boolean;
|
|
275
|
+
}
|
|
276
|
+
export interface RevokedOrgInvitation {
|
|
277
|
+
orgId: string;
|
|
278
|
+
invitationId: string;
|
|
279
|
+
revoked: boolean;
|
|
280
|
+
}
|
|
281
|
+
/** Status of the managed signing key, returned by `keys.status()`. */
|
|
282
|
+
export interface KeysStatus {
|
|
283
|
+
ageDays: number;
|
|
284
|
+
policy: {
|
|
285
|
+
enabled: boolean;
|
|
286
|
+
maxAgeDays: number;
|
|
287
|
+
keep: number;
|
|
288
|
+
};
|
|
289
|
+
nextRotationInDays: number | null;
|
|
290
|
+
}
|
|
291
|
+
/** Input for `keys.rotate()`. */
|
|
292
|
+
export interface KeysRotateInput {
|
|
293
|
+
retire?: boolean;
|
|
294
|
+
keep?: number;
|
|
295
|
+
}
|
|
296
|
+
/** Result of `keys.rotate()`. */
|
|
297
|
+
export interface KeysRotateResult {
|
|
298
|
+
rotated: true;
|
|
299
|
+
newKid: string;
|
|
300
|
+
retiredKids: string[];
|
|
301
|
+
keptKids: string[];
|
|
302
|
+
}
|
|
303
|
+
/** A runtime setting entry as projected by the Admin API. */
|
|
304
|
+
export interface AuthkitSetting {
|
|
305
|
+
key: string;
|
|
306
|
+
value: unknown;
|
|
307
|
+
updatedAt: string | null;
|
|
308
|
+
updatedBy: string | null;
|
|
309
|
+
}
|
|
310
|
+
export interface ListSettingsResult {
|
|
311
|
+
data: AuthkitSetting[];
|
|
312
|
+
}
|
|
313
|
+
export interface DeletedSetting {
|
|
314
|
+
key: string;
|
|
315
|
+
deleted: boolean;
|
|
316
|
+
}
|
|
317
|
+
/** The shared SDK interface, implemented identically by both drivers. */
|
|
318
|
+
export interface Authkit {
|
|
319
|
+
users: {
|
|
320
|
+
list(params?: ListUsersParams): Promise<ListUsersResult>;
|
|
321
|
+
get(id: string): Promise<AuthkitUser>;
|
|
322
|
+
create(input: CreateUserInput): Promise<AuthkitCreatedUser>;
|
|
323
|
+
update(id: string, input: UpdateUserInput): Promise<AuthkitUser>;
|
|
324
|
+
disable(id: string): Promise<UserStatusResult>;
|
|
325
|
+
enable(id: string): Promise<UserStatusResult>;
|
|
326
|
+
resetPassword(id: string): Promise<ResetPasswordResult>;
|
|
327
|
+
/** Permanently deletes a user and cascades all associated data (LGPD/GDPR). */
|
|
328
|
+
delete(id: string): Promise<DeletedUser>;
|
|
329
|
+
};
|
|
330
|
+
sessions: {
|
|
331
|
+
list(userId: string): Promise<ListSessionsResult>;
|
|
332
|
+
revokeAll(userId: string): Promise<RevokeSessionsResult>;
|
|
333
|
+
};
|
|
334
|
+
clients: {
|
|
335
|
+
list(): Promise<ListClientsResult>;
|
|
336
|
+
get(id: string): Promise<AuthkitClient>;
|
|
337
|
+
create(input: ClientInput): Promise<AuthkitCreatedClient>;
|
|
338
|
+
update(id: string, input: ClientInput): Promise<AuthkitClient>;
|
|
339
|
+
regenerateSecret(id: string): Promise<RegeneratedSecret>;
|
|
340
|
+
delete(id: string): Promise<DeletedClient>;
|
|
341
|
+
};
|
|
342
|
+
audit: {
|
|
343
|
+
list(params?: ListAuditParams): Promise<ListAuditResult>;
|
|
344
|
+
};
|
|
345
|
+
/** IdP summary metrics for dashboards (totals + MAU + 30-day series). */
|
|
346
|
+
stats(): Promise<AuthkitStats>;
|
|
347
|
+
tokens: {
|
|
348
|
+
verify(token: string): Promise<VerifyTokenResult>;
|
|
349
|
+
};
|
|
350
|
+
organizations: {
|
|
351
|
+
list(): Promise<ListOrganizationsResult>;
|
|
352
|
+
create(input: CreateOrganizationInput): Promise<AuthkitOrganization>;
|
|
353
|
+
get(id: string): Promise<AuthkitOrganizationDetail>;
|
|
354
|
+
update(id: string, input: UpdateOrganizationInput): Promise<AuthkitOrganization>;
|
|
355
|
+
delete(id: string): Promise<DeletedOrganization>;
|
|
356
|
+
members: {
|
|
357
|
+
list(orgId: string): Promise<AuthkitOrgMember[]>;
|
|
358
|
+
add(orgId: string, input: AddOrgMemberInput): Promise<AddedOrgMember>;
|
|
359
|
+
remove(orgId: string, accountId: string): Promise<RemovedOrgMember>;
|
|
360
|
+
updateRole(orgId: string, accountId: string, role: string): Promise<UpdatedOrgMemberRole>;
|
|
361
|
+
};
|
|
362
|
+
invitations: {
|
|
363
|
+
create(orgId: string, input: CreateOrgInvitationInput): Promise<AuthkitOrgInvitation>;
|
|
364
|
+
revoke(orgId: string, invitationId: string): Promise<RevokedOrgInvitation>;
|
|
365
|
+
};
|
|
366
|
+
};
|
|
367
|
+
/** Runtime settings — CRUD for entries in `auth_settings` table. */
|
|
368
|
+
settings: {
|
|
369
|
+
list(): Promise<ListSettingsResult>;
|
|
370
|
+
get(key: string): Promise<AuthkitSetting>;
|
|
371
|
+
set(key: string, value: unknown): Promise<AuthkitSetting>;
|
|
372
|
+
delete(key: string): Promise<DeletedSetting>;
|
|
373
|
+
};
|
|
374
|
+
/** Managed signing-key status and rotation (remote = Admin REST API, embedded = in-process; returns 501/throws when jwks is not managed+store). */
|
|
375
|
+
keys: {
|
|
376
|
+
/** GET /keys — age, policy and ETA to next rotation. */
|
|
377
|
+
status(): Promise<KeysStatus>;
|
|
378
|
+
/** POST /keys/rotate — rotate now, optionally retiring old keys. */
|
|
379
|
+
rotate(input?: KeysRotateInput): Promise<KeysRotateResult>;
|
|
380
|
+
};
|
|
381
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SDK-owned types. We DELIBERATELY duplicate the DTO shapes returned by the
|
|
3
|
+
* Admin REST API (`packages/authkit-server/.../admin_api/dto.ts`) rather than
|
|
4
|
+
* importing them from `@adonis-agora/authkit-server`, so that remote-only
|
|
5
|
+
* consumers can install JUST this package with ZERO dependency on the server
|
|
6
|
+
* kit. The embedded driver maps the server's runtime values into these exact
|
|
7
|
+
* shapes — keep them in sync with the server DTOs.
|
|
8
|
+
*/
|
|
9
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@adonis-agora/authkit-sdk",
|
|
3
|
+
"version": "0.6.0",
|
|
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
|
+
"license": "MIT",
|
|
6
|
+
"author": "dudousxd",
|
|
7
|
+
"homepage": "https://github.com/DavideCarvalho/adonis-authkit/tree/main/packages/authkit-sdk#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/DavideCarvalho/adonis-authkit.git",
|
|
11
|
+
"directory": "packages/authkit-sdk"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/DavideCarvalho/adonis-authkit/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"adonisjs",
|
|
18
|
+
"authkit",
|
|
19
|
+
"sdk",
|
|
20
|
+
"admin-api",
|
|
21
|
+
"oidc",
|
|
22
|
+
"authentication"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"type": "module",
|
|
28
|
+
"main": "./build/index.js",
|
|
29
|
+
"types": "./build/index.d.ts",
|
|
30
|
+
"files": [
|
|
31
|
+
"build"
|
|
32
|
+
],
|
|
33
|
+
"exports": {
|
|
34
|
+
".": "./build/index.js",
|
|
35
|
+
"./types": "./build/index.js"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@adonisjs/core": "7.3.3",
|
|
39
|
+
"@adonis-agora/authkit-server": ">=0.10.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependenciesMeta": {
|
|
42
|
+
"@adonisjs/core": {
|
|
43
|
+
"optional": true
|
|
44
|
+
},
|
|
45
|
+
"@adonis-agora/authkit-server": {
|
|
46
|
+
"optional": true
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@adonisjs/core": "7.3.3",
|
|
51
|
+
"@adonisjs/tsconfig": "2.0.0",
|
|
52
|
+
"@japa/assert": "4.2.0",
|
|
53
|
+
"@japa/runner": "5.3.0",
|
|
54
|
+
"@poppinss/ts-exec": "1.4.4",
|
|
55
|
+
"@types/node": "25.9.1",
|
|
56
|
+
"typescript": "6.0.3",
|
|
57
|
+
"@adonis-agora/authkit-server": "0.34.0"
|
|
58
|
+
},
|
|
59
|
+
"scripts": {
|
|
60
|
+
"build": "tsc",
|
|
61
|
+
"typecheck": "tsc --noEmit",
|
|
62
|
+
"test": "node --import=@poppinss/ts-exec bin/test.ts"
|
|
63
|
+
}
|
|
64
|
+
}
|