authmi 1.0.0 → 1.1.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.
@@ -1,609 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined") return require.apply(this, arguments);
11
- throw Error('Dynamic require of "' + x + '" is not supported');
12
- });
13
- var __commonJS = (cb, mod) => function __require2() {
14
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
- // If the importer is in node compatibility mode or this is not an ESM
26
- // file that has been converted to a CommonJS file using a Babel-
27
- // compatible transform (i.e. "__esModule" has not been set), then set
28
- // "default" to the CommonJS "module.exports" for node compatibility.
29
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
- mod
31
- ));
32
-
33
- // src/types.ts
34
- var AuthMiError = class extends Error {
35
- constructor(message, code, statusCode) {
36
- super(message);
37
- this.code = code;
38
- this.statusCode = statusCode;
39
- this.name = "AuthMiError";
40
- }
41
- };
42
- var ScopeError = class extends AuthMiError {
43
- constructor(message, requiredScopes, providedScopes) {
44
- super(message, "INSUFFICIENT_SCOPES", 403);
45
- this.requiredScopes = requiredScopes;
46
- this.providedScopes = providedScopes;
47
- this.name = "ScopeError";
48
- }
49
- };
50
- var _LocalStorageTokenStorage = class _LocalStorageTokenStorage {
51
- getToken() {
52
- if (typeof window === "undefined") return null;
53
- return localStorage.getItem(_LocalStorageTokenStorage.KEY);
54
- }
55
- setToken(token) {
56
- if (typeof window === "undefined") return;
57
- localStorage.setItem(_LocalStorageTokenStorage.KEY, token);
58
- }
59
- removeToken() {
60
- if (typeof window === "undefined") return;
61
- localStorage.removeItem(_LocalStorageTokenStorage.KEY);
62
- }
63
- };
64
- _LocalStorageTokenStorage.KEY = "authmi_token";
65
- var LocalStorageTokenStorage = _LocalStorageTokenStorage;
66
- var MemoryTokenStorage = class {
67
- constructor() {
68
- this.token = null;
69
- }
70
- getToken() {
71
- return this.token;
72
- }
73
- setToken(token) {
74
- this.token = token;
75
- }
76
- removeToken() {
77
- this.token = null;
78
- }
79
- };
80
-
81
- // src/client.ts
82
- var AuthMiClient = class {
83
- constructor(config, tokenStorage) {
84
- this.config = {
85
- apiKey: "",
86
- serviceId: "",
87
- clientId: "",
88
- clientSecret: "",
89
- defaultTokenExpiry: 24,
90
- ...config
91
- };
92
- this.tokenStorage = tokenStorage || new LocalStorageTokenStorage();
93
- }
94
- /** Build Basic auth header from clientId:clientSecret */
95
- basicAuthHeader() {
96
- if (this.config.clientId && this.config.clientSecret) {
97
- const encoded = btoa(`${this.config.clientId}:${this.config.clientSecret}`);
98
- return `Basic ${encoded}`;
99
- }
100
- return null;
101
- }
102
- // ============ HTTP Utilities ============
103
- async request(endpoint, options = {}, requireAuth = false) {
104
- const url = `${this.config.baseUrl}${endpoint}`;
105
- const headers = {
106
- "Content-Type": "application/json",
107
- ...options.headers || {}
108
- };
109
- const basic = this.basicAuthHeader();
110
- if (basic && !requireAuth && !headers["Authorization"]) {
111
- headers["Authorization"] = basic;
112
- } else if (this.config.apiKey && !requireAuth && !headers["Authorization"]) {
113
- headers["Authorization"] = `Bearer ${this.config.apiKey}`;
114
- }
115
- if (requireAuth) {
116
- const token = this.getAccessToken();
117
- if (token && !headers["Authorization"]) {
118
- headers["Authorization"] = `Bearer ${token}`;
119
- }
120
- }
121
- try {
122
- const response = await fetch(url, {
123
- ...options,
124
- headers
125
- });
126
- const data = await response.json();
127
- if (!response.ok) {
128
- if (response.status === 403 && data.required && data.provided) {
129
- throw new ScopeError(
130
- data.error || "Insufficient scopes",
131
- data.required,
132
- data.provided
133
- );
134
- }
135
- throw new AuthMiError(
136
- data.error || `HTTP ${response.status}`,
137
- data.code || "UNKNOWN_ERROR",
138
- response.status
139
- );
140
- }
141
- return data;
142
- } catch (error) {
143
- if (error instanceof AuthMiError) {
144
- throw error;
145
- }
146
- throw new AuthMiError(
147
- error instanceof Error ? error.message : "Network error",
148
- "NETWORK_ERROR"
149
- );
150
- }
151
- }
152
- // ============ Configuration ============
153
- /**
154
- * Update the client's service configuration
155
- */
156
- configure(config) {
157
- this.config = { ...this.config, ...config };
158
- }
159
- /**
160
- * Get current configuration (without sensitive data)
161
- */
162
- getConfig() {
163
- const { apiKey: _, clientSecret: __, ...rest } = this.config;
164
- return rest;
165
- }
166
- // ============ Token Management ============
167
- /**
168
- * Get the stored access token
169
- */
170
- getAccessToken() {
171
- return this.tokenStorage.getToken();
172
- }
173
- /**
174
- * Store an access token
175
- */
176
- setAccessToken(token) {
177
- this.tokenStorage.setToken(token);
178
- }
179
- /**
180
- * Remove the stored access token (logout)
181
- */
182
- clearAccessToken() {
183
- this.tokenStorage.removeToken();
184
- }
185
- /**
186
- * Check if user is logged in
187
- */
188
- isLoggedIn() {
189
- return !!this.getAccessToken();
190
- }
191
- // ============ Scope Validation ============
192
- /**
193
- * Introspect a token or API key and validate required scopes
194
- */
195
- async introspect(request) {
196
- return this.request("/api/v1/introspect", {
197
- method: "POST",
198
- body: JSON.stringify(request)
199
- });
200
- }
201
- /**
202
- * Validate the current token with optional scope checking
203
- */
204
- async validateWithScopes(requiredScopes) {
205
- const token = this.getAccessToken();
206
- if (!token) {
207
- return { valid: false, error: "No token provided" };
208
- }
209
- if (!this.config.apiKey && !this.config.clientSecret) {
210
- return { valid: false, error: "Service credentials not configured" };
211
- }
212
- if (!this.config.serviceId) {
213
- return { valid: false, error: "Service ID not configured in AuthMiConfig" };
214
- }
215
- try {
216
- const result = await this.introspect({
217
- serviceId: this.config.serviceId,
218
- token,
219
- requiredScopes
220
- });
221
- return {
222
- valid: result.valid,
223
- type: result.type === "bearer" ? "token" : "api_key",
224
- scopes: result.scopes,
225
- userId: result.userId,
226
- email: result.email,
227
- error: result.error
228
- };
229
- } catch (error) {
230
- if (error instanceof ScopeError) {
231
- return {
232
- valid: false,
233
- error: error.message,
234
- scopes: error.providedScopes
235
- };
236
- }
237
- if (error instanceof AuthMiError && error.statusCode === 401) {
238
- return { valid: false, error: "Invalid or expired token" };
239
- }
240
- throw error;
241
- }
242
- }
243
- /**
244
- * Check if the current user has all the required scopes
245
- * Throws ScopeError if scopes are insufficient
246
- */
247
- async requireScopes(...requiredScopes) {
248
- const result = await this.validateWithScopes(requiredScopes);
249
- if (!result.valid) {
250
- throw new AuthMiError(
251
- result.error || "Authentication required",
252
- "UNAUTHORIZED",
253
- 401
254
- );
255
- }
256
- const hasScopes = requiredScopes.every(
257
- (scope) => result.scopes?.includes(scope)
258
- );
259
- if (!hasScopes) {
260
- throw new ScopeError(
261
- `Required scopes: ${requiredScopes.join(", ")}`,
262
- requiredScopes,
263
- result.scopes || []
264
- );
265
- }
266
- return result;
267
- }
268
- /**
269
- * Execute a function only if the user has the required scopes
270
- */
271
- async withScope(scopes, fn) {
272
- await this.requireScopes(...scopes);
273
- return fn();
274
- }
275
- // ============ OAuth ============
276
- /**
277
- * Initiate OAuth login flow and return the authorization URL
278
- */
279
- async initiateOAuth(provider, redirectUri) {
280
- if (!this.config.apiKey && !this.config.clientSecret) {
281
- throw new AuthMiError(
282
- "API key or client credentials required for OAuth. Configure the client first.",
283
- "MISSING_CREDENTIALS"
284
- );
285
- }
286
- if (!this.config.serviceId) {
287
- throw new AuthMiError(
288
- "serviceId required for OAuth. Configure the client first.",
289
- "MISSING_SERVICE_ID"
290
- );
291
- }
292
- const response = await this.request(
293
- "/api/v1/auth/oauth/initiate",
294
- {
295
- method: "POST",
296
- body: JSON.stringify({ provider, redirectUri, client_id: this.config.serviceId })
297
- }
298
- );
299
- return response.url;
300
- }
301
- /**
302
- * Handle OAuth callback URL and store the access token
303
- * Returns null if no OAuth params are present in the URL
304
- */
305
- handleOAuthCallback(url) {
306
- const parsedUrl = typeof url === "string" ? new URL(url) : url;
307
- const token = parsedUrl.searchParams.get("token");
308
- const userId = parsedUrl.searchParams.get("user_id");
309
- const email = parsedUrl.searchParams.get("email");
310
- if (!token || !userId || !email) {
311
- return null;
312
- }
313
- this.setAccessToken(token);
314
- return { token, userId, email };
315
- }
316
- /**
317
- * Check if the current URL contains OAuth callback params
318
- */
319
- isOAuthCallback(url) {
320
- const parsedUrl = typeof url === "string" ? new URL(url) : url;
321
- return parsedUrl.searchParams.has("token") && parsedUrl.searchParams.has("user_id") && parsedUrl.searchParams.has("email");
322
- }
323
- // ============ Authentication ============
324
- /**
325
- * Login a user and store the access token
326
- */
327
- async login(credentials) {
328
- if (!this.config.apiKey && !this.config.clientSecret) {
329
- throw new AuthMiError(
330
- "API key or client credentials required for login. Configure the client first.",
331
- "MISSING_CREDENTIALS"
332
- );
333
- }
334
- const response = await this.request("/api/v1/auth/login", {
335
- method: "POST",
336
- body: JSON.stringify({
337
- email: credentials.email,
338
- password: credentials.password,
339
- client_id: this.config.serviceId,
340
- expires_in_hours: credentials.expiresInHours || this.config.defaultTokenExpiry,
341
- scopes: credentials.scopes
342
- })
343
- });
344
- const token = {
345
- accessToken: response.access_token,
346
- tokenType: response.token_type,
347
- expiresIn: response.expires_in,
348
- expiresAt: response.expires_at,
349
- userId: response.user_id,
350
- email: response.email,
351
- scopes: response.scopes
352
- };
353
- this.setAccessToken(token.accessToken);
354
- return token;
355
- }
356
- /**
357
- * Logout the current user
358
- */
359
- async logout() {
360
- const token = this.getAccessToken();
361
- if (token) {
362
- try {
363
- await this.request("/api/v1/auth/logout", {
364
- method: "POST"
365
- }, true);
366
- } catch (error) {
367
- }
368
- }
369
- this.clearAccessToken();
370
- }
371
- /**
372
- * Validate the current token or an API key
373
- * @deprecated Use validateWithScopes instead
374
- */
375
- async validate(_credential) {
376
- return this.validateWithScopes();
377
- }
378
- /**
379
- * Refresh the current token
380
- */
381
- async refreshToken() {
382
- const response = await this.request("/api/v1/auth/refresh", {
383
- method: "POST"
384
- }, true);
385
- const token = {
386
- accessToken: response.access_token,
387
- tokenType: response.token_type,
388
- expiresIn: response.expires_in,
389
- expiresAt: response.expires_at,
390
- userId: "",
391
- // Refresh doesn't return user info
392
- email: ""
393
- };
394
- this.setAccessToken(token.accessToken);
395
- return token;
396
- }
397
- // ============ User Management ============
398
- /**
399
- * Create a new user (requires admin API key)
400
- */
401
- async createUser(request) {
402
- const response = await this.request("/api/v1/users/create", {
403
- method: "POST",
404
- body: JSON.stringify(request)
405
- });
406
- return {
407
- userId: response.user_id,
408
- email: response.email,
409
- createdAt: response.created_at
410
- };
411
- }
412
- /**
413
- * List all users for the service
414
- */
415
- async listUsers() {
416
- const response = await this.request("/api/v1/users/list");
417
- return response.users.map((u) => ({
418
- userId: u.user_id,
419
- email: u.email,
420
- createdAt: u.created_at
421
- }));
422
- }
423
- /**
424
- * Delete a user
425
- */
426
- async deleteUser(userId) {
427
- await this.request("/api/v1/users/delete", {
428
- method: "POST",
429
- body: JSON.stringify({ user_id: userId })
430
- });
431
- }
432
- /**
433
- * Update user password
434
- */
435
- async updatePassword(userId, oldPassword, newPassword) {
436
- await this.request("/api/v1/users/password", {
437
- method: "POST",
438
- body: JSON.stringify({
439
- user_id: userId,
440
- old_password: oldPassword,
441
- new_password: newPassword
442
- })
443
- });
444
- }
445
- // ============ Scope Management ============
446
- /**
447
- * List custom scopes for the service
448
- */
449
- async listScopes() {
450
- const response = await this.request("/api/v1/scopes/list");
451
- return response.scopes;
452
- }
453
- /**
454
- * Create a custom scope
455
- */
456
- async createScope(request) {
457
- const response = await this.request("/api/v1/scopes/create", {
458
- method: "POST",
459
- body: JSON.stringify(request)
460
- });
461
- return {
462
- scopeId: response.scope_id,
463
- name: response.name,
464
- key: response.key,
465
- description: response.description,
466
- createdAt: response.created_at
467
- };
468
- }
469
- /**
470
- * Delete a custom scope
471
- */
472
- async deleteScope(scopeId) {
473
- await this.request("/api/v1/scopes/delete", {
474
- method: "POST",
475
- body: JSON.stringify({ scope_id: scopeId })
476
- });
477
- }
478
- // ============ API Key Management ============
479
- /**
480
- * List all API keys for the service
481
- */
482
- async listApiKeys() {
483
- const response = await this.request("/api/v1/keys/list");
484
- return response.keys.map((k) => ({
485
- keyId: k.keyId,
486
- name: k.name,
487
- scope: k.scope,
488
- scopes: [],
489
- keyType: k.keyType,
490
- revoked: k.revoked,
491
- createdAt: k.createdAt,
492
- tpsLimit: k.tpsLimit
493
- }));
494
- }
495
- /**
496
- * Create a new API key with optional custom scopes
497
- */
498
- async createApiKey(request) {
499
- const response = await this.request("/api/v1/keys/create", {
500
- method: "POST",
501
- body: JSON.stringify({
502
- user_id: request.userId,
503
- name: request.name,
504
- scope: request.scope || "service",
505
- scopes: request.scopes,
506
- key_type: request.keyType || "service",
507
- tps_limit: request.tpsLimit || 100
508
- })
509
- });
510
- return {
511
- keyId: response.key_id,
512
- apiKey: response.api_key,
513
- name: response.name,
514
- scope: response.scope,
515
- scopes: response.scopes
516
- };
517
- }
518
- /**
519
- * Revoke an API key
520
- */
521
- async revokeApiKey(keyId) {
522
- await this.request("/api/v1/keys/revoke", {
523
- method: "POST",
524
- body: JSON.stringify({ key_id: keyId })
525
- });
526
- }
527
- // ============ Service Management ============
528
- /**
529
- * Onboard a new service (requires master admin key)
530
- */
531
- async onboardService(request, masterAdminKey) {
532
- const response = await this.request("/api/v1/services/onboard", {
533
- method: "POST",
534
- headers: {
535
- "x-onboarding-admin-key": masterAdminKey
536
- },
537
- body: JSON.stringify({
538
- service_name: request.serviceName,
539
- owner_email: request.ownerEmail
540
- })
541
- });
542
- return {
543
- serviceId: response.service_id,
544
- serviceName: response.service_name,
545
- ownerEmail: response.owner_email,
546
- adminKeyId: response.admin_key_id,
547
- serviceAdminApiKey: response.service_admin_api_key,
548
- createdAt: response.created_at
549
- };
550
- }
551
- /**
552
- * Delete a service (requires master admin key)
553
- */
554
- async deleteService(serviceId, masterAdminKey) {
555
- await this.request("/api/v1/services/deboard", {
556
- method: "POST",
557
- headers: {
558
- "x-onboarding-admin-key": masterAdminKey
559
- },
560
- body: JSON.stringify({ service_id: serviceId })
561
- });
562
- }
563
- // ============ Webhook Management ============
564
- /**
565
- * List webhooks
566
- */
567
- async listWebhooks() {
568
- const response = await this.request(
569
- "/api/v1/webhooks/list"
570
- );
571
- return response.webhooks;
572
- }
573
- /**
574
- * Register a webhook
575
- */
576
- async registerWebhook(request) {
577
- const response = await this.request("/api/v1/webhooks/register", {
578
- method: "POST",
579
- body: JSON.stringify(request)
580
- });
581
- return {
582
- webhookId: response.webhook_id,
583
- url: response.url,
584
- events: response.events,
585
- active: response.active,
586
- createdAt: response.created_at
587
- };
588
- }
589
- /**
590
- * Delete a webhook
591
- */
592
- async deleteWebhook(webhookId) {
593
- await this.request("/api/v1/webhooks/delete", {
594
- method: "POST",
595
- body: JSON.stringify({ webhook_id: webhookId })
596
- });
597
- }
598
- };
599
-
600
- export {
601
- __require,
602
- __commonJS,
603
- __toESM,
604
- AuthMiError,
605
- ScopeError,
606
- LocalStorageTokenStorage,
607
- MemoryTokenStorage,
608
- AuthMiClient
609
- };