All files / blong-gogo/src/adapter/server keycloak.ts

81.1% Statements 644/794
41.26% Branches 52/126
90% Functions 9/10
81.1% Lines 644/794

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 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 7951x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 43x                   1x 43x       43x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x   43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 43x 10x 10x 10x 10x 10x 10x 10x 10x 2x 2x                 10x 10x 10x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 10x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 1x 1x 1x 1x 10x 10x 10x 2x 2x 2x 2x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x                 10x 10x                 10x 10x                     10x 10x                     10x 10x   10x 10x 43x 43x 9x 9x 9x 9x 9x 9x 9x 9x 2x 2x 2x 2x 9x 9x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 1x 1x 1x 1x 9x 9x 9x 1x 1x 1x 1x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x   9x 9x 43x 43x 8x 8x 8x 8x 8x 8x 8x 8x 2x 2x 2x 2x         2x 2x 2x 2x 8x 8x 8x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x   1x 1x 1x 1x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 2x 2x 2x 2x 2x 2x         2x 2x 2x 2x 2x 2x 8x 8x   8x 8x 43x 43x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x                 7x 7x 7x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 1x 1x 1x 1x 7x 7x             7x 7x             7x 7x   7x 7x 43x 43x 9x 9x 9x 9x 9x 9x 9x 9x 2x 2x 2x 2x 9x 9x 9x 3x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 2x 2x 2x 2x 9x 9x   9x 9x 43x                                                           43x 43x 43x 43x 43x 43x 10x 43x 43x 9x 43x 43x 8x 43x 43x 7x 43x 43x 9x 43x   43x 43x   43x 43x 2x 2x 2x 2x 2x 2x 2x 2x 2x                 2x 2x 43x 1x 1x  
import {
    adapter,
    type Adapter,
    type Errors,
    type IErrorMap,
    type IMeta,
} from '@feasibleone/blong/types';
import KcAdminClient from '@keycloak/keycloak-admin-client';
import got from 'got';
 
export interface IConfig {
    keycloak: {
        baseUrl: string;
        realmName?: string;
        username?: string;
        password?: string;
        clientId?: string;
        clientSecret?: string;
        grantType?: 'password' | 'client_credentials';
        totp?: string;
        requestConfig?: {
            timeout?: number;
            headers?: Record<string, string>;
        };
    };
    context: {
        kcAdminClient?: KcAdminClient;
    };
}
 
const errorMap: IErrorMap = {
    'keycloak.generic': 'Keycloak Error',
    'keycloak.invalid': 'Invalid Keycloak Operation',
    'keycloak.notFound': 'Keycloak Resource Not Found',
    'keycloak.exists': 'Keycloak Resource Already Exists',
    'keycloak.unauthorized': 'Keycloak Unauthorized',
    'keycloak.forbidden': 'Keycloak Access Forbidden',
    'keycloak.missingKey': 'Missing key value for {key}',
    'keycloak.authFailed': 'Keycloak authentication failed',
    'keycloak.invalidRealm': 'Invalid or missing realm',
};
 
let _errors: Errors<typeof errorMap>;
 
export default adapter<IConfig>(({utError}) => {
    _errors ||= utError.register(errorMap);
    let _authenticated = false;
 
    return {
        activation: {
            default: {
                type: 'keycloak',
            },
        },
        async start() {
            const kcAdminClient = new KcAdminClient({
                baseUrl: this.config.keycloak.baseUrl,
                realmName: this.config.keycloak.realmName || 'master',
                // requestOptions: {
                //     agent: new https.Agent({
                //         requestCert: true,
                //         rejectUnauthorized: false,
                //     }),
                // },
            });
 
            this.config.context = {kcAdminClient};
            _authenticated = false;
 
            super.connect();
            return super.start();
        },
        async authenticate(
            this: Adapter<IConfig>,
            {
                grantType = this.config.keycloak.grantType || 'password',
                clientId = this.config.keycloak.clientId || 'admin-cli',
                clientSecret = this.config.keycloak.clientSecret,
                username = this.config.keycloak.username,
                password = this.config.keycloak.password,
                totp = this.config.keycloak.totp,
            }: {
                grantType?: string;
                clientId?: string;
                clientSecret?: string;
                username?: string;
                password?: string;
                totp?: string;
            } = {},
            $meta?: IMeta,
        ) {
            if (_authenticated) return;
            // Authenticate with Keycloak
            try {
                if (grantType === 'password') {
                    if (!username || !password) {
                        throw _errors['keycloak.missingKey']({key: 'username or password'});
                    }
                    await this.config.context.kcAdminClient!.auth({
                        grantType: grantType as 'password',
                        clientId,
                        username,
                        password,
                        totp,
                    });
                } else if (grantType === 'client_credentials') {
                    if (!this.config.keycloak.clientId || !this.config.keycloak.clientSecret) {
                        throw _errors['keycloak.missingKey']({key: 'clientId or clientSecret'});
                    }
                    await this.config.context.kcAdminClient!.auth({
                        grantType: grantType as 'client_credentials',
                        clientId,
                        clientSecret,
                    });
                }
                _authenticated = true;
            } catch (cause) {
                if (typeof (cause as {type?: string}).type === 'string') throw cause;
                throw this.error(_errors['keycloak.authFailed'](cause), $meta as IMeta);
            }
        },
        async stop(...params: unknown[]) {
            let result;
            try {
                // No specific cleanup needed for Keycloak admin client
                _authenticated = false;
            } finally {
                this.config.context = {};
                result = await super.stop(...params);
            }
            return result;
        },
        async exec(
            params:
                | ({
                      realm?: string;
                      id?: string;
                      username?: string;
                      email?: string;
                      firstName?: string;
                      lastName?: string;
                      enabled?: boolean;
                      emailVerified?: boolean;
                      password?: string;
                      temporary?: boolean;
                      groupId?: string;
                      groupName?: string;
                      roleName?: string;
                      roleId?: string;
                      clientId?: string;
                      clientUuid?: string;
                      name?: string;
                      description?: string;
                      protocol?: string;
                      publicClient?: boolean;
                      bearerOnly?: boolean;
                      standardFlowEnabled?: boolean;
                      implicitFlowEnabled?: boolean;
                      directAccessGrantsEnabled?: boolean;
                      serviceAccountsEnabled?: boolean;
                      authorizationServicesEnabled?: boolean;
                      attributes?: Record<string, unknown>;
                      roles?: string[];
                      groups?: string[];
                      max?: number;
                      first?: number;
                      search?: string;
                      briefRepresentation?: boolean;
                  } & Record<string, unknown>)
                | unknown[],
            $meta: IMeta,
        ) {
            const {method} = $meta;
            const [, resourceType, operation] = method!.split('.');
            const targetRealm =
                (!Array.isArray(params) && params.realm) ||
                this.config.keycloak.realmName ||
                'master';
            await (
                this as unknown as {
                    authenticate: (args: unknown, $meta?: IMeta) => Promise<void>;
                }
            ).authenticate({}, $meta);
            const client = this.config.context.kcAdminClient!;
            client.setConfig({realmName: targetRealm});
            const config = this.config;
 
            const adapter = {
                async handleUserOperations(
                    operation: string,
                    params: unknown[] | Record<string, unknown>,
                    client: KcAdminClient,
                ): Promise<unknown> {
                    const handleParams = Array.isArray(params) ? {} : params;
 
                    switch (operation) {
                        case 'get': {
                            const {id, username} = handleParams;
                            if (id) return await client.users.findOne({id: id as string});
                            if (username) {
                                const users = await client.users.find({
                                    username: username as string,
                                });
                                return users[0] || null;
                            }
                            throw _errors['keycloak.missingKey']({key: 'id or username'});
                        }
 
                        case 'list':
                        case 'find': {
                            const {
                                max,
                                first,
                                search,
                                email,
                                firstName,
                                lastName,
                                briefRepresentation = true,
                            } = handleParams;
                            return await client.users.find({
                                max: max as number,
                                first: first as number,
                                search: search as string,
                                email: email as string,
                                firstName: firstName as string,
                                lastName: lastName as string,
                                briefRepresentation: briefRepresentation as boolean,
                            });
                        }
 
                        case 'create':
                        case 'add': {
                            const {
                                username: newUsername,
                                email: newEmail,
                                firstName: newFirstName,
                                lastName: newLastName,
                                enabled = true,
                                emailVerified = false,
                            } = handleParams;
                            if (!newUsername)
                                throw _errors['keycloak.missingKey']({key: 'username'});
                            return await client.users.create({
                                username: newUsername as string,
                                email: newEmail as string,
                                firstName: newFirstName as string,
                                lastName: newLastName as string,
                                enabled: enabled as boolean,
                                emailVerified: emailVerified as boolean,
                            });
                        }
 
                        case 'update':
                        case 'edit': {
                            const {id: userId, realm: _realm, ...updateData} = handleParams;
                            if (!userId) throw _errors['keycloak.missingKey']({key: 'id'});
                            return await client.users.update({id: userId as string}, updateData);
                        }
 
                        case 'delete':
                        case 'remove': {
                            const {id: deleteId} = handleParams;
                            if (!deleteId) throw _errors['keycloak.missingKey']({key: 'id'});
                            return await client.users.del({id: deleteId as string});
                        }
 
                        case 'setPassword': {
                            const {id: pwUserId, password, temporary = false} = handleParams;
                            if (!pwUserId || !password)
                                throw _errors['keycloak.missingKey']({key: 'id or password'});
                            return await client.users.resetPassword({
                                id: pwUserId as string,
                                credential: {
                                    type: 'password',
                                    value: password as string,
                                    temporary: temporary as boolean,
                                },
                            });
                        }
 
                        case 'addToGroup': {
                            const {id: groupUserId, groupId} = handleParams;
                            if (!groupUserId || !groupId)
                                throw _errors['keycloak.missingKey']({key: 'id or groupId'});
                            return await client.users.addToGroup({
                                id: groupUserId as string,
                                groupId: groupId as string,
                            });
                        }
 
                        case 'removeFromGroup': {
                            const {id: ungroupUserId, groupId: removeGroupId} = handleParams;
                            if (!ungroupUserId || !removeGroupId)
                                throw _errors['keycloak.missingKey']({key: 'id or groupId'});
                            return await client.users.delFromGroup({
                                id: ungroupUserId as string,
                                groupId: removeGroupId as string,
                            });
                        }
 
                        case 'addRealmRole': {
                            const {id: roleUserId, roles} = handleParams;
                            if (!roleUserId || !roles)
                                throw _errors['keycloak.missingKey']({key: 'id or roles'});
                            return await client.users.addRealmRoleMappings({
                                id: roleUserId as string,
                                roles: Array.isArray(roles)
                                    ? (roles as {id: string; name: string}[])
                                    : [],
                            });
                        }
 
                        case 'removeRealmRole': {
                            const {id: unroleUserId, roles: removeRoles} = handleParams;
                            if (!unroleUserId || !removeRoles)
                                throw _errors['keycloak.missingKey']({key: 'id or roles'});
                            return await client.users.delRealmRoleMappings({
                                id: unroleUserId as string,
                                roles: Array.isArray(removeRoles)
                                    ? (removeRoles as {id: string; name: string}[])
                                    : [],
                            });
                        }
 
                        default:
                            throw _errors['keycloak.invalid']();
                    }
                },
 
                async handleGroupOperations(
                    operation: string,
                    params: unknown[] | Record<string, unknown>,
                    client: KcAdminClient,
                ): Promise<unknown> {
                    const handleParams = Array.isArray(params) ? {} : params;
 
                    switch (operation) {
                        case 'get': {
                            const {id} = handleParams;
                            if (!id) throw _errors['keycloak.missingKey']({key: 'id'});
                            return await client.groups.findOne({id: id as string});
                        }
 
                        case 'list':
                        case 'find': {
                            const {
                                max: groupMax,
                                first: groupFirst,
                                search: groupSearch,
                                briefRepresentation: groupBrief = true,
                            } = handleParams;
                            return await client.groups.find({
                                max: groupMax as number,
                                first: groupFirst as number,
                                search: groupSearch as string,
                                briefRepresentation: groupBrief as boolean,
                            });
                        }
 
                        case 'create':
                        case 'add': {
                            const {name, path, attributes, subGroups} = handleParams;
                            if (!name) throw _errors['keycloak.missingKey']({key: 'name'});
                            return await client.groups.create({
                                name: name as string,
                                path: path as string,
                                attributes: attributes as Record<string, unknown>,
                                subGroups: subGroups,
                            } as Parameters<KcAdminClient['groups']['create']>[0]);
                        }
 
                        case 'update':
                        case 'edit': {
                            const {id: groupId, realm: _realm, ...updateData} = handleParams;
                            if (!groupId) throw _errors['keycloak.missingKey']({key: 'id'});
                            return await client.groups.update({id: groupId as string}, updateData);
                        }
 
                        case 'delete':
                        case 'remove': {
                            const {id: deleteId} = handleParams;
                            if (!deleteId) throw _errors['keycloak.missingKey']({key: 'id'});
                            return await client.groups.del({id: deleteId as string});
                        }
 
                        case 'members': {
                            const {
                                id: membersGroupId,
                                max: memberMax,
                                first: memberFirst,
                                briefRepresentation: memberBrief = true,
                            } = handleParams;
                            if (!membersGroupId) throw _errors['keycloak.missingKey']({key: 'id'});
                            return await client.groups.listMembers({
                                id: membersGroupId as string,
                                max: memberMax as number,
                                first: memberFirst as number,
                                briefRepresentation: memberBrief as boolean,
                            });
                        }
 
                        default:
                            throw _errors['keycloak.invalid']();
                    }
                },
 
                async handleRoleOperations(
                    operation: string,
                    params: unknown[] | Record<string, unknown>,
                    client: KcAdminClient,
                ): Promise<unknown> {
                    const handleParams = Array.isArray(params) ? {} : params;
 
                    switch (operation) {
                        case 'get': {
                            const {roleName, clientUuid} = handleParams;
                            if (!roleName) throw _errors['keycloak.missingKey']({key: 'roleName'});
 
                            if (clientUuid) {
                                return await client.clients.findRole({
                                    id: clientUuid as string,
                                    roleName: roleName as string,
                                });
                            } else {
                                return await client.roles.findOneByName({name: roleName as string});
                            }
                        }
 
                        case 'list':
                        case 'find': {
                            const {
                                clientUuid: listClientUuid,
                                max: roleMax,
                                first: roleFirst,
                                search: roleSearch,
                                briefRepresentation: roleBrief = true,
                            } = handleParams;
 
                            if (listClientUuid) {
                                return await client.clients.listRoles({
                                    id: listClientUuid as string,
                                });
                            } else {
                                return await client.roles.find({
                                    max: roleMax as number,
                                    first: roleFirst as number,
                                    search: roleSearch as string,
                                    briefRepresentation: roleBrief as boolean,
                                });
                            }
                        }
 
                        case 'create':
                        case 'add': {
                            const {
                                roleName: newRoleName,
                                description,
                                clientUuid: createClientUuid,
                                attributes,
                            } = handleParams;
                            if (!newRoleName)
                                throw _errors['keycloak.missingKey']({key: 'roleName'});
 
                            if (createClientUuid) {
                                return await client.clients.createRole({
                                    id: createClientUuid as string,
                                    name: newRoleName as string,
                                    description: description as string,
                                    attributes: attributes
                                        ? (attributes as Record<string, string[]>)
                                        : undefined,
                                });
                            } else {
                                return await client.roles.create({
                                    name: newRoleName as string,
                                    description: description as string,
                                    attributes: attributes
                                        ? (attributes as Record<string, string[]>)
                                        : undefined,
                                });
                            }
                        }
 
                        case 'update':
                        case 'edit': {
                            const {
                                roleName: updateRoleName,
                                clientUuid: updateClientUuid,
                                realm: _realm,
                                ...updateData
                            } = handleParams;
                            if (!updateRoleName)
                                throw _errors['keycloak.missingKey']({key: 'roleName'});
 
                            if (updateClientUuid) {
                                return await client.clients.updateRole(
                                    {
                                        id: updateClientUuid as string,
                                        roleName: updateRoleName as string,
                                    },
                                    updateData,
                                );
                            } else {
                                return await client.roles.updateByName(
                                    {name: updateRoleName as string},
                                    {name: updateRoleName as string, ...updateData},
                                );
                            }
                        }
 
                        case 'delete':
                        case 'remove': {
                            const {roleName: deleteRoleName, clientUuid: deleteClientUuid} =
                                handleParams;
                            if (!deleteRoleName)
                                throw _errors['keycloak.missingKey']({key: 'roleName'});
 
                            if (deleteClientUuid) {
                                return await client.clients.delRole({
                                    id: deleteClientUuid as string,
                                    roleName: deleteRoleName as string,
                                });
                            } else {
                                return await client.roles.delByName({
                                    name: deleteRoleName as string,
                                });
                            }
                        }
 
                        default:
                            throw _errors['keycloak.invalid']();
                    }
                },
 
                async handleClientOperations(
                    operation: string,
                    params: unknown[] | Record<string, unknown>,
                    client: KcAdminClient,
                ): Promise<unknown> {
                    const handleParams = Array.isArray(params) ? {} : params;
 
                    switch (operation) {
                        case 'get': {
                            const {id, clientId} = handleParams;
                            if (id) return await client.clients.findOne({id: id as string});
                            if (clientId) {
                                const clients = await client.clients.find({
                                    clientId: clientId as string,
                                });
                                return clients[0] || null;
                            }
                            throw _errors['keycloak.missingKey']({key: 'id or clientId'});
                        }
 
                        case 'list':
                        case 'find': {
                            const {
                                clientId: searchClientId,
                                max: clientMax,
                                first: clientFirst,
                                viewableOnly = false,
                            } = handleParams;
                            return await client.clients.find({
                                clientId: searchClientId as string,
                                max: clientMax as number,
                                first: clientFirst as number,
                                viewableOnly: viewableOnly as boolean,
                            });
                        }
 
                        case 'create':
                        case 'add': {
                            const {
                                clientId: newClientId,
                                name,
                                description,
                                enabled = true,
                                publicClient = false,
                                bearerOnly = false,
                                standardFlowEnabled = true,
                                implicitFlowEnabled = false,
                                directAccessGrantsEnabled = true,
                                serviceAccountsEnabled = false,
                                authorizationServicesEnabled = false,
                                protocol = 'openid-connect',
                                attributes,
                                redirectUris,
                                webOrigins,
                                adminUrl,
                                baseUrl,
                                rootUrl,
                            } = handleParams;
                            if (!newClientId)
                                throw _errors['keycloak.missingKey']({key: 'clientId'});
 
                            return await client.clients.create({
                                clientId: newClientId as string,
                                name: name as string,
                                description: description as string,
                                enabled: enabled as boolean,
                                publicClient: publicClient as boolean,
                                bearerOnly: bearerOnly as boolean,
                                standardFlowEnabled: standardFlowEnabled as boolean,
                                implicitFlowEnabled: implicitFlowEnabled as boolean,
                                directAccessGrantsEnabled: directAccessGrantsEnabled as boolean,
                                serviceAccountsEnabled: serviceAccountsEnabled as boolean,
                                authorizationServicesEnabled:
                                    authorizationServicesEnabled as boolean,
                                protocol: protocol as string,
                                attributes: attributes as Record<string, unknown>,
                                redirectUris: redirectUris as string[],
                                webOrigins: webOrigins as string[],
                                adminUrl: adminUrl as string,
                                baseUrl: baseUrl as string,
                                rootUrl: rootUrl as string,
                            });
                        }
 
                        case 'update':
                        case 'edit': {
                            const {
                                id: clientUpdateId,
                                realm: _realm,
                                ...clientUpdateData
                            } = handleParams;
                            if (!clientUpdateId) throw _errors['keycloak.missingKey']({key: 'id'});
                            return await client.clients.update(
                                {id: clientUpdateId as string},
                                clientUpdateData,
                            );
                        }
 
                        case 'delete':
                        case 'remove': {
                            const {id: deleteClientId} = handleParams;
                            if (!deleteClientId) throw _errors['keycloak.missingKey']({key: 'id'});
                            return await client.clients.del({id: deleteClientId as string});
                        }
 
                        case 'secret': {
                            const {id: secretClientId} = handleParams;
                            if (!secretClientId) throw _errors['keycloak.missingKey']({key: 'id'});
                            return await client.clients.getClientSecret({
                                id: secretClientId as string,
                            });
                        }
 
                        case 'regenerateSecret': {
                            const {id: regenClientId} = handleParams;
                            if (!regenClientId) throw _errors['keycloak.missingKey']({key: 'id'});
                            return await client.clients.generateNewClientSecret({
                                id: regenClientId as string,
                            });
                        }
 
                        default:
                            throw _errors['keycloak.invalid']();
                    }
                },
 
                async handleRealmOperations(
                    operation: string,
                    params: unknown[] | Record<string, unknown>,
                    client: KcAdminClient,
                ): Promise<unknown> {
                    const handleParams = Array.isArray(params) ? {} : params;
 
                    switch (operation) {
                        case 'get': {
                            const {realm} = handleParams;
                            if (!realm) throw _errors['keycloak.missingKey']({key: 'realm'});
                            return await client.realms.findOne({realm: realm as string});
                        }
 
                        case 'list':
                        case 'find':
                            return await client.realms.find();
 
                        case 'create':
                        case 'add': {
                            const {
                                realm: newRealm,
                                displayName,
                                enabled = true,
                                ...realmData
                            } = handleParams;
                            if (!newRealm) throw _errors['keycloak.missingKey']({key: 'realm'});
                            return await client.realms.create({
                                realm: newRealm as string,
                                displayName: displayName as string,
                                enabled: enabled as boolean,
                                ...realmData,
                            });
                        }
 
                        case 'update':
                        case 'edit': {
                            const {realm: updateRealm, ...realmUpdateData} = handleParams;
                            if (!updateRealm) throw _errors['keycloak.missingKey']({key: 'realm'});
                            return await client.realms.update(
                                {realm: updateRealm as string},
                                realmUpdateData,
                            );
                        }
 
                        case 'delete':
                        case 'remove': {
                            const {realm: deleteRealm} = handleParams;
                            if (!deleteRealm) throw _errors['keycloak.missingKey']({key: 'realm'});
                            return await client.realms.del({realm: deleteRealm as string});
                        }
 
                        default:
                            throw _errors['keycloak.invalid']();
                    }
                },
                async handleTokenOperations(
                    operation: string,
                    params: unknown[] | Record<string, unknown>,
                ): Promise<unknown> {
                    const handleParams = Array.isArray(params) ? {} : params;

                    switch (operation) {
                        case 'create': {
                            const {realm, clientId, clientSecret, grantType} = handleParams;
                            if (!realm) throw _errors['keycloak.missingKey']({key: 'realm'});
                            return (
                                await got.post({
                                    url: new URL(
                                        `/realms/${realm}/protocol/openid-connect/token`,
                                        config.keycloak.baseUrl,
                                    ),
                                    form: {
                                        client_id: clientId,
                                        client_secret: clientSecret,
                                        grant_type: grantType,
                                    },
                                    responseType: 'json',
                                })
                            ).body;
                        }

                        default:
                            throw _errors['keycloak.invalid']();
                    }
                },
            };
 
            try {
                switch (resourceType.toLowerCase()) {
                    case 'user':
                    case 'users':
                        return await adapter.handleUserOperations(operation, params, client);
                    case 'group':
                    case 'groups':
                        return await adapter.handleGroupOperations(operation, params, client);
                    case 'role':
                    case 'roles':
                        return await adapter.handleRoleOperations(operation, params, client);
                    case 'client':
                    case 'clients':
                        return await adapter.handleClientOperations(operation, params, client);
                    case 'realm':
                    case 'realms':
                        return await adapter.handleRealmOperations(operation, params, client);
                    case 'token':
                        return await adapter.handleTokenOperations(operation, params);
 
                    default:
                        throw _errors['keycloak.invalid']();
                }
            } catch (error: unknown) {
                // Re-throw already-typed blong errors without wrapping them
                if (typeof (error as {type?: string}).type === 'string') throw error;
                const keycloakError = error as {
                    response?: {status?: number; data?: {error?: string}};
                };
                let err;
                if (keycloakError.response?.status === 404) {
                    err = _errors['keycloak.notFound']();
                } else if (keycloakError.response?.status === 401) {
                    err = _errors['keycloak.unauthorized']();
                } else if (keycloakError.response?.status === 403) {
                    err = _errors['keycloak.forbidden']();
                } else if (keycloakError.response?.status === 409) {
                    err = _errors['keycloak.exists']();
                } else {
                    err = _errors['keycloak.generic']();
                }
                throw this.error(err, $meta);
            }
        },
    };
});