authtara-sdk 1.0.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.
@@ -0,0 +1,450 @@
1
+ /**
2
+ * Authtara SDK - HTTP Client
3
+ *
4
+ * HTTP client wrapper untuk komunikasi dengan DigitalSolution Platform API.
5
+ * Menggunakan fetch API yang tersedia di Node.js 18+ dan browser.
6
+ */
7
+ interface HttpClientConfig {
8
+ baseUrl: string;
9
+ apiKey: string;
10
+ timeout?: number;
11
+ }
12
+ interface RequestOptions {
13
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
14
+ path: string;
15
+ body?: unknown;
16
+ headers?: Record<string, string>;
17
+ }
18
+ /**
19
+ * HTTP Client untuk SDK
20
+ *
21
+ * Fitur:
22
+ * - Auto-inject Authorization header
23
+ * - JSON serialization/deserialization
24
+ * - Error handling dengan custom errors
25
+ * - Timeout support
26
+ */
27
+ declare class HttpClient {
28
+ private readonly baseUrl;
29
+ private readonly apiKey;
30
+ private readonly timeout;
31
+ constructor(config: HttpClientConfig);
32
+ /**
33
+ * Make HTTP request to Platform API
34
+ */
35
+ request<T>(options: RequestOptions): Promise<T>;
36
+ /**
37
+ * POST request shorthand
38
+ */
39
+ post<T>(path: string, body?: unknown): Promise<T>;
40
+ /**
41
+ * GET request shorthand
42
+ */
43
+ get<T>(path: string): Promise<T>;
44
+ }
45
+
46
+ /**
47
+ * Authtara SDK - Auth Module
48
+ *
49
+ * Menangani validasi SSO token dan exchange authorization code.
50
+ * Sesuai dengan Blueprint Ekosistem Developer V2.0.
51
+ */
52
+
53
+ /**
54
+ * Hasil verifikasi session dari SSO token
55
+ */
56
+ interface SessionVerifyResult {
57
+ isValid: boolean;
58
+ user?: {
59
+ id: string;
60
+ email: string;
61
+ name: string | null;
62
+ };
63
+ tenant?: {
64
+ id: string;
65
+ name: string;
66
+ subdomain: string;
67
+ role: string;
68
+ };
69
+ subscription?: {
70
+ plan: string;
71
+ status: string;
72
+ };
73
+ }
74
+ /**
75
+ * Hasil exchange authorization code
76
+ */
77
+ interface ExchangeResult {
78
+ token: string;
79
+ expiresIn: number;
80
+ user: {
81
+ id: string;
82
+ email: string;
83
+ name: string | null;
84
+ };
85
+ tenant: {
86
+ id: string;
87
+ name: string;
88
+ subdomain: string;
89
+ role: string;
90
+ };
91
+ subscription: {
92
+ plan: string;
93
+ status: string;
94
+ };
95
+ }
96
+ /**
97
+ * Auth Module
98
+ *
99
+ * Menyediakan fungsi untuk:
100
+ * - verifySession: Verifikasi JWT token secara offline menggunakan App Secret
101
+ * - exchangeCode: Menukar authorization code dengan JWT token (server-to-server)
102
+ */
103
+ declare class AuthModule {
104
+ private readonly apiKey;
105
+ private readonly httpClient;
106
+ private readonly issuer;
107
+ constructor(apiKey: string, httpClient: HttpClient, issuer?: string);
108
+ /**
109
+ * Verifikasi SSO JWT token secara offline
110
+ *
111
+ * Token diverifikasi menggunakan App Secret (HS256).
112
+ * Ini lebih cepat daripada memanggil API karena tidak memerlukan network request.
113
+ *
114
+ * @param token - JWT token dari SSO callback
115
+ * @returns SessionVerifyResult dengan data user, tenant, dan subscription
116
+ * @throws InvalidTokenError jika token tidak valid atau expired
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * const session = await ds.auth.verifySession(token);
121
+ * if (session.isValid) {
122
+ * console.log('User:', session.user);
123
+ * console.log('Tenant:', session.tenant);
124
+ * }
125
+ * ```
126
+ */
127
+ verifySession(token: string): Promise<SessionVerifyResult>;
128
+ /**
129
+ * Exchange authorization code untuk JWT token (server-to-server)
130
+ *
131
+ * Gunakan ini di callback endpoint untuk menukar authorization code
132
+ * menjadi JWT token yang bisa diverifikasi.
133
+ *
134
+ * @param code - Authorization code dari callback URL
135
+ * @returns ExchangeResult dengan token dan data context
136
+ *
137
+ * @example
138
+ * ```typescript
139
+ * // Di endpoint /api/sso/callback
140
+ * const code = searchParams.get('code');
141
+ * const result = await ds.auth.exchangeCode(code);
142
+ * // Simpan result.token ke session
143
+ * ```
144
+ */
145
+ exchangeCode(code: string): Promise<ExchangeResult>;
146
+ }
147
+
148
+ /**
149
+ * Authtara SDK - Billing Module
150
+ *
151
+ * Menangani pengecekan entitlement (hak akses) tenant ke fitur aplikasi.
152
+ * Sesuai dengan Blueprint Ekosistem Developer V2.0.
153
+ */
154
+
155
+ /**
156
+ * Parameter untuk pengecekan entitlement
157
+ */
158
+ interface CheckEntitlementParams {
159
+ /** Tenant ID yang ingin dicek */
160
+ tenantId: string;
161
+ /** Optional: Feature key untuk cek fitur spesifik */
162
+ featureKey?: string;
163
+ }
164
+ /**
165
+ * Hasil pengecekan entitlement
166
+ */
167
+ interface EntitlementResult {
168
+ /** Apakah akses diberikan */
169
+ granted: boolean;
170
+ /** Alasan jika akses tidak diberikan */
171
+ reason?: string;
172
+ /** Detail entitlement */
173
+ entitlement?: {
174
+ status: string;
175
+ subscription?: {
176
+ plan: string;
177
+ status: string;
178
+ };
179
+ };
180
+ }
181
+ /**
182
+ * Billing Module
183
+ *
184
+ * Menyediakan fungsi untuk mengecek hak akses tenant ke aplikasi Anda.
185
+ * Berguna untuk feature gating dan paywall logic.
186
+ *
187
+ * @example
188
+ * ```typescript
189
+ * const access = await ds.billing.checkEntitlement({
190
+ * tenantId: currentTenant.id,
191
+ * featureKey: 'premium_feature'
192
+ * });
193
+ *
194
+ * if (!access.granted) {
195
+ * return <UpgradeModal reason={access.reason} />;
196
+ * }
197
+ * ```
198
+ */
199
+ declare class BillingModule {
200
+ private readonly httpClient;
201
+ constructor(httpClient: HttpClient);
202
+ /**
203
+ * Cek apakah tenant memiliki akses ke aplikasi Anda
204
+ *
205
+ * @param params - Parameter pengecekan (tenantId wajib, featureKey opsional)
206
+ * @returns EntitlementResult dengan status akses
207
+ *
208
+ * @example
209
+ * ```typescript
210
+ * // Cek akses dasar
211
+ * const hasAccess = await ds.billing.checkEntitlement({
212
+ * tenantId: tenant.id
213
+ * });
214
+ *
215
+ * // Cek fitur spesifik
216
+ * const canUseAI = await ds.billing.checkEntitlement({
217
+ * tenantId: tenant.id,
218
+ * featureKey: 'ai_generator'
219
+ * });
220
+ *
221
+ * if (!canUseAI.granted) {
222
+ * throw new Error(canUseAI.reason);
223
+ * }
224
+ * ```
225
+ */
226
+ checkEntitlement(params: CheckEntitlementParams): Promise<EntitlementResult>;
227
+ }
228
+
229
+ /**
230
+ * Authtara SDK - Metering Module
231
+ *
232
+ * Menangani pencatatan penggunaan (usage-based billing).
233
+ * Sesuai dengan Blueprint Ekosistem Developer V2.0.
234
+ */
235
+
236
+ /**
237
+ * Parameter untuk pencatatan usage
238
+ */
239
+ interface RecordUsageParams {
240
+ /** Tenant ID yang penggunaannya dicatat */
241
+ tenantId: string;
242
+ /**
243
+ * Identifier metrik
244
+ *
245
+ * Metrik yang tersedia:
246
+ * - `message_sent` - Pesan yang dikirim (agregasi bulanan)
247
+ * - `api_call` - API calls (agregasi harian)
248
+ * - `connection_active` - Koneksi aktif (agregasi harian)
249
+ * - `websocket_connection` - WebSocket connections (agregasi harian)
250
+ */
251
+ metricSlug: string;
252
+ /** Jumlah yang dicatat (harus positif) */
253
+ amount: number;
254
+ /** Optional: Timestamp ISO (default: sekarang) */
255
+ timestamp?: string;
256
+ }
257
+ /**
258
+ * Hasil pencatatan usage
259
+ */
260
+ interface RecordUsageResult {
261
+ /** Apakah berhasil dicatat */
262
+ success: boolean;
263
+ /** ID record yang dibuat */
264
+ recordId?: string;
265
+ }
266
+ /**
267
+ * Metering Module
268
+ *
269
+ * Menyediakan fungsi untuk mencatat penggunaan aplikasi oleh tenant.
270
+ * Data ini digunakan untuk usage-based billing.
271
+ *
272
+ * @example
273
+ * ```typescript
274
+ * // Catat penggunaan API call
275
+ * await ds.metering.recordUsage({
276
+ * tenantId: tenant.id,
277
+ * metricSlug: 'api_call',
278
+ * amount: 1
279
+ * });
280
+ *
281
+ * // Catat batch messages
282
+ * await ds.metering.recordUsage({
283
+ * tenantId: tenant.id,
284
+ * metricSlug: 'message_sent',
285
+ * amount: 50
286
+ * });
287
+ * ```
288
+ */
289
+ declare class MeteringModule {
290
+ private readonly httpClient;
291
+ constructor(httpClient: HttpClient);
292
+ /**
293
+ * Catat penggunaan untuk usage-based billing
294
+ *
295
+ * @param params - Parameter pencatatan
296
+ * @returns RecordUsageResult
297
+ *
298
+ * @example
299
+ * ```typescript
300
+ * // Setelah user mengirim pesan
301
+ * await ds.metering.recordUsage({
302
+ * tenantId: currentTenant.id,
303
+ * metricSlug: 'message_sent',
304
+ * amount: 1
305
+ * });
306
+ *
307
+ * // Batch recording untuk efisiensi
308
+ * await ds.metering.recordUsage({
309
+ * tenantId: currentTenant.id,
310
+ * metricSlug: 'api_call',
311
+ * amount: 100 // Batch 100 API calls
312
+ * });
313
+ * ```
314
+ */
315
+ recordUsage(params: RecordUsageParams): Promise<RecordUsageResult>;
316
+ }
317
+
318
+ /**
319
+ * Authtara SDK - Custom Error Classes
320
+ *
321
+ * Error classes untuk SDK yang memudahkan error handling di aplikasi developer.
322
+ */
323
+ /**
324
+ * Base error class untuk semua Authtara SDK errors
325
+ */
326
+ declare class AuthtaraError extends Error {
327
+ readonly code: string;
328
+ readonly statusCode?: number;
329
+ constructor(message: string, code: string, statusCode?: number);
330
+ }
331
+ /**
332
+ * Error untuk token yang tidak valid atau expired
333
+ */
334
+ declare class InvalidTokenError extends AuthtaraError {
335
+ constructor(message?: string);
336
+ }
337
+ /**
338
+ * Error untuk akses yang ditolak (entitlement denied)
339
+ */
340
+ declare class EntitlementDeniedError extends AuthtaraError {
341
+ readonly reason?: string;
342
+ constructor(message?: string, reason?: string);
343
+ }
344
+ /**
345
+ * Error untuk API errors dari platform
346
+ */
347
+ declare class ApiError extends AuthtaraError {
348
+ readonly response?: unknown;
349
+ constructor(message: string, statusCode: number, response?: unknown);
350
+ }
351
+ /**
352
+ * Error untuk configuration issues
353
+ */
354
+ declare class ConfigurationError extends AuthtaraError {
355
+ constructor(message: string);
356
+ }
357
+
358
+ /**
359
+ * Authtara SDK
360
+ *
361
+ * SDK Client untuk integrasi dengan DigitalSolution Platform.
362
+ * Menyediakan SSO authentication, billing/entitlement check, dan usage metering.
363
+ *
364
+ * @packageDocumentation
365
+ *
366
+ * @example
367
+ * ```typescript
368
+ * import { Authtara } from '@authtara/sdk';
369
+ *
370
+ * const ds = new Authtara({
371
+ * apiKey: process.env.DS_APP_SECRET,
372
+ * endpoint: 'https://api.digitalsolution.com'
373
+ * });
374
+ *
375
+ * // Verify SSO token
376
+ * const session = await ds.auth.verifySession(token);
377
+ *
378
+ * // Check entitlement
379
+ * const access = await ds.billing.checkEntitlement({
380
+ * tenantId: session.tenant.id
381
+ * });
382
+ *
383
+ * // Record usage
384
+ * await ds.metering.recordUsage({
385
+ * tenantId: session.tenant.id,
386
+ * metricSlug: 'api_call',
387
+ * amount: 1
388
+ * });
389
+ * ```
390
+ */
391
+
392
+ /**
393
+ * Konfigurasi untuk Authtara SDK
394
+ */
395
+ interface AuthtaraConfig {
396
+ /**
397
+ * App Secret dari Dashboard Developer
398
+ *
399
+ * Didapatkan setelah aplikasi disetujui (status: APPROVED)
400
+ */
401
+ apiKey: string;
402
+ /**
403
+ * Base URL Platform API
404
+ *
405
+ * @default 'https://api.digitalsolution.com'
406
+ */
407
+ endpoint?: string;
408
+ /**
409
+ * Request timeout dalam milliseconds
410
+ *
411
+ * @default 30000 (30 detik)
412
+ */
413
+ timeout?: number;
414
+ }
415
+ /**
416
+ * Authtara SDK Client
417
+ *
418
+ * Main entry point untuk semua integrasi dengan DigitalSolution Platform.
419
+ *
420
+ * @example
421
+ * ```typescript
422
+ * const ds = new Authtara({
423
+ * apiKey: process.env.DS_APP_SECRET,
424
+ * endpoint: 'https://api.digitalsolution.com'
425
+ * });
426
+ * ```
427
+ */
428
+ declare class Authtara {
429
+ /**
430
+ * Auth module untuk SSO dan token verification
431
+ */
432
+ readonly auth: AuthModule;
433
+ /**
434
+ * Billing module untuk entitlement/access check
435
+ */
436
+ readonly billing: BillingModule;
437
+ /**
438
+ * Metering module untuk usage-based billing
439
+ */
440
+ readonly metering: MeteringModule;
441
+ /**
442
+ * Create new Authtara SDK instance
443
+ *
444
+ * @param config - Konfigurasi SDK
445
+ * @throws ConfigurationError jika apiKey tidak disediakan
446
+ */
447
+ constructor(config: AuthtaraConfig);
448
+ }
449
+
450
+ export { ApiError, Authtara, type AuthtaraConfig, AuthtaraError, type CheckEntitlementParams, ConfigurationError, EntitlementDeniedError, type EntitlementResult, type ExchangeResult, InvalidTokenError, type RecordUsageParams, type RecordUsageResult, type SessionVerifyResult, Authtara as default };