@drmhse/sso-sdk 0.2.7 → 0.2.9

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/dist/index.d.ts CHANGED
@@ -1,65 +1,27 @@
1
1
  /**
2
- * HTTP response wrapper
2
+ * Abstract storage interface for persisting tokens
3
3
  */
4
- interface HttpResponse<T = any> {
5
- data: T;
6
- status: number;
7
- headers: Headers;
4
+ interface TokenStorage {
5
+ getItem(key: string): Promise<string | null> | string | null;
6
+ setItem(key: string, value: string): Promise<void> | void;
7
+ removeItem(key: string): Promise<void> | void;
8
8
  }
9
9
  /**
10
- * HTTP client defaults
10
+ * In-memory storage (Default for Node/Server)
11
11
  */
12
- interface HttpDefaults {
13
- baseURL: string;
14
- headers: {
15
- common: Record<string, string>;
16
- };
17
- timeout: number;
12
+ declare class MemoryStorage implements TokenStorage {
13
+ private store;
14
+ getItem(key: string): string | null;
15
+ setItem(key: string, value: string): void;
16
+ removeItem(key: string): void;
18
17
  }
19
18
  /**
20
- * Custom HTTP client using native fetch API.
21
- * Provides an interface similar to Axios for easy migration.
19
+ * Browser LocalStorage adapter
22
20
  */
23
- declare class HttpClient {
24
- defaults: HttpDefaults;
25
- constructor(baseURL: string);
26
- /**
27
- * Build query string from params object
28
- */
29
- private buildQueryString;
30
- /**
31
- * Build full URL from path and params
32
- */
33
- private buildUrl;
34
- /**
35
- * Make HTTP request with timeout support
36
- */
37
- private request;
38
- /**
39
- * GET request
40
- */
41
- get<T = any>(path: string, config?: {
42
- params?: Record<string, any>;
43
- headers?: Record<string, string>;
44
- }): Promise<HttpResponse<T>>;
45
- /**
46
- * POST request
47
- */
48
- post<T = any>(path: string, data?: any, config?: {
49
- headers?: Record<string, string>;
50
- }): Promise<HttpResponse<T>>;
51
- /**
52
- * PATCH request
53
- */
54
- patch<T = any>(path: string, data?: any, config?: {
55
- headers?: Record<string, string>;
56
- }): Promise<HttpResponse<T>>;
57
- /**
58
- * DELETE request
59
- */
60
- delete<T = any>(path: string, config?: {
61
- headers?: Record<string, string>;
62
- }): Promise<HttpResponse<T>>;
21
+ declare class BrowserStorage implements TokenStorage {
22
+ getItem(key: string): string | null;
23
+ setItem(key: string, value: string): void;
24
+ removeItem(key: string): void;
63
25
  }
64
26
 
65
27
  /**
@@ -75,13 +37,19 @@ interface User {
75
37
  created_at: string;
76
38
  }
77
39
  /**
78
- * User profile response (includes context from JWT)
40
+ * User profile response (includes context from JWT and cached permissions)
79
41
  */
80
42
  interface UserProfile {
81
43
  id: string;
82
44
  email: string;
45
+ is_platform_owner: boolean;
46
+ email_verified_at: string | null;
47
+ created_at: string;
83
48
  org?: string;
84
49
  service?: string;
50
+ permissions: string[];
51
+ plan: string | null;
52
+ features: string[] | null;
85
53
  }
86
54
  /**
87
55
  * Paginated response wrapper
@@ -153,6 +121,12 @@ interface JwtClaims {
153
121
  * List of enabled features
154
122
  */
155
123
  features?: string[];
124
+ /**
125
+ * List of user permissions (Zanzibar relation tuples)
126
+ * Format: "namespace:object_id#relation"
127
+ * Example: ["organization:acme#owner", "service:api#admin"]
128
+ */
129
+ permissions?: string[];
156
130
  /**
157
131
  * Expiration timestamp (Unix epoch)
158
132
  */
@@ -225,6 +199,12 @@ interface LoginUrlParams {
225
199
  * Optional user code for device flow authorization
226
200
  */
227
201
  user_code?: string;
202
+ /**
203
+ * Optional connection ID for enterprise IdP routing (from HRD lookup).
204
+ * When provided, routes user to specific upstream provider instead of using default OAuth.
205
+ * Example: "azure-ad-connection", "okta-enterprise"
206
+ */
207
+ connection_id?: string;
228
208
  }
229
209
  /**
230
210
  * Parameters for constructing admin login URL
@@ -325,6 +305,43 @@ interface MfaVerificationResponse {
325
305
  refresh_token: string;
326
306
  expires_in: number;
327
307
  }
308
+ /**
309
+ * Home Realm Discovery (HRD) request payload
310
+ */
311
+ interface LookupEmailRequest {
312
+ /**
313
+ * Email address to lookup
314
+ */
315
+ email: string;
316
+ }
317
+ /**
318
+ * Home Realm Discovery (HRD) response
319
+ */
320
+ interface LookupEmailResponse {
321
+ /**
322
+ * The connection ID to use for authentication, if any.
323
+ * If present, use this to route the user to their enterprise IdP.
324
+ */
325
+ connection_id: string | null;
326
+ /**
327
+ * The name of the upstream provider, for display purposes.
328
+ * Example: "Acme Corp Azure AD", "Partner Okta"
329
+ */
330
+ provider_name: string | null;
331
+ /**
332
+ * Whether the email domain is verified.
333
+ * true = domain is verified and owned by an organization
334
+ * false = domain is not verified, use default auth flow
335
+ */
336
+ domain_verified: boolean;
337
+ /**
338
+ * The authentication method to use:
339
+ * - "upstream": Route to enterprise IdP via connection_id
340
+ * - "password": Use email/password authentication
341
+ * - "oauth": Use default OAuth providers (GitHub, Google, Microsoft)
342
+ */
343
+ auth_method: 'upstream' | 'password' | 'oauth';
344
+ }
328
345
 
329
346
  /**
330
347
  * User subscription details
@@ -413,6 +430,54 @@ interface MfaVerifyResponse {
413
430
  interface BackupCodesResponse {
414
431
  backup_codes: string[];
415
432
  }
433
+ /**
434
+ * User device information
435
+ */
436
+ interface UserDevice {
437
+ /** Unique device identifier */
438
+ id: string;
439
+ /** Device name/description */
440
+ device_name: string;
441
+ /** When the device was first seen */
442
+ first_seen_at: string;
443
+ /** When the device was last used */
444
+ last_used_at: string;
445
+ /** When the device trust expires */
446
+ expires_at: string;
447
+ /** IP address when device was registered */
448
+ registration_ip?: string;
449
+ /** Risk score for this device */
450
+ risk_score: number;
451
+ /** Whether this device is currently trusted */
452
+ is_trusted: boolean;
453
+ }
454
+ /**
455
+ * List devices response
456
+ */
457
+ interface ListDevicesResponse {
458
+ /** Array of user devices */
459
+ devices: UserDevice[];
460
+ /** Total number of devices */
461
+ total: number;
462
+ }
463
+ /**
464
+ * Revoke device request
465
+ */
466
+ interface RevokeDeviceRequest {
467
+ /** Device ID to revoke */
468
+ device_id: string;
469
+ /** Optional reason for revocation */
470
+ reason?: string;
471
+ }
472
+ /**
473
+ * Revoke device response
474
+ */
475
+ interface RevokeDeviceResponse {
476
+ /** Success message */
477
+ message: string;
478
+ /** Whether revocation was successful */
479
+ success: boolean;
480
+ }
416
481
 
417
482
  /**
418
483
  * Organization entity
@@ -477,12 +542,11 @@ interface OrganizationMember {
477
542
  joined_at: string;
478
543
  }
479
544
  /**
480
- * Create organization payload (public endpoint)
545
+ * Create organization payload (authenticated endpoint)
481
546
  */
482
547
  interface CreateOrganizationPayload {
483
548
  slug: string;
484
549
  name: string;
485
- owner_email: string;
486
550
  }
487
551
  /**
488
552
  * Create organization response
@@ -496,6 +560,8 @@ interface CreateOrganizationResponse {
496
560
  created_at: string;
497
561
  };
498
562
  membership: Membership;
563
+ access_token: string;
564
+ refresh_token: string;
499
565
  }
500
566
  /**
501
567
  * Update organization payload
@@ -757,6 +823,37 @@ interface UpdateBrandingRequest {
757
823
  logo_url?: string | null;
758
824
  primary_color?: string | null;
759
825
  }
826
+ /**
827
+ * Risk settings response
828
+ */
829
+ interface GetRiskSettingsResponse {
830
+ enforcement_mode: string;
831
+ low_threshold: number;
832
+ medium_threshold: number;
833
+ new_device_score: number;
834
+ impossible_travel_score: number;
835
+ velocity_threshold: number;
836
+ velocity_score: number;
837
+ }
838
+ /**
839
+ * Update risk settings request
840
+ */
841
+ interface UpdateRiskSettingsRequest {
842
+ enforcement_mode?: string;
843
+ low_threshold?: number;
844
+ medium_threshold?: number;
845
+ new_device_score?: number;
846
+ impossible_travel_score?: number;
847
+ velocity_threshold?: number;
848
+ velocity_score?: number;
849
+ }
850
+ /**
851
+ * Update risk settings response
852
+ */
853
+ interface UpdateRiskSettingsResponse {
854
+ message: string;
855
+ settings: GetRiskSettingsResponse;
856
+ }
760
857
 
761
858
  /**
762
859
  * Service entity
@@ -803,6 +900,7 @@ interface Plan {
803
900
  price_cents: number;
804
901
  currency: string;
805
902
  features: string;
903
+ stripe_price_id?: string;
806
904
  created_at: string;
807
905
  }
808
906
  /**
@@ -866,6 +964,7 @@ interface CreatePlanPayload {
866
964
  price_cents: number;
867
965
  currency: string;
868
966
  features?: string[];
967
+ stripe_price_id?: string;
869
968
  }
870
969
  /**
871
970
  * Update plan payload
@@ -875,6 +974,7 @@ interface UpdatePlanPayload {
875
974
  price_cents?: number;
876
975
  currency?: string;
877
976
  features?: string[];
977
+ stripe_price_id?: string | null;
878
978
  }
879
979
  /**
880
980
  * Service with aggregated details
@@ -981,6 +1081,21 @@ interface SamlCertificate {
981
1081
  is_active: boolean;
982
1082
  created_at: string;
983
1083
  }
1084
+ /**
1085
+ * Create checkout session payload
1086
+ */
1087
+ interface CreateCheckoutPayload {
1088
+ plan_id: string;
1089
+ success_url: string;
1090
+ cancel_url: string;
1091
+ }
1092
+ /**
1093
+ * Create checkout session response
1094
+ */
1095
+ interface CreateCheckoutResponse {
1096
+ checkout_url: string;
1097
+ session_id: string;
1098
+ }
984
1099
 
985
1100
  /**
986
1101
  * Invitation entity
@@ -1175,6 +1290,31 @@ interface PlatformAnalyticsDateRangeParams {
1175
1290
  start_date?: string;
1176
1291
  end_date?: string;
1177
1292
  }
1293
+ /**
1294
+ * Impersonation request payload
1295
+ */
1296
+ interface ImpersonateRequest {
1297
+ user_id: string;
1298
+ reason: string;
1299
+ }
1300
+ /**
1301
+ * User info for impersonation response
1302
+ */
1303
+ interface ImpersonationUserInfo {
1304
+ id: string;
1305
+ email: string;
1306
+ is_platform_owner: boolean;
1307
+ org_id?: string;
1308
+ org_name?: string;
1309
+ }
1310
+ /**
1311
+ * Impersonation response
1312
+ */
1313
+ interface ImpersonateResponse {
1314
+ token: string;
1315
+ target_user: ImpersonationUserInfo;
1316
+ actor_user: ImpersonationUserInfo;
1317
+ }
1178
1318
 
1179
1319
  /**
1180
1320
  * End-user subscription details
@@ -1277,134 +1417,792 @@ interface AnalyticsQuery {
1277
1417
  }
1278
1418
 
1279
1419
  /**
1280
- * Analytics and login tracking methods
1420
+ * WebAuthn/Passkey authentication types
1281
1421
  */
1282
- declare class AnalyticsModule {
1283
- private http;
1284
- constructor(http: HttpClient);
1285
- /**
1286
- * Get login trends over time.
1287
- * Returns daily login counts grouped by date.
1288
- *
1289
- * @param orgSlug Organization slug
1290
- * @param params Optional query parameters (date range)
1291
- * @returns Array of login trend data points
1292
- *
1293
- * @example
1294
- * ```typescript
1295
- * const trends = await sso.analytics.getLoginTrends('acme-corp', {
1296
- * start_date: '2025-01-01',
1297
- * end_date: '2025-01-31'
1298
- * });
1299
- * trends.forEach(point => console.log(point.date, point.count));
1300
- * ```
1301
- */
1302
- getLoginTrends(orgSlug: string, params?: AnalyticsQuery): Promise<LoginTrendPoint[]>;
1303
- /**
1304
- * Get login counts grouped by service.
1305
- * Shows which services have the most authentication activity.
1306
- *
1307
- * @param orgSlug Organization slug
1308
- * @param params Optional query parameters (date range)
1309
- * @returns Array of login counts per service
1310
- *
1311
- * @example
1312
- * ```typescript
1313
- * const byService = await sso.analytics.getLoginsByService('acme-corp', {
1314
- * start_date: '2025-01-01',
1315
- * end_date: '2025-01-31'
1316
- * });
1317
- * byService.forEach(s => console.log(s.service_name, s.count));
1318
- * ```
1319
- */
1320
- getLoginsByService(orgSlug: string, params?: AnalyticsQuery): Promise<LoginsByService[]>;
1321
- /**
1322
- * Get login counts grouped by OAuth provider.
1323
- * Shows which authentication providers are being used (GitHub, Google, Microsoft).
1324
- *
1325
- * @param orgSlug Organization slug
1326
- * @param params Optional query parameters (date range)
1327
- * @returns Array of login counts per provider
1328
- *
1329
- * @example
1330
- * ```typescript
1331
- * const byProvider = await sso.analytics.getLoginsByProvider('acme-corp', {
1332
- * start_date: '2025-01-01',
1333
- * end_date: '2025-01-31'
1334
- * });
1335
- * byProvider.forEach(p => console.log(p.provider, p.count));
1336
- * ```
1337
- */
1338
- getLoginsByProvider(orgSlug: string, params?: AnalyticsQuery): Promise<LoginsByProvider[]>;
1339
- /**
1340
- * Get the most recent login events.
1341
- *
1342
- * @param orgSlug Organization slug
1343
- * @param params Optional query parameters (limit)
1344
- * @returns Array of recent login events
1345
- *
1346
- * @example
1347
- * ```typescript
1348
- * const recentLogins = await sso.analytics.getRecentLogins('acme-corp', {
1349
- * limit: 10
1350
- * });
1351
- * recentLogins.forEach(login => {
1352
- * console.log(login.user_id, login.provider, login.created_at);
1353
- * });
1354
- * ```
1355
- */
1356
- getRecentLogins(orgSlug: string, params?: AnalyticsQuery): Promise<RecentLogin[]>;
1422
+ /**
1423
+ * Request to start passkey registration
1424
+ */
1425
+ interface PasskeyRegisterStartRequest {
1426
+ name?: string;
1357
1427
  }
1358
-
1359
1428
  /**
1360
- * Authentication and OAuth flow methods
1429
+ * Response from starting passkey registration
1361
1430
  */
1362
- declare class AuthModule {
1363
- private http;
1364
- constructor(http: HttpClient);
1365
- /**
1366
- * Constructs the OAuth login URL for end-users.
1367
- * This does not perform the redirect; the consuming application
1368
- * should redirect the user's browser to this URL.
1369
- *
1370
- * @param provider The OAuth provider to use
1371
- * @param params Login parameters (org, service, redirect_uri)
1372
- * @returns The full URL to redirect the user to
1373
- *
1374
- * @example
1375
- * ```typescript
1376
- * const url = sso.auth.getLoginUrl('github', {
1377
- * org: 'acme-corp',
1378
- * service: 'main-app',
1379
- * redirect_uri: 'https://app.acme.com/callback'
1380
- * });
1381
- * window.location.href = url;
1382
- * ```
1383
- */
1384
- getLoginUrl(provider: OAuthProvider, params: LoginUrlParams): string;
1385
- /**
1386
- * Constructs the OAuth login URL for platform/organization admins.
1387
- * This uses the platform's dedicated OAuth credentials.
1388
- *
1389
- * @param provider The OAuth provider to use
1390
- * @param params Optional admin login parameters
1391
- * @returns The full URL to redirect the admin to
1392
- *
1393
- * @example
1394
- * ```typescript
1395
- * const url = sso.auth.getAdminLoginUrl('github', {
1396
- * org_slug: 'acme-corp'
1397
- * });
1398
- * window.location.href = url;
1399
- * ```
1400
- */
1401
- getAdminLoginUrl(provider: OAuthProvider, params?: AdminLoginUrlParams): string;
1402
- /**
1403
- * Device Flow: Request a device code for CLI/device authentication.
1404
- *
1405
- * @param payload Device code request payload
1406
- * @returns Device code response with user code and verification URI
1407
- *
1431
+ interface PasskeyRegisterStartResponse {
1432
+ challenge_id: string;
1433
+ options: any;
1434
+ }
1435
+ /**
1436
+ * Request to finish passkey registration
1437
+ */
1438
+ interface PasskeyRegisterFinishRequest {
1439
+ challenge_id: string;
1440
+ credential: RegistrationResponseJSON;
1441
+ }
1442
+ /**
1443
+ * Response from finishing passkey registration
1444
+ */
1445
+ interface PasskeyRegisterFinishResponse {
1446
+ success: boolean;
1447
+ passkey_id: string;
1448
+ }
1449
+ /**
1450
+ * Request to start passkey authentication
1451
+ */
1452
+ interface PasskeyAuthStartRequest {
1453
+ email: string;
1454
+ }
1455
+ /**
1456
+ * Response from starting passkey authentication
1457
+ */
1458
+ interface PasskeyAuthStartResponse {
1459
+ challenge_id: string;
1460
+ options: any;
1461
+ }
1462
+ /**
1463
+ * Request to finish passkey authentication
1464
+ */
1465
+ interface PasskeyAuthFinishRequest {
1466
+ challenge_id: string;
1467
+ credential: AuthenticationResponseJSON;
1468
+ }
1469
+ /**
1470
+ * Response from finishing passkey authentication
1471
+ */
1472
+ interface PasskeyAuthFinishResponse {
1473
+ token: string;
1474
+ user_id: string;
1475
+ }
1476
+ /**
1477
+ * JSON-serializable version of WebAuthn registration response
1478
+ */
1479
+ interface RegistrationResponseJSON {
1480
+ id: string;
1481
+ rawId: string;
1482
+ response: {
1483
+ clientDataJSON: string;
1484
+ attestationObject: string;
1485
+ transports?: string[];
1486
+ };
1487
+ authenticatorAttachment?: 'platform' | 'cross-platform';
1488
+ clientExtensionResults: Record<string, unknown>;
1489
+ type: 'public-key';
1490
+ }
1491
+ /**
1492
+ * JSON-serializable version of WebAuthn authentication response
1493
+ */
1494
+ interface AuthenticationResponseJSON {
1495
+ id: string;
1496
+ rawId: string;
1497
+ response: {
1498
+ clientDataJSON: string;
1499
+ authenticatorData: string;
1500
+ signature: string;
1501
+ userHandle?: string;
1502
+ };
1503
+ authenticatorAttachment?: 'platform' | 'cross-platform';
1504
+ clientExtensionResults: Record<string, unknown>;
1505
+ type: 'public-key';
1506
+ }
1507
+ /**
1508
+ * Passkey information
1509
+ */
1510
+ interface Passkey {
1511
+ id: string;
1512
+ user_id: string;
1513
+ credential_id: string;
1514
+ name: string;
1515
+ aaguid?: string;
1516
+ backup_eligible: boolean;
1517
+ backup_state: boolean;
1518
+ transports?: string;
1519
+ last_used_at?: string;
1520
+ created_at: string;
1521
+ }
1522
+
1523
+ /**
1524
+ * Risk assessment and engine types
1525
+ */
1526
+ /**
1527
+ * Risk score levels
1528
+ */
1529
+ type RiskScore = number;
1530
+ /**
1531
+ * Risk assessment results from the risk engine
1532
+ */
1533
+ interface RiskAssessment {
1534
+ /** Overall risk score (0-100, higher is more risky) */
1535
+ score: RiskScore;
1536
+ /** Action to take based on risk assessment */
1537
+ action: RiskAction;
1538
+ /** Specific risk factors that contributed to the score */
1539
+ factors: RiskFactor[];
1540
+ /** Geolocation data if available */
1541
+ location?: GeolocationData;
1542
+ /** When the assessment was performed */
1543
+ assessedAt: string;
1544
+ /** Additional metadata about the assessment */
1545
+ metadata?: Record<string, unknown>;
1546
+ }
1547
+ /**
1548
+ * Risk actions the engine can recommend
1549
+ */
1550
+ declare enum RiskAction {
1551
+ /** Allow the authentication to proceed */
1552
+ ALLOW = "allow",
1553
+ /** Log only - allow but monitor */
1554
+ LOG_ONLY = "log_only",
1555
+ /** Require additional verification (MFA) */
1556
+ CHALLENGE_MFA = "challenge_mfa",
1557
+ /** Block the authentication attempt */
1558
+ BLOCK = "block"
1559
+ }
1560
+ /**
1561
+ * Individual risk factors that contribute to overall risk score
1562
+ */
1563
+ interface RiskFactor {
1564
+ /** Type of risk factor */
1565
+ type: RiskFactorType;
1566
+ /** How much this factor contributes to the score */
1567
+ weight: number;
1568
+ /** Human-readable description */
1569
+ description: string;
1570
+ /** Additional data about this factor */
1571
+ data?: Record<string, unknown>;
1572
+ }
1573
+ /**
1574
+ * Types of risk factors the engine can detect
1575
+ */
1576
+ declare enum RiskFactorType {
1577
+ /** Unknown IP address or never seen before */
1578
+ NEW_IP = "new_ip",
1579
+ /** IP from high-risk country or region */
1580
+ HIGH_RISK_LOCATION = "high_risk_location",
1581
+ /** Impossible travel - login from geographically impossible locations */
1582
+ IMPOSSIBLE_TRAVEL = "impossible_travel",
1583
+ /** New device or browser fingerprint */
1584
+ NEW_DEVICE = "new_device",
1585
+ /** Multiple failed login attempts */
1586
+ FAILED_ATTEMPTS = "failed_attempts",
1587
+ /** Login from unusual time of day */
1588
+ UNUSUAL_TIME = "unusual_time",
1589
+ /** Suspicious user agent or bot patterns */
1590
+ SUSPICIOUS_USER_AGENT = "suspicious_user_agent",
1591
+ /** Tor exit node or VPN detected */
1592
+ ANONYMOUS_NETWORK = "anonymous_network",
1593
+ /** Account is new (recently created) */
1594
+ NEW_ACCOUNT = "new_account",
1595
+ /** Account has suspicious activity history */
1596
+ SUSPICIOUS_HISTORY = "suspicious_history",
1597
+ /** Velocity-based detection (too many actions) */
1598
+ HIGH_VELOCITY = "high_velocity",
1599
+ /** Custom rule triggered */
1600
+ CUSTOM_RULE = "custom_rule"
1601
+ }
1602
+ /**
1603
+ * Geolocation data for risk assessment
1604
+ */
1605
+ interface GeolocationData {
1606
+ /** Two-letter ISO country code */
1607
+ country: string;
1608
+ /** City name if available */
1609
+ city?: string;
1610
+ /** Region/state if available */
1611
+ region?: string;
1612
+ /** Latitude coordinate */
1613
+ latitude?: number;
1614
+ /** Longitude coordinate */
1615
+ longitude?: number;
1616
+ /** ISP or organization name */
1617
+ isp?: string;
1618
+ /** Whether this is a known VPN/proxy */
1619
+ isVpn?: boolean;
1620
+ /** Whether this is a Tor exit node */
1621
+ isTor?: boolean;
1622
+ }
1623
+ /**
1624
+ * Context provided to risk engine for assessment
1625
+ */
1626
+ interface RiskContext {
1627
+ /** User ID being authenticated */
1628
+ userId: string;
1629
+ /** Organization ID if applicable */
1630
+ orgId?: string;
1631
+ /** IP address of the request */
1632
+ ipAddress: string;
1633
+ /** User agent string */
1634
+ userAgent: string;
1635
+ /** Device fingerprint or cookie if available */
1636
+ deviceCookie?: string;
1637
+ /** Authentication method being used */
1638
+ authMethod: AuthMethod;
1639
+ /** Additional context data */
1640
+ metadata?: Record<string, unknown>;
1641
+ }
1642
+ /**
1643
+ * Authentication methods for risk assessment
1644
+ */
1645
+ declare enum AuthMethod {
1646
+ /** Email and password */
1647
+ PASSWORD = "password",
1648
+ /** OAuth provider (Google, GitHub, etc.) */
1649
+ OAUTH = "oauth",
1650
+ /** WebAuthn passkeys */
1651
+ PASSKEY = "passkey",
1652
+ /** Magic link email */
1653
+ MAGIC_LINK = "magic_link",
1654
+ /** Multi-factor authentication */
1655
+ MFA = "mfa",
1656
+ /** SAML SSO */
1657
+ SAML = "saml"
1658
+ }
1659
+ /**
1660
+ * Risk engine configuration for organizations
1661
+ */
1662
+ interface RiskEngineConfig {
1663
+ /** Enable/disable risk engine */
1664
+ enabled: boolean;
1665
+ /** Risk score threshold for blocking */
1666
+ blockThreshold: RiskScore;
1667
+ /** Risk score threshold for requiring MFA */
1668
+ mfaThreshold: RiskScore;
1669
+ /** Which risk factors to consider */
1670
+ enabledFactors: RiskFactorType[];
1671
+ /** Custom rules and weights */
1672
+ customRules?: RiskRule[];
1673
+ /** How long to remember trusted devices */
1674
+ deviceTrustDuration: number;
1675
+ /** Whether to enable location-based risk assessment */
1676
+ enableLocationTracking: boolean;
1677
+ /** Max failed attempts before increased risk */
1678
+ maxFailedAttempts: number;
1679
+ /** Time window for velocity checks */
1680
+ velocityWindow: number;
1681
+ }
1682
+ /**
1683
+ * Custom risk rule definition
1684
+ */
1685
+ interface RiskRule {
1686
+ /** Unique rule identifier */
1687
+ id: string;
1688
+ /** Rule name for display */
1689
+ name: string;
1690
+ /** Rule description */
1691
+ description: string;
1692
+ /** Condition to trigger the rule */
1693
+ condition: RiskRuleCondition;
1694
+ /** Action to take when rule triggers */
1695
+ action: RiskAction;
1696
+ /** How much weight this rule carries */
1697
+ weight: number;
1698
+ /** Whether the rule is enabled */
1699
+ enabled: boolean;
1700
+ }
1701
+ /**
1702
+ * Risk rule condition
1703
+ */
1704
+ interface RiskRuleCondition {
1705
+ /** Field to check */
1706
+ field: string;
1707
+ /** Operator for comparison */
1708
+ operator: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'contains' | 'regex';
1709
+ /** Value to compare against */
1710
+ value: unknown;
1711
+ /** Additional conditions (AND logic) */
1712
+ and?: RiskRuleCondition[];
1713
+ /** Alternative conditions (OR logic) */
1714
+ or?: RiskRuleCondition[];
1715
+ }
1716
+ /**
1717
+ * Device trust information
1718
+ */
1719
+ interface DeviceTrust {
1720
+ /** Device ID */
1721
+ deviceId: string;
1722
+ /** User ID this device belongs to */
1723
+ userId: string;
1724
+ /** Device name or description */
1725
+ deviceName: string;
1726
+ /** When the device was first seen */
1727
+ firstSeenAt: string;
1728
+ /** When the device was last used */
1729
+ lastSeenAt: string;
1730
+ /** When the device trust expires */
1731
+ expiresAt: string;
1732
+ /** IP address when device was registered */
1733
+ registrationIp?: string;
1734
+ /** Risk score for this device */
1735
+ riskScore: RiskScore;
1736
+ /** Whether this device is currently trusted */
1737
+ isTrusted: boolean;
1738
+ }
1739
+ /**
1740
+ * Risk event for logging and monitoring
1741
+ */
1742
+ interface RiskEvent {
1743
+ /** Unique event ID */
1744
+ id: string;
1745
+ /** User ID involved */
1746
+ userId: string;
1747
+ /** Organization ID if applicable */
1748
+ orgId?: string;
1749
+ /** Risk assessment that triggered this event */
1750
+ assessment: RiskAssessment;
1751
+ /** Authentication context */
1752
+ context: RiskContext;
1753
+ /** When the event occurred */
1754
+ timestamp: string;
1755
+ /** Event outcome */
1756
+ outcome: RiskEventOutcome;
1757
+ /** Additional event metadata */
1758
+ metadata?: Record<string, unknown>;
1759
+ }
1760
+ /**
1761
+ * Risk event outcomes
1762
+ */
1763
+ declare enum RiskEventOutcome {
1764
+ /** Authentication was allowed */
1765
+ ALLOWED = "allowed",
1766
+ /** Authentication was blocked */
1767
+ BLOCKED = "blocked",
1768
+ /** Additional verification was required */
1769
+ CHALLENGED = "challenged",
1770
+ /** Event was logged but no action taken */
1771
+ LOGGED = "logged"
1772
+ }
1773
+ /**
1774
+ * Risk engine analytics and reporting
1775
+ */
1776
+ interface RiskAnalytics {
1777
+ /** Total risk assessments in time period */
1778
+ totalAssessments: number;
1779
+ /** Risk score distribution */
1780
+ scoreDistribution: {
1781
+ low: number;
1782
+ medium: number;
1783
+ high: number;
1784
+ critical: number;
1785
+ };
1786
+ /** Most common risk factors */
1787
+ topRiskFactors: Array<{
1788
+ factor: RiskFactorType;
1789
+ count: number;
1790
+ percentage: number;
1791
+ }>;
1792
+ /** Blocked authentication attempts */
1793
+ blockedAttempts: number;
1794
+ /** MFA challenges issued */
1795
+ mfaChallenges: number;
1796
+ /** Geographic risk data */
1797
+ locationRisk: Array<{
1798
+ country: string;
1799
+ riskCount: number;
1800
+ riskScore: number;
1801
+ }>;
1802
+ /** Time-based risk patterns */
1803
+ temporalPatterns: {
1804
+ hourly: number[];
1805
+ daily: number[];
1806
+ };
1807
+ }
1808
+
1809
+ /**
1810
+ * Privacy and GDPR compliance types
1811
+ */
1812
+ /**
1813
+ * User membership export data
1814
+ */
1815
+ interface MembershipExport {
1816
+ organization_id: string;
1817
+ organization_slug: string;
1818
+ role: string;
1819
+ joined_at: string;
1820
+ }
1821
+ /**
1822
+ * Login event export data
1823
+ */
1824
+ interface LoginEventExport {
1825
+ id: string;
1826
+ timestamp: string;
1827
+ ip_address: string | null;
1828
+ user_agent: string | null;
1829
+ provider: string | null;
1830
+ success: boolean;
1831
+ risk_score: number | null;
1832
+ risk_factors: string | null;
1833
+ geo_country: string | null;
1834
+ geo_city: string | null;
1835
+ }
1836
+ /**
1837
+ * OAuth identity export data
1838
+ */
1839
+ interface OAuthIdentityExport {
1840
+ provider: string;
1841
+ provider_user_id: string;
1842
+ linked_at: string;
1843
+ }
1844
+ /**
1845
+ * MFA event export data
1846
+ */
1847
+ interface MfaEventExport {
1848
+ event_type: string;
1849
+ timestamp: string;
1850
+ success: boolean;
1851
+ }
1852
+ /**
1853
+ * Passkey export data
1854
+ */
1855
+ interface PasskeyExport {
1856
+ id: string;
1857
+ name: string | null;
1858
+ aaguid: string | null;
1859
+ backup_eligible: boolean;
1860
+ created_at: string;
1861
+ last_used_at: string | null;
1862
+ }
1863
+ /**
1864
+ * Complete user data export response (GDPR Right to Access)
1865
+ */
1866
+ interface ExportUserDataResponse {
1867
+ user_id: string;
1868
+ email: string;
1869
+ created_at: string;
1870
+ memberships: MembershipExport[];
1871
+ login_events_count: number;
1872
+ login_events: LoginEventExport[];
1873
+ oauth_identities: OAuthIdentityExport[];
1874
+ mfa_events: MfaEventExport[];
1875
+ passkeys: PasskeyExport[];
1876
+ }
1877
+ /**
1878
+ * User anonymization response (GDPR Right to be Forgotten)
1879
+ */
1880
+ interface ForgetUserResponse {
1881
+ success: boolean;
1882
+ message: string;
1883
+ user_id: string;
1884
+ }
1885
+
1886
+ /**
1887
+ * SIEM (Security Information and Event Management) types
1888
+ */
1889
+ /**
1890
+ * SIEM provider types
1891
+ */
1892
+ type SiemProviderType = 'Datadog' | 'Splunk' | 'Elastic' | 'Custom';
1893
+ /**
1894
+ * SIEM configuration response
1895
+ */
1896
+ interface SiemConfigResponse {
1897
+ id: string;
1898
+ org_id: string;
1899
+ name: string;
1900
+ provider_type: SiemProviderType;
1901
+ endpoint_url: string;
1902
+ batch_size: number;
1903
+ enabled: boolean;
1904
+ last_successful_batch_at: string | null;
1905
+ failure_count: number;
1906
+ created_at: string;
1907
+ }
1908
+ /**
1909
+ * Create SIEM configuration request
1910
+ */
1911
+ interface CreateSiemConfigRequest {
1912
+ name: string;
1913
+ provider_type: SiemProviderType;
1914
+ endpoint_url: string;
1915
+ api_key?: string;
1916
+ auth_header?: string;
1917
+ batch_size?: number;
1918
+ }
1919
+ /**
1920
+ * Update SIEM configuration request
1921
+ */
1922
+ interface UpdateSiemConfigRequest {
1923
+ name?: string;
1924
+ endpoint_url?: string;
1925
+ api_key?: string | null;
1926
+ auth_header?: string | null;
1927
+ batch_size?: number;
1928
+ enabled?: boolean;
1929
+ }
1930
+ /**
1931
+ * List SIEM configurations response
1932
+ */
1933
+ interface ListSiemConfigsResponse {
1934
+ siem_configs: SiemConfigResponse[];
1935
+ total: number;
1936
+ }
1937
+ /**
1938
+ * Test SIEM connection response
1939
+ */
1940
+ interface TestConnectionResponse {
1941
+ success: boolean;
1942
+ message: string;
1943
+ }
1944
+
1945
+ interface SessionConfig {
1946
+ storageKeyPrefix?: string;
1947
+ autoRefresh?: boolean;
1948
+ }
1949
+ declare class SessionManager {
1950
+ private storage;
1951
+ private refreshHandler;
1952
+ private config;
1953
+ private accessToken;
1954
+ private refreshToken;
1955
+ private refreshPromise;
1956
+ private listeners;
1957
+ constructor(storage: TokenStorage, refreshHandler: (token: string) => Promise<RefreshTokenResponse>, config?: SessionConfig);
1958
+ /**
1959
+ * Initialize session from storage
1960
+ */
1961
+ loadSession(): Promise<void>;
1962
+ /**
1963
+ * Set the session data (used after login/register)
1964
+ */
1965
+ setSession(tokens: {
1966
+ access_token: string;
1967
+ refresh_token?: string;
1968
+ }): Promise<void>;
1969
+ /**
1970
+ * Clear session (logout)
1971
+ */
1972
+ clearSession(): Promise<void>;
1973
+ /**
1974
+ * Get the current access token, refreshing it if necessary/possible
1975
+ */
1976
+ getToken(): Promise<string | null>;
1977
+ /**
1978
+ * Handle logic for when a 401 occurs
1979
+ */
1980
+ refreshSession(): Promise<string>;
1981
+ isAuthenticated(): boolean;
1982
+ /**
1983
+ * Subscribe to auth state changes (useful for UI updates)
1984
+ */
1985
+ subscribe(listener: (isAuthenticated: boolean) => void): () => void;
1986
+ private notifyListeners;
1987
+ }
1988
+
1989
+ /**
1990
+ * HTTP response wrapper
1991
+ */
1992
+ interface HttpResponse<T = any> {
1993
+ data: T;
1994
+ status: number;
1995
+ headers: Headers;
1996
+ }
1997
+ /**
1998
+ * HTTP client defaults
1999
+ */
2000
+ interface HttpDefaults {
2001
+ baseURL: string;
2002
+ headers: {
2003
+ common: Record<string, string>;
2004
+ };
2005
+ timeout: number;
2006
+ }
2007
+ /**
2008
+ * Custom HTTP client using native fetch API.
2009
+ * Provides an interface similar to Axios for easy migration.
2010
+ */
2011
+ declare class HttpClient {
2012
+ defaults: HttpDefaults;
2013
+ private sessionManager?;
2014
+ constructor(baseURL: string);
2015
+ /**
2016
+ * Allow injecting session manager after construction to avoid circular dep
2017
+ */
2018
+ setSessionManager(manager: SessionManager): void;
2019
+ /**
2020
+ * Build query string from params object
2021
+ */
2022
+ private buildQueryString;
2023
+ /**
2024
+ * Build full URL from path and params
2025
+ */
2026
+ private buildUrl;
2027
+ /**
2028
+ * Make HTTP request with timeout support
2029
+ */
2030
+ private request;
2031
+ /**
2032
+ * GET request
2033
+ */
2034
+ get<T = any>(path: string, config?: {
2035
+ params?: Record<string, any>;
2036
+ headers?: Record<string, string>;
2037
+ }): Promise<HttpResponse<T>>;
2038
+ /**
2039
+ * POST request
2040
+ */
2041
+ post<T = any>(path: string, data?: any, config?: {
2042
+ headers?: Record<string, string>;
2043
+ }): Promise<HttpResponse<T>>;
2044
+ /**
2045
+ * PUT request
2046
+ */
2047
+ put<T = any>(path: string, data?: any, config?: {
2048
+ headers?: Record<string, string>;
2049
+ }): Promise<HttpResponse<T>>;
2050
+ /**
2051
+ * PATCH request
2052
+ */
2053
+ patch<T = any>(path: string, data?: any, config?: {
2054
+ headers?: Record<string, string>;
2055
+ }): Promise<HttpResponse<T>>;
2056
+ /**
2057
+ * DELETE request
2058
+ */
2059
+ delete<T = any>(path: string, config?: {
2060
+ headers?: Record<string, string>;
2061
+ }): Promise<HttpResponse<T>>;
2062
+ }
2063
+
2064
+ /**
2065
+ * Analytics and login tracking methods
2066
+ */
2067
+ declare class AnalyticsModule {
2068
+ private http;
2069
+ constructor(http: HttpClient);
2070
+ /**
2071
+ * Get login trends over time.
2072
+ * Returns daily login counts grouped by date.
2073
+ *
2074
+ * @param orgSlug Organization slug
2075
+ * @param params Optional query parameters (date range)
2076
+ * @returns Array of login trend data points
2077
+ *
2078
+ * @example
2079
+ * ```typescript
2080
+ * const trends = await sso.analytics.getLoginTrends('acme-corp', {
2081
+ * start_date: '2025-01-01',
2082
+ * end_date: '2025-01-31'
2083
+ * });
2084
+ * trends.forEach(point => console.log(point.date, point.count));
2085
+ * ```
2086
+ */
2087
+ getLoginTrends(orgSlug: string, params?: AnalyticsQuery): Promise<LoginTrendPoint[]>;
2088
+ /**
2089
+ * Get login counts grouped by service.
2090
+ * Shows which services have the most authentication activity.
2091
+ *
2092
+ * @param orgSlug Organization slug
2093
+ * @param params Optional query parameters (date range)
2094
+ * @returns Array of login counts per service
2095
+ *
2096
+ * @example
2097
+ * ```typescript
2098
+ * const byService = await sso.analytics.getLoginsByService('acme-corp', {
2099
+ * start_date: '2025-01-01',
2100
+ * end_date: '2025-01-31'
2101
+ * });
2102
+ * byService.forEach(s => console.log(s.service_name, s.count));
2103
+ * ```
2104
+ */
2105
+ getLoginsByService(orgSlug: string, params?: AnalyticsQuery): Promise<LoginsByService[]>;
2106
+ /**
2107
+ * Get login counts grouped by OAuth provider.
2108
+ * Shows which authentication providers are being used (GitHub, Google, Microsoft).
2109
+ *
2110
+ * @param orgSlug Organization slug
2111
+ * @param params Optional query parameters (date range)
2112
+ * @returns Array of login counts per provider
2113
+ *
2114
+ * @example
2115
+ * ```typescript
2116
+ * const byProvider = await sso.analytics.getLoginsByProvider('acme-corp', {
2117
+ * start_date: '2025-01-01',
2118
+ * end_date: '2025-01-31'
2119
+ * });
2120
+ * byProvider.forEach(p => console.log(p.provider, p.count));
2121
+ * ```
2122
+ */
2123
+ getLoginsByProvider(orgSlug: string, params?: AnalyticsQuery): Promise<LoginsByProvider[]>;
2124
+ /**
2125
+ * Get the most recent login events.
2126
+ *
2127
+ * @param orgSlug Organization slug
2128
+ * @param params Optional query parameters (limit)
2129
+ * @returns Array of recent login events
2130
+ *
2131
+ * @example
2132
+ * ```typescript
2133
+ * const recentLogins = await sso.analytics.getRecentLogins('acme-corp', {
2134
+ * limit: 10
2135
+ * });
2136
+ * recentLogins.forEach(login => {
2137
+ * console.log(login.user_id, login.provider, login.created_at);
2138
+ * });
2139
+ * ```
2140
+ */
2141
+ getRecentLogins(orgSlug: string, params?: AnalyticsQuery): Promise<RecentLogin[]>;
2142
+ }
2143
+
2144
+ /**
2145
+ * Authentication and OAuth flow methods
2146
+ */
2147
+ declare class AuthModule {
2148
+ private http;
2149
+ private session;
2150
+ constructor(http: HttpClient, session: SessionManager);
2151
+ /**
2152
+ * Constructs the OAuth login URL for end-users.
2153
+ * This does not perform the redirect; the consuming application
2154
+ * should redirect the user's browser to this URL.
2155
+ *
2156
+ * @param provider The OAuth provider to use
2157
+ * @param params Login parameters (org, service, redirect_uri, connection_id)
2158
+ * @returns The full URL to redirect the user to
2159
+ *
2160
+ * @example
2161
+ * ```typescript
2162
+ * // Standard OAuth login
2163
+ * const url = sso.auth.getLoginUrl('github', {
2164
+ * org: 'acme-corp',
2165
+ * service: 'main-app',
2166
+ * redirect_uri: 'https://app.acme.com/callback'
2167
+ * });
2168
+ * window.location.href = url;
2169
+ *
2170
+ * // Enterprise IdP login (after HRD lookup)
2171
+ * const hrd = await sso.auth.lookupEmail('user@enterprise.com');
2172
+ * if (hrd.connection_id) {
2173
+ * const url = sso.auth.getLoginUrl('github', {
2174
+ * org: 'acme-corp',
2175
+ * service: 'main-app',
2176
+ * connection_id: hrd.connection_id
2177
+ * });
2178
+ * window.location.href = url;
2179
+ * }
2180
+ * ```
2181
+ */
2182
+ getLoginUrl(provider: OAuthProvider, params: LoginUrlParams): string;
2183
+ /**
2184
+ * Constructs the OAuth login URL for platform/organization admins.
2185
+ * This uses the platform's dedicated OAuth credentials.
2186
+ *
2187
+ * @param provider The OAuth provider to use
2188
+ * @param params Optional admin login parameters
2189
+ * @returns The full URL to redirect the admin to
2190
+ *
2191
+ * @example
2192
+ * ```typescript
2193
+ * const url = sso.auth.getAdminLoginUrl('github', {
2194
+ * org_slug: 'acme-corp'
2195
+ * });
2196
+ * window.location.href = url;
2197
+ * ```
2198
+ */
2199
+ getAdminLoginUrl(provider: OAuthProvider, params?: AdminLoginUrlParams): string;
2200
+ /**
2201
+ * Device Flow: Request a device code for CLI/device authentication.
2202
+ *
2203
+ * @param payload Device code request payload
2204
+ * @returns Device code response with user code and verification URI
2205
+ *
1408
2206
  * @example
1409
2207
  * ```typescript
1410
2208
  * const response = await sso.auth.deviceCode.request({
@@ -1437,6 +2235,9 @@ declare class AuthModule {
1437
2235
  /**
1438
2236
  * Exchange a device code for a JWT token.
1439
2237
  * This should be polled by the device/CLI after displaying the user code.
2238
+ * Note: This returns a TokenResponse (not RefreshTokenResponse) and typically
2239
+ * only includes access_token. For device flows that need persistence,
2240
+ * manually call sso.session.setSession() if needed.
1440
2241
  *
1441
2242
  * @param payload Token request payload
1442
2243
  * @returns Token response with JWT
@@ -1452,7 +2253,7 @@ declare class AuthModule {
1452
2253
  * client_id: 'service-client-id'
1453
2254
  * });
1454
2255
  * clearInterval(interval);
1455
- * sso.setAuthToken(token.access_token);
2256
+ * // Session is automatically configured
1456
2257
  * } catch (error) {
1457
2258
  * if (error.errorCode !== 'authorization_pending') {
1458
2259
  * clearInterval(interval);
@@ -1466,15 +2267,12 @@ declare class AuthModule {
1466
2267
  };
1467
2268
  /**
1468
2269
  * Logout the current user by revoking their JWT.
1469
- * After calling this, you should clear the token from storage
1470
- * and call `sso.setAuthToken(null)`.
2270
+ * Automatically clears the session and tokens from storage.
1471
2271
  *
1472
2272
  * @example
1473
2273
  * ```typescript
1474
2274
  * await sso.auth.logout();
1475
- * sso.setAuthToken(null);
1476
- * localStorage.removeItem('sso_access_token');
1477
- * localStorage.removeItem('sso_refresh_token');
2275
+ * // Session is automatically cleared - no need for manual cleanup
1478
2276
  * ```
1479
2277
  */
1480
2278
  logout(): Promise<void>;
@@ -1537,8 +2335,7 @@ declare class AuthModule {
1537
2335
  register(payload: RegisterRequest): Promise<RegisterResponse>;
1538
2336
  /**
1539
2337
  * Login with email and password.
1540
- * Returns access token and refresh token on successful authentication.
1541
- * The user's email must be verified before login.
2338
+ * Automatically persists the session and configures the client.
1542
2339
  *
1543
2340
  * @param payload Login credentials (email and password)
1544
2341
  * @returns Access token, refresh token, and expiration info
@@ -1549,9 +2346,7 @@ declare class AuthModule {
1549
2346
  * email: 'user@example.com',
1550
2347
  * password: 'SecurePassword123!'
1551
2348
  * });
1552
- * sso.setAuthToken(tokens.access_token);
1553
- * localStorage.setItem('sso_access_token', tokens.access_token);
1554
- * localStorage.setItem('sso_refresh_token', tokens.refresh_token);
2349
+ * // Session is automatically saved - no need for manual token management
1555
2350
  * ```
1556
2351
  */
1557
2352
  login(payload: LoginRequest): Promise<RefreshTokenResponse>;
@@ -1560,6 +2355,7 @@ declare class AuthModule {
1560
2355
  * This method should be called after login when the user has MFA enabled.
1561
2356
  * The login will return a pre-auth token with a short expiration (5 minutes).
1562
2357
  * Exchange the pre-auth token and TOTP code for a full session.
2358
+ * Automatically persists the session after successful MFA verification.
1563
2359
  *
1564
2360
  * @param preauthToken The pre-authentication token received from login
1565
2361
  * @param code The TOTP code from the user's authenticator app or a backup code
@@ -1578,9 +2374,7 @@ declare class AuthModule {
1578
2374
  * // User needs to provide MFA code
1579
2375
  * const mfaCode = prompt('Enter your 6-digit code from authenticator app');
1580
2376
  * const tokens = await sso.auth.verifyMfa(loginResponse.access_token, mfaCode);
1581
- * sso.setAuthToken(tokens.access_token);
1582
- * localStorage.setItem('sso_access_token', tokens.access_token);
1583
- * localStorage.setItem('sso_refresh_token', tokens.refresh_token);
2377
+ * // Session is automatically saved - no need for manual token management
1584
2378
  * }
1585
2379
  * ```
1586
2380
  */
@@ -1619,6 +2413,44 @@ declare class AuthModule {
1619
2413
  * ```
1620
2414
  */
1621
2415
  resetPassword(payload: ResetPasswordRequest): Promise<ResetPasswordResponse>;
2416
+ /**
2417
+ * Lookup an email address to determine which authentication method to use.
2418
+ * This implements Home Realm Discovery (HRD), allowing users to simply enter
2419
+ * their email address and be automatically routed to the correct identity provider.
2420
+ *
2421
+ * The system will:
2422
+ * 1. Extract the domain from the email address
2423
+ * 2. Check if the domain is verified and mapped to an enterprise IdP
2424
+ * 3. Return routing information (connection_id) if found
2425
+ * 4. Otherwise, indicate to use default authentication (password or OAuth)
2426
+ *
2427
+ * @param email The user's email address
2428
+ * @returns HRD response with routing information
2429
+ *
2430
+ * @example
2431
+ * ```typescript
2432
+ * // Lookup email to determine authentication flow
2433
+ * const result = await sso.auth.lookupEmail('john@acmecorp.com');
2434
+ *
2435
+ * if (result.auth_method === 'upstream' && result.connection_id) {
2436
+ * // Route to enterprise IdP
2437
+ * console.log(`Redirecting to ${result.provider_name}`);
2438
+ * const url = sso.auth.getLoginUrl('github', {
2439
+ * org: 'acme-corp',
2440
+ * service: 'main-app',
2441
+ * connection_id: result.connection_id
2442
+ * });
2443
+ * window.location.href = url;
2444
+ * } else if (result.auth_method === 'password') {
2445
+ * // Show password login form
2446
+ * showPasswordForm();
2447
+ * } else {
2448
+ * // Show default OAuth provider buttons (GitHub, Google, Microsoft)
2449
+ * showOAuthButtons();
2450
+ * }
2451
+ * ```
2452
+ */
2453
+ lookupEmail(email: string): Promise<LookupEmailResponse>;
1622
2454
  }
1623
2455
 
1624
2456
  /**
@@ -1738,6 +2570,100 @@ declare class MfaModule {
1738
2570
  */
1739
2571
  regenerateBackupCodes(): Promise<BackupCodesResponse>;
1740
2572
  }
2573
+ /**
2574
+ * Device management methods
2575
+ */
2576
+ declare class DevicesModule {
2577
+ private http;
2578
+ constructor(http: HttpClient);
2579
+ /**
2580
+ * List all devices associated with the authenticated user.
2581
+ *
2582
+ * @param options Optional query parameters for pagination
2583
+ * @returns Array of user devices
2584
+ *
2585
+ * @example
2586
+ * ```typescript
2587
+ * const { devices, total } = await sso.user.devices.list();
2588
+ * console.log(devices); // Array of trusted devices
2589
+ * ```
2590
+ */
2591
+ list(options?: {
2592
+ page?: number;
2593
+ limit?: number;
2594
+ sort_by?: 'first_seen_at' | 'last_used_at' | 'device_name';
2595
+ sort_order?: 'asc' | 'desc';
2596
+ }): Promise<ListDevicesResponse>;
2597
+ /**
2598
+ * Get details for a specific device.
2599
+ *
2600
+ * @param deviceId The device ID to retrieve
2601
+ * @returns Device details
2602
+ *
2603
+ * @example
2604
+ * ```typescript
2605
+ * const device = await sso.user.devices.get('device-123');
2606
+ * console.log(device.device_name, device.is_trusted);
2607
+ * ```
2608
+ */
2609
+ get(deviceId: string): Promise<UserDevice>;
2610
+ /**
2611
+ * Revoke access for a specific device.
2612
+ * This will remove the device's trust and require re-authentication.
2613
+ *
2614
+ * @param deviceId The device ID to revoke
2615
+ * @param reason Optional reason for revocation
2616
+ * @returns Confirmation message
2617
+ *
2618
+ * @example
2619
+ * ```typescript
2620
+ * const result = await sso.user.devices.revoke('device-123', 'Device lost');
2621
+ * console.log(result.message);
2622
+ * ```
2623
+ */
2624
+ revoke(deviceId: string, reason?: string): Promise<RevokeDeviceResponse>;
2625
+ /**
2626
+ * Revoke all devices except the current one.
2627
+ * This is useful when you suspect account compromise or want to force re-authentication on all devices.
2628
+ *
2629
+ * @returns Confirmation message
2630
+ *
2631
+ * @example
2632
+ * ```typescript
2633
+ * const result = await sso.user.devices.revokeAll();
2634
+ * console.log(result.message); // "All other devices have been revoked"
2635
+ * ```
2636
+ */
2637
+ revokeAll(): Promise<RevokeDeviceResponse>;
2638
+ /**
2639
+ * Update the name of a device.
2640
+ *
2641
+ * @param deviceId The device ID to update
2642
+ * @param deviceName New device name
2643
+ * @returns Updated device information
2644
+ *
2645
+ * @example
2646
+ * ```typescript
2647
+ * const device = await sso.user.devices.updateName('device-123', 'My Laptop');
2648
+ * console.log(device.device_name); // "My Laptop"
2649
+ * ```
2650
+ */
2651
+ updateName(deviceId: string, deviceName: string): Promise<UserDevice>;
2652
+ /**
2653
+ * Mark a device as trusted manually.
2654
+ * This is useful for devices that you want to explicitly trust regardless of risk assessment.
2655
+ *
2656
+ * @param deviceId The device ID to trust
2657
+ * @returns Updated device information
2658
+ *
2659
+ * @example
2660
+ * ```typescript
2661
+ * const device = await sso.user.devices.trust('device-123');
2662
+ * console.log(device.is_trusted); // true
2663
+ * ```
2664
+ */
2665
+ trust(deviceId: string): Promise<UserDevice>;
2666
+ }
1741
2667
  /**
1742
2668
  * User profile and subscription methods
1743
2669
  */
@@ -1745,6 +2671,7 @@ declare class UserModule {
1745
2671
  private http;
1746
2672
  readonly identities: IdentitiesModule;
1747
2673
  readonly mfa: MfaModule;
2674
+ readonly devices: DevicesModule;
1748
2675
  constructor(http: HttpClient);
1749
2676
  /**
1750
2677
  * Get the profile of the currently authenticated user.
@@ -2047,23 +2974,24 @@ declare class OrganizationsModule {
2047
2974
  */
2048
2975
  webhooks: WebhooksModule;
2049
2976
  /**
2050
- * Create a new organization (public endpoint).
2051
- * The organization will be created with 'pending' status and requires
2052
- * platform owner approval before becoming active.
2977
+ * Create a new organization (requires authentication).
2978
+ * The authenticated user becomes the organization owner.
2979
+ * Returns JWT tokens with organization context, eliminating the need to re-authenticate.
2053
2980
  *
2054
2981
  * @param payload Organization creation payload
2055
- * @returns Created organization with owner and membership details
2982
+ * @returns Created organization with owner, membership, and JWT tokens
2056
2983
  *
2057
2984
  * @example
2058
2985
  * ```typescript
2059
- * const result = await sso.organizations.createPublic({
2986
+ * const result = await sso.organizations.create({
2060
2987
  * slug: 'acme-corp',
2061
- * name: 'Acme Corporation',
2062
- * owner_email: 'founder@acme.com'
2988
+ * name: 'Acme Corporation'
2063
2989
  * });
2990
+ * // Store the new tokens with org context
2991
+ * authStore.setTokens(result.access_token, result.refresh_token);
2064
2992
  * ```
2065
2993
  */
2066
- createPublic(payload: CreateOrganizationPayload): Promise<CreateOrganizationResponse>;
2994
+ create(payload: CreateOrganizationPayload): Promise<CreateOrganizationResponse>;
2067
2995
  /**
2068
2996
  * List all organizations the authenticated user is a member of.
2069
2997
  *
@@ -2471,6 +3399,170 @@ declare class OrganizationsModule {
2471
3399
  * ```
2472
3400
  */
2473
3401
  getPublicBranding(orgSlug: string): Promise<BrandingConfiguration>;
3402
+ /**
3403
+ * Risk settings management methods
3404
+ */
3405
+ riskSettings: {
3406
+ /**
3407
+ * Get risk settings for an organization.
3408
+ * Requires 'owner' or 'admin' role.
3409
+ *
3410
+ * @param orgSlug Organization slug
3411
+ * @returns Risk settings configuration
3412
+ *
3413
+ * @example
3414
+ * ```typescript
3415
+ * const settings = await sso.organizations.riskSettings.get('acme-corp');
3416
+ * console.log('Enforcement mode:', settings.enforcement_mode);
3417
+ * console.log('Low threshold:', settings.low_threshold);
3418
+ * ```
3419
+ */
3420
+ get: (orgSlug: string) => Promise<GetRiskSettingsResponse>;
3421
+ /**
3422
+ * Update risk settings for an organization.
3423
+ * Requires 'owner' or 'admin' role.
3424
+ *
3425
+ * @param orgSlug Organization slug
3426
+ * @param payload Risk settings update payload
3427
+ * @returns Updated risk settings
3428
+ *
3429
+ * @example
3430
+ * ```typescript
3431
+ * const result = await sso.organizations.riskSettings.update('acme-corp', {
3432
+ * enforcement_mode: 'challenge',
3433
+ * low_threshold: 30,
3434
+ * medium_threshold: 70,
3435
+ * new_device_score: 20,
3436
+ * impossible_travel_score: 50
3437
+ * });
3438
+ * console.log(result.message);
3439
+ * ```
3440
+ */
3441
+ update: (orgSlug: string, payload: UpdateRiskSettingsRequest) => Promise<UpdateRiskSettingsResponse>;
3442
+ /**
3443
+ * Reset risk settings to default values.
3444
+ * Requires 'owner' or 'admin' role.
3445
+ *
3446
+ * @param orgSlug Organization slug
3447
+ * @returns Reset confirmation with default values
3448
+ *
3449
+ * @example
3450
+ * ```typescript
3451
+ * const result = await sso.organizations.riskSettings.reset('acme-corp');
3452
+ * console.log('Risk settings reset to defaults');
3453
+ * ```
3454
+ */
3455
+ reset: (orgSlug: string) => Promise<UpdateRiskSettingsResponse>;
3456
+ };
3457
+ /**
3458
+ * SIEM (Security Information and Event Management) configuration methods
3459
+ */
3460
+ siem: {
3461
+ /**
3462
+ * Create a new SIEM configuration.
3463
+ * Requires 'owner' or 'admin' role.
3464
+ *
3465
+ * @param orgSlug Organization slug
3466
+ * @param payload SIEM configuration payload
3467
+ * @returns Created SIEM configuration
3468
+ *
3469
+ * @example
3470
+ * ```typescript
3471
+ * const config = await sso.organizations.siem.create('acme-corp', {
3472
+ * name: 'Datadog Integration',
3473
+ * provider_type: 'Datadog',
3474
+ * endpoint_url: 'https://http-intake.logs.datadoghq.com/v1/input',
3475
+ * api_key: 'dd-api-key',
3476
+ * batch_size: 100
3477
+ * });
3478
+ * ```
3479
+ */
3480
+ create: (orgSlug: string, payload: CreateSiemConfigRequest) => Promise<SiemConfigResponse>;
3481
+ /**
3482
+ * List all SIEM configurations for an organization.
3483
+ * Requires 'owner' or 'admin' role.
3484
+ *
3485
+ * @param orgSlug Organization slug
3486
+ * @returns List of SIEM configurations
3487
+ *
3488
+ * @example
3489
+ * ```typescript
3490
+ * const result = await sso.organizations.siem.list('acme-corp');
3491
+ * console.log(`Total SIEM configs: ${result.total}`);
3492
+ * result.siem_configs.forEach(config => {
3493
+ * console.log(config.name, config.provider_type, config.enabled);
3494
+ * });
3495
+ * ```
3496
+ */
3497
+ list: (orgSlug: string) => Promise<ListSiemConfigsResponse>;
3498
+ /**
3499
+ * Get a specific SIEM configuration.
3500
+ * Requires 'owner' or 'admin' role.
3501
+ *
3502
+ * @param orgSlug Organization slug
3503
+ * @param configId SIEM configuration ID
3504
+ * @returns SIEM configuration
3505
+ *
3506
+ * @example
3507
+ * ```typescript
3508
+ * const config = await sso.organizations.siem.get('acme-corp', 'config-id');
3509
+ * console.log(config.name, config.endpoint_url);
3510
+ * ```
3511
+ */
3512
+ get: (orgSlug: string, configId: string) => Promise<SiemConfigResponse>;
3513
+ /**
3514
+ * Update a SIEM configuration.
3515
+ * Requires 'owner' or 'admin' role.
3516
+ *
3517
+ * @param orgSlug Organization slug
3518
+ * @param configId SIEM configuration ID
3519
+ * @param payload Update payload
3520
+ * @returns Updated SIEM configuration
3521
+ *
3522
+ * @example
3523
+ * ```typescript
3524
+ * const updated = await sso.organizations.siem.update('acme-corp', 'config-id', {
3525
+ * enabled: false,
3526
+ * batch_size: 200
3527
+ * });
3528
+ * ```
3529
+ */
3530
+ update: (orgSlug: string, configId: string, payload: UpdateSiemConfigRequest) => Promise<SiemConfigResponse>;
3531
+ /**
3532
+ * Delete a SIEM configuration.
3533
+ * Requires 'owner' or 'admin' role.
3534
+ *
3535
+ * @param orgSlug Organization slug
3536
+ * @param configId SIEM configuration ID
3537
+ *
3538
+ * @example
3539
+ * ```typescript
3540
+ * await sso.organizations.siem.delete('acme-corp', 'config-id');
3541
+ * console.log('SIEM configuration deleted');
3542
+ * ```
3543
+ */
3544
+ delete: (orgSlug: string, configId: string) => Promise<void>;
3545
+ /**
3546
+ * Test connection to a SIEM endpoint.
3547
+ * Sends a test event to verify the configuration.
3548
+ * Requires 'owner' or 'admin' role.
3549
+ *
3550
+ * @param orgSlug Organization slug
3551
+ * @param configId SIEM configuration ID
3552
+ * @returns Test result
3553
+ *
3554
+ * @example
3555
+ * ```typescript
3556
+ * const result = await sso.organizations.siem.test('acme-corp', 'config-id');
3557
+ * if (result.success) {
3558
+ * console.log('Connection successful:', result.message);
3559
+ * } else {
3560
+ * console.error('Connection failed:', result.message);
3561
+ * }
3562
+ * ```
3563
+ */
3564
+ test: (orgSlug: string, configId: string) => Promise<TestConnectionResponse>;
3565
+ };
2474
3566
  }
2475
3567
 
2476
3568
  /**
@@ -2868,23 +3960,52 @@ declare class ServicesModule {
2868
3960
  * Get the SAML SSO endpoint URL for this service.
2869
3961
  * This is where Service Providers should redirect users to initiate SSO.
2870
3962
  *
2871
- * @param baseURL SSO platform base URL
3963
+ * @param baseURL SSO platform base URL
3964
+ * @param orgSlug Organization slug
3965
+ * @param serviceSlug Service slug
3966
+ * @returns SSO endpoint URL
3967
+ *
3968
+ * @example
3969
+ * ```typescript
3970
+ * const ssoUrl = sso.services.saml.getSsoUrl(
3971
+ * 'https://sso.example.com',
3972
+ * 'acme-corp',
3973
+ * 'main-app'
3974
+ * );
3975
+ * console.log('SSO endpoint:', ssoUrl);
3976
+ * // https://sso.example.com/saml/acme-corp/main-app/sso
3977
+ * ```
3978
+ */
3979
+ getSsoUrl: (baseURL: string, orgSlug: string, serviceSlug: string) => string;
3980
+ };
3981
+ /**
3982
+ * Stripe billing and checkout methods
3983
+ */
3984
+ billing: {
3985
+ /**
3986
+ * Create a Stripe checkout session for the authenticated user to subscribe to a plan.
3987
+ * Requires organization membership.
3988
+ *
3989
+ * IMPORTANT: The plan must have a `stripe_price_id` configured to be available for purchase.
3990
+ *
2872
3991
  * @param orgSlug Organization slug
2873
3992
  * @param serviceSlug Service slug
2874
- * @returns SSO endpoint URL
3993
+ * @param payload Checkout payload containing plan_id and redirect URLs
3994
+ * @returns Checkout session with URL to redirect user to
2875
3995
  *
2876
3996
  * @example
2877
3997
  * ```typescript
2878
- * const ssoUrl = sso.services.saml.getSsoUrl(
2879
- * 'https://sso.example.com',
2880
- * 'acme-corp',
2881
- * 'main-app'
2882
- * );
2883
- * console.log('SSO endpoint:', ssoUrl);
2884
- * // https://sso.example.com/saml/acme-corp/main-app/sso
3998
+ * const checkout = await sso.services.billing.createCheckout('acme-corp', 'main-app', {
3999
+ * plan_id: 'plan_pro',
4000
+ * success_url: 'https://app.acme.com/billing/success?session_id={CHECKOUT_SESSION_ID}',
4001
+ * cancel_url: 'https://app.acme.com/billing/cancel'
4002
+ * });
4003
+ *
4004
+ * // Redirect user to Stripe checkout
4005
+ * window.location.href = checkout.checkout_url;
2885
4006
  * ```
2886
4007
  */
2887
- getSsoUrl: (baseURL: string, orgSlug: string, serviceSlug: string) => string;
4008
+ createCheckout: (orgSlug: string, serviceSlug: string, payload: CreateCheckoutPayload) => Promise<CreateCheckoutResponse>;
2888
4009
  };
2889
4010
  }
2890
4011
 
@@ -3302,6 +4423,38 @@ declare class PlatformModule {
3302
4423
  */
3303
4424
  getRecentOrganizations: (params?: GetAuditLogParams) => Promise<RecentOrganization[]>;
3304
4425
  };
4426
+ /**
4427
+ * Impersonate a user (Platform Owner or Org Admin only).
4428
+ * Returns a short-lived JWT (15 minutes) that allows acting as the target user.
4429
+ *
4430
+ * Security:
4431
+ * - Platform Owners can impersonate any user
4432
+ * - Organization Admins can only impersonate users within their organization
4433
+ * - All impersonation actions are logged to the platform audit log with HIGH severity
4434
+ * - Tokens contain RFC 8693 actor claim for full audit trail
4435
+ *
4436
+ * @param payload Impersonation details (user_id and reason)
4437
+ * @returns Impersonation token and user context
4438
+ *
4439
+ * @example
4440
+ * ```typescript
4441
+ * const result = await sso.platform.impersonateUser({
4442
+ * user_id: 'user-uuid-123',
4443
+ * reason: 'Investigating support ticket #456'
4444
+ * });
4445
+ *
4446
+ * // Use the returned token to create a new client acting as the user
4447
+ * const userClient = new SsoClient({
4448
+ * baseURL: 'https://sso.example.com',
4449
+ * token: result.token
4450
+ * });
4451
+ *
4452
+ * // Now all requests with userClient are made as the target user
4453
+ * const profile = await userClient.user.getProfile();
4454
+ * console.log('Acting as:', result.target_user.email);
4455
+ * ```
4456
+ */
4457
+ impersonateUser(payload: ImpersonateRequest): Promise<ImpersonateResponse>;
3305
4458
  }
3306
4459
 
3307
4460
  /**
@@ -3453,6 +4606,435 @@ declare class ServiceApiModule {
3453
4606
  deleteSubscription(userId: string): Promise<void>;
3454
4607
  }
3455
4608
 
4609
+ /**
4610
+ * Permission checking and management methods
4611
+ *
4612
+ * This module provides utilities for working with ReBAC (Relationship-Based Access Control)
4613
+ * permissions. Permissions use Zanzibar-style relation tuples and are now fetched from the
4614
+ * API instead of being embedded in JWT tokens (for improved security and smaller token size).
4615
+ */
4616
+ declare class PermissionsModule {
4617
+ private http;
4618
+ constructor(http: HttpClient);
4619
+ /**
4620
+ * Check if user has a specific permission.
4621
+ * Fetches from user profile API (which uses cached permissions).
4622
+ *
4623
+ * @param permission Permission in format "namespace:object_id#relation"
4624
+ * @returns true if the permission is present
4625
+ *
4626
+ * @example
4627
+ * ```typescript
4628
+ * const hasAccess = await sso.permissions.hasPermission('organization:acme#owner');
4629
+ * ```
4630
+ */
4631
+ hasPermission(permission: string): Promise<boolean>;
4632
+ /**
4633
+ * Get all user permissions.
4634
+ * Fetches from user profile API (which uses cached permissions).
4635
+ *
4636
+ * @returns Array of permission strings
4637
+ *
4638
+ * @example
4639
+ * ```typescript
4640
+ * const permissions = await sso.permissions.listPermissions();
4641
+ * // ["organization:acme#owner", "service:api#admin"]
4642
+ * ```
4643
+ */
4644
+ listPermissions(): Promise<string[]>;
4645
+ /**
4646
+ * Check if user has access to a feature.
4647
+ *
4648
+ * @param feature Feature name to check
4649
+ * @returns true if the feature is available
4650
+ *
4651
+ * @example
4652
+ * ```typescript
4653
+ * const canExport = await sso.permissions.hasFeature('advanced-export');
4654
+ * ```
4655
+ */
4656
+ hasFeature(feature: string): Promise<boolean>;
4657
+ /**
4658
+ * Get current plan name.
4659
+ *
4660
+ * @returns Current plan name or null if not in org/service context
4661
+ *
4662
+ * @example
4663
+ * ```typescript
4664
+ * const plan = await sso.permissions.getPlan();
4665
+ * console.log(plan); // "pro", "enterprise", etc.
4666
+ * ```
4667
+ */
4668
+ getPlan(): Promise<string | null>;
4669
+ /**
4670
+ * Check if user has a specific permission on a resource.
4671
+ *
4672
+ * @param namespace The permission namespace (e.g., "organization", "service")
4673
+ * @param objectId The object ID (e.g., organization slug, service slug)
4674
+ * @param relation The relation type (e.g., "owner", "admin", "member")
4675
+ * @returns true if the user has the permission
4676
+ *
4677
+ * @example
4678
+ * ```typescript
4679
+ * const isOwner = await sso.permissions.can('organization', 'acme-corp', 'owner');
4680
+ * ```
4681
+ */
4682
+ can(namespace: string, objectId: string, relation: string): Promise<boolean>;
4683
+ /**
4684
+ * Check if user is a member of an organization.
4685
+ *
4686
+ * @param orgId The organization ID or slug
4687
+ * @returns true if the user is a member
4688
+ *
4689
+ * @example
4690
+ * ```typescript
4691
+ * if (await sso.permissions.isOrgMember('acme-corp')) {
4692
+ * // User is a member
4693
+ * }
4694
+ * ```
4695
+ */
4696
+ isOrgMember(orgId: string): Promise<boolean>;
4697
+ /**
4698
+ * Check if user is an admin of an organization.
4699
+ *
4700
+ * @param orgId The organization ID or slug
4701
+ * @returns true if the user is an admin
4702
+ *
4703
+ * @example
4704
+ * ```typescript
4705
+ * if (await sso.permissions.isOrgAdmin('acme-corp')) {
4706
+ * // User is an admin
4707
+ * }
4708
+ * ```
4709
+ */
4710
+ isOrgAdmin(orgId: string): Promise<boolean>;
4711
+ /**
4712
+ * Check if user is an owner of an organization.
4713
+ *
4714
+ * @param orgId The organization ID or slug
4715
+ * @returns true if the user is an owner
4716
+ *
4717
+ * @example
4718
+ * ```typescript
4719
+ * if (await sso.permissions.isOrgOwner('acme-corp')) {
4720
+ * // User is an owner
4721
+ * }
4722
+ * ```
4723
+ */
4724
+ isOrgOwner(orgId: string): Promise<boolean>;
4725
+ /**
4726
+ * Check if user has access to a service.
4727
+ *
4728
+ * @param serviceId The service ID or slug
4729
+ * @returns true if the user has access
4730
+ *
4731
+ * @example
4732
+ * ```typescript
4733
+ * if (await sso.permissions.hasServiceAccess('api-service')) {
4734
+ * // User has access to the service
4735
+ * }
4736
+ * ```
4737
+ */
4738
+ hasServiceAccess(serviceId: string): Promise<boolean>;
4739
+ /**
4740
+ * Filter permissions by namespace.
4741
+ *
4742
+ * @param namespace The namespace to filter by (e.g., "organization", "service")
4743
+ * @returns Array of permissions matching the namespace
4744
+ *
4745
+ * @example
4746
+ * ```typescript
4747
+ * const orgPermissions = await sso.permissions.getPermissionsByNamespace('organization');
4748
+ * ```
4749
+ */
4750
+ getPermissionsByNamespace(namespace: string): Promise<string[]>;
4751
+ /**
4752
+ * @deprecated Use `hasPermission()` instead (without token parameter)
4753
+ * Decode a JWT token to extract claims (including permissions)
4754
+ * Note: This does NOT verify the signature - it only decodes the payload
4755
+ *
4756
+ * @param token The JWT access token
4757
+ * @returns The decoded JWT claims
4758
+ * @throws Error if the token is malformed
4759
+ */
4760
+ decodeToken(token: string): JwtClaims;
4761
+ /**
4762
+ * @deprecated JWT tokens no longer contain permissions. Use `hasPermission(permission)` instead.
4763
+ * Check if a JWT token contains a specific permission
4764
+ *
4765
+ * @param token The JWT access token (ignored)
4766
+ * @param permission Permission in format "namespace:object_id#relation"
4767
+ * @returns true if the permission is present in the token
4768
+ */
4769
+ hasPermissionFromToken(token: string, permission: string): boolean;
4770
+ /**
4771
+ * @deprecated JWT tokens no longer contain permissions. Use `can(namespace, objectId, relation)` instead.
4772
+ * Check if a user has a specific permission on a resource
4773
+ *
4774
+ * @param token The JWT access token (ignored)
4775
+ * @param namespace The permission namespace (e.g., "organization", "service")
4776
+ * @param objectId The object ID (e.g., organization slug, service slug)
4777
+ * @param relation The relation type (e.g., "owner", "admin", "member")
4778
+ * @returns true if the user has the permission
4779
+ */
4780
+ canFromToken(token: string, namespace: string, objectId: string, relation: string): boolean;
4781
+ /**
4782
+ * @deprecated JWT tokens no longer contain permissions. Use `isOrgMember(orgId)` instead.
4783
+ * Check if user is a member of an organization
4784
+ *
4785
+ * @param token The JWT access token (ignored)
4786
+ * @param orgId The organization ID or slug
4787
+ * @returns true if the user is a member
4788
+ */
4789
+ isOrgMemberFromToken(token: string, orgId: string): boolean;
4790
+ /**
4791
+ * @deprecated JWT tokens no longer contain permissions. Use `isOrgAdmin(orgId)` instead.
4792
+ * Check if user is an admin of an organization
4793
+ *
4794
+ * @param token The JWT access token (ignored)
4795
+ * @param orgId The organization ID or slug
4796
+ * @returns true if the user is an admin
4797
+ */
4798
+ isOrgAdminFromToken(token: string, orgId: string): boolean;
4799
+ /**
4800
+ * @deprecated JWT tokens no longer contain permissions. Use `isOrgOwner(orgId)` instead.
4801
+ * Check if user is an owner of an organization
4802
+ *
4803
+ * @param token The JWT access token (ignored)
4804
+ * @param orgId The organization ID or slug
4805
+ * @returns true if the user is an owner
4806
+ */
4807
+ isOrgOwnerFromToken(token: string, orgId: string): boolean;
4808
+ /**
4809
+ * @deprecated JWT tokens no longer contain permissions. Use `hasServiceAccess(serviceId)` instead.
4810
+ * Check if user has access to a service
4811
+ *
4812
+ * @param token The JWT access token (ignored)
4813
+ * @param serviceId The service ID or slug
4814
+ * @returns true if the user has access
4815
+ */
4816
+ hasServiceAccessFromToken(token: string, serviceId: string): boolean;
4817
+ /**
4818
+ * @deprecated JWT tokens no longer contain permissions. Use `listPermissions()` instead.
4819
+ * Get all permissions from a JWT token
4820
+ *
4821
+ * @param token The JWT access token
4822
+ * @returns Array of permission strings, or empty array if none
4823
+ */
4824
+ getAllPermissionsFromToken(token: string): string[];
4825
+ /**
4826
+ * Parse a permission string into its components
4827
+ *
4828
+ * @param permission Permission string in format "namespace:object_id#relation"
4829
+ * @returns Parsed permission components or null if invalid format
4830
+ *
4831
+ * @example
4832
+ * ```typescript
4833
+ * const parsed = sso.permissions.parsePermission('organization:acme#owner');
4834
+ * // { namespace: 'organization', objectId: 'acme', relation: 'owner' }
4835
+ * ```
4836
+ */
4837
+ parsePermission(permission: string): {
4838
+ namespace: string;
4839
+ objectId: string;
4840
+ relation: string;
4841
+ } | null;
4842
+ /**
4843
+ * @deprecated JWT tokens no longer contain permissions. Use `getPermissionsByNamespace(namespace)` instead.
4844
+ * Filter permissions by namespace
4845
+ *
4846
+ * @param token The JWT access token (ignored)
4847
+ * @param namespace The namespace to filter by (e.g., "organization", "service")
4848
+ * @returns Array of permissions matching the namespace
4849
+ */
4850
+ getPermissionsByNamespaceFromToken(token: string, namespace: string): string[];
4851
+ }
4852
+
4853
+ /**
4854
+ * WebAuthn/Passkey authentication module
4855
+ *
4856
+ * Provides methods for registering and authenticating with FIDO2 passkeys.
4857
+ * Requires a browser environment with WebAuthn support.
4858
+ *
4859
+ * @example
4860
+ * ```typescript
4861
+ * // Register a new passkey (requires authenticated session)
4862
+ * await sso.passkeys.register();
4863
+ *
4864
+ * // Login with passkey
4865
+ * const { token } = await sso.passkeys.login('user@example.com');
4866
+ * sso.setToken(token);
4867
+ * ```
4868
+ */
4869
+ declare class PasskeysModule {
4870
+ private http;
4871
+ constructor(http: HttpClient);
4872
+ /**
4873
+ * Check if WebAuthn is supported in the current browser
4874
+ */
4875
+ isSupported(): boolean;
4876
+ /**
4877
+ * Check if platform authenticator (like Touch ID, Face ID, Windows Hello) is available
4878
+ */
4879
+ isPlatformAuthenticatorAvailable(): Promise<boolean>;
4880
+ /**
4881
+ * Register a new passkey for the authenticated user
4882
+ *
4883
+ * This method requires an authenticated session (JWT token must be set).
4884
+ * It starts the WebAuthn registration ceremony, prompts the user to create
4885
+ * a passkey using their device's authenticator (e.g., Touch ID, Face ID,
4886
+ * Windows Hello, or hardware security key), and stores the credential.
4887
+ *
4888
+ * @param displayName Optional display name for the passkey
4889
+ * @returns Promise resolving to the registered passkey ID
4890
+ * @throws {Error} If WebAuthn is not supported or registration fails
4891
+ *
4892
+ * @example
4893
+ * ```typescript
4894
+ * try {
4895
+ * const passkeyId = await sso.passkeys.register('My MacBook Pro');
4896
+ * console.log('Passkey registered:', passkeyId);
4897
+ * } catch (error) {
4898
+ * console.error('Passkey registration failed:', error);
4899
+ * }
4900
+ * ```
4901
+ */
4902
+ register(displayName?: string): Promise<string>;
4903
+ /**
4904
+ * Authenticate with a passkey and obtain a JWT token
4905
+ *
4906
+ * This method prompts the user to authenticate using their passkey.
4907
+ * Upon successful authentication, a JWT token is returned which can
4908
+ * be used to make authenticated API requests.
4909
+ *
4910
+ * @param email User's email address
4911
+ * @returns Promise resolving to authentication response with JWT token
4912
+ * @throws {Error} If WebAuthn is not supported or authentication fails
4913
+ *
4914
+ * @example
4915
+ * ```typescript
4916
+ * try {
4917
+ * const { token, user_id } = await sso.passkeys.login('user@example.com');
4918
+ * sso.setToken(token);
4919
+ * console.log('Logged in as:', user_id);
4920
+ * } catch (error) {
4921
+ * console.error('Passkey login failed:', error);
4922
+ * }
4923
+ * ```
4924
+ */
4925
+ login(email: string): Promise<PasskeyAuthFinishResponse>;
4926
+ /**
4927
+ * Convert Base64URL string to Uint8Array
4928
+ */
4929
+ private base64UrlToUint8Array;
4930
+ /**
4931
+ * Convert Uint8Array to Base64URL string
4932
+ */
4933
+ private uint8ArrayToBase64Url;
4934
+ }
4935
+
4936
+ /**
4937
+ * Magic link request payload
4938
+ */
4939
+ interface MagicLinkRequest {
4940
+ /** Email address to send the magic link to */
4941
+ email: string;
4942
+ /** Optional organization context */
4943
+ orgSlug?: string;
4944
+ }
4945
+ /**
4946
+ * Magic link response
4947
+ */
4948
+ interface MagicLinkResponse {
4949
+ /** Success message */
4950
+ message: string;
4951
+ }
4952
+ /**
4953
+ * Magic links module for passwordless authentication
4954
+ */
4955
+ declare class MagicLinks {
4956
+ private http;
4957
+ constructor(http: HttpClient);
4958
+ /**
4959
+ * Request a magic link to be sent to the user's email
4960
+ *
4961
+ * @param data Magic link request data
4962
+ * @returns Promise resolving to magic link response
4963
+ */
4964
+ request(data: MagicLinkRequest): Promise<MagicLinkResponse>;
4965
+ /**
4966
+ * Verify a magic link token and complete authentication
4967
+ * Note: This is typically handled by redirecting to the magic link URL
4968
+ * The backend will handle verification and either redirect or return tokens
4969
+ *
4970
+ * @param token The magic link token to verify
4971
+ * @param redirectUri Optional where to redirect after success
4972
+ * @returns URL to redirect to for verification
4973
+ */
4974
+ getVerificationUrl(token: string, redirectUri?: string): string;
4975
+ /**
4976
+ * Verify a magic link token via API call
4977
+ * This is an alternative to redirect-based verification
4978
+ *
4979
+ * @param token The magic link token
4980
+ * @param redirectUri Optional redirect URI
4981
+ * @returns Promise resolving to authentication response
4982
+ */
4983
+ verify(token: string, redirectUri?: string): Promise<any>;
4984
+ /**
4985
+ * Construct the complete magic link URL that would be sent via email
4986
+ *
4987
+ * @param token The magic link token
4988
+ * @param redirectUri Optional redirect URI
4989
+ * @returns Complete magic link URL
4990
+ */
4991
+ constructMagicLink(token: string, redirectUri?: string): string;
4992
+ }
4993
+
4994
+ /**
4995
+ * Privacy and GDPR compliance methods
4996
+ */
4997
+ declare class PrivacyModule {
4998
+ private http;
4999
+ constructor(http: HttpClient);
5000
+ /**
5001
+ * Export all user data (GDPR Right to Access).
5002
+ * Users can export their own data, or organization owners can export their members' data.
5003
+ *
5004
+ * @param userId User ID to export data for
5005
+ * @returns Complete user data export including memberships, login events, identities, MFA events, and passkeys
5006
+ *
5007
+ * @example
5008
+ * ```typescript
5009
+ * const userData = await sso.privacy.exportData('user-id');
5010
+ * console.log(`Exported ${userData.login_events_count} login events`);
5011
+ * console.log(`User has ${userData.memberships.length} organization memberships`);
5012
+ * ```
5013
+ */
5014
+ exportData(userId: string): Promise<ExportUserDataResponse>;
5015
+ /**
5016
+ * Anonymize user data (GDPR Right to be Forgotten).
5017
+ * Requires organization owner permission for all organizations the user is a member of.
5018
+ * Platform owners cannot be anonymized.
5019
+ *
5020
+ * This operation:
5021
+ * - Soft-deletes the user account
5022
+ * - Hard-deletes PII from identities and passkeys tables
5023
+ * - Preserves audit logs for compliance
5024
+ *
5025
+ * @param userId User ID to anonymize
5026
+ * @returns Anonymization confirmation response
5027
+ *
5028
+ * @example
5029
+ * ```typescript
5030
+ * const result = await sso.privacy.forgetUser('user-id');
5031
+ * console.log(result.message);
5032
+ * // "User data has been anonymized. PII has been removed while preserving audit logs."
5033
+ * ```
5034
+ */
5035
+ forgetUser(userId: string): Promise<ForgetUserResponse>;
5036
+ }
5037
+
3456
5038
  /**
3457
5039
  * Configuration options for the SSO client
3458
5040
  */
@@ -3469,6 +5051,15 @@ interface SsoClientOptions {
3469
5051
  * Optional API key for service-to-service authentication
3470
5052
  */
3471
5053
  apiKey?: string;
5054
+ /**
5055
+ * Custom storage provider (optional).
5056
+ * Defaults to localStorage in browser, Memory in Node.
5057
+ */
5058
+ storage?: TokenStorage;
5059
+ /**
5060
+ * Prefix for storage keys. Default: 'sso_'
5061
+ */
5062
+ storagePrefix?: string;
3472
5063
  }
3473
5064
  /**
3474
5065
  * Main SSO client class.
@@ -3488,6 +5079,7 @@ interface SsoClientOptions {
3488
5079
  */
3489
5080
  declare class SsoClient {
3490
5081
  private http;
5082
+ private session;
3491
5083
  /**
3492
5084
  * Analytics and login tracking methods
3493
5085
  */
@@ -3520,6 +5112,22 @@ declare class SsoClient {
3520
5112
  * Service API methods (requires API key authentication)
3521
5113
  */
3522
5114
  readonly serviceApi: ServiceApiModule;
5115
+ /**
5116
+ * Permission checking and management methods
5117
+ */
5118
+ readonly permissions: PermissionsModule;
5119
+ /**
5120
+ * WebAuthn/Passkey authentication methods
5121
+ */
5122
+ readonly passkeys: PasskeysModule;
5123
+ /**
5124
+ * Magic link authentication methods
5125
+ */
5126
+ readonly magicLinks: MagicLinks;
5127
+ /**
5128
+ * Privacy and GDPR compliance methods
5129
+ */
5130
+ readonly privacy: PrivacyModule;
3523
5131
  constructor(options: SsoClientOptions);
3524
5132
  /**
3525
5133
  * Sets the JWT for all subsequent authenticated requests.
@@ -3557,6 +5165,34 @@ declare class SsoClient {
3557
5165
  * Gets the current base URL
3558
5166
  */
3559
5167
  getBaseURL(): string;
5168
+ /**
5169
+ * Check if the user is currently authenticated
5170
+ */
5171
+ isAuthenticated(): boolean;
5172
+ /**
5173
+ * Subscribe to authentication state changes.
5174
+ * Useful for updating UI when login/logout/expiration occurs.
5175
+ *
5176
+ * @param listener Callback function that receives the authentication state
5177
+ * @returns Unsubscribe function
5178
+ *
5179
+ * @example
5180
+ * ```typescript
5181
+ * const unsubscribe = sso.onAuthStateChange((isAuth) => {
5182
+ * console.log(isAuth ? 'User is logged in' : 'User is logged out');
5183
+ * });
5184
+ *
5185
+ * // Later, to stop listening
5186
+ * unsubscribe();
5187
+ * ```
5188
+ */
5189
+ onAuthStateChange(listener: (isAuthenticated: boolean) => void): () => void;
5190
+ /**
5191
+ * Manually retrieve the current access token
5192
+ *
5193
+ * @returns The current access token, or null if not authenticated
5194
+ */
5195
+ getToken(): Promise<string | null>;
3560
5196
  }
3561
5197
 
3562
5198
  /**
@@ -3595,4 +5231,4 @@ declare class SsoApiError extends Error {
3595
5231
  isNotFound(): boolean;
3596
5232
  }
3597
5233
 
3598
- export { type AcceptInvitationPayload, type AdminLoginUrlParams, type AnalyticsQuery, type ApiKey, type ApiKeyCreateResponse, type ApproveOrganizationPayload, type AuditLog, type AuditLogEntry, type AuditLogQueryParams, type AuditLogResponse, AuthModule, type BackupCodesResponse, type BrandingConfiguration, type ChangePasswordRequest, type ChangePasswordResponse, type ConfigureSamlPayload, type ConfigureSamlResponse, type CreateApiKeyPayload, type CreateInvitationPayload, type CreateOrganizationPayload, type CreateOrganizationResponse, type CreatePlanPayload, type CreateServicePayload, type CreateServiceResponse, type CreateWebhookRequest, type DeclineInvitationPayload, type DeviceCodeRequest, type DeviceCodeResponse, type DeviceVerifyResponse, type DomainConfiguration, type DomainVerificationMethod, type DomainVerificationResponse, type DomainVerificationResult, type EndUser, type EndUserDetailResponse, type EndUserIdentity, type EndUserListResponse, type EndUserSubscription, type EventTypeInfo, type ForgotPasswordRequest, type ForgotPasswordResponse, type GetAuditLogParams, type GrowthTrendPoint, type Identity, type Invitation, type InvitationStatus, type InvitationWithOrg, InvitationsModule, type JwtClaims, type ListApiKeysResponse, type ListEndUsersParams, type ListOrganizationsParams, type ListPlatformOrganizationsParams, type LoginActivityPoint, type LoginRequest, type LoginTrendPoint, type LoginUrlParams, type LoginsByProvider, type LoginsByService, type MemberListResponse, type MemberRole, type Membership, type MfaSetupResponse, type MfaStatusResponse, type MfaVerificationRequest, type MfaVerificationResponse, type MfaVerifyRequest, type MfaVerifyResponse, type OAuthCredentials, type OAuthProvider, type Organization, type OrganizationMember, type OrganizationResponse, type OrganizationStatus, type OrganizationStatusBreakdown, type OrganizationTier, OrganizationsModule, type PaginatedResponse, type PaginationInfo, type PaginationParams, type Plan, type PlanResponse, type PlatformAnalyticsDateRangeParams, PlatformModule, type PlatformOrganizationResponse, type PlatformOrganizationsListResponse, type PlatformOverviewMetrics, type PromotePlatformOwnerPayload, type ProviderToken, type ProviderTokenGrant, type RecentLogin, type RecentOrganization, type RefreshTokenRequest, type RefreshTokenResponse, type RegisterRequest, type RegisterResponse, type RejectOrganizationPayload, type ResetPasswordRequest, type ResetPasswordResponse, type RevokeSessionsResponse, type SamlCertificate, type SamlConfig, type Service, ServiceApiModule, type ServiceListResponse, type ServiceResponse, type ServiceType, type ServiceWithDetails, ServicesModule, type SetCustomDomainRequest, type SetOAuthCredentialsPayload, type SetPasswordRequest, type SetPasswordResponse, type SetSmtpRequest, type SmtpConfigResponse, SsoApiError, SsoClient, type SsoClientOptions, type StartLinkResponse, type Subscription, type TokenRequest, type TokenResponse, type TopOrganization, type TransferOwnershipPayload, type UpdateBrandingRequest, type UpdateMemberRolePayload, type UpdateOrganizationPayload, type UpdateOrganizationTierPayload, type UpdatePlanPayload, type UpdateServicePayload, type UpdateUserProfilePayload, type UpdateWebhookRequest, type User, UserModule, type UserProfile, type Webhook, type WebhookDelivery, type WebhookDeliveryListResponse, type WebhookDeliveryQueryParams, type WebhookListResponse, type WebhookResponse };
5234
+ export { type AcceptInvitationPayload, type AdminLoginUrlParams, type AnalyticsQuery, type ApiKey, type ApiKeyCreateResponse, type ApproveOrganizationPayload, type AuditLog, type AuditLogEntry, type AuditLogQueryParams, type AuditLogResponse, AuthMethod, AuthModule, type AuthenticationResponseJSON, type BackupCodesResponse, type BrandingConfiguration, BrowserStorage, type ChangePasswordRequest, type ChangePasswordResponse, type ConfigureSamlPayload, type ConfigureSamlResponse, type CreateApiKeyPayload, type CreateCheckoutPayload, type CreateCheckoutResponse, type CreateInvitationPayload, type CreateOrganizationPayload, type CreateOrganizationResponse, type CreatePlanPayload, type CreateServicePayload, type CreateServiceResponse, type CreateSiemConfigRequest, type CreateWebhookRequest, type DeclineInvitationPayload, type DeviceCodeRequest, type DeviceCodeResponse, type DeviceTrust, type DeviceVerifyResponse, type DomainConfiguration, type DomainVerificationMethod, type DomainVerificationResponse, type DomainVerificationResult, type EndUser, type EndUserDetailResponse, type EndUserIdentity, type EndUserListResponse, type EndUserSubscription, type EventTypeInfo, type ExportUserDataResponse, type ForgetUserResponse, type ForgotPasswordRequest, type ForgotPasswordResponse, type GeolocationData, type GetAuditLogParams, type GetRiskSettingsResponse, type GrowthTrendPoint, type Identity, type ImpersonateRequest, type ImpersonateResponse, type ImpersonationUserInfo, type Invitation, type InvitationStatus, type InvitationWithOrg, InvitationsModule, type JwtClaims, type ListApiKeysResponse, type ListDevicesResponse, type ListEndUsersParams, type ListOrganizationsParams, type ListPlatformOrganizationsParams, type ListSiemConfigsResponse, type LoginActivityPoint, type LoginEventExport, type LoginRequest, type LoginTrendPoint, type LoginUrlParams, type LoginsByProvider, type LoginsByService, type LookupEmailRequest, type LookupEmailResponse, MagicLinks, type MemberListResponse, type MemberRole, type Membership, type MembershipExport, MemoryStorage, type MfaEventExport, type MfaSetupResponse, type MfaStatusResponse, type MfaVerificationRequest, type MfaVerificationResponse, type MfaVerifyRequest, type MfaVerifyResponse, type OAuthCredentials, type OAuthIdentityExport, type OAuthProvider, type Organization, type OrganizationMember, type OrganizationResponse, type OrganizationStatus, type OrganizationStatusBreakdown, type OrganizationTier, OrganizationsModule, type PaginatedResponse, type PaginationInfo, type PaginationParams, type Passkey, type PasskeyAuthFinishRequest, type PasskeyAuthFinishResponse, type PasskeyAuthStartRequest, type PasskeyAuthStartResponse, type PasskeyExport, type PasskeyRegisterFinishRequest, type PasskeyRegisterFinishResponse, type PasskeyRegisterStartRequest, type PasskeyRegisterStartResponse, PasskeysModule, PermissionsModule, type Plan, type PlanResponse, type PlatformAnalyticsDateRangeParams, PlatformModule, type PlatformOrganizationResponse, type PlatformOrganizationsListResponse, type PlatformOverviewMetrics, type PromotePlatformOwnerPayload, type ProviderToken, type ProviderTokenGrant, type RecentLogin, type RecentOrganization, type RefreshTokenRequest, type RefreshTokenResponse, type RegisterRequest, type RegisterResponse, type RegistrationResponseJSON, type RejectOrganizationPayload, type ResetPasswordRequest, type ResetPasswordResponse, type RevokeDeviceRequest, type RevokeDeviceResponse, type RevokeSessionsResponse, RiskAction, type RiskAnalytics, type RiskAssessment, type RiskContext, type RiskEngineConfig, type RiskEvent, RiskEventOutcome, type RiskFactor, RiskFactorType, type RiskRule, type RiskRuleCondition, type RiskScore, type SamlCertificate, type SamlConfig, type Service, ServiceApiModule, type ServiceListResponse, type ServiceResponse, type ServiceType, type ServiceWithDetails, ServicesModule, type SetCustomDomainRequest, type SetOAuthCredentialsPayload, type SetPasswordRequest, type SetPasswordResponse, type SetSmtpRequest, type SiemConfigResponse, type SiemProviderType, type SmtpConfigResponse, SsoApiError, SsoClient, type SsoClientOptions, type StartLinkResponse, type Subscription, type TestConnectionResponse, type TokenRequest, type TokenResponse, type TokenStorage, type TopOrganization, type TransferOwnershipPayload, type UpdateBrandingRequest, type UpdateMemberRolePayload, type UpdateOrganizationPayload, type UpdateOrganizationTierPayload, type UpdatePlanPayload, type UpdateRiskSettingsRequest, type UpdateRiskSettingsResponse, type UpdateServicePayload, type UpdateSiemConfigRequest, type UpdateUserProfilePayload, type UpdateWebhookRequest, type User, type UserDevice, UserModule, type UserProfile, type Webhook, type WebhookDelivery, type WebhookDeliveryListResponse, type WebhookDeliveryQueryParams, type WebhookListResponse, type WebhookResponse };