All files / core/blong-gogo/src Gateway.ts

86.87% Statements 781/899
59.09% Branches 78/132
83.33% Functions 15/18
86.87% Lines 781/899

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 9001x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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 1x 1x 1x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 1x 162x 162x 162x 162x 162x 162x 162x 162x 1x 24x 24x 24x 1x 1x 1x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x   15x 24x 24x 24x   15x 24x 24x 24x 24x 24x 24x 24x 24x 22x 22x 24x 24x 24x 24x 24x 24x 24x 24x 24x 1x 1x 8x 8x 1x 1x 11x 11x 1x 1x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 594x 594x 528x 594x 66x 66x 1x 1x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x   66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 1x 1x 66x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 180x 15x 15x 15x 15x 17x 15x 15x     15x 180x 15x 66x 66x 1x 1x 18x 18x 18x 18x 18x 726x 726x 726x 726x 726x 726x 726x 726x 726x 726x 726x 16x 726x 726x 726x 726x 726x 726x 726x 726x 726x 726x 726x 726x   726x 710x 710x 710x 710x 710x 710x 710x 710x 726x 726x   726x 710x 710x 710x 710x 617x 617x 617x 617x 617x 617x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 93x 710x 726x 726x 726x 109x 617x 617x 617x 726x 726x 726x 726x 726x 726x 726x 726x 726x 726x 726x 726x 66x 66x 66x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 66x 66x 66x 66x 66x   66x 66x         66x 66x 66x 66x 66x 66x 66x   66x 66x 66x 66x 66x         66x           66x 66x 10x 10x 10x 10x 10x 10x 10x 10x   10x 10x 66x                       56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 50x 50x 50x 56x 6x 6x 6x 56x 56x 56x 56x 56x 56x     56x 56x 56x 56x 56x 56x 56x     56x 56x 56x 66x 6x 6x 6x 6x 6x 6x 5x 5x 5x 5x 5x 5x         5x 5x 5x 5x 5x 5x 5x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 66x 726x 726x 18x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 710x 61x 61x               61x 61x 61x 61x 61x 61x     61x 710x 18x 18x 18x 5x 5x 5x 5x 5x 5x 5x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 79x 79x     79x 79x 79x 79x 79x   79x 79x 79x 79x 79x 79x 79x 79x 79x   79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 18x 18x 18x 18x 15x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 8x 8x 18x 18x 18x 18x 18x 18x                   18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 1x 1x       1x 1x 11x 11x 77x 29x 29x 29x 29x 29x     29x   29x 29x 77x 77x 11x 11x 11x 1x  
import type {
    ApiSchema,
    Errors,
    GatewaySchema,
    ICallLog,
    IErrorFactory,
    IErrorMap,
    IGateway,
    IGatewayRoute,
    ILocal,
    ILog,
    IManifest,
    IMeta,
    IPlatformApi,
} from '@feasibleone/blong/types';
import {Internal} from '@feasibleone/blong/types';
import fastify, {type FastifyReply, type FastifyRequest, type RouteOptions} from 'fastify';
import os from 'os';
import type {LevelWithSilent} from 'pino';
import {Type, type TSchema} from 'typebox';
import Value from 'typebox/value';
import {v4} from 'uuid';
 
import {TRACE_HEADER, withoutCapabilities} from '@feasibleone/semantic-log/capability';
import {CALLS_CAPABILITY, GRANT_HEADER} from './callTrace.ts';
import {grantedCalls, grantKeyFrom} from './grant.ts';
import {
    callsFor,
    declareCall,
    enterCapability,
    enterRequestFlow,
    runInFlow,
} from './semanticContext.ts';
 
import {type TypeBoxTypeProvider} from '@fastify/type-provider-typebox';
import type {IResolution} from './Resolution.ts';
import type {IRpcClient} from './RpcClient.ts';
import jwt from './jwt.ts';
import {isExpectedError, methodId, methodParts, snakeToCamel} from './lib.ts';
import type {IConfig as IConfigMLE} from './mle.ts';
import isPublic from './public.ts';
import swagger from './swagger.ts';
 
const osName: string = [os.type(), os.platform(), os.release()].join(':');
const hostName: string = os.hostname();
 
const typedError: TSchema = Type.Object({
    message: Type.Optional(Type.String()),
    type: Type.Optional(Type.String()),
    print: Type.Optional(Type.String()),
});
 
const jsonRpcError: TSchema = Type.Object({
    // error
    jsonrpc: Type.Literal('2.0'),
    id: Type.Union([Type.String(), Type.Number()]),
    error: typedError,
});
 
type GatewayRequest = FastifyRequest;
 
const errorMap: IErrorMap = {
    'gateway.jwtMissingHeader': {message: 'Missing bearer authorization header', statusCode: 401},
};
 
declare module 'fastify' {
    interface FastifyContextConfig {
        auth: unknown;
        mle?: unknown;
    }
}
 
interface IConfig extends IConfigMLE {
    host?: string;
    port?: number;
    logLevel?: LevelWithSilent;
    cors?: unknown;
    debug?: boolean;
    /**
     * When true, the gateway accepts the `expect` field from JSON-RPC request
     * bodies and uses it to suppress error-level log entries for declared
     * expected errors (demoting them to `debug` level).
     *
     * Set to `true` in the `dev` intent.  Must be `false` (the default) in
     * production to prevent callers from suppressing audit-level error logs.
     */
    expectedErrors?: boolean;
    /**
     * Optional handler name (semantic triple) that returns the list of allowed
     * actions for the authenticated user.  When set, the gateway calls this
     * handler during authentication and stores the result in credentials,
     * then enforces that every request's methodId is in the allowed list.
     */
    authorize?: string;
    /**
     * Optional access-check audit.  When set, the gateway records every
     * authorization decision (allow/deny) at the access-check point into the
     * configured handler, plus sanitised DML context for access.* write
     * methods.  `exclude` lists methodId patterns (exact or `prefix*`) that
     * must not be audited.  Best-effort — audit failures never block requests.
     */
    audit?: {
        handler: string;
        exclude?: string[];
    };
    errorFields: unknown[];
    jwt: {
        cache: object;
        audience: string;
    };
    static?: {
        root: string;
    };
}
 
function operationParams(
    operation: GatewaySchema['operation'],
    bodySchema: ApiSchema | undefined,
    request: GatewayRequest,
): unknown {
    const result: Record<string, unknown> =
        operation?.parameters?.reduce(
            (result: Record<string, unknown>, parameter) => {
                if ('in' in parameter && 'name' in parameter) {
                    let where: Record<string, unknown> | undefined;
                    switch (parameter.in) {
                        case 'header':
                            where = request.headers as Record<string, unknown>;
                            break;
                        case 'query':
                            where = request.query as Record<string, unknown>;
                            break;
                        case 'path':
                            where = request.params as Record<string, unknown>;
                            break;
                        case 'cookie':
                            where = request.cookies as Record<string, unknown>;
                            break;
                        case 'body':
                            if (request.body) {
                                if (parameter.schema?.additionalProperties)
                                    Object.assign(result, request.body);
                                else if (parameter.schema?.properties)
                                    Object.entries(parameter.schema.properties).forEach(
                                        ([name]) => {
                                            if (name in (request.body as Record<string, unknown>))
                                                result[snakeToCamel(name)] = (
                                                    request.body as Record<string, unknown>
                                                )[name];
                                        },
                                    );
                            }
                            break;
                    }
                    if (where && parameter.name in where)
                        result[snakeToCamel(parameter.name)] = where[parameter.name];
                }
                return result;
            },
            {} as Record<string, unknown>,
        ) ?? {};
    if (
        bodySchema &&
        'type' in bodySchema &&
        bodySchema?.type === 'object' &&
        (bodySchema.properties ||
            ('additionalProperties' in bodySchema && bodySchema?.additionalProperties))
    ) {
        if ('additionalProperties' in bodySchema && bodySchema.additionalProperties)
            Object.assign(result, request.body);
        else if (bodySchema.properties)
            Object.entries(bodySchema.properties).forEach(([name]) => {
                if (name in (request.body as Record<string, unknown>))
                    result[snakeToCamel(name)] = (request.body as Record<string, unknown>)[name];
            });
    }
    return result;
}
 
export default class Gateway extends Internal implements IGateway {
    #server: ReturnType<typeof fastify> | null = null;
    #resolution: IResolution;
    #log: ILog;
    #logger: ReturnType<ILog['child']> | undefined;
    /** The gateway's own call channel: the framework's record of the calls it makes. */
    #calls: ICallLog | undefined;
    #config: IConfig = {
        host: '0.0.0.0',
        port: 8080,
        logLevel: 'warn',
        cors: undefined,
        sign: undefined as IConfig['sign'] | undefined,
        encrypt: undefined as IConfig['encrypt'] | undefined,
        public: {
            sign: undefined,
            encrypt: undefined,
        },
        debug: false,
        expectedErrors: false,
        authorize: undefined,
        audit: undefined,
        errorFields: [],
        jwt: {
            cache: {},
            audience: 'blong',
        },
    };
 
    #errors: Errors<typeof errorMap>;
    #rpcClient: IRpcClient;
    #routes: RouteOptions[] = [];
    #local: ILocal;
 
    /**
     * The registered routes as plain data.
     *
     * Derived from the same list that is handed to fastify, so callers (for
     * example the MCP server) see exactly the surface that is served — including
     * the per-route auth requirement, which is not inferable from the method name.
     */
    public describe(): IGatewayRoute[] {
        return this.#routes.map(route => {
            const config = route.config as {methodName?: string; auth?: unknown} | undefined;
            return {
                method: config?.methodName ?? '',
                url: route.url,
                httpMethod: String(route.method ?? 'POST'),
                auth: config?.auth ?? 'jwt',
            };
        });
    }
    #errorFields: [string, unknown][] = [];
    #plugins: {plugin: unknown; options: unknown}[] = [];
    #platform: IPlatformApi;
    #manifest: IManifest | undefined;
 
    public constructor(
        config: IConfig,
        {
            log,
            remote,
            error,
            resolution,
            local,
            platform,
            manifest,
        }: {
            log?: ILog;
            error?: IErrorFactory;
            remote?: IRpcClient;
            local?: ILocal;
            resolution?: IResolution;
            platform?: IPlatformApi;
            manifest?: IManifest;
        },
    ) {
        super({log});
        this.#log = log!;
        this.#platform = platform!;
 
        this.merge(this.#config, config);
        this.#config.sign ||= (
            process.env.GATEWAY_SIGN_KEY
                ? {env: 'GATEWAY_SIGN_KEY'}
                : {generate: {alg: 'ES384', crv: 'P-384', use: 'sig'}}
        ) as IConfig['sign'];
        this.#config.encrypt ||= (
            process.env.GATEWAY_ENCRYPT_KEY
                ? {env: 'GATEWAY_ENCRYPT_KEY'}
                : {generate: {alg: 'ECDH-ES+A256KW', crv: 'P-384', use: 'enc'}}
        ) as IConfig['encrypt'];
        this.#errorFields = Object.entries({
            type: true,
            message: true,
            print: true,
            validation: true,
            params: true,
            ...(this.#config.debug && {
                stack: true,
                cause: 'error',
            }),
            ...this.#config.errorFields,
        });
        this.#errors = error!.register(errorMap);
        this.#resolution = resolution!;
        this.#rpcClient = remote!;
        this.#local = local!;
        this.#manifest = manifest;
    }
 
    protected config(): object {
        return Object.freeze({...this.#config});
    }
 
    public registerPlugin(plugin: unknown, options?: unknown): void {
        this.#plugins.push({plugin, options});
    }
 
    private _forward(headers: object): Record<string, string> {
        return (
            [
                ['x-request-id'],
                // The framework's own identity header (see `semanticContext.ts`). It
                // travels in the body as well, but a request that never reached the
                // route handler — the one the hooks rejected — is only readable from
                // here, and this is what lets it keep the flow it was given. The
                // capabilities decided for the flow travel inside it, in its `cap`
                // field, which the earliest hook has already rewritten.
                ['x-semantic-trace'],
                ['x-b3-traceid', () => v4().replace(/-/g, '')],
                ['x-b3-spanid'],
                ['x-b3-parentspanid'],
                ['x-b3-sampled'],
                ['x-b3-flags'],
                ['x-ot-span-context'],
                ['x-ut-stack'],
            ] as [string, (() => string)?][]
        ).reduce(function (object: Record<string, string>, [key, value]) {
            if (typeof key === 'string' && key in (headers as Record<string, unknown>))
                object[key] = (headers as Record<string, unknown>)[key] as string;
            else if (value) object[key] = value();
            return object;
        }, {});
    }
 
    private _meta(req: GatewayRequest, version: string, serviceName: string): Partial<IMeta> {
        const {
            'user-agent': frontEnd,
            'geo-position': gps, // https://datatracker.ietf.org/doc/html/draft-daviel-http-geo-header-05
            'x-ut-device': deviceId,
            'x-forwarded-host': forwardedHost,
            'x-forwarded-for': forwardedIp,
        } = req.headers || {};
        const {localAddress, localPort} = req.raw?.socket || {};
        const [latitude, longitude] =
            typeof gps === 'string'
                ? gps.split(' ', 1)[0].split(';')
                : [req.headers.latitude, req.headers.longitude];
        const {language, ...auth} = req.auth?.credentials || {};
        return {
            forward: this._forward(req.headers),
            frontEnd,
            latitude,
            longitude,
            deviceId,
            localAddress,
            localPort,
            ...(req.auth?.credentials && {auth, language}),
            hostName: (forwardedHost || req.hostname) as string,
            ipAddress: (
                ([] as string[]).concat(forwardedIp as string | string[])[0] ||
                req.socket.remoteAddress ||
                ''
            ).split(',')[0],
            machineName: hostName,
            os: osName,
            version,
            serviceName,
            httpRequest: {
                url: req.protocol + '://' + req.host + req.url,
                state: req.cookies as Record<string, string>,
                headers: req.headers as Record<string, string | string[]>,
            },
        } as Partial<IMeta>;
    }
 
    private _applyMeta(response: object, {httpResponse}: {httpResponse?: unknown}): object {
        if (httpResponse) {
            const httpResp = httpResponse as Record<string, unknown>;
            const resp = response as Record<string, (...args: unknown[]) => void>;
            [
                'code',
                'redirect',
                'type',
                'created',
                'etag',
                'location',
                'ttl',
                'temporary',
                'permanent',
                'state',
                'unstate', // todo
                'header',
            ].forEach(method => {
                if (Object.prototype.hasOwnProperty.call(httpResp, method)) {
                    const params = httpResp[method];
                    if (Array.isArray((params as unknown[])?.[0])) {
                        // setting multiple headers and cookies require nested arrays
                        (params as unknown[][]).forEach(param =>
                            resp[method](...([] as unknown[]).concat(param)),
                        );
                    } else {
                        resp[method](...([] as unknown[]).concat(params));
                    }
                }
            });
        }
        return response;
    }
 
    public route(
        validations: Record<string, GatewaySchema>,
        pkg: {name: string; version: string},
    ): void {
        this.#routes = [];
        Object.entries(validations).forEach(([method, value]) => {
            const reqName = `ports.${value.destination ?? method.split('.', 1)[0]}.request`;
            const pubName = `ports.${value.destination ?? method.split('.', 1)[0]}.publish`;
            const isWildcard = method.endsWith('.*');
            this.#resolution?.announce(
                method.split('.')[0].replace(/\//g, '-'),
                this.#config.port!,
            );
            this.#routes.push({
                method: 'method' in value ? value.method : 'POST',
                url:
                    'path' in value
                        ? `${value.basePath ?? '/rpc/' + method.split('.', 1)[0]}${value.path}`
                        : `/${value.basePath ?? 'rpc'}/${method.split('.').join('/')}`,
                config: {
                    auth: value.auth ?? 'jwt',
                    methodName: method,
                    ...(value.bundle !== undefined && {bundle: value.bundle}),
                    ...(value.creditCost !== undefined && {creditCost: value.creditCost}),
                    ...(value.meter !== undefined && {meter: value.meter}),
                    ...(value.audit !== undefined && {audit: value.audit}),
                    ...(value.skipAuthorize && {skipAuthorize: true}),
                },
                schema: Type && {
                    ...('body' in value
                        ? {body: value.body}
                        : 'params' in value
                          ? {
                                body: Type.Object({
                                    jsonrpc: Type.Literal('2.0'),
                                    id: Type.Optional(Type.Union([Type.String(), Type.Number()])),
                                    method: isWildcard ? Type.String() : Type.Literal(method),
                                    params: value.params,
                                }),
                            }
                          : undefined),
                    ...('response' in value && value.response
                        ? {response: {'2xx': value.response}}
                        : 'result' in value
                          ? {
                                response:
                                    (this.#config.sign || this.#config.encrypt) &&
                                    (value.auth ?? 'jwt')
                                        ? {
                                              '2xx': value.result,
                                              '3xx': typedError,
                                              '4xx': typedError,
                                              '5xx': typedError,
                                          }
                                        : {
                                              '2xx': Type.Union([
                                                  Type.Object({
                                                      // response
                                                      jsonrpc: Type.Literal('2.0'),
                                                      id: Type.Union([
                                                          Type.String(),
                                                          Type.Number(),
                                                      ]),
                                                      result: value.result,
                                                      checkpoints: Type.Optional(
                                                          Type.Array(Type.Any()),
                                                      ),
                                                  }),
                                                  Type.Object({
                                                      // notification
                                                      jsonrpc: Type.Literal('2.0'),
                                                      result: Type.Boolean(),
                                                  }),
                                              ]),
                                              '3xx': jsonRpcError,
                                              '4xx': jsonRpcError,
                                              '5xx': jsonRpcError,
                                          },
                            }
                          : undefined),
                    security: [
                        value.auth === false
                            ? {}
                            : {
                                  'blong-login': ['api'],
                              },
                    ],
                    tags: [method.split('.')[0] + ' ' + pkg.name + '@' + pkg.version],
                },
                // onError: async(request, reply, error) => {
                //     const {id} = 'params' in value ? request.body as {id: string} : {id: 1};
                //     return {
                //         jsonrpc: '2.0',
                //         id,
                //         error: this.formatError(error)
                //     };
                // },
                handler: async (request: GatewayRequest, reply) => {
                    const {id, params, timeout, expect} =
                        'params' in value
                            ? (request.body as {
                                  id: string;
                                  params: unknown;
                                  timeout: number;
                                  expect: string | string[];
                              })
                            : {
                                  id: 1,
                                  params: operationParams(
                                      value.operation,
                                      'body' in value ? value.body?.schema : undefined,
                                      request,
                                  ),
                                  timeout: false,
                                  expect: undefined,
                              };
                    // Only honour `expect` from the request body when the gateway
                    // is configured to allow it.  This prevents external callers
                    // from suppressing error-level logs in production.
                    const resolvedExpect =
                        this.#config.expectedErrors && expect
                            ? ([] as string[]).concat(expect)
                            : undefined;
                    const methodName = isWildcard
                        ? new URL(request.url, 'http://localhost').pathname
                              .slice(5)
                              .split('/')
                              .join('.')
                        : method;
                    try {
                        const meta = {
                            mtid: !id ? 'notification' : 'request',
                            method: methodName,
                            opcode: methodName.split('.').pop(),
                            ...(timeout && {
                                timeout: this.#platform.timing.after(timeout as number),
                            }),
                            ...(resolvedExpect && {expect: resolvedExpect}),
                            ...this._meta(request, pkg?.version, methodName.split('.')[0]),
                        };
                        const notfound = (): unknown =>
                            reply
                                .code(404)
                                .type('text/plain')
                                .send('namespace not found for method ' + methodName);
                        if (isWildcard && !validations[methodParts(methodName)]) {
                            return reply
                                .code(404)
                                .type('text/plain')
                                .send('validation not found for method ' + methodName);
                        }
 
                        if (!('result' in value)) {
                            const req = this.#local.get(reqName);
                            if (!req) return notfound();
                            // The outermost entry mints the flow: everything this
                            // request does downstream joins it, and the method it
                            // was addressed to is the flow's kind.
                            const [result, resultMeta] =
                                (await runInFlow(meta as IMeta, methodName, () =>
                                    req.method(params, meta),
                                )) ?? null;
                            this._applyMeta(reply, resultMeta as {httpResponse?: unknown});
                            return result;
                        } else if (id == null) {
                            const pub = this.#local.get(pubName);
                            if (!pub) return notfound();
                            // A notification is an entry of its own, so it starts a
                            // flow rather than joining one nobody sent.
                            runInFlow(meta as IMeta, methodName, () =>
                                pub.method(params, meta),
                            ).catch(() => {});
                            return {
                                jsonrpc: '2.0',
                                result: true,
                            };
                        } else {
                            const req = this.#local.get(reqName);
                            if (!req) return notfound();
                            // The same entry as the branch above, and it is the ordinary
                            // request/response path — which is why it matters most: the
                            // `onRequest` hook enters the flow with `enterWith`, and that
                            // does not reach a handler the router schedules from its own
                            // async resource, so for a while only the *wildcard* branch
                            // ran inside a flow. Every call the handler made was then
                            // declared in no flow at all, which is why no served request
                            // ever produced a leg while tap runs did. `runInFlow` adopts
                            // the identity the hook published when the meta carries one,
                            // so this does not mint a second flow for the same request.
                            const [result, resultMeta] =
                                (await runInFlow(meta as IMeta, methodName, () =>
                                    // Declare the hop this route is making. The route is the
                                    // caller, and `methodName` is already the dotted wire name
                                    // the leg grammar wants, so the leg names the method the
                                    // request asked for. The callee's receipt then carries the
                                    // same leg, which is what makes the drawing a call rather
                                    // than a participation.
                                    declareCall(
                                        'gateway',
                                        methodName,
                                        () => {
                                            // The caller's own records, written inside the leg it
                                            // just declared: the callee answers with a receipt for
                                            // the same leg, and a call is finished when it answers -
                                            // so the start, the end and the failure all belong here.
                                            // They go through the call channel rather than the level
                                            // logger: a call is either wanted for the whole flow or
                                            // it is not, and a request that records nothing pays for
                                            // no record at all.
                                            const calls = this.#calls;
                                            calls?.start(methodName);
                                            const answered = req.method(params, meta);
                                            if (answered instanceof Promise) {
                                                return Promise.resolve(answered).then(
                                                    value => {
                                                        calls?.end(methodName);
                                                        return value;
                                                    },
                                                    error => {
                                                        calls?.error(methodName, error);
                                                        throw error;
                                                    },
                                                );
                                            }
                                            calls?.end(methodName);
                                            return answered;
                                        },
                                        meta as IMeta,
                                    ),
                                )) ?? null;
                            this._applyMeta(reply, resultMeta as {httpResponse?: unknown});
                            return {
                                jsonrpc: '2.0',
                                id,
                                result,
                                ...((resultMeta as {checkpoints?: unknown[]})?.checkpoints
                                    ?.length && {
                                    checkpoints: (resultMeta as {checkpoints?: unknown[]})
                                        .checkpoints,
                                }),
                            };
                        }
                    } catch (error) {
                        const typedError = error as {
                            statusCode?: number;
                            httpResponse?: unknown;
                            [key: string]: unknown;
                        };
                        if (!typedError.silent) {
                            if (
                                isExpectedError(
                                    typedError.type as string | undefined,
                                    resolvedExpect,
                                )
                            ) {
                                request.log.debug?.(
                                    {err: error, method: methodName},
                                    'gateway expected error',
                                );
                            } else {
                                request.log.error?.(
                                    {err: error, method: methodName},
                                    'gateway handler error',
                                );
                            }
                        }
                        this._applyMeta(
                            reply
                                .header('x-envoy-decorator-operation', methodName)
                                .code(typedError?.statusCode || 500),
                            {httpResponse: typedError.httpResponse},
                        );
                        return {
                            jsonrpc: '2.0',
                            id,
                            error: this._formatError(typedError),
                        };
                    }
                },
            });
        });
    }
 
    public async start(): Promise<IGateway> {
        const old = this.#server;
        this.#logger = this.#log.child({name: 'gateway'}, {level: this.#config.logLevel});
        // The call channel of *this* component, so its records carry the component the
        // way its level records do (`logger()` binds the name). Taken once, next to
        // the logger it belongs to.
        this.#calls = this.#log.logger(this.#config.logLevel ?? 'info', {name: 'gateway'}).calls;
        try {
            this.#server = fastify({
                loggerInstance: this.#logger,
                forceCloseConnections: true,
                // fastify's own request logging is off, and the framework's records
                // replace it: it writes the whole request at `info` — headers, the
                // `Authorization` bearer among them — and a completion line, which is
                // both more than a reader needs and less than the flow records say.
                // Nothing else depends on those two lines: the request has a flow, the
                // flow has its calls, and both are recorded where they belong.
                disableRequestLogging: true,
                ajv: {
                    customOptions: {
                        allErrors: true,
                        strict: false,
                    },
                },
            }).withTypeProvider<TypeBoxTypeProvider>();
 
            this.#server.setValidatorCompiler(({schema}: {schema: TSchema}) => {
                return (data: unknown) => {
                    // 1. Runtime validation check
                    if (!Value.Check(schema, data)) {
                        const errors = [...Value.Errors(schema, data)];
                        return {
                            error: new Error(
                                `Validation failed: ${errors.map(e => e.message).join(', ')}`,
                            ),
                        };
                    }
 
                    // 2. Transform/Decode the validated string into a Date object
                    try {
                        const decoded = Value.Decode(schema, data);
                        return {value: decoded};
                    } catch (error) {
                        return {error};
                    }
                };
            });
 
            this.#server.setErrorHandler(
                (error: Record<string, unknown>, request: FastifyRequest, reply: FastifyReply) => {
                    request.log.error({err: error}, 'gateway unhandled error');
                    return reply.status((error as {statusCode?: number}).statusCode || 500).send({
                        jsonrpc: '2.0',
                        id: (request.body as {id?: unknown})?.id,
                        error: this._formatError(error),
                    });
                },
            );
            // The entry of a request is its earliest hook, not its route handler: the
            // authentication and metering hooks run in between, and a call they reject
            // has no route to be wrapped by, so its records would name no flow at all
            // (T-105). The identity is published back onto the request headers, which is
            // where the route handler reads it from when it adopts this same flow.
            //
            // Declared with the three-argument callback shape on purpose. Fastify picks the
            // hook's style from its arity, and a plain function of one argument is awaited
            // nowhere: every request then stopped in this hook, which looked for a day like a
            // slow database rather than a signature - the MLE readiness probe timed out at
            // startup and every realm's tap run failed with a different symptom each time.
            //
            // The metadata endpoints and the static assets are not calls: they are the
            // framework's own plumbing (the MLE key endpoint, the API documentation, what a
            // browser fetches), and minting an execution per probe filled the observed kinds
            // with names like `login..well-known.mle` - a deployment's health checks read as
            // traffic in an observation of its business.
            this.#server.addHook(
                'onRequest',
                async (request: FastifyRequest, _reply: FastifyReply): Promise<void> => {
                    const pathname = new URL(request.url, 'http://localhost').pathname;
                    if (isPublic(pathname) && pathname.includes('/.well-known/')) {
                        return;
                    }
                    // Only what the earliest hook can see: the route handler knows the
                    // real method and re-enters this flow with it, so a path that does
                    // not name one is left unlabelled rather than guessed at.
                    const kind = pathname.startsWith('/rpc/')
                        ? pathname.slice(5).split('/').filter(Boolean).join('.')
                        : '';
                    // A capability decides what this process may cost itself, so an
                    // outside caller does not get to set one: the field is stripped
                    // from the identity it arrived with, and the decision is made here
                    // and published in its place. The rest of the identity is adopted
                    // exactly as it arrived.
                    const identity = withoutCapabilities(
                        request.headers[TRACE_HEADER] as string | undefined,
                    );
                    if (identity.length > 0) {
                        request.headers[TRACE_HEADER] = identity;
                    } else {
                        delete request.headers[TRACE_HEADER];
                    }
                    // The grant, if one arrived, is verified here and now — once per
                    // request, at the earliest point there is — and what travels on is
                    // the capability it decided, not the token.
                    const grantedCallsToRecord = await grantedCalls(
                        request.headers[GRANT_HEADER] as string | undefined,
                        grantKeyFrom(this.#config),
                    );
                    // A grant wins over the configuration; with none, the configuration
                    // answers and the answer is published for the process that serves
                    // the call. Either way the flow is decided here, before the hooks
                    // that may reject the request: a flow the entry point refused to
                    // record is not recorded by the service it reaches.
                    enterCapability(
                        CALLS_CAPABILITY,
                        grantedCallsToRecord || callsFor({forward: request.headers} as IMeta, kind),
                    );
                    Object.assign(request.headers, enterRequestFlow(request.headers, kind));
                },
            );
            await this.#server.register(jwt, {
                cache: this.#config.jwt?.cache,
                verify: (token: string, options: {nonce?: string; audience: string}) =>
                    this.#rpcClient.verify(token, options),
                errors: this.#errors,
                audience: this.#config.jwt.audience,
                authorize: this.#config.authorize,
                audit: this.#config.audit,
                local: this.#local,
                methodId: methodId,
                methodParts: methodParts,
            });
            if (this.#config.static)
                await this.#server.register(
                    (await import('./static.ts')).default,
                    this.#config.static,
                );
            if (this.#config.cors)
                await this.#server.register((await import('./cors.ts')).default, this.#config.cors);
            if (this.#config.sign || this.#config.encrypt) {
                await this.#server.register((await import('./mle.ts')).default, this.#config);
            } else {
                this.#server.route({
                    method: 'GET',
                    url: '/rpc/login/.well-known/mle',
                    config: {auth: false},
                    handler() {
                        return {};
                    },
                });
            }
            await this.#server.register(swagger, {
                version: '',
            });
            for (const {plugin, options} of this.#plugins)
                await this.#server.register(plugin, options);
            this.#routes.forEach(route => this.#server!.route(route));
        } finally {
            await old?.close();
        }
        await this.#server.listen({
            port: this.#config.port,
            host: this.#config.host,
        });
        // Publish the effective port to the manifest so other platforms
        // (e.g. browser backend adapter) can discover it.
        // The manifest proxy automatically resolves any pending deferred.
        const address = this.#server.server.address();
        if (this.#manifest && address && typeof address === 'object') {
            this.#manifest.gatewayPort = address.port;
        }
 
        if (!this.#config.port && !['info', 'debug', 'trace'].includes(this.#config.logLevel ?? ''))
            this.#logger?.warn?.(`gateway listening at random port ${address.port}`);
        return this;
    }
 
    public async stop(): Promise<IGateway> {
        // fastify's close() waits on the socket layer, and keep-alive connections made by a
        // browser backend (or a leftover probe) hold it open indefinitely: the run ends with
        // a tap "timeout!" against a live server long after every test passed, because the
        // process never exits. Close the connections first so shutting down actually
        // shuts down.
        this.#server?.server.closeIdleConnections?.();
        this.#server?.server.closeAllConnections?.();
        await this.#server?.close();
        this.#server = null;
        return this;
    }
 
    protected async restart(): Promise<void> {
        await this.stop();
        await this.start();
    }
 
    private _formatError(error: Record<string, unknown>): object {
        return this.#errorFields.reduce(
            (e, [key, value]) => {
                if (value && typeof error[key] !== 'undefined') {
                    switch (value) {
                        case true:
                            e[key] = error[key];
                            break;
                        case 'error':
                            e[key] = this._formatError(error[key] as Record<string, unknown>);
                            break;
                        default:
                            break;
                    }
                }
                return e;
            },
            {} as Record<string, unknown>,
        );
    }
}