Member Junction
    Preparing search index...

    Main orchestrator for API key operations and authorization

    Provides methods for:

    • Generating, creating, and revoking API keys
    • Validating API keys and returning user context
    • Authorizing requests against scope rules
    • Logging API key usage
    const engine = GetAPIKeyEngine();

    // Create a new API key
    const result = await engine.CreateAPIKey({
    userId: 'user-guid',
    label: 'My Integration'
    }, contextUser);

    // Validate and authorize a request
    const authResult = await engine.Authorize(
    hash, 'MJAPI', 'view:run', 'Users', contextUser
    );
    Index

    Constructors

    Accessors

    Methods

    • Validate and authorize an API key request against scope rules. This method ALWAYS logs the authorization decision for audit purposes.

      This implements the three-tier permission model:

      1. User Permissions - What the user can do (already checked by authentication)
      2. Application Ceiling - Maximum scope the application allows
      3. API Key Scopes - Specific scopes granted to this key

      Parameters

      • apiKeyHash: string

        The SHA-256 hash of the API key

      • applicationName: string

        The name of the calling application (e.g., 'MJAPI', 'MCPServer')

      • scopePath: string

        The scope being requested (e.g., 'view:run')

      • resource: string

        The specific resource (e.g., entity name)

      • contextUser: UserInfo

        User context for database operations

      • OptionalrequestContext: {
            endpoint?: string;
            ipAddress?: string | null;
            method?: string;
            operation?: string | null;
            userAgent?: string | null;
        }

        Optional request context for logging (endpoint, method, etc.)

      • Optionaloptions: { skipLogging?: boolean }
        • OptionalskipLogging?: boolean

          When true, skip writing to the usage log. Useful for speculative checks (e.g. full_access probe) that are not the real authorization decision.

      Returns Promise<AuthorizationResult & { LogId?: string }>

      Authorization result with optional log ID

    • Authorize and log the request.

      Parameters

      • apiKeyHash: string
      • applicationName: string
      • scopePath: string
      • resource: string
      • endpoint: string
      • method: string
      • operation: string | null
      • ipAddress: string | null
      • userAgent: string | null
      • contextUser: UserInfo

      Returns Promise<AuthorizationResult & { LogId?: string }>

      Use Authorize() instead - it now always logs. This method is kept for backward compatibility.

    • Configure the engine and ensure the base engine is loaded. This should be called during server startup to preload all metadata.

      Parameters

      • OptionalforceRefresh: boolean

        If true, forces a reload even if already loaded

      • OptionalcontextUser: UserInfo

        User context for database operations

      • Optionalprovider: IMetadataProvider

        Optional metadata provider override

      Returns Promise<void>

    • Creates a new API key and stores it in the database.

      This method:

      1. Generates a new cryptographically secure API key
      2. Hashes it for secure storage
      3. Creates an APIKey entity record in the database

      IMPORTANT: The raw key is only returned once. Store it securely or show it to the user immediately - it cannot be recovered later.

      Parameters

      Returns Promise<CreateAPIKeyResult>

      Result containing the raw key (if successful) or error

      const result = await engine.CreateAPIKey({
      userId: 'user-guid-here',
      label: 'MCP Server Integration',
      description: 'Used for Claude Desktop MCP connections',
      expiresAt: new Date('2025-12-31')
      }, contextUser);

      if (result.Success) {
      console.log('Save this key:', result.RawKey);
      }
    • Generates a new API key using the configured generation parameters.

      The key format is: {prefix}{encodedRandomBytes}

      • Prefix, entropy size, encoding, and hash algorithm are all configurable
      • Defaults: mj_sk_ prefix, 32 bytes entropy, hex encoding, SHA-256 hash

      Returns GeneratedAPIKey

      Object containing the raw key and its hash (hash always hex-encoded)

      const { Raw, Hash } = engine.GenerateAPIKey();
      // Raw: 'mj_sk_a1b2c3...' (show to user once)
      // Hash: '7f83b1657ff1...' (store in database)
    • Hashes an API key for storage or comparison.

      Uses the configured hash algorithm to create a one-way hash of the key. The hash is always output as a hex string regardless of the key encoding.

      Parameters

      • key: string

        The raw API key to hash

      Returns string

      The hash as a hex string

    • Validates that an API key has the correct format.

      Checks that the key matches the configured prefix, encoding character set, and expected length derived from the entropy bytes. This is a quick syntactic check before attempting database validation.

      Parameters

      • key: string

        The API key to validate

      Returns boolean

      True if the format is valid, false otherwise

    • Revokes an API key, permanently disabling it.

      Once revoked, an API key cannot be reactivated. Create a new key if needed.

      Parameters

      • apiKeyId: string

        The database ID of the API key to revoke

      • contextUser: UserInfo

        User context for database operations

      • Optionalprovider: IMetadataProvider

      Returns Promise<boolean>

      True if revocation succeeded, false otherwise

    • Validates an API key and returns the associated user context.

      This is the main entry point for API key authentication. It:

      1. Validates the key format
      2. Hashes the key and looks it up in the database
      3. Checks key status (active vs revoked)
      4. Checks expiration
      5. Checks application binding (if ApplicationId/ApplicationName provided)
      6. Retrieves and validates the associated user
      7. Logs the usage (if logging is enabled)

      Parameters

      Returns Promise<APIKeyValidationResult>

      Validation result with user context if valid

      const result = await engine.ValidateAPIKey({
      RawKey: request.headers['x-api-key'],
      ApplicationName: 'MCPServer', // Check if key is valid for MCP
      Endpoint: '/graphql',
      Method: 'POST',
      Operation: 'GetUsersRecord',
      StatusCode: 200,
      IPAddress: request.ip,
      UserAgent: request.headers['user-agent']
      }, systemUser);

      if (result.IsValid) {
      // Proceed with the user context
      // Use result.APIKeyHash for subsequent Authorize() calls
      return result.User;
      }