@nauth-toolkit/client 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -127,22 +127,32 @@ var defaultEndpoints = {
127
127
  mfaVerifySetup: "/mfa/verify-setup",
128
128
  mfaPreferred: "/mfa/devices/:deviceId/preferred",
129
129
  mfaBackupCodes: "/mfa/backup-codes/generate",
130
+ mfaAvailableMethods: "/mfa/available-methods",
130
131
  socialLinked: "/social/linked",
131
132
  socialLink: "/social/link",
132
133
  socialUnlink: "/social/unlink",
133
134
  socialVerify: "/social/:provider/verify",
134
135
  socialRedirectStart: "/social/:provider/redirect",
135
136
  socialExchange: "/social/exchange",
137
+ socialCanSetPassword: "/social/can-set-password",
138
+ socialSetPassword: "/social/set-password",
136
139
  trustDevice: "/trust-device",
137
140
  isTrustedDevice: "/is-trusted-device",
138
141
  auditHistory: "/audit/history",
139
- updateProfile: "/profile"
142
+ updateProfile: "/profile",
143
+ sessions: "/sessions",
144
+ logoutSession: "/sessions/:sessionId",
145
+ trustedDevices: "/trusted-devices",
146
+ trustedDevice: "/trusted-devices/:deviceId"
140
147
  };
141
148
  var defaultAdminEndpoints = {
142
149
  signup: "/signup",
143
150
  signupSocial: "/signup-social",
144
151
  getUsers: "/users",
145
152
  getUser: "/users/:sub",
153
+ getUserByEmail: "/users/by-email",
154
+ updateUser: "/users/:sub",
155
+ updateVerifiedStatus: "/users/:sub/verified-status",
146
156
  deleteUser: "/users/:sub",
147
157
  disableUser: "/users/:sub/disable",
148
158
  enableUser: "/users/:sub/enable",
@@ -150,13 +160,22 @@ var defaultAdminEndpoints = {
150
160
  setPassword: "/set-password",
151
161
  resetPasswordInitiate: "/reset-password/initiate",
152
162
  getUserSessions: "/users/:sub/sessions",
163
+ revokeUserSession: "/users/:sub/sessions/:sessionId",
164
+ trustedDevices: "/users/:sub/trusted-devices",
165
+ trustedDevice: "/users/:sub/trusted-devices/:deviceId",
153
166
  logoutAll: "/users/:sub/logout-all",
154
167
  getMfaStatus: "/users/:sub/mfa/status",
155
168
  getMfaDevices: "/users/:sub/mfa/devices",
156
169
  removeMfaDeviceById: "/mfa/devices/:deviceId",
157
170
  setPreferredMfaDevice: "/users/:sub/mfa/devices/:deviceId/preferred",
158
171
  setMfaExemption: "/mfa/exemption",
159
- getAuditHistory: "/audit/history"
172
+ getAuditHistory: "/audit/history",
173
+ getEventsByType: "/audit/events",
174
+ getSuspiciousActivity: "/audit/suspicious",
175
+ getRiskAssessmentHistory: "/audit/risk",
176
+ apiKeys: "/api-keys",
177
+ apiKey: "/api-keys/:keyId",
178
+ apiKeyRevoke: "/api-keys/:keyId/revoke"
160
179
  };
161
180
  var resolveConfig = (config, defaultAdapter) => {
162
181
  const resolvedEndpoints = {
@@ -1209,6 +1228,193 @@ var AdminOperations = class {
1209
1228
  const queryString = this.buildQueryString(params);
1210
1229
  return this.get(`${path}${queryString}`);
1211
1230
  }
1231
+ /**
1232
+ * Resolve a user by email address.
1233
+ *
1234
+ * Email is not necessarily a stable identifier - an account's address can be changed,
1235
+ * and with `requireEmailVerified` unset an unverified address matches too - so prefer
1236
+ * `sub` wherever the caller already holds one.
1237
+ *
1238
+ * @param params - Email to look up, and whether to require a verified address
1239
+ * @returns The matching user
1240
+ */
1241
+ async getUserByEmail(params) {
1242
+ const path = this.buildAdminUrl(this.adminEndpoints.getUserByEmail);
1243
+ const queryString = this.buildQueryString(params);
1244
+ return this.get(`${path}${queryString}`);
1245
+ }
1246
+ /**
1247
+ * Update a user's profile attributes.
1248
+ *
1249
+ * @param sub - Target user's external identifier
1250
+ * @param attributes - Attributes to change; omitted fields are left as they are
1251
+ * @returns The updated user
1252
+ */
1253
+ async updateUser(sub, attributes) {
1254
+ const path = this.buildAdminUrl(this.adminEndpoints.updateUser, { sub });
1255
+ return this.put(path, attributes);
1256
+ }
1257
+ /**
1258
+ * Set a user's email/phone verified flags directly.
1259
+ *
1260
+ * Marks contact details verified without the user completing a verification challenge -
1261
+ * for accounts migrated from a system that already verified them, or verified out of
1262
+ * band. Omitted flags are left unchanged.
1263
+ *
1264
+ * @param sub - Target user's external identifier
1265
+ * @param status - Flags to set
1266
+ * @returns The updated user
1267
+ */
1268
+ async updateVerifiedStatus(sub, status) {
1269
+ const path = this.buildAdminUrl(this.adminEndpoints.updateVerifiedStatus, { sub });
1270
+ return this.post(path, status);
1271
+ }
1272
+ /**
1273
+ * Revoke one specific session of a user.
1274
+ *
1275
+ * Signs that one device out and leaves the user's other sessions alone; to end every
1276
+ * session use {@link logoutAllSessions}.
1277
+ *
1278
+ * @param sub - Target user's external identifier
1279
+ * @param sessionId - Session to revoke
1280
+ * @returns Whether the session was revoked
1281
+ */
1282
+ async revokeUserSession(sub, sessionId) {
1283
+ const path = this.buildAdminUrl(this.adminEndpoints.revokeUserSession, { sub, sessionId });
1284
+ return this.delete(path);
1285
+ }
1286
+ /**
1287
+ * List a user's trusted devices.
1288
+ *
1289
+ * These are the devices allowed to skip MFA for that user. Expired devices are
1290
+ * filtered out server-side.
1291
+ *
1292
+ * @param sub - Target user's external identifier
1293
+ * @returns The user's unexpired trusted devices, most recently used first
1294
+ */
1295
+ async getUserTrustedDevices(sub) {
1296
+ const path = this.buildAdminUrl(this.adminEndpoints.trustedDevices, { sub });
1297
+ return this.get(path);
1298
+ }
1299
+ /**
1300
+ * Revoke one of a user's trusted devices.
1301
+ *
1302
+ * That device must satisfy MFA again on its next sign-in; the user's other devices
1303
+ * are left alone.
1304
+ *
1305
+ * @param sub - Target user's external identifier
1306
+ * @param deviceId - Trusted device record id, from {@link getUserTrustedDevices}
1307
+ * @returns Whether a matching device was revoked
1308
+ */
1309
+ async revokeUserTrustedDevice(sub, deviceId) {
1310
+ const path = this.buildAdminUrl(this.adminEndpoints.trustedDevice, { sub, deviceId: String(deviceId) });
1311
+ return this.delete(path);
1312
+ }
1313
+ /**
1314
+ * Revoke every trusted device belonging to a user.
1315
+ *
1316
+ * Each of their devices must then satisfy MFA again. This does not sign them out —
1317
+ * use {@link logoutAllSessions} for that.
1318
+ *
1319
+ * @param sub - Target user's external identifier
1320
+ * @returns How many devices were revoked
1321
+ */
1322
+ async revokeAllUserTrustedDevices(sub) {
1323
+ const path = this.buildAdminUrl(this.adminEndpoints.trustedDevices, { sub });
1324
+ return this.delete(path);
1325
+ }
1326
+ /**
1327
+ * Fetch audit events of a single type, across all users.
1328
+ *
1329
+ * @param params - Event type to filter on, plus paging and an optional date window
1330
+ * @returns Paginated matching events
1331
+ */
1332
+ async getEventsByType(params) {
1333
+ const path = this.buildAdminUrl(this.adminEndpoints.getEventsByType);
1334
+ const queryString = this.buildQueryString(params);
1335
+ return this.get(`${path}${queryString}`);
1336
+ }
1337
+ /**
1338
+ * Fetch events the risk engine flagged as suspicious.
1339
+ *
1340
+ * @param params - Optional user to restrict to, and a result cap
1341
+ * @returns The flagged events
1342
+ */
1343
+ async getSuspiciousActivity(params = {}) {
1344
+ const path = this.buildAdminUrl(this.adminEndpoints.getSuspiciousActivity);
1345
+ const queryString = this.buildQueryString(params);
1346
+ return this.get(`${path}${queryString}`);
1347
+ }
1348
+ /**
1349
+ * Fetch a user's risk assessment history.
1350
+ *
1351
+ * @param params - Target user, and a result cap
1352
+ * @returns The user's recorded risk assessments
1353
+ */
1354
+ async getRiskAssessmentHistory(params) {
1355
+ const path = this.buildAdminUrl(this.adminEndpoints.getRiskAssessmentHistory);
1356
+ const queryString = this.buildQueryString(params);
1357
+ return this.get(`${path}${queryString}`);
1358
+ }
1359
+ /**
1360
+ * Create an API key on behalf of a user.
1361
+ *
1362
+ * Bypasses the server's `allowUserCreation` setting - which governs users creating
1363
+ * their own keys - but still enforces per-user limits, expiry rules, and IP
1364
+ * restrictions. The plaintext key is returned exactly once.
1365
+ *
1366
+ * @param request - Target user plus label, expiry, and optional IP allowlist
1367
+ * @returns The plaintext key and its sanitized metadata
1368
+ */
1369
+ async createApiKey(request) {
1370
+ const path = this.buildAdminUrl(this.adminEndpoints.apiKeys);
1371
+ return this.post(path, request);
1372
+ }
1373
+ /**
1374
+ * List a user's API keys.
1375
+ *
1376
+ * @param sub - Target user's external identifier
1377
+ * @returns Sanitized key metadata; never includes plaintext keys
1378
+ */
1379
+ async listApiKeys(sub) {
1380
+ const path = this.buildAdminUrl(this.adminEndpoints.apiKeys);
1381
+ const queryString = this.buildQueryString({ sub });
1382
+ return this.get(`${path}${queryString}`);
1383
+ }
1384
+ /**
1385
+ * Update the label and/or IP allowlist of a user's API key.
1386
+ *
1387
+ * @param sub - Target user's external identifier
1388
+ * @param keyId - Key to update
1389
+ * @param updates - New label and/or replacement IP allowlist
1390
+ * @returns The key's updated metadata
1391
+ */
1392
+ async updateApiKey(sub, keyId, updates) {
1393
+ const path = this.buildAdminUrl(this.adminEndpoints.apiKey, { keyId });
1394
+ return this.patch(path, { sub, ...updates });
1395
+ }
1396
+ /**
1397
+ * Revoke a user's API key, leaving it in place but unusable.
1398
+ *
1399
+ * @param sub - Target user's external identifier
1400
+ * @param keyId - Key to revoke
1401
+ * @returns Whether the key was revoked
1402
+ */
1403
+ async revokeApiKey(sub, keyId) {
1404
+ const path = this.buildAdminUrl(this.adminEndpoints.apiKeyRevoke, { keyId });
1405
+ return this.post(path, { sub });
1406
+ }
1407
+ /**
1408
+ * Permanently delete a user's API key.
1409
+ *
1410
+ * @param sub - Target user's external identifier
1411
+ * @param keyId - Key to delete
1412
+ * @returns Whether the key was deleted
1413
+ */
1414
+ async deleteApiKey(sub, keyId) {
1415
+ const path = this.buildAdminUrl(this.adminEndpoints.apiKey, { keyId });
1416
+ return this.delete(path, { sub });
1417
+ }
1212
1418
  // ============================================================================
1213
1419
  // Private Helper Methods
1214
1420
  // ============================================================================
@@ -1388,14 +1594,64 @@ var AdminOperations = class {
1388
1594
  throw this.handleError(error);
1389
1595
  }
1390
1596
  }
1597
+ /**
1598
+ * Execute PUT request
1599
+ *
1600
+ * @param path - Full URL path
1601
+ * @param body - Request body
1602
+ * @returns Response data
1603
+ * @private
1604
+ */
1605
+ async put(path, body) {
1606
+ const headers = await this.buildHeaders(true, "PUT");
1607
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1608
+ try {
1609
+ const response = await this.config.httpAdapter.request({
1610
+ method: "PUT",
1611
+ url: path,
1612
+ headers,
1613
+ body,
1614
+ credentials
1615
+ });
1616
+ return response.data;
1617
+ } catch (error) {
1618
+ throw this.handleError(error);
1619
+ }
1620
+ }
1621
+ /**
1622
+ * Execute PATCH request
1623
+ *
1624
+ * @param path - Full URL path
1625
+ * @param body - Request body
1626
+ * @returns Response data
1627
+ * @private
1628
+ */
1629
+ async patch(path, body) {
1630
+ const headers = await this.buildHeaders(true, "PATCH");
1631
+ const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1632
+ try {
1633
+ const response = await this.config.httpAdapter.request({
1634
+ method: "PATCH",
1635
+ url: path,
1636
+ headers,
1637
+ body,
1638
+ credentials
1639
+ });
1640
+ return response.data;
1641
+ } catch (error) {
1642
+ throw this.handleError(error);
1643
+ }
1644
+ }
1391
1645
  /**
1392
1646
  * Execute DELETE request
1393
1647
  *
1394
1648
  * @param path - Full URL path
1649
+ * @param body - Optional request body, for routes that identify their target from the
1650
+ * body as well as the path
1395
1651
  * @returns Response data
1396
1652
  * @private
1397
1653
  */
1398
- async delete(path) {
1654
+ async delete(path, body) {
1399
1655
  const headers = await this.buildHeaders(true, "DELETE");
1400
1656
  const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
1401
1657
  try {
@@ -1403,6 +1659,7 @@ var AdminOperations = class {
1403
1659
  method: "DELETE",
1404
1660
  url: path,
1405
1661
  headers,
1662
+ ...body === void 0 ? {} : { body },
1406
1663
  credentials
1407
1664
  });
1408
1665
  return response.data;
@@ -2424,16 +2681,27 @@ var NAuthClient = class {
2424
2681
  * - Passkey: WebAuthn registration options
2425
2682
  *
2426
2683
  * @param method - MFA method to set up
2684
+ * @param setupData - Method-specific enrolment input. SMS and email enrolment need a
2685
+ * destination (`{ phoneNumber }` in E.164, or `{ emailAddress }`) whenever the account
2686
+ * does not already hold a verified one; without it the server answers `PHONE_REQUIRED`
2687
+ * or `EMAIL_REQUIRED`. Pass `deviceName` to label the device.
2427
2688
  * @returns Promise of setup data response
2428
2689
  *
2429
2690
  * @example
2430
2691
  * ```typescript
2431
2692
  * const result = await client.setupMfaDevice('totp');
2432
2693
  * console.log('QR Code:', result.setupData.qrCode);
2694
+ *
2695
+ * // Enrolling a phone the account does not have on file yet
2696
+ * await client.setupMfaDevice('sms', { phoneNumber: '+15551234567', deviceName: 'Work phone' });
2433
2697
  * ```
2434
2698
  */
2435
- async setupMfaDevice(method) {
2436
- return this.post(this.config.endpoints.mfaSetupData, { methodName: method }, true);
2699
+ async setupMfaDevice(method, setupData) {
2700
+ return this.post(
2701
+ this.config.endpoints.mfaSetupData,
2702
+ setupData ? { methodName: method, setupData } : { methodName: method },
2703
+ true
2704
+ );
2437
2705
  }
2438
2706
  /**
2439
2707
  * Verify MFA setup (authenticated user).
@@ -2552,6 +2820,83 @@ var NAuthClient = class {
2552
2820
  const result = await this.post(this.config.endpoints.mfaBackupCodes, {}, true);
2553
2821
  return result.codes;
2554
2822
  }
2823
+ /**
2824
+ * List the MFA methods this deployment permits.
2825
+ *
2826
+ * Reflects what the server has registered and enabled, not what the caller has
2827
+ * enrolled - use {@link getMfaDevices} for that. Enrolment screens use this to decide
2828
+ * which options to offer.
2829
+ *
2830
+ * @returns The allowed method names
2831
+ */
2832
+ async getAvailableMfaMethods() {
2833
+ return this.get(this.config.endpoints.mfaAvailableMethods, true);
2834
+ }
2835
+ /**
2836
+ * ============================================================================
2837
+ * Sessions
2838
+ * ============================================================================
2839
+ */
2840
+ /**
2841
+ * List the caller's own active sessions.
2842
+ *
2843
+ * @returns The caller's sessions, one entry per active device/session
2844
+ */
2845
+ async listSessions() {
2846
+ return this.get(this.config.endpoints.sessions, true);
2847
+ }
2848
+ /**
2849
+ * Revoke one of the caller's own sessions.
2850
+ *
2851
+ * Revoking the session that is making the request signs the caller out; the response's
2852
+ * `wasCurrentSession` reports that, so the caller can clear local auth state.
2853
+ *
2854
+ * @param sessionId - Session to revoke
2855
+ * @returns Whether the session was revoked, and whether it was the caller's own
2856
+ */
2857
+ async revokeSession(sessionId) {
2858
+ const path = this.config.endpoints.logoutSession.replace(":sessionId", encodeURIComponent(sessionId));
2859
+ return this.delete(path, true);
2860
+ }
2861
+ /**
2862
+ * ============================================================================
2863
+ * Trusted Devices
2864
+ * ============================================================================
2865
+ */
2866
+ /**
2867
+ * List the caller's own trusted devices.
2868
+ *
2869
+ * These are the devices allowed to skip MFA. Expired devices are filtered out
2870
+ * server-side, so the list is what can currently be used and is worth showing.
2871
+ *
2872
+ * @returns The caller's unexpired trusted devices, most recently used first
2873
+ */
2874
+ async listTrustedDevices() {
2875
+ return this.get(this.config.endpoints.trustedDevices, true);
2876
+ }
2877
+ /**
2878
+ * Revoke one of the caller's own trusted devices.
2879
+ *
2880
+ * That device must satisfy MFA again on its next sign-in.
2881
+ *
2882
+ * @param deviceId - Trusted device record id, from {@link listTrustedDevices}
2883
+ * @returns Whether a matching device was revoked
2884
+ */
2885
+ async revokeTrustedDevice(deviceId) {
2886
+ const path = this.config.endpoints.trustedDevice.replace(":deviceId", encodeURIComponent(String(deviceId)));
2887
+ return this.delete(path, true);
2888
+ }
2889
+ /**
2890
+ * Revoke every trusted device belonging to the caller.
2891
+ *
2892
+ * Every device must then satisfy MFA again. This does not sign anyone out — use
2893
+ * {@link logoutAll} for that.
2894
+ *
2895
+ * @returns How many devices were revoked
2896
+ */
2897
+ async revokeAllTrustedDevices() {
2898
+ return this.delete(this.config.endpoints.trustedDevices, true);
2899
+ }
2555
2900
  /**
2556
2901
  * ============================================================================
2557
2902
  * Event System
@@ -2706,6 +3051,29 @@ var NAuthClient = class {
2706
3051
  async unlinkSocialAccount(provider) {
2707
3052
  return this.post(this.config.endpoints.socialUnlink, { provider }, true);
2708
3053
  }
3054
+ /**
3055
+ * Check whether the caller may set a first password.
3056
+ *
3057
+ * True for a social-only account that has no password yet. Use it to decide whether to
3058
+ * offer "set a password" (this call) or "change password" ({@link changePassword}).
3059
+ *
3060
+ * @returns Whether the caller can set a first password
3061
+ */
3062
+ async canSetPassword() {
3063
+ return this.get(this.config.endpoints.socialCanSetPassword, true);
3064
+ }
3065
+ /**
3066
+ * Give a social-only account its first password.
3067
+ *
3068
+ * Only valid while {@link canSetPassword} is true; an account that already has one must
3069
+ * use {@link changePassword}, which verifies the existing password.
3070
+ *
3071
+ * @param newPassword - Password to set, subject to the server's password policy
3072
+ * @returns Confirmation message
3073
+ */
3074
+ async setPasswordForSocialUser(newPassword) {
3075
+ return this.post(this.config.endpoints.socialSetPassword, { password: newPassword }, true);
3076
+ }
2709
3077
  /**
2710
3078
  * Trust current device.
2711
3079
  */