All files / lib cognito-admin.ts

0% Statements 0/81
0% Branches 0/48
0% Functions 0/21
0% Lines 0/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Cognito Admin SDK Helpers
 * Server-side utilities for managing Cognito users via Admin APIs
 * @see JCN-4 Phase 7: Wire E2E Tests to Real Backend
 */
import {
  CognitoIdentityProviderClient,
  AdminGetUserCommand,
  AdminDisableUserCommand,
  AdminEnableUserCommand,
  AdminDeleteUserCommand,
  AdminUpdateUserAttributesCommand,
  ListUsersCommand,
  type AttributeType,
  type UserType,
} from "@aws-sdk/client-cognito-identity-provider";
import outputs from "../../amplify_outputs.json";
 
// Initialize client with region from Amplify outputs
const cognitoClient = new CognitoIdentityProviderClient({
  region: outputs.auth.aws_region,
});
 
const USER_POOL_ID = outputs.auth.user_pool_id;
 
/**
 * B2C User as returned by our API
 */
export interface B2CUser {
  id: string;
  email: string;
  status: "Active" | "Disabled" | "Deleted";
  tenantId: string | null;
  userType: string | null;
  role: string | null;
  platformRole: string | null;
  createdAt: string;
  lastLogin?: string;
  emailVerified: boolean;
}
 
/**
 * Convert Cognito AttributeType array to a key-value object
 */
function attributesToObject(
  attributes?: AttributeType[]
): Record<string, string> {
  if (!attributes) return {};
  return attributes.reduce(
    (acc, attr) => {
      if (attr.Name && attr.Value) {
        acc[attr.Name] = attr.Value;
      }
      return acc;
    },
    {} as Record<string, string>
  );
}
 
/**
 * Convert Cognito UserType to our B2CUser format
 */
function cognitoUserToB2CUser(user: UserType): B2CUser {
  const attrs = attributesToObject(user.Attributes);
 
  // Determine status from Cognito user status
  let status: "Active" | "Disabled" | "Deleted" = "Active";
  if (!user.Enabled) {
    status = "Disabled";
  }
  if (user.UserStatus === "ARCHIVED") {
    status = "Deleted";
  }
 
  return {
    id: user.Username || "",
    email: attrs["email"] || "",
    status,
    tenantId: attrs["custom:tenant_id"] || null,
    userType: attrs["custom:user_type"] || null,
    role: attrs["custom:role"] || null,
    platformRole: attrs["custom:platform_role"] || null,
    createdAt: user.UserCreateDate?.toISOString() || "",
    lastLogin: user.UserLastModifiedDate?.toISOString(),
    emailVerified: attrs["email_verified"] === "true",
  };
}
 
/**
 * List all users in the Cognito User Pool
 * Supports pagination and filtering
 */
export async function listUsers(options?: {
  limit?: number;
  paginationToken?: string;
  filter?: string;
}): Promise<{
  users: B2CUser[];
  paginationToken?: string;
}> {
  const command = new ListUsersCommand({
    UserPoolId: USER_POOL_ID,
    Limit: options?.limit || 60,
    PaginationToken: options?.paginationToken,
    Filter: options?.filter,
  });
 
  const response = await cognitoClient.send(command);
 
  return {
    users: (response.Users || []).map(cognitoUserToB2CUser),
    paginationToken: response.PaginationToken,
  };
}
 
/**
 * List users filtered by user type (b2c, b2b)
 */
export async function listB2CUsers(options?: {
  limit?: number;
  paginationToken?: string;
}): Promise<{
  users: B2CUser[];
  paginationToken?: string;
}> {
  // Note: Cognito doesn't support filtering by custom attributes directly
  // We fetch all users and filter client-side
  const result = await listUsers({
    limit: options?.limit,
    paginationToken: options?.paginationToken,
  });
 
  // Filter to only B2C users (user_type = 'b2c')
  const b2cUsers = result.users.filter(
    (user) => user.userType === "b2c" || user.userType === null
  );
 
  return {
    users: b2cUsers,
    paginationToken: result.paginationToken,
  };
}
 
/**
 * List users with platform_role = 'super_admin'
 */
export async function listSuperAdmins(options?: {
  limit?: number;
  paginationToken?: string;
}): Promise<{
  users: B2CUser[];
  paginationToken?: string;
}> {
  const result = await listUsers({
    limit: options?.limit,
    paginationToken: options?.paginationToken,
  });
 
  // Filter to only super admins
  const superAdmins = result.users.filter(
    (user) => user.platformRole === "super_admin"
  );
 
  return {
    users: superAdmins,
    paginationToken: result.paginationToken,
  };
}
 
/**
 * Get a specific user by username (email or ID)
 */
export async function getUser(username: string): Promise<B2CUser | null> {
  try {
    const command = new AdminGetUserCommand({
      UserPoolId: USER_POOL_ID,
      Username: username,
    });
 
    const response = await cognitoClient.send(command);
 
    const attrs = attributesToObject(response.UserAttributes);
 
    let status: "Active" | "Disabled" | "Deleted" = "Active";
    if (!response.Enabled) {
      status = "Disabled";
    }
 
    return {
      id: response.Username || "",
      email: attrs["email"] || "",
      status,
      tenantId: attrs["custom:tenant_id"] || null,
      userType: attrs["custom:user_type"] || null,
      role: attrs["custom:role"] || null,
      platformRole: attrs["custom:platform_role"] || null,
      createdAt: response.UserCreateDate?.toISOString() || "",
      lastLogin: response.UserLastModifiedDate?.toISOString(),
      emailVerified: attrs["email_verified"] === "true",
    };
  } catch (error) {
    if ((error as Error).name === "UserNotFoundException") {
      return null;
    }
    throw error;
  }
}
 
/**
 * Disable a user account
 */
export async function disableUser(username: string): Promise<void> {
  const command = new AdminDisableUserCommand({
    UserPoolId: USER_POOL_ID,
    Username: username,
  });
 
  await cognitoClient.send(command);
}
 
/**
 * Enable a user account
 */
export async function enableUser(username: string): Promise<void> {
  const command = new AdminEnableUserCommand({
    UserPoolId: USER_POOL_ID,
    Username: username,
  });
 
  await cognitoClient.send(command);
}
 
/**
 * Delete a user account (soft delete - marks as deleted)
 */
export async function deleteUser(username: string): Promise<void> {
  const command = new AdminDeleteUserCommand({
    UserPoolId: USER_POOL_ID,
    Username: username,
  });
 
  await cognitoClient.send(command);
}
 
/**
 * Grant super admin role to a user
 */
export async function grantSuperAdmin(username: string): Promise<void> {
  const command = new AdminUpdateUserAttributesCommand({
    UserPoolId: USER_POOL_ID,
    Username: username,
    UserAttributes: [
      {
        Name: "custom:platform_role",
        Value: "super_admin",
      },
    ],
  });
 
  await cognitoClient.send(command);
}
 
/**
 * Revoke super admin role from a user
 */
export async function revokeSuperAdmin(username: string): Promise<void> {
  const command = new AdminUpdateUserAttributesCommand({
    UserPoolId: USER_POOL_ID,
    Username: username,
    UserAttributes: [
      {
        Name: "custom:platform_role",
        Value: "",
      },
    ],
  });
 
  await cognitoClient.send(command);
}
 
/**
 * Search users by email (partial match)
 */
export async function searchUsersByEmail(emailQuery: string): Promise<B2CUser[]> {
  // Cognito supports email prefix search
  const filter = `email ^= "${emailQuery}"`;
 
  try {
    const result = await listUsers({ filter });
    return result.users;
  } catch {
    // Fallback: fetch all and filter client-side
    const result = await listUsers({ limit: 60 });
    return result.users.filter((user) =>
      user.email.toLowerCase().includes(emailQuery.toLowerCase())
    );
  }
}
 
/**
 * List users belonging to a specific tenant
 */
export async function listUsersByTenant(tenantId: string): Promise<B2CUser[]> {
  // Cognito doesn't support filtering by custom attributes directly
  // We fetch all users and filter client-side
  const result = await listUsers({ limit: 60 });
 
  return result.users.filter(
    (user) => user.tenantId === tenantId
  );
}
 
/**
 * Update a user's role within their tenant
 */
export async function updateUserRole(
  username: string,
  role: "owner" | "admin" | "member"
): Promise<void> {
  const command = new AdminUpdateUserAttributesCommand({
    UserPoolId: USER_POOL_ID,
    Username: username,
    UserAttributes: [
      {
        Name: "custom:role",
        Value: role,
      },
    ],
  });
 
  await cognitoClient.send(command);
}
 
/**
 * Remove a user from their tenant (set tenant_id to empty)
 */
export async function removeUserFromTenant(username: string): Promise<void> {
  const command = new AdminUpdateUserAttributesCommand({
    UserPoolId: USER_POOL_ID,
    Username: username,
    UserAttributes: [
      {
        Name: "custom:tenant_id",
        Value: "",
      },
      {
        Name: "custom:role",
        Value: "",
      },
      {
        Name: "custom:user_type",
        Value: "b2c", // Revert to B2C user after leaving org
      },
    ],
  });
 
  await cognitoClient.send(command);
}
 
/**
 * Set user's tenant and role (used when accepting invitation)
 */
export async function assignUserToTenant(
  username: string,
  tenantId: string,
  role: "owner" | "admin" | "member"
): Promise<void> {
  const command = new AdminUpdateUserAttributesCommand({
    UserPoolId: USER_POOL_ID,
    Username: username,
    UserAttributes: [
      {
        Name: "custom:tenant_id",
        Value: tenantId,
      },
      {
        Name: "custom:role",
        Value: role,
      },
      {
        Name: "custom:user_type",
        Value: "org",
      },
    ],
  });
 
  await cognitoClient.send(command);
}
 
export { USER_POOL_ID, cognitoClient };