@scalekit-sdk/node 2.2.0 → 2.2.2

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.
Files changed (62) hide show
  1. package/{reference.md → REFERENCE.md} +530 -77
  2. package/lib/core.js +1 -1
  3. package/package.json +9 -3
  4. package/.github/dependabot.yml +0 -10
  5. package/.nvmrc +0 -1
  6. package/buf.gen.yaml +0 -20
  7. package/jest.config.js +0 -15
  8. package/src/auth.ts +0 -99
  9. package/src/connect.ts +0 -32
  10. package/src/connection.ts +0 -267
  11. package/src/constants/user.ts +0 -22
  12. package/src/core.ts +0 -139
  13. package/src/directory.ts +0 -431
  14. package/src/domain.ts +0 -273
  15. package/src/errors/base-exception.ts +0 -263
  16. package/src/errors/index.ts +0 -3
  17. package/src/errors/specific-exceptions.ts +0 -88
  18. package/src/index.ts +0 -10
  19. package/src/organization.ts +0 -571
  20. package/src/passwordless.ts +0 -139
  21. package/src/permission.ts +0 -310
  22. package/src/pkg/grpc/buf/validate/validate_pb.ts +0 -28
  23. package/src/pkg/grpc/google/api/annotations_pb.ts +0 -28
  24. package/src/pkg/grpc/google/api/field_behavior_pb.ts +0 -28
  25. package/src/pkg/grpc/google/api/visibility_pb.ts +0 -28
  26. package/src/pkg/grpc/protoc-gen-openapiv2/options/annotations_pb.ts +0 -28
  27. package/src/pkg/grpc/scalekit/v1/auditlogs/auditlogs_pb.ts +0 -257
  28. package/src/pkg/grpc/scalekit/v1/auth/auth_pb.ts +0 -836
  29. package/src/pkg/grpc/scalekit/v1/auth/passwordless_pb.ts +0 -264
  30. package/src/pkg/grpc/scalekit/v1/auth/webauthn_pb.ts +0 -794
  31. package/src/pkg/grpc/scalekit/v1/commons/commons_pb.ts +0 -452
  32. package/src/pkg/grpc/scalekit/v1/connections/connections_pb.ts +0 -2645
  33. package/src/pkg/grpc/scalekit/v1/directories/directories_pb.ts +0 -1393
  34. package/src/pkg/grpc/scalekit/v1/domains/domains_pb.ts +0 -599
  35. package/src/pkg/grpc/scalekit/v1/errdetails/errdetails_pb.ts +0 -311
  36. package/src/pkg/grpc/scalekit/v1/options/options_pb.ts +0 -200
  37. package/src/pkg/grpc/scalekit/v1/organizations/organizations_pb.ts +0 -1141
  38. package/src/pkg/grpc/scalekit/v1/roles/roles_pb.ts +0 -1491
  39. package/src/pkg/grpc/scalekit/v1/sessions/sessions_pb.ts +0 -497
  40. package/src/pkg/grpc/scalekit/v1/users/users_pb.ts +0 -1404
  41. package/src/role.ts +0 -463
  42. package/src/scalekit.ts +0 -800
  43. package/src/session.ts +0 -323
  44. package/src/types/auth.ts +0 -73
  45. package/src/types/organization.ts +0 -12
  46. package/src/types/scalekit.ts +0 -50
  47. package/src/types/user.ts +0 -21
  48. package/src/user.ts +0 -829
  49. package/src/webauthn.ts +0 -99
  50. package/tests/README.md +0 -25
  51. package/tests/connection.test.ts +0 -42
  52. package/tests/directory.test.ts +0 -46
  53. package/tests/domain.test.ts +0 -293
  54. package/tests/organization.test.ts +0 -81
  55. package/tests/passwordless.test.ts +0 -108
  56. package/tests/permission.test.ts +0 -399
  57. package/tests/role.test.ts +0 -323
  58. package/tests/scalekit.test.ts +0 -104
  59. package/tests/setup.ts +0 -34
  60. package/tests/users.test.ts +0 -168
  61. package/tests/utils/test-data.ts +0 -490
  62. package/tsconfig.json +0 -19
package/src/session.ts DELETED
@@ -1,323 +0,0 @@
1
- import { create } from "@bufbuild/protobuf";
2
- import { timestampFromDate } from "@bufbuild/protobuf/wkt";
3
- import type { Client } from "@connectrpc/connect";
4
- import GrpcConnect from "./connect";
5
- import CoreClient from "./core";
6
- import {
7
- SessionService,
8
- SessionDetailsRequest,
9
- SessionDetails,
10
- UserSessionDetailsRequest,
11
- UserSessionDetails,
12
- UserSessionDetailsRequestSchema,
13
- UserSessionFilterSchema,
14
- RevokeSessionRequest,
15
- RevokeSessionResponse,
16
- RevokeAllUserSessionsRequest,
17
- RevokeAllUserSessionsResponse,
18
- } from "./pkg/grpc/scalekit/v1/sessions/sessions_pb";
19
-
20
- export default class SessionClient {
21
- private client: Client<typeof SessionService>;
22
-
23
- constructor(
24
- private readonly grpcConnect: GrpcConnect,
25
- private readonly coreClient: CoreClient
26
- ) {
27
- this.client = this.grpcConnect.createClient(SessionService);
28
- }
29
-
30
- /**
31
- * Retrieves comprehensive metadata and status for a specific user session.
32
- *
33
- * Fetches complete session information including authentication status, device details,
34
- * IP address, geolocation, and expiration timelines.
35
- *
36
- * @param {string} sessionId - The session identifier to retrieve (format: "ses_...")
37
- *
38
- * @returns {Promise<SessionDetails>} Session details containing:
39
- * - sessionId: Unique session identifier
40
- * - userId: User who owns this session
41
- * - organizationId: Organization context for the session
42
- * - status: Current session status ('active', 'expired', 'revoked', 'logout')
43
- * - deviceInfo: Browser and operating system information
44
- * - ipAddress: IP address from which session was created
45
- * - geoLocation: Geographic location data (city, region, country)
46
- * - createTime: When the session was created
47
- * - lastActivityTime: Most recent session activity
48
- * - idleExpirationTime: When session expires due to inactivity
49
- * - absoluteExpirationTime: Maximum session lifetime
50
- * - expirationTime: Actual expiration time (if session has ended)
51
- *
52
- * @throws {Error} If the session is not found
53
- *
54
- * @example
55
- * // Get session details
56
- * const session = await scalekitClient.session.getSession('ses_123456');
57
- *
58
- * console.log('Status:', session.status);
59
- * console.log('User:', session.userId);
60
- * console.log('Device:', session.deviceInfo);
61
- * console.log('Location:', session.geoLocation);
62
- * console.log('Last active:', session.lastActivityTime);
63
- *
64
- *
65
- * @see {@link https://docs.scalekit.com/apis/#tag/sessions | Get Session API}
66
- * @see {@link getUserSessions} - List all sessions for a user
67
- * @see {@link revokeSession} - Revoke this session
68
- */
69
- async getSession(sessionId: string): Promise<SessionDetails> {
70
- return this.coreClient.connectExec(this.client.getSession, {
71
- sessionId,
72
- });
73
- }
74
-
75
- /**
76
- * Retrieves a paginated list of all sessions for a specific user across all devices and browsers.
77
- *
78
- * Lists all user sessions with support for filtering by status and time range. Essential for
79
- * displaying active sessions in account management, auditing user activity, verifying authentication
80
- * across devices, or identifying suspicious sessions. Use filtering to find active sessions,
81
- * sessions from specific time periods, or sessions with particular statuses.
82
- *
83
- * @param {string} userId - The user identifier (format: "usr_...")
84
- * @param {object} [options] - Optional pagination and filtering parameters
85
- * @param {number} [options.pageSize] - Number of sessions to return per page
86
- * @param {string} [options.pageToken] - Token for retrieving the next page from previous response
87
- * @param {object} [options.filter] - Filter criteria for sessions
88
- * @param {string[]} [options.filter.status] - Filter by status values: 'active', 'expired', 'revoked', 'logout'
89
- * (multiple values use OR logic)
90
- * @param {Date} [options.filter.startTime] - Include sessions created on or after this time
91
- * @param {Date} [options.filter.endTime] - Include sessions created before this time
92
- * (must be after startTime)
93
- *
94
- * @returns {Promise<UserSessionDetails>} Response containing:
95
- * - sessions: Array of session objects with device info, location, and status
96
- * - nextPageToken: Token for fetching the next page
97
- * - totalSize: Total number of sessions matching the filter
98
- *
99
- * @example
100
- * // List all active sessions for a user
101
- * const response = await scalekitClient.session.getUserSessions('usr_123456', {
102
- * filter: { status: ['active'] },
103
- * pageSize: 20
104
- * });
105
- *
106
- * console.log(`User has ${response.totalSize} active sessions`);
107
- * response.sessions.forEach(session => {
108
- * console.log(`- ${session.deviceInfo} from ${session.geoLocation?.city}`);
109
- * console.log(` Last active: ${session.lastActivityTime}`);
110
- * });
111
- *
112
- * @example
113
- * // Get all sessions (active and inactive)
114
- * const response = await scalekitClient.session.getUserSessions('usr_123456');
115
- * console.log(`Total sessions: ${response.totalSize}`);
116
- *
117
- * @example
118
- * // Find sessions from the last 7 days
119
- * const sevenDaysAgo = new Date();
120
- * sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
121
- *
122
- * const response = await scalekitClient.session.getUserSessions('usr_123456', {
123
- * filter: {
124
- * startTime: sevenDaysAgo,
125
- * status: ['active', 'logout']
126
- * }
127
- * });
128
- *
129
- * console.log(`Sessions in last 7 days: ${response.sessions.length}`);
130
- *
131
- *
132
- * @see {@link https://docs.scalekit.com/apis/#tag/sessions | List User Sessions API}
133
- * @see {@link getSession} - Get details of a specific session
134
- * @see {@link revokeSession} - Revoke a specific session
135
- * @see {@link revokeAllUserSessions} - Revoke all sessions for user
136
- */
137
- async getUserSessions(
138
- userId: string,
139
- options?: {
140
- pageSize?: number;
141
- pageToken?: string;
142
- filter?: {
143
- status?: string[];
144
- startTime?: Date;
145
- endTime?: Date;
146
- };
147
- }
148
- ): Promise<UserSessionDetails> {
149
- const filter = options?.filter
150
- ? create(UserSessionFilterSchema, {
151
- status: options.filter.status,
152
- startTime: options.filter.startTime ? timestampFromDate(options.filter.startTime) : undefined,
153
- endTime: options.filter.endTime ? timestampFromDate(options.filter.endTime) : undefined,
154
- })
155
- : undefined;
156
-
157
- const request = create(UserSessionDetailsRequestSchema, {
158
- userId,
159
- pageSize: options?.pageSize,
160
- pageToken: options?.pageToken,
161
- filter,
162
- });
163
-
164
- return this.coreClient.connectExec(this.client.getUserSessions, request);
165
- }
166
-
167
- /**
168
- * Immediately invalidates a specific user session by setting its status to 'revoked'.
169
- *
170
- * Terminates a single session, forcing the user to re-authenticate on that specific device.
171
- * Use this for session-level logout, terminating suspicious sessions, forcing re-authentication
172
- * on specific devices, or implementing "logout from this device" functionality. The revocation
173
- * is instantaneous and irreversible - once revoked, the session cannot be used for any future
174
- * API requests or application access.
175
- *
176
- * @param {string} sessionId - The session identifier to revoke (format: "ses_...")
177
- *
178
- * @returns {Promise<RevokeSessionResponse>} Response containing:
179
- * - sessionId: The ID of the revoked session
180
- * - userId: User who owned the session
181
- * - revokedAt: Timestamp when the session was revoked
182
- * - status: Updated session status ('revoked')
183
- *
184
- * @throws {Error} If the session is not found
185
- *
186
- * @example
187
- * // Revoke a specific session
188
- * const response = await scalekitClient.session.revokeSession('ses_123456');
189
- * console.log('Session revoked at:', response.revokedAt);
190
- * console.log('Status:', response.status); // 'revoked'
191
- *
192
- * @example
193
- * // Logout from specific device
194
- * app.post('/api/sessions/:sessionId/logout', async (req, res) => {
195
- * const { sessionId } = req.params;
196
- *
197
- * try {
198
- * await scalekitClient.session.revokeSession(sessionId);
199
- * res.json({ message: 'Session terminated successfully' });
200
- * } catch (error) {
201
- * res.status(500).json({ error: 'Failed to revoke session' });
202
- * }
203
- * });
204
- *
205
- * @example
206
- * // Revoke suspicious session
207
- * const session = await scalekitClient.session.getSession(sessionId);
208
- *
209
- * if (session.geoLocation?.country !== expectedCountry) {
210
- * console.log('Suspicious session detected');
211
- * console.log(`Location: ${session.geoLocation?.city}, ${session.geoLocation?.country}`);
212
- * console.log(`IP: ${session.ipAddress}`);
213
- *
214
- * await scalekitClient.session.revokeSession(sessionId);
215
- * console.log('Session revoked for security');
216
- *
217
- * // Send security alert to user
218
- * await sendSecurityAlert(session.userId, {
219
- * message: 'Unusual login location detected and session terminated',
220
- * location: session.geoLocation
221
- * });
222
- * }
223
- *
224
- * @example
225
- * // Revoke all non-current sessions for a user
226
- * const response = await scalekitClient.session.getUserSessions(userId, {
227
- * filter: { status: ['active'] }
228
- * });
229
- *
230
- * for (const session of response.sessions) {
231
- * if (session.sessionId !== currentSessionId) {
232
- * await scalekitClient.session.revokeSession(session.sessionId);
233
- * console.log(`Revoked session from: ${session.deviceInfo}`);
234
- * }
235
- * }
236
- *
237
- * @see {@link https://docs.scalekit.com/apis/#tag/sessions | Revoke Session API}
238
- * @see {@link revokeAllUserSessions} - Revoke all sessions for a user
239
- * @see {@link getUserSessions} - List user sessions to find suspicious ones
240
- * @see {@link getSession} - Get session details before revoking
241
- */
242
- async revokeSession(sessionId: string): Promise<RevokeSessionResponse> {
243
- return this.coreClient.connectExec(this.client.revokeSession, {
244
- sessionId,
245
- });
246
- }
247
-
248
- /**
249
- * Immediately invalidates all active sessions for a user across all devices and browsers.
250
- *
251
- * Terminates all active sessions simultaneously, forcing the user to re-authenticate everywhere.
252
- * Use this to implement global logout, force re-authentication after security incidents (password
253
- * compromise, suspicious activity), terminate all sessions following password reset, or revoke
254
- * access after account changes. Only active sessions are revoked; already expired, logout, or
255
- * previously revoked sessions remain unchanged. This operation is atomic, instantaneous, and
256
- * cannot be undone.
257
- *
258
- * @param {string} userId - The user identifier whose sessions should be revoked (format: "usr_...")
259
- *
260
- * @returns {Promise<RevokeAllUserSessionsResponse>} Response containing:
261
- * - revokedSessions: Array of all revoked session objects with details
262
- * - totalCount: Number of sessions that were revoked
263
- * - revokedAt: Timestamp when revocation occurred
264
- *
265
- * @throws {Error} When userId is missing or invalid
266
- * @throws {Error} If the user is not found
267
- *
268
- * @example
269
- * // Revoke all user sessions (global logout)
270
- * const response = await scalekitClient.session.revokeAllUserSessions('usr_123456');
271
- *
272
- * console.log(`Revoked ${response.totalCount} sessions`);
273
- * console.log('User must re-authenticate on all devices');
274
- *
275
- * @example
276
- * // Force logout after password reset
277
- * app.post('/api/users/:userId/reset-password', async (req, res) => {
278
- * const { userId } = req.params;
279
- * const { newPassword } = req.body;
280
- *
281
- * try {
282
- * // Update password
283
- * await updateUserPassword(userId, newPassword);
284
- *
285
- * // Revoke all existing sessions
286
- * const response = await scalekitClient.session.revokeAllUserSessions(userId);
287
- *
288
- * res.json({
289
- * message: 'Password updated successfully',
290
- * sessionsRevoked: response.totalCount,
291
- * note: 'Please log in again with your new password'
292
- * });
293
- * } catch (error) {
294
- * res.status(500).json({ error: 'Failed to reset password' });
295
- * }
296
- * });
297
- *
298
- * @example
299
- * // Force re-authentication after role change
300
- * async function updateUserRole(userId, newRole) {
301
- * await updateRole(userId, newRole);
302
- *
303
- * // Force re-authentication to apply new permissions
304
- * await scalekitClient.session.revokeAllUserSessions(userId);
305
- * console.log('User will re-authenticate with new role permissions');
306
- * }
307
- *
308
- * @see {@link https://docs.scalekit.com/apis/#tag/sessions | Revoke All Sessions API}
309
- * @see {@link revokeSession} - Revoke a specific session
310
- * @see {@link getUserSessions} - View user's active sessions before revoking
311
- */
312
- async revokeAllUserSessions(
313
- userId: string
314
- ): Promise<RevokeAllUserSessionsResponse> {
315
- if (!userId) {
316
- throw new Error("userId is required");
317
- }
318
-
319
- return this.coreClient.connectExec(this.client.revokeAllUserSessions, {
320
- userId,
321
- });
322
- }
323
- }
package/src/types/auth.ts DELETED
@@ -1,73 +0,0 @@
1
- export type User = {
2
- id: string;
3
- username: string | undefined;
4
- name: string;
5
- givenName: string;
6
- familyName: string | undefined;
7
- email: string;
8
- emailVerified: boolean;
9
- phoneNumber: string | undefined;
10
- phoneNumberVerified: boolean | undefined;
11
- profile: string | undefined;
12
- picture: string | undefined;
13
- gender: string | undefined;
14
- birthDate: string | undefined;
15
- zoneInfo: string | undefined;
16
- locale: string | undefined;
17
- updatedAt: string | undefined;
18
- identities: Identity[];
19
- metadata: string | undefined;
20
- }
21
-
22
- export type Identity = {
23
- connectionId: string;
24
- organizationId: string;
25
- connectionType: string;
26
- providerName: string;
27
- social: boolean;
28
- providerRawAttributes: string;
29
- }
30
-
31
- export type IdTokenClaimIdentity = {
32
- connection_id: string;
33
- organization_id: string;
34
- connection_type: string;
35
- provider_name: string;
36
- social: boolean;
37
- provider_raw_attributes: string;
38
- }
39
-
40
- export type IdTokenClaim = {
41
- sub: string;
42
- name: string;
43
- preferred_username: string | undefined;
44
- given_name: string;
45
- family_name: string | undefined;
46
- email: string;
47
- email_verified: boolean;
48
- phone_number: string | undefined;
49
- phone_number_verified: boolean | undefined;
50
- profile: string | undefined;
51
- picture: string | undefined;
52
- gender: string | undefined;
53
- birthdate: string | undefined;
54
- zoneinfo: string | undefined;
55
- locale: string | undefined;
56
- updated_at: string | undefined;
57
- identities: IdTokenClaimIdentity[];
58
- metadata: string | undefined;
59
- }
60
-
61
- export type TokenResponse = {
62
- access_token: string;
63
- id_token: string;
64
- expires_in: number;
65
- refresh_token: string;
66
- }
67
-
68
- export type IdpInitiatedLoginClaims ={
69
- connection_id: string;
70
- organization_id: string;
71
- login_hint: string;
72
- relay_state?: string;
73
- }
@@ -1,12 +0,0 @@
1
- export type OrganizationSettings = {
2
- features: Feature[];
3
- }
4
-
5
- export type Feature = {
6
- name: string;
7
- enabled: boolean;
8
- }
9
-
10
- export type OrganizationUserManagementSettingsInput = {
11
- maxAllowedUsers?: number | null;
12
- }
@@ -1,50 +0,0 @@
1
- import { User } from './auth';
2
-
3
- export enum GrantType {
4
- AuthorizationCode = 'authorization_code',
5
- RefreshToken = 'refresh_token',
6
- ClientCredentials = 'client_credentials',
7
- }
8
-
9
- export type AuthorizationUrlOptions = {
10
- connectionId?: string;
11
- organizationId?: string;
12
- scopes?: string[];
13
- state?: string;
14
- nonce?: string;
15
- domainHint?: string;
16
- loginHint?: string;
17
- codeChallenge?: string;
18
- codeChallengeMethod?: string;
19
- provider?: string;
20
- prompt?: string;
21
- }
22
-
23
- export type AuthenticationOptions = {
24
- codeVerifier?: string;
25
- }
26
-
27
- export type TokenValidationOptions = {
28
- issuer?: string;
29
- audience?: string[];
30
- requiredScopes?: string[];
31
- }
32
-
33
- export type AuthenticationResponse = {
34
- user: User;
35
- idToken: string;
36
- accessToken: string;
37
- expiresIn: number;
38
- refreshToken: string;
39
- }
40
-
41
- export type RefreshTokenResponse = {
42
- accessToken: string;
43
- refreshToken: string;
44
- }
45
-
46
- export interface LogoutUrlOptions {
47
- idTokenHint?: string;
48
- postLogoutRedirectUri?: string;
49
- state?: string;
50
- }
package/src/types/user.ts DELETED
@@ -1,21 +0,0 @@
1
- export interface CreateUserRequest {
2
- email: string;
3
- externalId?: string;
4
- phoneNumber?: string;
5
- userProfile?: {
6
- firstName?: string;
7
- lastName?: string;
8
- };
9
- metadata?: Record<string, string>;
10
- sendInvitationEmail?: boolean;
11
- }
12
-
13
- export interface UpdateUserRequest {
14
- email?: string;
15
- externalId?: string;
16
- userProfile?: {
17
- firstName?: string;
18
- lastName?: string;
19
- };
20
- metadata?: Record<string, string>;
21
- }