All files / realm/blong-gateway/adapter/db gatewayBundleMerge.ts

99.55% Statements 223/224
40% Branches 8/20
100% Functions 1/1
99.55% Lines 223/224

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 2251x 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 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 1x 3x 3x 3x 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 3x 3x 3x 3x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 3x 3x 3x 3x 3x 3x 1x  
import {type IMeta, handler} from '@feasibleone/blong';
 
import {splitNames, uuidBuf} from './gatewayUuid.ts';
 
type KnexQb = any;
 
/**
 * Create/merge API bundles plus plain capabilities/roles.
 *
 * Wire: `gateway.bundle.merge` — a bundle wraps an `access.role` whose
 * capabilities/actions are the bundle's authorized scopes.  Also accepts
 * generic `capability` (name → action list) and `role` (name → capability
 * list) maps so seeds can wire management capabilities onto roles (e.g. a
 * Developer role), keeping authorization uniform in the jwt plugin.
 *
 * Resource creation goes through the shared `core.resource.ensure` helper and
 * graph edges through the shared `core.triple.merge` helper (P3), so the seed
 * no longer hand-rolls `core_triple` inserts or `access_pathRefresh()`.
 */
export default handler(
    ({
        handler: {
            'db/accessRoleEnsure': accessRoleEnsure,
            'db/coreResourceEnsure': coreResourceEnsure,
            'db/coreTripleMerge': coreTripleMerge,
        },
    }) =>
        async function gatewayBundleMerge(
            params: {
                /** capabilityName → comma-separated action names. */
                capability?: Record<string, string>;
                /** roleName → comma-separated capability names. */
                role?: Record<string, string>;
                bundle?: Record<
                    string,
                    {
                        roleBit?: number;
                        /** Capability name to wrap. */
                        capability?: string;
                        /** Comma-separated action names granted by the capability. */
                        actions?: string;
                        baseMonthlyCredits?: number;
                        rateLimit?: number;
                        rateWindowSec?: number;
                        isActive?: boolean;
                        description?: string;
                    }
                >;
            },
            $meta: IMeta,
        ): Promise<{success: boolean}> {
            const qb: KnexQb = this.config?.context?.queryBuilder;
            if (!qb) throw new Error('Database not available');
 
            const triples: Array<{
                subjectId: string;
                predicateName: string;
                objectId: string;
            }> = [];
 
            // 1. Capabilities + their actions
            if (params.capability) {
                for (const [capabilityName, actionList] of Object.entries(params.capability)) {
                    const {resourceId: capabilityId} = await coreResourceEnsure<{
                        resourceId: string;
                    }>(
                        {
                            name: capabilityName,
                            typeAlias: 'access.capability',
                            table: 'access_capability',
                            extraColumns: {description: `${capabilityName} capability`},
                            keyName: 'capabilityId',
                        },
                        $meta,
                    );
                    for (const actionName of splitNames(actionList)) {
                        const {resourceId: actionId} = await coreResourceEnsure<{
                            resourceId: string;
                        }>(
                            {
                                name: actionName,
                                typeAlias: 'access.action',
                                table: 'access_action',
                                extraColumns: {description: `${actionName} action`},
                                keyName: 'actionId',
                            },
                            $meta,
                        );
                        triples.push({
                            subjectId: capabilityId,
                            predicateName: 'hasAction',
                            objectId: actionId,
                        });
                    }
                }
            }
 
            // 2. Roles + their capabilities
            if (params.role) {
                for (const [roleName, capabilityList] of Object.entries(params.role)) {
                    const {role: ensuredRole} = await accessRoleEnsure<{role: {roleId: string}}>(
                        {role: {roleName}},
                        $meta,
                    );
                    for (const capabilityName of splitNames(capabilityList)) {
                        const {resourceId: capabilityId} = await coreResourceEnsure<{
                            resourceId: string;
                        }>(
                            {
                                name: capabilityName,
                                typeAlias: 'access.capability',
                                table: 'access_capability',
                                extraColumns: {description: `${capabilityName} capability`},
                                keyName: 'capabilityId',
                            },
                            $meta,
                        );
                        triples.push({
                            subjectId: ensuredRole.roleId,
                            predicateName: 'hasCapability',
                            objectId: capabilityId,
                        });
                    }
                }
            }
 
            // 3. Bundles (role-wrapped capabilities with rate/credit metadata)
            if (params.bundle) {
                for (const [bundleName, bundleDef] of Object.entries(params.bundle)) {
                    // 1. Capability + actions
                    const capabilityName = bundleDef.capability ?? bundleName;
                    const actionNames = splitNames(bundleDef.actions ?? '');
                    for (const actionName of actionNames) {
                        const {resourceId: actionId} = await coreResourceEnsure<{
                            resourceId: string;
                        }>(
                            {
                                name: actionName,
                                typeAlias: 'access.action',
                                table: 'access_action',
                                extraColumns: {description: `${actionName} action`},
                                keyName: 'actionId',
                            },
                            $meta,
                        );
                        const {resourceId: capabilityId} = await coreResourceEnsure<{
                            resourceId: string;
                        }>(
                            {
                                name: capabilityName,
                                typeAlias: 'access.capability',
                                table: 'access_capability',
                                extraColumns: {description: `${capabilityName} capability`},
                                keyName: 'capabilityId',
                            },
                            $meta,
                        );
                        triples.push({
                            subjectId: capabilityId,
                            predicateName: 'hasAction',
                            objectId: actionId,
                        });
                    }
 
                    // 2. Role (the bundle) + hasCapability edges.  A declared bit
                    // is honoured; otherwise the framework allocates one.
                    const {role: bundleRole} = await accessRoleEnsure<{role: {roleId: string}}>(
                        {
                            role: {
                                roleName: bundleName,
                                description: `${bundleName} bundle role`,
                                ...(bundleDef.roleBit === undefined || bundleDef.roleBit === null
                                    ? {}
                                    : {roleBit: bundleDef.roleBit}),
                            },
                        },
                        $meta,
                    );
                    const roleId = bundleRole.roleId;
                    const {resourceId: capabilityId} = await coreResourceEnsure<{
                        resourceId: string;
                    }>(
                        {
                            name: capabilityName,
                            typeAlias: 'access.capability',
                            table: 'access_capability',
                            extraColumns: {description: `${capabilityName} capability`},
                            keyName: 'capabilityId',
                        },
                        $meta,
                    );
                    triples.push({
                        subjectId: roleId,
                        predicateName: 'hasCapability',
                        objectId: capabilityId,
                    });
 
                    // 3. Bundle metadata row
                    await qb('gateway_bundle')
                        .insert({
                            bundleId: uuidBuf(roleId),
                            roleId: uuidBuf(roleId),
                            isActive: bundleDef.isActive ?? 1,
                            baseMonthlyCredits: bundleDef.baseMonthlyCredits ?? 0,
                            rateLimit: bundleDef.rateLimit ?? 0,
                            rateWindowSec: bundleDef.rateWindowSec ?? 60,
                            description: bundleDef.description ?? null,
                        })
                        .onConflict(['bundleId'])
                        .merge({
                            isActive: bundleDef.isActive ?? 1,
                            baseMonthlyCredits: bundleDef.baseMonthlyCredits ?? 0,
                            rateLimit: bundleDef.rateLimit ?? 0,
                            rateWindowSec: bundleDef.rateWindowSec ?? 60,
                            description: bundleDef.description ?? null,
                        });
                }
            }
 
            await coreTripleMerge({triples, refreshPath: true}, $meta);
 
            return {success: true};
        },
);