All files / realm/blong-access/adapter/db accessModel.ts

84.96% Statements 780/918
59.32% Branches 70/118
91.3% Functions 21/23
84.96% Lines 780/918

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 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 9191x 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 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 135x 135x 135x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 150x 150x 150x 150x 150x 150x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 149x 149x 149x 2x 2x 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 1003x 1003x 1003x 781x 781x 781x 781x 781x 51x 51x 51x     1x 1x 477x 477x 477x 477x 1x 1x 7x 7x 7x 7x 7x 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 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 83x 341x 341x 341x 341x 83x 1x 1x 1x 1x 1x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 1x 1x 1x 1x 1x 1x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 116x 116x 497x 497x 34x 34x 497x 82x 82x 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 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x               2x     3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                   2x 2x 2x 1x 1x 1x 1x 1x 1x 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 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 1x 1x 1x 2x 2x 2x 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 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 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 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x  
/**
 * Shared persistence helpers for the access UI models (`access.db` group).
 *
 * Injected library functions: every member below is handed to the group's
 * handlers as `lib.<member>`, and a handler takes the type from `AccessModelLib`
 * so its call sites stay typed:
 *
 *     const model = lib as unknown as AccessModelLib;
 *
 * Handlers reach `core.resource.ensure` by delegation (`super.coreResourceEnsure`,
 * which is how a library realm is called), pass the knex query builder in, and
 * every helper works on that alone.
 */
import crypto from 'node:crypto';
 
import {type IMeta, library} from '@feasibleone/blong';
 
import {type CredentialParams} from './password.ts';
 
type KnexQb = any;
 
/** The verdict of the adapter's record-level ACL evaluation. */
export type AclCheckVerdict = {
    /** `false` when the entity does not opt into the ACL (or the action is not RBAC-managed). */
    guarded: boolean;
    allowed: boolean;
    /** The guarded entity (`subject.object`) the action belongs to. */
    entity?: string;
    /** The method's predicate (`get` / `edit` / `remove` / `add` / `find` / …). */
    predicate?: string;
    /** The resolved action resource — reused by `access.session.verify`. */
    actionId?: Buffer;
};
 
/**
 * The adapter's record-level ACL surface, reached through the port from a realm
 * handler (`this as unknown as AclHost`) — the runtime package is not a library
 * dependency of a realm, so this is the only way to reuse the SQL the generic
 * CRUD already applies.  See `core/blong-gogo/src/adapter/server/acl.ts`.
 */
export type AclHost = {
    aclCheck(
        params: {
            entity?: string;
            method?: string;
            recordId?: string;
            scopeIds?: string[];
            actorId?: string;
        },
        $meta?: IMeta,
    ): Promise<AclCheckVerdict>;
    /** Raw predicate + bindings for filtering a list — apply with `whereRaw`. */
    aclFilter(
        params: {entity: string; method?: string; actorId?: string},
        $meta?: IMeta,
    ): Promise<{sql: string; bindings: unknown[]} | undefined>;
};
 
/**
 * Join the display names of an ACL row's principal, action and target, so the
 * exceptions page and the effective panel are readable without a lookup per
 * row.  `joinResourceNames` covers the two resource id columns; the action name
 * needs its own lookup because `access_action`'s PK is the resource itself.
 */
async function attachAclNames<T extends Record<string, unknown>>(
    qb: KnexQb,
    rows: T[],
): Promise<Array<T & {principalName?: string; actionName?: string; targetName?: string}>> {
    if (!rows.length) return rows;
    const withPrincipal = await joinResourceNames(qb, rows, 'principalId', 'principalName');
    const withTarget = await joinResourceNames(qb, withPrincipal, 'targetId', 'targetName');
    const actionIds = [
        ...new Set(
            withTarget
                .map(row => row.actionId)
                .filter((id): id is string => typeof id === 'string'),
        ),
    ];
    if (!actionIds.length) return withTarget;
    const actions = (await qb('access_action as at')
        .join('core_resource as r', 'r.resourceId', 'at.actionId')
        .whereIn(
            'at.actionId',
            actionIds.map(id => Buffer.from(binHex(id) as string, 'hex')),
        )
        .select('at.actionId', 'r.resourceName as actionName')) as Array<{
        actionId: Buffer;
        actionName: string;
    }>;
    const byId = new Map(actions.map(a => [bufToBase64(a.actionId), a.actionName]));
    return withTarget.map(row => ({
        ...row,
        actionName: byId.get(String(row.actionId)),
    }));
}
 
/**
 * Options for a dropdown listing graph resources of the given types, labelled
 * `<short type>: <resource name>` so an administrator can tell the kinds apart.
 */
/**
 * How a graph resource is labelled in the ACL dropdowns and in the ACL matrix:
 * `<short type>: <resource name>`, so an administrator can tell the kinds apart.
 */
function resourceLabel(typeAlias: string, resourceName: string): string {
    const shortOf = new Map(
        Object.entries(SHORT_TYPE_ALIASES).map(([short, full]) => [full, short]),
    );
    return `${shortOf.get(typeAlias) ?? typeAlias}: ${resourceName}`;
}
 
async function resourceOptions(
    qb: KnexQb,
    typeAliases: string[],
): Promise<Array<{value: string; label: string}>> {
    const rows = (await qb('core_resource as r')
        .join('core_type as t', 't.typeId', 'r.typeId')
        .whereIn('t.typeAlias', typeAliases)
        .select('r.resourceId', 'r.resourceName', 't.typeAlias')) as Array<{
        resourceId: Buffer;
        resourceName: string;
        typeAlias: string;
    }>;
    return rows
        .map(row => ({
            value: bufToBase64(row.resourceId) ?? '',
            label: resourceLabel(row.typeAlias, row.resourceName),
        }))
        .sort((a, b) => a.label.localeCompare(b.label));
}
 
/** The standard CRUD predicates a capability can grant in the action pivot grid. */
const STANDARD_CRUD_PREDICATES = ['find', 'get', 'add', 'edit', 'remove'] as const;
 
/**
 * Highest usable role bit.  `access_role.roleBit` is the bit *position* of the
 * role in a minted token's `per` permission mask (`access.permission.list` packs
 * it into a 1024-bit mask), so the whole space has to stay inside it.
 */
const ROLE_BIT_MAX = 1023;
 
/** Result of the shared `access.role.ensure` helper (see `accessRoleEnsure.ts`). */
export type EnsuredRole = {role: {roleId: string; roleName: string; roleBit: number}};
 
/**
 * Short type names used by ACL declarations, seeds and UI dropdowns, mapped to
 * the full `core_type.typeAlias` of the entity they refer to.
 */
const SHORT_TYPE_ALIASES: Record<string, string> = {
    user: 'access.user',
    role: 'access.role',
    capability: 'access.capability',
    action: 'access.action',
    unit: 'party.unit',
    organization: 'party.organization',
    person: 'party.person',
    /** The wildcard target: an ACL rule anchored on it matches every record. */
    all: 'access.any',
};
 
/**
 * Normalise a `binary(16)` value (Buffer or base64 string) to a hex string.
 * Returns `undefined` for empty values. The wire representation of binary
 * columns is base64 (see the knex adapter `prepareResultRow`).
 */
function binHex(value: Buffer | string | undefined): string | undefined {
    if (value === undefined || value === null) return undefined;
    if (Buffer.isBuffer(value)) return value.toString('hex');
    if (typeof value === 'string') {
        if (!value) return undefined;
        // Base64-encoded `binary(16)` (the wire format) — decode to hex.
        const buf = Buffer.from(value, 'base64');
        if (buf.length === 16) return buf.toString('hex');
        // Dashed hex UUID (e.g. `core.resource.ensure`) — strip dashes.
        return value.replace(/-/g, '');
    }
    return undefined;
}
 
/** Convert a `binary(16)` value to its base64 wire representation. */
function bufToBase64(value: Buffer | string | undefined): string | undefined {
    if (value === undefined || value === null) return undefined;
    return Buffer.isBuffer(value) ? value.toString('base64') : value;
}
 
/** Fetch the `core_resource.resourceName` for a resource-backed entity row. */
async function resourceNameFor(qb: KnexQb, resourceId: Buffer | string): Promise<string | null> {
    const hex = binHex(resourceId);
    if (!hex) return null;
    const row = (await qb('core_resource')
        .where('resourceId', Buffer.from(hex, 'hex'))
        .first('resourceName')) as {resourceName: string} | undefined;
    return row?.resourceName ?? null;
}
 
/**
 * The `core_resource.resourceId` a name and a type alias name, or `undefined`.
 *
 * The name is how a person refers to an entity — a login, a role, a capability — while
 * every table refers to it by id. `access.user.remove` takes either, so the caller that
 * reads a list of logins does not have to decode the ids first. The type alias is part of
 * the question, not a filter a caller may forget: a role and a user may be named alike.
 */
async function resourceIdByName(
    qb: KnexQb,
    resourceName: string,
    typeAlias: string,
): Promise<Buffer | undefined> {
    const row = (await qb('core_resource as r')
        .join('core_type as t', 't.typeId', 'r.typeId')
        .where('r.resourceName', resourceName)
        .where('t.typeAlias', typeAlias)
        .first('r.resourceId')) as {resourceId: Buffer} | undefined;
    return row?.resourceId;
}
 
/**
 * Enrich rows with the resource name for their resource-backed key, e.g.
 * `{roleId, roleBit, description}` → `{..., roleName}`.
 */
async function joinResourceNames<T extends Record<string, unknown>>(
    qb: KnexQb,
    rows: T[],
    idField: string,
    nameField: string,
): Promise<T[]> {
    const ids = rows
        .map(r => binHex(r[idField] as Buffer | string))
        .filter((x): x is string => !!x);
    if (!ids.length) return rows;
    const found = (await qb('core_resource')
        .whereIn(
            'resourceId',
            ids.map(hex => Buffer.from(hex, 'hex')),
        )
        .select('resourceId', 'resourceName')) as Array<{resourceId: Buffer; resourceName: string}>;
    const names = new Map<string, string>();
    for (const r of found) names.set(r.resourceId.toString('hex'), r.resourceName);
    return rows.map(row => {
        const hex = binHex(row[idField] as Buffer | string);
        const name = hex ? names.get(hex) : undefined;
        return name !== undefined ? ({...row, [nameField]: name} as T) : row;
    });
}
 
/**
 * Object ids (hex) of the graph edges `subjectId -predicate-> objectId`
 * (`core_triple`). Returns `[]` when the subject has no such edges.
 */
async function listEdgeObjectIds(
    qb: KnexQb,
    subjectId: Buffer | string,
    predicateName: string,
): Promise<string[]> {
    const hex = binHex(subjectId);
    if (!hex) return [];
    const rows = (await qb('core_triple')
        .where('subjectId', Buffer.from(hex, 'hex'))
        .where('predicateName', predicateName)
        .select('objectId')) as Array<{objectId: Buffer}>;
    return rows.map(r => r.objectId.toString('hex'));
}
 
/**
 * Rows of the objects reachable from `subjectId` via `predicateName`, joined
 * with their resource name and serialized as base64 ids (matching the wire
 * format the model pivot tables expect).
 */
async function edgeRowsWithNames<T extends Record<string, unknown>>(
    qb: KnexQb,
    subjectId: Buffer | string,
    predicateName: string,
    table: string,
    idField: string,
    nameField: string,
): Promise<T[]> {
    const ids = await listEdgeObjectIds(qb, subjectId, predicateName);
    if (!ids.length) return [];
    const rows = (await qb(table).whereIn(
        idField,
        ids.map(hex => Buffer.from(hex, 'hex')),
    )) as T[];
    const named = await joinResourceNames(qb, rows, idField, nameField);
    return named.map(row => ({...row, [idField]: bufToBase64(row[idField] as Buffer)}) as T);
}
 
/**
 * Split a standard-CRUD action name into its entity + predicate.
 *
 * Every action whose name ends with a capitalised standard CRUD predicate
 * (`accessUserFind`, `accessRoleEdit`, …) collapses to one entity row in the
 * capability action pivot (`accessUser`, `accessRole`, …). Returns `undefined`
 * for actions with a non-CRUD predicate (e.g. `accessSessionClose`) and for
 * anything not matching the `access` + `Entity` + capitalised predicate shape.
 */
function crudActionParts(actionName: string): {entity: string; predicate: string} | undefined {
    for (const p of STANDARD_CRUD_PREDICATES) {
        const suffix = p[0].toUpperCase() + p.slice(1);
        if (actionName.length > suffix.length && actionName.endsWith(suffix)) {
            return {entity: actionName.slice(0, -suffix.length), predicate: p};
        }
    }
    return undefined;
}
 
/** `accessUser` + `find` → `accessUserFind`. */
function crudActionName(entityName: string, predicate: string): string {
    return `${entityName}${predicate[0].toUpperCase()}${predicate.slice(1)}`;
}
 
/**
 * The action-assignment rows of a capability (from its `hasAction` edges):
 * - `action` — every standard-CRUD action collapses to ONE pivot row per
 *   entity (`accessUser`, `accessRole`, …) with boolean columns for the
 *   standard CRUD predicates, derived from the granted `access` + `Entity` +
 *   capitalised predicate actions. Used by the CRUD pivot grid on the
 *   capability Open form.
 * - `otherAction` — every remaining action (non-CRUD predicates and anything
 *   not of the `access` + `Entity` + capitalised predicate shape), each with a
 *   `granted` boolean, shown in the "Other Actions" card inside the Action tab.
 */
async function capabilityActionRows(
    qb: KnexQb,
    capabilityId: Buffer | string,
): Promise<{action: Array<Record<string, unknown>>; otherAction: Array<Record<string, unknown>>}> {
    const ids = await listEdgeObjectIds(qb, capabilityId, 'hasAction');
    const byEntity = new Map<string, Set<string>>();
    const otherAction: Array<Record<string, unknown>> = [];
    if (ids.length) {
        const rows = (await qb('access_action').whereIn(
            'actionId',
            ids.map(hex => Buffer.from(hex, 'hex')),
        )) as Array<{actionId: Buffer; description?: string; [k: string]: unknown}>;
        const named = await joinResourceNames(qb, rows, 'actionId', 'actionName');
        for (const row of named) {
            const actionName = (row.actionName as string) ?? '';
            const parts = crudActionParts(actionName);
            if (parts) {
                let predicates = byEntity.get(parts.entity);
                if (!predicates) {
                    predicates = new Set();
                    byEntity.set(parts.entity, predicates);
                }
                predicates.add(parts.predicate);
            } else {
                otherAction.push({
                    actionId: bufToBase64(row.actionId),
                    actionName,
                    granted: true,
                });
            }
        }
    }
    const action: Array<Record<string, unknown>> = [];
    for (const [entity, predicates] of byEntity) {
        const row: Record<string, unknown> = {entityName: entity};
        for (const p of STANDARD_CRUD_PREDICATES) row[p] = predicates.has(p);
        action.push(row);
    }
    action.sort((a, b) => String(a.entityName).localeCompare(String(b.entityName)));
    return {action, otherAction};
}
 
/**
 * Map submitted CRUD pivot rows to their `access` + `Entity` + capitalised
 * predicate action object ids. Each ticked column ensures its action resource
 * exists (the CRUD actions are not pre-seeded) and returns its hex id.
 * Non-ticked columns and rows without an `entityName` are skipped.
 */
async function crudPivotActionIds(
    qb: KnexQb,
    coreResourceEnsure: (
        params: Record<string, unknown>,
        $meta: IMeta,
    ) => Promise<{resourceId: Buffer | string}> | {resourceId: Buffer | string},
    rows: Array<Record<string, unknown>>,
    $meta: IMeta,
): Promise<string[]> {
    const ids: string[] = [];
    for (const row of rows) {
        if (typeof row.entityName !== 'string' || !row.entityName) continue;
        for (const p of STANDARD_CRUD_PREDICATES) {
            if (row[p] === true) {
                const actionName = crudActionName(row.entityName, p);
                const {resourceId} = await coreResourceEnsure(
                    {
                        name: actionName,
                        typeAlias: 'access.action',
                        table: 'access_action',
                        extraColumns: {description: `${actionName} action`},
                        keyName: 'actionId',
                    },
                    $meta,
                );
                const hex = binHex(resourceId);
                if (!hex) throw new Error(`Could not resolve action resource id for ${actionName}`);
                ids.push(hex);
            }
        }
    }
    return ids;
}
 
/**
 * The role ids a `role` array of an add/edit form asks for, in hex, in order.
 *
 * A row may name its role by id (what the screens submit — the role picker knows
 * the ids) or by name. The name was accepted by the gateway schema and then
 * silently DROPPED: `role: [{roleName: 'Admin'}]` stored no edge at all, so the
 * caller saw a success and a user that could not log in. Resolving it here keeps
 * the two forms equivalent, and an unknown name is an error rather than a grant
 * that quietly did not happen.
 */
async function resolveRoleIds(
    qb: KnexQb,
    rows: Array<{roleId?: string; roleName?: string; granted?: boolean}>,
): Promise<string[]> {
    const ids: string[] = [];
    for (const row of rows) {
        if (row.granted === false) continue;
        const byId = binHex(row.roleId);
        if (byId) {
            ids.push(byId);
            continue;
        }
        const roleName = typeof row.roleName === 'string' ? row.roleName.trim() : '';
        if (!roleName) continue;
        const found = await qb
            .select('role.roleId as roleId')
            .from('access_role as role')
            .join('core_resource as res', 'res.resourceId', 'role.roleId')
            .where('res.resourceName', roleName)
            .first();
        const hex = binHex(found?.roleId);
        if (!hex) throw new Error(`Unknown role: ${roleName}`);
        ids.push(hex);
    }
    return ids;
}
 
/**
 * Bring `subjectId -predicate-> objectId` edges in line with `objectHexIds`.
 *
 * One transaction: the missing edges, the stale ones, and the single
 * `access_pathRefresh()` that follows them. This is the path the access UI
 * manages roles, users and capabilities through, so it must not be able to commit
 * an edge without its rebuild — a write that landed while the rebuild did not
 * would leave a caller's grants lagging until some later write happened to
 * rebuild, and a crash between two transactions is exactly that. Rolling the whole
 * change back on failure is the same guarantee the generic CRUD's own edge sync
 * gives (`syncGraphEdges` in the knex adapter, which this mirrors).
 */
async function syncEdges(
    qb: KnexQb,
    subjectId: Buffer | string,
    predicateName: string,
    objectHexIds: string[],
): Promise<void> {
    const subjectHex = binHex(subjectId);
    if (!subjectHex) return;
    const existing = await listEdgeObjectIds(qb, subjectHex, predicateName);
    const existingSet = new Set(existing);
    const target = new Set(objectHexIds);
    const toAdd = objectHexIds.filter(id => !existingSet.has(id));
    const toRemove = existing.filter(id => !target.has(id));
    if (!toAdd.length && !toRemove.length) return;
    await qb.transaction(async (trx: KnexQb) => {
        if (toAdd.length) {
            // One batched statement, and `ignore` rather than a duplicate-key
            // error: two edits racing on the same subject compute the same
            // missing set, and the loser's rows are already there.
            await trx('core_triple')
                .insert(
                    toAdd.map(objectId => ({
                        subjectId: Buffer.from(subjectHex, 'hex'),
                        predicateName,
                        objectId: Buffer.from(objectId, 'hex'),
                    })),
                )
                .onConflict()
                .ignore();
        }
        if (toRemove.length) {
            await trx('core_triple')
                .where('subjectId', Buffer.from(subjectHex, 'hex'))
                .where('predicateName', predicateName)
                .whereIn(
                    'objectId',
                    toRemove.map(id => Buffer.from(id, 'hex')),
                )
                .del();
        }
        await trx.raw('CALL access_pathRefresh()');
    });
}
 
/**
 * Credential rows of a user (safe columns only — never the hash/salt/params),
 * serialized like the knex adapter: binary `userId` as base64, `credentialId`
 * as-is.
 */
async function listCredentials(
    qb: KnexQb,
    userId: Buffer | string,
): Promise<Array<Record<string, unknown>>> {
    const hex = binHex(userId);
    if (!hex) return [];
    const rows = (await qb('access_credential')
        .where('userId', Buffer.from(hex, 'hex'))
        .orderBy('credentialId', 'asc')
        .select('credentialId', 'userId', 'credentialType', 'isActive', 'expiresAt')) as Array<
        Record<string, unknown>
    >;
    return rows.map(row => ({...row, userId: bufToBase64(row.userId as Buffer)}));
}
 
/**
 * Sync the submitted credential rows with the stored ones for a user.
 *
 * Rows carrying a `credentialId` are updated in place; rows without one are
 * inserted (hashing `password`/`secret` for `password`/`clientSecret` types);
 * stored rows absent from the submission are removed. Callers must only invoke
 * this when the form actually submitted a `credential` array (see the
 * `accessUserEdit` guard).
 */
async function syncCredentials(
    qb: KnexQb,
    deps: {
        hashPassword: (
            password: string,
            salt: string,
            source?: Partial<CredentialParams> | null,
        ) => {hash: string; params: Record<string, unknown>};
        credentialPolicyParams: (
            qb: KnexQb,
            type: string,
        ) => Promise<Partial<CredentialParams> | null>;
    },
    userIdHex: string,
    rows: Array<Record<string, unknown>>,
): Promise<void> {
    const userIdBuf = Buffer.from(userIdHex, 'hex');
    const existing = (await qb('access_credential')
        .where('userId', userIdBuf)
        .select('credentialId')) as Array<{credentialId: number}>;
    const existingIds = new Set(existing.map(r => r.credentialId));
    const submittedIds = new Set<number>();
    for (const row of rows) {
        const credentialId = Number(row.credentialId);
        if (Number.isInteger(credentialId) && credentialId > 0) {
            submittedIds.add(credentialId);
            const patch: Record<string, unknown> = {};
            if (typeof row.credentialType === 'string') patch.credentialType = row.credentialType;
            if (row.isActive !== undefined) patch.isActive = row.isActive ? 1 : 0;
            if (row.expiresAt !== undefined) patch.expiresAt = row.expiresAt || null;
            if (Object.keys(patch).length) {
                await qb('access_credential').where('credentialId', credentialId).update(patch);
            }
        } else if (typeof row.credentialType === 'string' && row.credentialType) {
            // New credential — hash the secret so only the digest is stored.
            const secret =
                row.credentialType === 'google'
                    ? (row.googleSubjectId as string) || ''
                    : ((row.password ?? row.secret) as string) || '';
            const salt = crypto.randomUUID();
            const policyParams = await deps.credentialPolicyParams(qb, row.credentialType);
            const {hash, params} = deps.hashPassword(secret, salt, policyParams);
            await qb('access_credential').insert({
                userId: userIdBuf,
                credentialType: row.credentialType,
                credentialHash: hash,
                credentialSalt: salt,
                // `*JSON` column — the knex adapter stores this object as JSON.
                credentialParamsJSON: params,
                isActive: row.isActive ? 1 : 0,
            });
        }
    }
    for (const id of existingIds) {
        if (!submittedIds.has(id)) {
            await qb('access_credential').where('credentialId', id).del();
        }
    }
}
 
/**
 * The verbs the ACL matrix exposes as tri-state columns. A cell is `''` (no
 * rule — the entity/verb is governed by RBAC alone), `allow` or `deny`.
 */
const ACL_MATRIX_PREDICATES = STANDARD_CRUD_PREDICATES;
 
/** One row of the ACL matrix: a (target scope, entity) pair with verb cells. */
export type AclMatrixRow = {
    /** Target scope resource id (base64, as the wire round-trips it). */
    targetId?: string;
    /** Target scope display name (read-only, joined by `aclMatrixRows`). */
    targetName?: string;
    /** `accessUser`, `partyPerson`, … — the entity whose actions are restricted. */
    entityName?: string;
    [verb: string]: unknown;
};
 
/** The `(entity, verb) → effect` rules an ACL matrix row asks for. */
type DesiredAclRule = {actionHex: string; targetHex: string; effect: string};
 
/** Dependencies the ACL matrix sync needs from the calling handler. */
export type AclMatrixDeps = {
    /**
     * `core.resource.ensure`, as the calling handler delegates it
     * (`(p, m) => super.coreResourceEnsure(p, m, trx)`).  Deliberately loose: the
     * delegated call is untyped, and a narrower concrete function type would not
     * accept it — the params are contravariant and the result widens to `unknown`.
     */
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    coreResourceEnsure: (params: any, $meta: IMeta) => Promise<any>;
    /** Mints the `aclId` of a new rule (a ULID, as the column requires). */
    newAclId: () => Buffer;
};
 
/** `actionHex|targetHex` — the identity of a scope-level ACL rule. */
function aclRuleKey(actionHex: string, targetHex: string): string {
    return `${actionHex}|${targetHex}`;
}
 
/**
 * Split an action resource name into its entity + CRUD predicate, accepting both
 * the runtime's camelCase form (`partyPersonEdit`) and the dotted form the seeds
 * register (`party.person.edit`) — the ACL matches action names with the dots
 * ignored, so the matrix must read them the same way.
 */
function aclActionParts(actionName: string): {entity: string; predicate: string} | undefined {
    const segments = actionName.split('.');
    if (segments.length > 1) {
        const predicate = segments[segments.length - 1];
        if (!(STANDARD_CRUD_PREDICATES as readonly string[]).includes(predicate)) {
            return undefined;
        }
        const entity = segments
            .slice(0, -1)
            .map((part, index) => (index === 0 ? part : part[0].toUpperCase() + part.slice(1)))
            .join('');
        return {entity, predicate};
    }
    return crudActionParts(actionName);
}
 
/**
 * The `access_action` resource id (hex) of one entity + CRUD verb, matched the
 * way the *runtime* matches it — the dots of `party.person.edit` are ignored, so
 * that action and `partyPersonEdit` are the same action.  An action the seeds
 * already registered is reused; one that does not exist yet is created.
 *
 * Matching instead of creating is essential: two rows with the same
 * dot-stripped name would make the runtime's pattern lookup pick either one, and
 * a rule pointing at the other would silently not apply.
 */
async function aclActionResourceId(
    qb: KnexQb,
    coreResourceEnsure: AclMatrixDeps['coreResourceEnsure'],
    entityName: string,
    predicate: string,
    $meta: IMeta,
): Promise<string> {
    const actionName = crudActionName(entityName, predicate);
    const existing = (await qb('access_action as at')
        .join('core_resource as r', 'r.resourceId', 'at.actionId')
        .whereRaw("LOWER(REPLACE(r.resourceName, '.', '')) = ?", [
            actionName.replaceAll('.', '').toLowerCase(),
        ])
        .first('at.actionId as actionId')) as {actionId: Buffer} | undefined;
    const existingHex = binHex(existing?.actionId);
    if (existingHex) return existingHex;
    const {resourceId} = await coreResourceEnsure(
        {
            name: actionName,
            typeAlias: 'access.action',
            table: 'access_action',
            extraColumns: {description: `${actionName} action`},
            keyName: 'actionId',
        },
        $meta,
    );
    const hex = binHex(resourceId);
    if (!hex) throw new Error(`Could not resolve action resource id for ${actionName}`);
    return hex;
}
 
/**
 * Read a principal's scope-level `access_acl` rules as ACL matrix rows: one row
 * per `(target scope, entity)` pair with a tri-state cell per CRUD verb, derived
 * from the action name (`accessUserFind` → entity `accessUser`, verb `find`).
 *
 * Only `targetKind: 'scope'` rules are returned — they are the ones the matrix
 * writes; `record` rules stay in the ACL Rules page, where the exact record is
 * chosen.
 *
 * The scope name is formatted exactly like the `access.aclTarget` dropdown's
 * option label ({@link resourceLabel}) — that label is the pivot's row identity,
 * so a bare `core_resource.resourceName` would never match its option and the
 * stored rules would render as an empty row.
 */
async function aclMatrixRows(qb: KnexQb, principalId: Buffer | string): Promise<AclMatrixRow[]> {
    const hex = binHex(principalId);
    if (!hex) return [];
    const rows = (await qb('access_acl as ab')
        .join('core_resource as ar', 'ar.resourceId', 'ab.actionId')
        .where('ab.principalId', Buffer.from(hex, 'hex'))
        .where('ab.targetKind', 'scope')
        .where('ab.isActive', 1)
        .select(
            'ab.targetId as targetId',
            'ab.effect as effect',
            'ar.resourceName as actionName',
        )) as Array<{targetId: Buffer; effect: string; actionName: string}>;
    if (!rows.length) return [];
    const byKey = new Map<string, AclMatrixRow>();
    for (const row of rows) {
        const targetId = bufToBase64(row.targetId);
        const parts = aclActionParts(String(row.actionName));
        if (!targetId || !parts) continue;
        const key = `${targetId}|${parts.entity}`;
        let entry = byKey.get(key);
        if (!entry) {
            entry = {targetId, entityName: parts.entity};
            for (const p of ACL_MATRIX_PREDICATES) entry[p] = '';
            byKey.set(key, entry);
        }
        entry[parts.predicate] = row.effect === 'deny' ? 'deny' : 'allow';
    }
    const items = [...byKey.values()];
    const targetRows = (await qb('core_resource as r')
        .join('core_type as t', 't.typeId', 'r.typeId')
        .whereIn(
            'r.resourceId',
            items.map(item => Buffer.from(item.targetId as string, 'base64')),
        )
        .select(
            'r.resourceId as resourceId',
            'r.resourceName as resourceName',
            't.typeAlias as typeAlias',
        )) as Array<{
        resourceId: Buffer;
        resourceName: string;
        typeAlias: string;
    }>;
    const labelOf = new Map(
        targetRows.map(row => [
            bufToBase64(row.resourceId) ?? '',
            resourceLabel(row.typeAlias, row.resourceName),
        ]),
    );
    const named = items.map(item => ({...item, targetName: labelOf.get(item.targetId ?? '')}));
    return named
        .filter(item => item.targetName !== undefined)
        .sort(
            (a, b) =>
                String(a.targetName ?? '').localeCompare(String(b.targetName ?? '')) ||
                String(a.entityName ?? '').localeCompare(String(b.entityName ?? '')),
        );
}
 
/**
 * Bring a principal's scope-level `access_acl` rules in line with the submitted
 * ACL matrix.
 *
 * Each `allow`/`deny` cell ensures the `access` + `Entity` + capitalised verb
 * action resource (`partyPersonEdit`, …) and asks for the rule
 * `(principal, action, target scope, effect)`. An empty cell asks for the rule
 * to be gone, which is how an implicit grant is narrowed back and how an
 * explicitly forbidden record is released. Rules of other principals and
 * `record`-kind rules are never touched.
 */
async function syncAclMatrix(
    qb: KnexQb,
    deps: AclMatrixDeps,
    principalId: Buffer | string,
    matrix: AclMatrixRow[],
    $meta: IMeta,
): Promise<void> {
    const principalHex = binHex(principalId);
    if (!principalHex) return;
    const principalBuf = Buffer.from(principalHex, 'hex');
    const desired = new Map<string, DesiredAclRule>();
    for (const row of matrix) {
        const targetHex = binHex(row.targetId);
        const entityName =
            typeof row.entityName === 'string' && row.entityName ? row.entityName : undefined;
        if (!targetHex || !entityName) continue;
        for (const p of ACL_MATRIX_PREDICATES) {
            const value = row[p];
            if (value !== 'allow' && value !== 'deny') continue;
            const actionHex = await aclActionResourceId(
                qb,
                deps.coreResourceEnsure,
                entityName,
                p,
                $meta,
            );
            desired.set(aclRuleKey(actionHex, targetHex), {
                actionHex,
                targetHex,
                effect: value,
            });
        }
    }
    const existing = (await qb('access_acl')
        .where('principalId', principalBuf)
        .where('targetKind', 'scope')
        .select('actionId as actionId', 'targetId as targetId', 'effect as effect')) as Array<{
        actionId: Buffer;
        targetId: Buffer;
        effect: string;
    }>;
    const existingEffects = new Map<string, string>();
    for (const row of existing) {
        const key = aclRuleKey(binHex(row.actionId) ?? '', binHex(row.targetId) ?? '');
        existingEffects.set(key, String(row.effect));
        if (desired.has(key)) continue;
        await qb('access_acl')
            .where('principalId', principalBuf)
            .where('targetKind', 'scope')
            .where('actionId', row.actionId)
            .where('targetId', row.targetId)
            .del();
    }
    for (const [key, rule] of desired) {
        const present = existingEffects.get(key);
        if (present === rule.effect) continue;
        if (present !== undefined) {
            await qb('access_acl')
                .where('principalId', principalBuf)
                .where('targetKind', 'scope')
                .where('actionId', Buffer.from(rule.actionHex, 'hex'))
                .where('targetId', Buffer.from(rule.targetHex, 'hex'))
                .update({effect: rule.effect, isActive: 1});
            continue;
        }
        await qb('access_acl')
            .insert({
                aclId: deps.newAclId(),
                principalId: principalBuf,
                actionId: Buffer.from(rule.actionHex, 'hex'),
                targetId: Buffer.from(rule.targetHex, 'hex'),
                targetKind: 'scope',
                effect: rule.effect,
                isActive: 1,
            })
            .onConflict()
            .ignore();
    }
}
 
/**
 * The ACL/UI model helpers, as a handler sees them: `lib as unknown as AccessModelLib`.
 *
 * One bundle rather than a file per helper: these functions share the knex query
 * builder argument and the `core_resource` conventions, and a handler usually
 * needs several of them at once.
 */
export type AccessModelLib = {
    attachAclNames: typeof attachAclNames;
    resourceLabel: typeof resourceLabel;
    resourceOptions: typeof resourceOptions;
    STANDARD_CRUD_PREDICATES: typeof STANDARD_CRUD_PREDICATES;
    ROLE_BIT_MAX: typeof ROLE_BIT_MAX;
    SHORT_TYPE_ALIASES: typeof SHORT_TYPE_ALIASES;
    binHex: typeof binHex;
    bufToBase64: typeof bufToBase64;
    resourceNameFor: typeof resourceNameFor;
    resourceIdByName: typeof resourceIdByName;
    joinResourceNames: typeof joinResourceNames;
    listEdgeObjectIds: typeof listEdgeObjectIds;
    edgeRowsWithNames: typeof edgeRowsWithNames;
    crudActionParts: typeof crudActionParts;
    crudActionName: typeof crudActionName;
    capabilityActionRows: typeof capabilityActionRows;
    crudPivotActionIds: typeof crudPivotActionIds;
    syncEdges: typeof syncEdges;
    resolveRoleIds: typeof resolveRoleIds;
    listCredentials: typeof listCredentials;
    syncCredentials: typeof syncCredentials;
    ACL_MATRIX_PREDICATES: typeof ACL_MATRIX_PREDICATES;
    aclActionParts: typeof aclActionParts;
    aclActionResourceId: typeof aclActionResourceId;
    aclMatrixRows: typeof aclMatrixRows;
    syncAclMatrix: typeof syncAclMatrix;
};
 
export default library(
    (): AccessModelLib => ({
        attachAclNames,
        resourceLabel,
        resourceOptions,
        STANDARD_CRUD_PREDICATES,
        ROLE_BIT_MAX,
        SHORT_TYPE_ALIASES,
        binHex,
        bufToBase64,
        resourceNameFor,
        resourceIdByName,
        joinResourceNames,
        listEdgeObjectIds,
        edgeRowsWithNames,
        crudActionParts,
        crudActionName,
        capabilityActionRows,
        crudPivotActionIds,
        syncEdges,
        resolveRoleIds,
        listCredentials,
        syncCredentials,
        ACL_MATRIX_PREDICATES,
        aclActionParts,
        aclActionResourceId,
        aclMatrixRows,
        syncAclMatrix,
    }),
);