@nauth-toolkit/client 0.5.0 → 0.6.1

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.cjs CHANGED
@@ -174,22 +174,32 @@ var defaultEndpoints = {
174
174
  mfaVerifySetup: "/mfa/verify-setup",
175
175
  mfaPreferred: "/mfa/devices/:deviceId/preferred",
176
176
  mfaBackupCodes: "/mfa/backup-codes/generate",
177
+ mfaAvailableMethods: "/mfa/available-methods",
177
178
  socialLinked: "/social/linked",
178
179
  socialLink: "/social/link",
179
180
  socialUnlink: "/social/unlink",
180
181
  socialVerify: "/social/:provider/verify",
181
182
  socialRedirectStart: "/social/:provider/redirect",
182
183
  socialExchange: "/social/exchange",
184
+ socialCanSetPassword: "/social/can-set-password",
185
+ socialSetPassword: "/social/set-password",
183
186
  trustDevice: "/trust-device",
184
187
  isTrustedDevice: "/is-trusted-device",
185
188
  auditHistory: "/audit/history",
186
- updateProfile: "/profile"
189
+ updateProfile: "/profile",
190
+ sessions: "/sessions",
191
+ logoutSession: "/sessions/:sessionId",
192
+ trustedDevices: "/trusted-devices",
193
+ trustedDevice: "/trusted-devices/:deviceId"
187
194
  };
188
195
  var defaultAdminEndpoints = {
189
196
  signup: "/signup",
190
197
  signupSocial: "/signup-social",
191
198
  getUsers: "/users",
192
199
  getUser: "/users/:sub",
200
+ getUserByEmail: "/users/by-email",
201
+ updateUser: "/users/:sub",
202
+ updateVerifiedStatus: "/users/:sub/verified-status",
193
203
  deleteUser: "/users/:sub",
194
204
  disableUser: "/users/:sub/disable",
195
205
  enableUser: "/users/:sub/enable",
@@ -197,13 +207,22 @@ var defaultAdminEndpoints = {
197
207
  setPassword: "/set-password",
198
208
  resetPasswordInitiate: "/reset-password/initiate",
199
209
  getUserSessions: "/users/:sub/sessions",
210
+ revokeUserSession: "/users/:sub/sessions/:sessionId",
211
+ trustedDevices: "/users/:sub/trusted-devices",
212
+ trustedDevice: "/users/:sub/trusted-devices/:deviceId",
200
213
  logoutAll: "/users/:sub/logout-all",
201
214
  getMfaStatus: "/users/:sub/mfa/status",
202
215
  getMfaDevices: "/users/:sub/mfa/devices",
203
216
  removeMfaDeviceById: "/mfa/devices/:deviceId",
204
217
  setPreferredMfaDevice: "/users/:sub/mfa/devices/:deviceId/preferred",
205
218
  setMfaExemption: "/mfa/exemption",
206
- getAuditHistory: "/audit/history"
219
+ getAuditHistory: "/audit/history",
220
+ getEventsByType: "/audit/events",
221
+ getSuspiciousActivity: "/audit/suspicious",
222
+ getRiskAssessmentHistory: "/audit/risk",
223
+ apiKeys: "/api-keys",
224
+ apiKey: "/api-keys/:keyId",
225
+ apiKeyRevoke: "/api-keys/:keyId/revoke"
207
226
  };
208
227
  var resolveConfig = (config, defaultAdapter) => {
209
228
  const resolvedEndpoints = {
@@ -1256,6 +1275,193 @@ var AdminOperations = class {
1256
1275
  const queryString = this.buildQueryString(params);
1257
1276
  return this.get(`${path}${queryString}`);
1258
1277
  }
1278
+ /**
1279
+ * Resolve a user by email address.
1280
+ *
1281
+ * Email is not necessarily a stable identifier - an account's address can be changed,
1282
+ * and with `requireEmailVerified` unset an unverified address matches too - so prefer
1283
+ * `sub` wherever the caller already holds one.
1284
+ *
1285
+ * @param params - Email to look up, and whether to require a verified address
1286
+ * @returns The matching user
1287
+ */
1288
+ async getUserByEmail(params) {
1289
+ const path = this.buildAdminUrl(this.adminEndpoints.getUserByEmail);
1290
+ const queryString = this.buildQueryString(params);
1291
+ return this.get(`${path}${queryString}`);
1292
+ }
1293
+ /**
1294
+ * Update a user's profile attributes.
1295
+ *
1296
+ * @param sub - Target user's external identifier
1297
+ * @param attributes - Attributes to change; omitted fields are left as they are
1298
+ * @returns The updated user
1299
+ */
1300
+ async updateUser(sub, attributes) {
1301
+ const path = this.buildAdminUrl(this.adminEndpoints.updateUser, { sub });
1302
+ return this.put(path, attributes);
1303
+ }
1304
+ /**
1305
+ * Set a user's email/phone verified flags directly.
1306
+ *
1307
+ * Marks contact details verified without the user completing a verification challenge -
1308
+ * for accounts migrated from a system that already verified them, or verified out of
1309
+ * band. Omitted flags are left unchanged.
1310
+ *
1311
+ * @param sub - Target user's external identifier
1312
+ * @param status - Flags to set
1313
+ * @returns The updated user
1314
+ */
1315
+ async updateVerifiedStatus(sub, status) {
1316
+ const path = this.buildAdminUrl(this.adminEndpoints.updateVerifiedStatus, { sub });
1317
+ return this.post(path, status);
1318
+ }
1319
+ /**
1320
+ * Revoke one specific session of a user.
1321
+ *
1322
+ * Signs that one device out and leaves the user's other sessions alone; to end every
1323
+ * session use {@link logoutAllSessions}.
1324
+ *
1325
+ * @param sub - Target user's external identifier
1326
+ * @param sessionId - Session to revoke
1327
+ * @returns Whether the session was revoked
1328
+ */
1329
+ async revokeUserSession(sub, sessionId) {
1330
+ const path = this.buildAdminUrl(this.adminEndpoints.revokeUserSession, { sub, sessionId });
1331
+ return this.delete(path);
1332
+ }
1333
+ /**
1334
+ * List a user's trusted devices.
1335
+ *
1336
+ * These are the devices allowed to skip MFA for that user. Expired devices are
1337
+ * filtered out server-side.
1338
+ *
1339
+ * @param sub - Target user's external identifier
1340
+ * @returns The user's unexpired trusted devices, most recently used first
1341
+ */
1342
+ async getUserTrustedDevices(sub) {
1343
+ const path = this.buildAdminUrl(this.adminEndpoints.trustedDevices, { sub });
1344
+ return this.get(path);
1345
+ }
1346
+ /**
1347
+ * Revoke one of a user's trusted devices.
1348
+ *
1349
+ * That device must satisfy MFA again on its next sign-in; the user's other devices
1350
+ * are left alone.
1351
+ *
1352
+ * @param sub - Target user's external identifier
1353
+ * @param deviceId - Trusted device record id, from {@link getUserTrustedDevices}
1354
+ * @returns Whether a matching device was revoked
1355
+ */
1356
+ async revokeUserTrustedDevice(sub, deviceId) {
1357
+ const path = this.buildAdminUrl(this.adminEndpoints.trustedDevice, { sub, deviceId: String(deviceId) });
1358
+ return this.delete(path);
1359
+ }
1360
+ /**
1361
+ * Revoke every trusted device belonging to a user.
1362
+ *
1363
+ * Each of their devices must then satisfy MFA again. This does not sign them out —
1364
+ * use {@link logoutAllSessions} for that.
1365
+ *
1366
+ * @param sub - Target user's external identifier
1367
+ * @returns How many devices were revoked
1368
+ */
1369
+ async revokeAllUserTrustedDevices(sub) {
1370
+ const path = this.buildAdminUrl(this.adminEndpoints.trustedDevices, { sub });
1371
+ return this.delete(path);
1372
+ }
1373
+ /**
1374
+ * Fetch audit events of a single type, across all users.
1375
+ *
1376
+ * @param params - Event type to filter on, plus paging and an optional date window
1377
+ * @returns Paginated matching events
1378
+ */
1379
+ async getEventsByType(params) {
1380
+ const path = this.buildAdminUrl(this.adminEndpoints.getEventsByType);
1381
+ const queryString = this.buildQueryString(params);
1382
+ return this.get(`${path}${queryString}`);
1383
+ }
1384
+ /**
1385
+ * Fetch events the risk engine flagged as suspicious.
1386
+ *
1387
+ * @param params - Optional user to restrict to, and a result cap
1388
+ * @returns The flagged events
1389
+ */
1390
+ async getSuspiciousActivity(params = {}) {
1391
+ const path = this.buildAdminUrl(this.adminEndpoints.getSuspiciousActivity);
1392
+ const queryString = this.buildQueryString(params);
1393
+ return this.get(`${path}${queryString}`);
1394
+ }
1395
+ /**
1396
+ * Fetch a user's risk assessment history.
1397
+ *
1398
+ * @param params - Target user, and a result cap
1399
+ * @returns The user's recorded risk assessments
1400
+ */
1401
+ async getRiskAssessmentHistory(params) {
1402
+ const path = this.buildAdminUrl(this.adminEndpoints.getRiskAssessmentHistory);
1403
+ const queryString = this.buildQueryString(params);
1404
+ return this.get(`${path}${queryString}`);
1405
+ }
1406
+ /**
1407
+ * Create an API key on behalf of a user.
1408
+ *
1409
+ * Bypasses the server's `allowUserCreation` setting - which governs users creating
1410
+ * their own keys - but still enforces per-user limits, expiry rules, and IP
1411
+ * restrictions. The plaintext key is returned exactly once.
1412
+ *
1413
+ * @param request - Target user plus label, expiry, and optional IP allowlist
1414
+ * @returns The plaintext key and its sanitized metadata
1415
+ */
1416
+ async createApiKey(request) {
1417
+ const path = this.buildAdminUrl(this.adminEndpoints.apiKeys);
1418
+ return this.post(path, request);
1419
+ }
1420
+ /**
1421
+ * List a user's API keys.
1422
+ *
1423
+ * @param sub - Target user's external identifier
1424
+ * @returns Sanitized key metadata; never includes plaintext keys
1425
+ */
1426
+ async listApiKeys(sub) {
1427
+ const path = this.buildAdminUrl(this.adminEndpoints.apiKeys);
1428
+ const queryString = this.buildQueryString({ sub });
1429
+ return this.get(`${path}${queryString}`);
1430
+ }
1431
+ /**
1432
+ * Update the label and/or IP allowlist of a user's API key.
1433
+ *
1434
+ * @param sub - Target user's external identifier
1435
+ * @param keyId - Key to update
1436
+ * @param updates - New label and/or replacement IP allowlist
1437
+ * @returns The key's updated metadata
1438
+ */
1439
+ async updateApiKey(sub, keyId, updates) {
1440
+ const path = this.buildAdminUrl(this.adminEndpoints.apiKey, { keyId });
1441
+ return this.patch(path, { sub, ...updates });
1442
+ }
1443
+ /**
1444
+ * Revoke a user's API key, leaving it in place but unusable.
1445
+ *
1446
+ * @param sub - Target user's external identifier
1447
+ * @param keyId - Key to revoke
1448
+ * @returns Whether the key was revoked
1449
+ */
1450
+ async revokeApiKey(sub, keyId) {
1451
+ const path = this.buildAdminUrl(this.adminEndpoints.apiKeyRevoke, { keyId });
1452
+ return this.post(path, { sub });
1453
+ }
1454
+ /**
1455
+ * Permanently delete a user's API key.
1456
+ *
1457
+ * @param sub - Target user's external identifier
1458
+ * @param keyId - Key to delete
1459
+ * @returns Whether the key was deleted
1460
+ */
1461
+ async deleteApiKey(sub, keyId) {
1462
+ const path = this.buildAdminUrl(this.adminEndpoints.apiKey, { keyId });
1463
+ return this.delete(path, { sub });
1464
+ }
1259
1465
  // ============================================================================
1260
1466
  // Private Helper Methods
1261
1467
  // ============================================================================
@@ -1435,14 +1641,64 @@ var AdminOperations = class {
1435
1641
  throw this.handleError(error);
1436
1642
  }
1437
1643
  }
1644
+ /**
1645
+ * Execute PUT request
1646
+ *
1647
+ * @param path - Full URL path
1648
+ * @param body - Request body
1649
+ * @returns Response data
1650
+ * @private
1651
+ */
1652
+ async put(path, body) {
1653
+ const headers = await this.buildHeaders(true, "PUT");
1654
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1655
+ try {
1656
+ const response = await this.config.httpAdapter.request({
1657
+ method: "PUT",
1658
+ url: path,
1659
+ headers,
1660
+ body,
1661
+ credentials
1662
+ });
1663
+ return response.data;
1664
+ } catch (error) {
1665
+ throw this.handleError(error);
1666
+ }
1667
+ }
1668
+ /**
1669
+ * Execute PATCH request
1670
+ *
1671
+ * @param path - Full URL path
1672
+ * @param body - Request body
1673
+ * @returns Response data
1674
+ * @private
1675
+ */
1676
+ async patch(path, body) {
1677
+ const headers = await this.buildHeaders(true, "PATCH");
1678
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1679
+ try {
1680
+ const response = await this.config.httpAdapter.request({
1681
+ method: "PATCH",
1682
+ url: path,
1683
+ headers,
1684
+ body,
1685
+ credentials
1686
+ });
1687
+ return response.data;
1688
+ } catch (error) {
1689
+ throw this.handleError(error);
1690
+ }
1691
+ }
1438
1692
  /**
1439
1693
  * Execute DELETE request
1440
1694
  *
1441
1695
  * @param path - Full URL path
1696
+ * @param body - Optional request body, for routes that identify their target from the
1697
+ * body as well as the path
1442
1698
  * @returns Response data
1443
1699
  * @private
1444
1700
  */
1445
- async delete(path) {
1701
+ async delete(path, body) {
1446
1702
  const headers = await this.buildHeaders(true, "DELETE");
1447
1703
  const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1448
1704
  try {
@@ -1450,6 +1706,7 @@ var AdminOperations = class {
1450
1706
  method: "DELETE",
1451
1707
  url: path,
1452
1708
  headers,
1709
+ ...body === void 0 ? {} : { body },
1453
1710
  credentials
1454
1711
  });
1455
1712
  return response.data;
@@ -2471,16 +2728,27 @@ var NAuthClient = class {
2471
2728
  * - Passkey: WebAuthn registration options
2472
2729
  *
2473
2730
  * @param method - MFA method to set up
2731
+ * @param setupData - Method-specific enrolment input. SMS and email enrolment need a
2732
+ * destination (`{ phoneNumber }` in E.164, or `{ emailAddress }`) whenever the account
2733
+ * does not already hold a verified one; without it the server answers `PHONE_REQUIRED`
2734
+ * or `EMAIL_REQUIRED`. Pass `deviceName` to label the device.
2474
2735
  * @returns Promise of setup data response
2475
2736
  *
2476
2737
  * @example
2477
2738
  * ```typescript
2478
2739
  * const result = await client.setupMfaDevice('totp');
2479
2740
  * console.log('QR Code:', result.setupData.qrCode);
2741
+ *
2742
+ * // Enrolling a phone the account does not have on file yet
2743
+ * await client.setupMfaDevice('sms', { phoneNumber: '+15551234567', deviceName: 'Work phone' });
2480
2744
  * ```
2481
2745
  */
2482
- async setupMfaDevice(method) {
2483
- return this.post(this.config.endpoints.mfaSetupData, { methodName: method }, true);
2746
+ async setupMfaDevice(method, setupData) {
2747
+ return this.post(
2748
+ this.config.endpoints.mfaSetupData,
2749
+ setupData ? { methodName: method, setupData } : { methodName: method },
2750
+ true
2751
+ );
2484
2752
  }
2485
2753
  /**
2486
2754
  * Verify MFA setup (authenticated user).
@@ -2599,6 +2867,83 @@ var NAuthClient = class {
2599
2867
  const result = await this.post(this.config.endpoints.mfaBackupCodes, {}, true);
2600
2868
  return result.codes;
2601
2869
  }
2870
+ /**
2871
+ * List the MFA methods this deployment permits.
2872
+ *
2873
+ * Reflects what the server has registered and enabled, not what the caller has
2874
+ * enrolled - use {@link getMfaDevices} for that. Enrolment screens use this to decide
2875
+ * which options to offer.
2876
+ *
2877
+ * @returns The allowed method names
2878
+ */
2879
+ async getAvailableMfaMethods() {
2880
+ return this.get(this.config.endpoints.mfaAvailableMethods, true);
2881
+ }
2882
+ /**
2883
+ * ============================================================================
2884
+ * Sessions
2885
+ * ============================================================================
2886
+ */
2887
+ /**
2888
+ * List the caller's own active sessions.
2889
+ *
2890
+ * @returns The caller's sessions, one entry per active device/session
2891
+ */
2892
+ async listSessions() {
2893
+ return this.get(this.config.endpoints.sessions, true);
2894
+ }
2895
+ /**
2896
+ * Revoke one of the caller's own sessions.
2897
+ *
2898
+ * Revoking the session that is making the request signs the caller out; the response's
2899
+ * `wasCurrentSession` reports that, so the caller can clear local auth state.
2900
+ *
2901
+ * @param sessionId - Session to revoke
2902
+ * @returns Whether the session was revoked, and whether it was the caller's own
2903
+ */
2904
+ async revokeSession(sessionId) {
2905
+ const path = this.config.endpoints.logoutSession.replace(":sessionId", encodeURIComponent(sessionId));
2906
+ return this.delete(path, true);
2907
+ }
2908
+ /**
2909
+ * ============================================================================
2910
+ * Trusted Devices
2911
+ * ============================================================================
2912
+ */
2913
+ /**
2914
+ * List the caller's own trusted devices.
2915
+ *
2916
+ * These are the devices allowed to skip MFA. Expired devices are filtered out
2917
+ * server-side, so the list is what can currently be used and is worth showing.
2918
+ *
2919
+ * @returns The caller's unexpired trusted devices, most recently used first
2920
+ */
2921
+ async listTrustedDevices() {
2922
+ return this.get(this.config.endpoints.trustedDevices, true);
2923
+ }
2924
+ /**
2925
+ * Revoke one of the caller's own trusted devices.
2926
+ *
2927
+ * That device must satisfy MFA again on its next sign-in.
2928
+ *
2929
+ * @param deviceId - Trusted device record id, from {@link listTrustedDevices}
2930
+ * @returns Whether a matching device was revoked
2931
+ */
2932
+ async revokeTrustedDevice(deviceId) {
2933
+ const path = this.config.endpoints.trustedDevice.replace(":deviceId", encodeURIComponent(String(deviceId)));
2934
+ return this.delete(path, true);
2935
+ }
2936
+ /**
2937
+ * Revoke every trusted device belonging to the caller.
2938
+ *
2939
+ * Every device must then satisfy MFA again. This does not sign anyone out — use
2940
+ * {@link logoutAll} for that.
2941
+ *
2942
+ * @returns How many devices were revoked
2943
+ */
2944
+ async revokeAllTrustedDevices() {
2945
+ return this.delete(this.config.endpoints.trustedDevices, true);
2946
+ }
2602
2947
  /**
2603
2948
  * ============================================================================
2604
2949
  * Event System
@@ -2753,6 +3098,29 @@ var NAuthClient = class {
2753
3098
  async unlinkSocialAccount(provider) {
2754
3099
  return this.post(this.config.endpoints.socialUnlink, { provider }, true);
2755
3100
  }
3101
+ /**
3102
+ * Check whether the caller may set a first password.
3103
+ *
3104
+ * True for a social-only account that has no password yet. Use it to decide whether to
3105
+ * offer "set a password" (this call) or "change password" ({@link changePassword}).
3106
+ *
3107
+ * @returns Whether the caller can set a first password
3108
+ */
3109
+ async canSetPassword() {
3110
+ return this.get(this.config.endpoints.socialCanSetPassword, true);
3111
+ }
3112
+ /**
3113
+ * Give a social-only account its first password.
3114
+ *
3115
+ * Only valid while {@link canSetPassword} is true; an account that already has one must
3116
+ * use {@link changePassword}, which verifies the existing password.
3117
+ *
3118
+ * @param newPassword - Password to set, subject to the server's password policy
3119
+ * @returns Confirmation message
3120
+ */
3121
+ async setPasswordForSocialUser(newPassword) {
3122
+ return this.post(this.config.endpoints.socialSetPassword, { password: newPassword }, true);
3123
+ }
2756
3124
  /**
2757
3125
  * Trust current device.
2758
3126
  */