unit uB2PermissaoClient;

{==============================================================================
  B2Sync.Permissoes — SDK Oficial Delphi (VCL Delphi 10.x / 11 / 12)
  Cliente de Autenticação Segura, Assinatura Assimétrica RSA-2048,
  Cache Offline (.b2perm), Anti-Replay, Anti-Clock-Rollback e Auto-Seed.

  Compatível com:
    - Delphi 10.3 Rio, 10.4 Sydney, Delphi 11 Alexandria, Delphi 12 Athens
    - Windows 32-bit e 64-bit (VCL Forms & Actions)
    - Padrão IAM B2Sync com Suporte Multi-Sistema (SGE Retaguarda, PDV, Fechamento)
 ==============================================================================}

interface

uses
  Winapi.Windows,
  System.SysUtils,
  System.Classes,
  System.IOUtils,
  System.Net.HttpClient,
  System.Net.URLClient,
  System.NetEncoding,
  System.JSON,
  System.DateUtils,
  System.Hash,
  System.Generics.Collections,
  Vcl.Forms,
  Vcl.ActnList,
  Vcl.Menus,
  Vcl.Controls;

type
  { Exceções de Segurança e Contingência }
  EB2PermissaoException = class(Exception);
  EB2PermissaoSecurityException = class(EB2PermissaoException);
  EB2PermissaoReplayAttackException = class(EB2PermissaoSecurityException);
  EB2PermissaoClockRollbackException = class(EB2PermissaoSecurityException);
  EB2PermissaoHardwareMismatchException = class(EB2PermissaoSecurityException);
  EB2PermissaoOfflineExpiredException = class(EB2PermissaoSecurityException);
  EB2PermissaoInvalidSignatureException = class(EB2PermissaoSecurityException);

  { Ações granulares de cada item/menu }
  TB2PermissaoAcoes = record
    Ler: Boolean;
    Criar: Boolean;
    Editar: Boolean;
    Excluir: Boolean;
    Exportar: Boolean;
    Especial: Boolean;
    procedure Reset;
    function HasAction(const AAcao: string): Boolean;
    class function FromJSON(AJson: TJSONObject): TB2PermissaoAcoes; static;
    function ToJSON: TJSONObject;
  end;

  { Dados do Usuário na Sessão }
  TB2PermissaoUsuario = record
    Id: Integer;
    Nome: string;
    Login: string;
    LegacyUserId: Integer;
    GrupoId: Integer;
    ModoPermissao: string;
    EmpresaAtiva: Integer;
    Empresas: TArray<Integer>;
    OfflineVerifier: string;
    procedure Reset;
    class function FromJSON(AJson: TJSONObject): TB2PermissaoUsuario; static;
  end;

  { Sessão Descriptografada e Validada em RAM }
  TB2PermissaoSession = class
  private
    FSystemUID: string;
    FSystemSlug: string;
    FSystemNome: string;
    FUsuario: TB2PermissaoUsuario;
    FRequestNonce: string;
    FMachineHash: string;
    FIssuedAt: Int64;
    FOfflineExpiresAt: Int64;
    FAllowedTabs: TList<string>;
    FPermissoes: TDictionary<string, TB2PermissaoAcoes>;
    FRawPayloadJson: string;
    FSignatureBase64: string;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Clear;
    procedure LoadFromPayloadJSON(const AJsonString, ASignatureBase64: string);

    function HasPermission(const AChaveItem, AAcao: string): Boolean;
    function IsTabAllowed(const ATabSlug: string): Boolean;

    property SystemUID: string read FSystemUID;
    property SystemSlug: string read FSystemSlug;
    property SystemNome: string read FSystemNome;
    property Usuario: TB2PermissaoUsuario read FUsuario;
    property RequestNonce: string read FRequestNonce;
    property MachineHash: string read FMachineHash;
    property IssuedAt: Int64 read FIssuedAt;
    property OfflineExpiresAt: Int64 read FOfflineExpiresAt;
    property RawPayloadJson: string read FRawPayloadJson;
    property SignatureBase64: string read FSignatureBase64;
    property Permissoes: TDictionary<string, TB2PermissaoAcoes> read FPermissoes;
  end;

  { Cliente Principal de Permissões }
  TB2PermissaoClient = class
  private
    FSystemUID: string;
    FApiBaseUrl: string;
    FPublicKeyPem: string;
    FCacheFilePath: string;
    FLocalNonce: string;
    FSession: TB2PermissaoSession;
    FIsOfflineMode: Boolean;
    FLastErrorMessage: string;
    FHttpTimeoutSec: Integer;

    function PostHttp(const AEndpoint: string; ABody: TJSONObject; out AResponseStr: string; out AStatusCode: Integer): Boolean;
    procedure SaveOfflineBundle(const ARawPayloadBase64, ASignatureBase64: string);
    function LoadOfflineBundle(out ARawPayloadJson, ASignatureBase64: string): Boolean;
    function VerifyOfflineClockIntegrity(AIssuedAt: Int64; AMaxFirebirdDate: TDateTime): Boolean;
    function InternalVerifySignatureWinApi(const ARawDataBytes: TBytes; const ASignatureBytes: TBytes): Boolean;
  public
    constructor Create(const ASystemUID: string;
                       const AApiBaseUrl: string = 'http://localhost:3045';
                       const APublicKeyPem: string = '');
    destructor Destroy; override;

    { Métodos Criptográficos e de Hardware }
    function GetMachineHash: string;
    function GenerateRequestNonce: string;
    function VerifySignatureRSA2048(const ARawPayloadJson, ASignatureBase64: string): Boolean;
    function VerifyOfflinePassword(const APlainPassword, AVerifierString: string): Boolean;

    { Handshake de Autenticação Online com Contingência Offline }
    function Login(const AUsuario, ASenha: string;
                   AEmpresaCodigo: Integer = 1;
                   AMaxFirebirdDate: TDateTime = 0): Boolean;

    { Verificação de Acessos em Tempo Real }
    function HasPermission(const AChaveItem: string; const AAcao: string = 'ler'): Boolean;
    function IsTabAllowed(const ATabSlug: string): Boolean;

    { Automação de Interface VCL }
    procedure ApplyToForm(AForm: TForm);
    function SyncFormCatalog(AForm: TForm): Boolean;

    { Propriedades de Estado }
    property SystemUID: string read FSystemUID write FSystemUID;
    property ApiBaseUrl: string read FApiBaseUrl write FApiBaseUrl;
    property PublicKeyPem: string read FPublicKeyPem write FPublicKeyPem;
    property CacheFilePath: string read FCacheFilePath write FCacheFilePath;
    property Session: TB2PermissaoSession read FSession;
    property IsOfflineMode: Boolean read FIsOfflineMode;
    property LastErrorMessage: string read FLastErrorMessage;
    property LocalNonce: string read FLocalNonce;
    property HttpTimeoutSec: Integer read FHttpTimeoutSec write FHttpTimeoutSec;
  end;

implementation

{ Declarações da Windows CryptoAPI / Crypt32 para Validação RSA-2048 }
const
  CRYPT_STRING_BASE64HEADER = $00000000;
  CRYPT_STRING_BASE64       = $00000001;
  X509_PUBLIC_KEY_INFO      = PAnsiChar(8);
  PROV_RSA_AES              = 24;
  CRYPT_VERIFYCONTEXT       = $F0000000;
  CALG_SHA_256              = $0000800C;
  HP_HASHVAL                = $0002;

function CryptStringToBinaryA(pszString: PAnsiChar; cchString: DWORD; dwFlags: DWORD;
  pbBinary: PByte; var pcbBinary: DWORD; pdwSkip: PDWORD; pdwFlags: PDWORD): BOOL; stdcall;
  external 'crypt32.dll' name 'CryptStringToBinaryA';

function CryptDecodeObjectEx(dwCertEncodingType: DWORD; lpszStructType: PAnsiChar;
  pbEncoded: PByte; cbEncoded: DWORD; dwFlags: DWORD; pDecodePara: Pointer;
  pvStructInfo: Pointer; var pcbStructInfo: DWORD): BOOL; stdcall;
  external 'crypt32.dll' name 'CryptDecodeObjectEx';

function CryptAcquireContextW(var phProv: THandle; szContainer: LPCWSTR; szProvider: LPCWSTR;
  dwProvType: DWORD; dwFlags: DWORD): BOOL; stdcall;
  external 'advapi32.dll' name 'CryptAcquireContextW';

function CryptReleaseContext(hProv: THandle; dwFlags: DWORD): BOOL; stdcall;
  external 'advapi32.dll' name 'CryptReleaseContext';

function CryptImportPublicKeyInfo(hProv: THandle; dwCertEncodingType: DWORD;
  pInfo: Pointer; var phKey: THandle): BOOL; stdcall;
  external 'advapi32.dll' name 'CryptImportPublicKeyInfo';

function CryptDestroyKey(hKey: THandle): BOOL; stdcall;
  external 'advapi32.dll' name 'CryptDestroyKey';

function CryptCreateHash(hProv: THandle; Algid: DWORD; hKey: THandle; dwFlags: DWORD;
  var phHash: THandle): BOOL; stdcall;
  external 'advapi32.dll' name 'CryptCreateHash';

function CryptHashData(hHash: THandle; pbData: PByte; dwDataLen: DWORD; dwFlags: DWORD): BOOL; stdcall;
  external 'advapi32.dll' name 'CryptHashData';

function CryptVerifySignatureW(hHash: THandle; pbSignature: PByte; dwSigLen: DWORD;
  hPubKey: THandle; szDescription: LPCWSTR; dwFlags: DWORD): BOOL; stdcall;
  external 'advapi32.dll' name 'CryptVerifySignatureW';

function CryptDestroyHash(hHash: THandle): BOOL; stdcall;
  external 'advapi32.dll' name 'CryptDestroyHash';

{ Helper para PBKDF2 em puro Pascal }
function PBKDF2_SHA256(const APassword, ASalt: string; AIterations, AKeyLen: Integer): TBytes;
var
  LPassBytes, LSaltBytes, LBlockIndexBytes, LU, LT: TBytes;
  LBlockCount, LBlockIndex, i, k: Integer;
  LHMAC: THashSHA2;
begin
  SetLength(Result, AKeyLen);
  LPassBytes := TEncoding.UTF8.GetBytes(APassword);
  LSaltBytes := TEncoding.UTF8.GetBytes(ASalt);

  LBlockCount := (AKeyLen + 31) div 32;
  SetLength(LBlockIndexBytes, 4);

  for LBlockIndex := 1 to LBlockCount do
  begin
    LBlockIndexBytes[0] := Byte((LBlockIndex shr 24) and $FF);
    LBlockIndexBytes[1] := Byte((LBlockIndex shr 16) and $FF);
    LBlockIndexBytes[2] := Byte((LBlockIndex shr 8) and $FF);
    LBlockIndexBytes[3] := Byte(LBlockIndex and $FF);

    { U_1 = PRF(Password, Salt || INT_32_BE(i)) }
    LHMAC := THashSHA2.Create(THashSHA2.TSHA2Version.SHA256);
    LU := THashSHA2.GetHMACAsBytes(Concat(LSaltBytes, LBlockIndexBytes), LPassBytes, THashSHA2.TSHA2Version.SHA256);
    LT := Copy(LU, 0, Length(LU));

    for i := 2 to AIterations do
    begin
      LU := THashSHA2.GetHMACAsBytes(LU, LPassBytes, THashSHA2.TSHA2Version.SHA256);
      for k := 0 to High(LT) do
        LT[k] := LT[k] xor LU[k];
    end;

    for k := 0 to High(LT) do
    begin
      if ((LBlockIndex - 1) * 32 + k) < AKeyLen then
        Result[(LBlockIndex - 1) * 32 + k] := LT[k];
    end;
  end;
end;

{ ============================================================================
  TB2PermissaoAcoes
  ============================================================================ }

procedure TB2PermissaoAcoes.Reset;
begin
  Ler := False;
  Criar := False;
  Editar := False;
  Excluir := False;
  Exportar := False;
  Especial := False;
end;

function TB2PermissaoAcoes.HasAction(const AAcao: string): Boolean;
var
  A: string;
begin
  A := LowerCase(Trim(AAcao));
  if A = 'ler' then Result := Ler
  else if A = 'criar' then Result := Criar
  else if A = 'editar' then Result := Editar
  else if A = 'excluir' then Result := Excluir
  else if A = 'exportar' then Result := Exportar
  else if A = 'especial' then Result := Especial
  else Result := False;
end;

class function TB2PermissaoAcoes.FromJSON(AJson: TJSONObject): TB2PermissaoAcoes;
begin
  Result.Reset;
  if not Assigned(AJson) then Exit;
  Result.Ler := AJson.GetValue<Boolean>('ler', False);
  Result.Criar := AJson.GetValue<Boolean>('criar', False);
  Result.Editar := AJson.GetValue<Boolean>('editar', False);
  Result.Excluir := AJson.GetValue<Boolean>('excluir', False);
  Result.Exportar := AJson.GetValue<Boolean>('exportar', False);
  Result.Especial := AJson.GetValue<Boolean>('especial', False);
end;

function TB2PermissaoAcoes.ToJSON: TJSONObject;
begin
  Result := TJSONObject.Create;
  Result.AddPair('ler', TJSONBool.Create(Ler));
  Result.AddPair('criar', TJSONBool.Create(Criar));
  Result.AddPair('editar', TJSONBool.Create(Editar));
  Result.AddPair('excluir', TJSONBool.Create(Excluir));
  Result.AddPair('exportar', TJSONBool.Create(Exportar));
  Result.AddPair('especial', TJSONBool.Create(Especial));
end;

{ ============================================================================
  TB2PermissaoUsuario
  ============================================================================ }

procedure TB2PermissaoUsuario.Reset;
begin
  Id := 0;
  Nome := '';
  Login := '';
  LegacyUserId := 0;
  GrupoId := 0;
  ModoPermissao := 'HIBRIDO';
  EmpresaAtiva := 1;
  SetLength(Empresas, 0);
  OfflineVerifier := '';
end;

class function TB2PermissaoUsuario.FromJSON(AJson: TJSONObject): TB2PermissaoUsuario;
var
  LEmpArray: TJSONArray;
  i: Integer;
begin
  Result.Reset;
  if not Assigned(AJson) then Exit;
  Result.Id := AJson.GetValue<Integer>('id', 0);
  Result.Nome := AJson.GetValue<string>('nome', '');
  Result.Login := AJson.GetValue<string>('login', '');
  Result.LegacyUserId := AJson.GetValue<Integer>('legacyUserId', Result.Id);
  Result.GrupoId := AJson.GetValue<Integer>('grupoId', 0);
  Result.ModoPermissao := AJson.GetValue<string>('modoPermissao', 'HIBRIDO');
  Result.EmpresaAtiva := AJson.GetValue<Integer>('empresaAtiva', 1);
  Result.OfflineVerifier := AJson.GetValue<string>('offlineVerifier', '');

  LEmpArray := AJson.GetValue<TJSONArray>('empresas', nil);
  if Assigned(LEmpArray) then
  begin
    SetLength(Result.Empresas, LEmpArray.Count);
    for i := 0 to LEmpArray.Count - 1 do
      Result.Empresas[i] := (LEmpArray.Items[i] as TJSONNumber).AsInt;
  end;
end;

{ ============================================================================
  TB2PermissaoSession
  ============================================================================ }

constructor TB2PermissaoSession.Create;
begin
  inherited Create;
  FAllowedTabs := TList<string>.Create;
  FPermissoes := TDictionary<string, TB2PermissaoAcoes>.Create;
  Clear;
end;

destructor TB2PermissaoSession.Destroy;
begin
  FAllowedTabs.Free;
  FPermissoes.Free;
  inherited Destroy;
end;

procedure TB2PermissaoSession.Clear;
begin
  FSystemUID := '';
  FSystemSlug := '';
  FSystemNome := '';
  FUsuario.Reset;
  FRequestNonce := '';
  FMachineHash := '';
  FIssuedAt := 0;
  FOfflineExpiresAt := 0;
  FRawPayloadJson := '';
  FSignatureBase64 := '';
  FAllowedTabs.Clear;
  FPermissoes.Clear;
end;

procedure TB2PermissaoSession.LoadFromPayloadJSON(const AJsonString, ASignatureBase64: string);
var
  LRoot: TJSONObject;
  LTabsArray: TJSONArray;
  LPermObj: TJSONObject;
  LPair: TJSONPair;
  i: Integer;
  LAcoes: TB2PermissaoAcoes;
begin
  Clear;
  FRawPayloadJson := AJsonString;
  FSignatureBase64 := ASignatureBase64;

  LRoot := TJSONObject.ParseJSONValue(AJsonString) as TJSONObject;
  if not Assigned(LRoot) then
    raise EB2PermissaoException.Create('Payload JSON de permissões corrompido ou inválido.');

  try
    FSystemUID := LRoot.GetValue<string>('systemUid', '');
    FSystemSlug := LRoot.GetValue<string>('systemSlug', '');
    FSystemNome := LRoot.GetValue<string>('systemNome', '');
    FRequestNonce := LRoot.GetValue<string>('requestNonce', '');
    FMachineHash := LRoot.GetValue<string>('machineHash', '');
    FIssuedAt := LRoot.GetValue<Int64>('issuedAt', 0);
    FOfflineExpiresAt := LRoot.GetValue<Int64>('offlineExpiresAt', 0);

    { Usuário }
    if LRoot.FindValue('usuario') is TJSONObject then
    begin
      FUsuario := TB2PermissaoUsuario.FromJSON(LRoot.GetValue<TJSONObject>('usuario'));
      { Fallback para offlineVerifier no nível raiz se não estiver no usuario }
      if (FUsuario.OfflineVerifier = '') and (LRoot.FindValue('offlineVerifier') <> nil) then
        FUsuario.OfflineVerifier := LRoot.GetValue<string>('offlineVerifier', '');
    end;

    { Allowed Tabs }
    LTabsArray := LRoot.GetValue<TJSONArray>('allowedTabs', nil);
    if Assigned(LTabsArray) then
    begin
      for i := 0 to LTabsArray.Count - 1 do
        FAllowedTabs.Add(LTabsArray.Items[i].Value);
    end;

    { Permissões Granulares por Chave }
    LPermObj := LRoot.GetValue<TJSONObject>('permissoes', nil);
    if Assigned(LPermObj) then
    begin
      for i := 0 to LPermObj.Count - 1 do
      begin
        LPair := LPermObj.Pairs[i];
        if LPair.JsonValue is TJSONObject then
        begin
          LAcoes := TB2PermissaoAcoes.FromJSON(LPair.JsonValue as TJSONObject);
          FPermissoes.AddOrSetValue(LPair.JsonString.Value, LAcoes);
        end;
      end;
    end;
  finally
    LRoot.Free;
  end;
end;

function TB2PermissaoSession.HasPermission(const AChaveItem, AAcao: string): Boolean;
var
  LAcoes: TB2PermissaoAcoes;
begin
  Result := False;
  if FPermissoes.TryGetValue(AChaveItem, LAcoes) then
    Result := LAcoes.HasAction(AAcao);
end;

function TB2PermissaoSession.IsTabAllowed(const ATabSlug: string): Boolean;
begin
  Result := FAllowedTabs.Contains(ATabSlug);
end;

{ ============================================================================
  TB2PermissaoClient
  ============================================================================ }

constructor TB2PermissaoClient.Create(const ASystemUID: string;
  const AApiBaseUrl: string; const APublicKeyPem: string);
begin
  inherited Create;
  FSystemUID := Trim(ASystemUID);
  FApiBaseUrl := Trim(AApiBaseUrl);
  if (FApiBaseUrl <> '') and FApiBaseUrl.EndsWith('/') then
    FApiBaseUrl := Copy(FApiBaseUrl, 1, Length(FApiBaseUrl) - 1);

  FPublicKeyPem := APublicKeyPem;
  FCacheFilePath := TPath.Combine(ExtractFilePath(ParamStr(0)), 'b2permissao_offline.b2perm');
  FSession := TB2PermissaoSession.Create;
  FIsOfflineMode := False;
  FLastErrorMessage := '';
  FHttpTimeoutSec := 5;
end;

destructor TB2PermissaoClient.Destroy;
begin
  FSession.Free;
  inherited Destroy;
end;

function TB2PermissaoClient.GetMachineHash: string;
var
  LVolumeSerial: DWORD;
  LMaxComponentLen, LFlags: DWORD;
  LComputerName: array[0..MAX_COMPUTERNAME_LENGTH + 1] of Char;
  LSize: DWORD;
  LCombinedString: string;
begin
  LVolumeSerial := 0;
  GetVolumeInformation('C:\', nil, 0, @LVolumeSerial, LMaxComponentLen, LFlags, nil, 0);

  LSize := MAX_COMPUTERNAME_LENGTH + 1;
  if not GetComputerName(LComputerName, LSize) then
    LCombinedString := 'DELPHI_VCL_PC_' + IntToHex(LVolumeSerial, 8)
  else
    LCombinedString := string(LComputerName) + '_' + IntToHex(LVolumeSerial, 8);

  Result := THashSHA2.GetHashString(LCombinedString, THashSHA2.TSHA2Version.SHA256);
end;

function TB2PermissaoClient.GenerateRequestNonce: string;
var
  LGUID: TGUID;
begin
  CreateGUID(LGUID);
  FLocalNonce := GUIDToString(LGUID).Replace('{', '').Replace('}', '').ToLower;
  Result := FLocalNonce;
end;

function TB2PermissaoClient.PostHttp(const AEndpoint: string; ABody: TJSONObject;
  out AResponseStr: string; out AStatusCode: Integer): Boolean;
var
  LHttp: THTTPClient;
  LResponse: IHTTPResponse;
  LRequestStream: TStringStream;
  LUrl: string;
begin
  Result := False;
  AResponseStr := '';
  AStatusCode := 0;
  LHttp := THTTPClient.Create;
  try
    LHttp.ConnectionTimeout := FHttpTimeoutSec * 1000;
    LHttp.ResponseTimeout := FHttpTimeoutSec * 1000;
    LHttp.CustomHeaders['X-System-UID'] := FSystemUID;
    LHttp.ContentType := 'application/json';

    LUrl := FApiBaseUrl + AEndpoint;
    LRequestStream := TStringStream.Create(ABody.ToJSON, TEncoding.UTF8);
    try
      LResponse := LHttp.Post(LUrl, LRequestStream);
      AStatusCode := LResponse.StatusCode;
      AResponseStr := LResponse.ContentAsString(TEncoding.UTF8);
      Result := (AStatusCode >= 200) and (AStatusCode < 300);
    finally
      LRequestStream.Free;
    end;
  except
    on E: Exception do
    begin
      FLastErrorMessage := 'Falha de conexão com a API IAM: ' + E.Message;
      Result := False;
    end;
  end;
  LHttp.Free;
end;

function TB2PermissaoClient.InternalVerifySignatureWinApi(const ARawDataBytes, ASignatureBytes: TBytes): Boolean;
var
  LDerBytes: TBytes;
  LDerSize: DWORD;
  LProv: THandle;
  LKey: THandle;
  LHash: THandle;
  LKeyInfo: Pointer;
  LKeyInfoSize: DWORD;
  LPemAnsi: AnsiString;
  LReversedSig: TBytes;
  i, LLen: Integer;
begin
  Result := False;
  if (FPublicKeyPem = '') or (Length(ARawDataBytes) = 0) or (Length(ASignatureBytes) = 0) then
    Exit;

  LPemAnsi := AnsiString(FPublicKeyPem);
  LDerSize := 0;

  { 1. Converte Chave Pública PEM para Binário DER via CryptStringToBinaryA }
  if not CryptStringToBinaryA(PAnsiChar(LPemAnsi), Length(LPemAnsi),
    CRYPT_STRING_BASE64HEADER, nil, LDerSize, nil, nil) then
  begin
    { Tenta sem header }
    if not CryptStringToBinaryA(PAnsiChar(LPemAnsi), Length(LPemAnsi),
      CRYPT_STRING_BASE64, nil, LDerSize, nil, nil) then
      Exit;
  end;

  SetLength(LDerBytes, LDerSize);
  CryptStringToBinaryA(PAnsiChar(LPemAnsi), Length(LPemAnsi),
    CRYPT_STRING_BASE64HEADER, @LDerBytes[0], LDerSize, nil, nil);

  { 2. Decodifica estrutura X509_PUBLIC_KEY_INFO }
  LKeyInfoSize := 0;
  if not CryptDecodeObjectEx($00000001 {X509_ASN_ENCODING}, X509_PUBLIC_KEY_INFO,
    @LDerBytes[0], LDerSize, 0, nil, nil, LKeyInfoSize) then
    Exit;

  GetMem(LKeyInfo, LKeyInfoSize);
  try
    if not CryptDecodeObjectEx($00000001, X509_PUBLIC_KEY_INFO,
      @LDerBytes[0], LDerSize, 0, nil, LKeyInfo, LKeyInfoSize) then
      Exit;

    { 3. Adquire contexto de Provedor RSA_AES }
    LProv := 0;
    if not CryptAcquireContextW(LProv, nil, nil, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) then
      Exit;

    try
      LKey := 0;
      if not CryptImportPublicKeyInfo(LProv, $00000001, LKeyInfo, LKey) then
        Exit;

      try
        LHash := 0;
        if not CryptCreateHash(LProv, CALG_SHA_256, 0, 0, LHash) then
          Exit;

        try
          if not CryptHashData(LHash, @ARawDataBytes[0], Length(ARawDataBytes), 0) then
            Exit;

          { CryptoAPI no Windows espera a assinatura RSA em Little-Endian (invertida) }
          LLen := Length(ASignatureBytes);
          SetLength(LReversedSig, LLen);
          for i := 0 to LLen - 1 do
            LReversedSig[i] := ASignatureBytes[LLen - 1 - i];

          Result := CryptVerifySignatureW(LHash, @LReversedSig[0], LLen, LKey, nil, 0);
        finally
          CryptDestroyHash(LHash);
        end;
      finally
        CryptDestroyKey(LKey);
      end;
    finally
      CryptReleaseContext(LProv, 0);
    end;
  finally
    FreeMem(LKeyInfo);
  end;
end;

function TB2PermissaoClient.VerifySignatureRSA2048(const ARawPayloadJson, ASignatureBase64: string): Boolean;
var
  LDataBytes, LSigBytes: TBytes;
begin
  Result := False;
  if (ARawPayloadJson = '') or (ASignatureBase64 = '') then Exit;

  try
    LDataBytes := TEncoding.UTF8.GetBytes(ARawPayloadJson);
    LSigBytes := TNetEncoding.Base64.DecodeStringToBytes(ASignatureBase64);
    Result := InternalVerifySignatureWinApi(LDataBytes, LSigBytes);
  except
    Result := False;
  end;
end;

function TB2PermissaoClient.VerifyOfflinePassword(const APlainPassword, AVerifierString: string): Boolean;
var
  LParts: TArray<string>;
  LIterations: Integer;
  LSalt, LExpectedHex: string;
  LComputedBytes: TBytes;
  LComputedHex: string;
  i: Integer;
begin
  Result := False;
  if AVerifierString = '' then Exit;

  LParts := AVerifierString.Split(['$']);
  if (Length(LParts) <> 5) or (LParts[0] <> 'pbkdf2') or (LParts[1] <> 'sha256') then
    Exit;

  LIterations := StrToIntDef(LParts[2], 0);
  LSalt := LParts[3];
  LExpectedHex := LowerCase(LParts[4]);
  if (LIterations <= 0) or (LSalt = '') or (LExpectedHex = '') then Exit;

  LComputedBytes := PBKDF2_SHA256(APlainPassword, LSalt, LIterations, 32);
  LComputedHex := '';
  for i := 0 to High(LComputedBytes) do
    LComputedHex := LComputedHex + IntToHex(LComputedBytes[i], 2).ToLower;

  Result := (LComputedHex = LExpectedHex);
end;

procedure TB2PermissaoClient.SaveOfflineBundle(const ARawPayloadBase64, ASignatureBase64: string);
var
  LDiskBundle: TJSONObject;
begin
  try
    LDiskBundle := TJSONObject.Create;
    try
      LDiskBundle.AddPair('systemUid', FSystemUID);
      LDiskBundle.AddPair('rawPayloadBase64', ARawPayloadBase64);
      LDiskBundle.AddPair('signatureBase64', ASignatureBase64);
      LDiskBundle.AddPair('savedAt', DateTimeToISO8601(Now));
      TFile.WriteAllText(FCacheFilePath, LDiskBundle.ToJSON, TEncoding.UTF8);
    finally
      LDiskBundle.Free;
    end;
  except
    { Falha em salvar cache offline não interrompe o login online }
  end;
end;

function TB2PermissaoClient.LoadOfflineBundle(out ARawPayloadJson, ASignatureBase64: string): Boolean;
var
  LText: string;
  LDiskObj: TJSONObject;
  LRawBase64: string;
begin
  Result := False;
  ARawPayloadJson := '';
  ASignatureBase64 := '';

  if not TFile.Exists(FCacheFilePath) then
  begin
    FLastErrorMessage := 'Arquivo de contingência offline não encontrado (.b2perm). Faça login online ao menos uma vez neste PC.';
    Exit;
  end;

  try
    LText := TFile.ReadAllText(FCacheFilePath, TEncoding.UTF8);
    LDiskObj := TJSONObject.ParseJSONValue(LText) as TJSONObject;
    if not Assigned(LDiskObj) then Exit;
    try
      if LDiskObj.GetValue<string>('systemUid', '') <> FSystemUID then
      begin
        FLastErrorMessage := 'Cache offline pertence a outro Sistema UID.';
        Exit;
      end;

      LRawBase64 := LDiskObj.GetValue<string>('rawPayloadBase64', '');
      ASignatureBase64 := LDiskObj.GetValue<string>('signatureBase64', '');

      ARawPayloadJson := TEncoding.UTF8.GetString(TNetEncoding.Base64.DecodeStringToBytes(LRawBase64));
      Result := (ARawPayloadJson <> '') and (ASignatureBase64 <> '');
    finally
      LDiskObj.Free;
    end;
  except
    on E: Exception do
    begin
      FLastErrorMessage := 'Erro ao ler cache offline: ' + E.Message;
      Result := False;
    end;
  end;
end;

function TB2PermissaoClient.VerifyOfflineClockIntegrity(AIssuedAt: Int64; AMaxFirebirdDate: TDateTime): Boolean;
var
  LNowSec: Int64;
  LMaxFbSec: Int64;
begin
  Result := False;
  LNowSec := DateTimeToUnix(Now, False);

  { 1. O relógio do Windows não pode estar antes da data de emissão do pacote }
  if LNowSec < (AIssuedAt - 60) then
    raise EB2PermissaoClockRollbackException.Create(
      'ALERTA DE SEGURANÇA: O relógio desta estação foi atrasado! ' +
      'Data atual é anterior à emissão da licença assinada.');

  { 2. Se informada a maior data de movimento do Firebird, o relógio não pode estar antes do banco }
  if AMaxFirebirdDate > 0 then
  begin
    LMaxFbSec := DateTimeToUnix(AMaxFirebirdDate, False);
    if LNowSec < (LMaxFbSec - 300) then
      raise EB2PermissaoClockRollbackException.Create(
        'ALERTA DE SEGURANÇA: Data do Windows inferior à última movimentação gravada no Firebird!');
  end;

  Result := True;
end;

function TB2PermissaoClient.Login(const AUsuario, ASenha: string;
  AEmpresaCodigo: Integer; AMaxFirebirdDate: TDateTime): Boolean;
var
  LBody: TJSONObject;
  LNonce: string;
  LMachineHash: string;
  LResponseStr: string;
  LStatusCode: Integer;
  LOnlineSuccess: Boolean;
  LResObj: TJSONObject;
  LRawPayloadBase64, LSignatureBase64: string;
  LPayloadJson: string;
  LNowSec: Int64;
begin
  Result := False;
  FIsOfflineMode := False;
  FLastErrorMessage := '';

  LNonce := GenerateRequestNonce;
  LMachineHash := GetMachineHash;

  { Tenta Obter Chave Pública da API se não estiver chumbada }
  if FPublicKeyPem = '' then
  begin
    if PostHttp('/api/v1/b2permissao/public-key', TJSONObject.Create, LResponseStr, LStatusCode) then
    begin
      LResObj := TJSONObject.ParseJSONValue(LResponseStr) as TJSONObject;
      if Assigned(LResObj) then
      begin
        FPublicKeyPem := LResObj.GetValue<string>('publicKeyPem', '');
        LResObj.Free;
      end;
    end;
  end;

  { ── TENTATIVA ONLINE ────────────────────────────────────────────────────── }
  LBody := TJSONObject.Create;
  try
    LBody.AddPair('usuario', AUsuario);
    LBody.AddPair('senha', ASenha);
    LBody.AddPair('systemUid', FSystemUID);
    LBody.AddPair('requestNonce', LNonce);
    LBody.AddPair('machineHash', LMachineHash);
    LBody.AddPair('empresaCodigo', TJSONNumber.Create(AEmpresaCodigo));

    LOnlineSuccess := PostHttp('/api/v1/b2permissao/auth/login', LBody, LResponseStr, LStatusCode);
  finally
    LBody.Free;
  end;

  if LOnlineSuccess then
  begin
    LResObj := TJSONObject.ParseJSONValue(LResponseStr) as TJSONObject;
    if not Assigned(LResObj) then
    begin
      FLastErrorMessage := 'Resposta da API não é um JSON válido.';
      Exit;
    end;

    try
      LRawPayloadBase64 := LResObj.GetValue<string>('rawPayloadBase64', '');
      LSignatureBase64 := LResObj.GetValue<string>('signatureBase64', '');

      if (LRawPayloadBase64 = '') or (LSignatureBase64 = '') then
      begin
        FLastErrorMessage := 'Resposta da API não contém pacote assinado RSA-2048.';
        Exit;
      end;

      LPayloadJson := TEncoding.UTF8.GetString(TNetEncoding.Base64.DecodeStringToBytes(LRawPayloadBase64));

      { 1. Valida Assinatura RSA-2048 da Chave Pública }
      if not VerifySignatureRSA2048(LPayloadJson, LSignatureBase64) then
        raise EB2PermissaoInvalidSignatureException.Create(
          'FALHA GRAVE: A assinatura RSA-2048 do pacote de permissões recebido é inválida! ' +
          'Possível ataque de Man-In-The-Middle ou Proxy interceptador.');

      { 2. Carrega a Sessão em RAM }
      FSession.LoadFromPayloadJSON(LPayloadJson, LSignatureBase64);

      { 3. Confere Nonce Anti-Replay }
      if FSession.RequestNonce <> LNonce then
        raise EB2PermissaoReplayAttackException.Create(
          'ATAQUE DE REPLAY DETECTADO: O nonce do servidor não confere com o gerado nesta requisição.');

      { 4. Salva Cache Assinado para Contingência Offline }
      SaveOfflineBundle(LRawPayloadBase64, LSignatureBase64);

      FIsOfflineMode := False;
      Result := True;
      Exit;
    finally
      LResObj.Free;
    end;
  end;

  { ── FALLBACK CONTINGÊNCIA OFFLINE ───────────────────────────────────────── }
  FIsOfflineMode := True;
  if not LoadOfflineBundle(LPayloadJson, LSignatureBase64) then
  begin
    { Mensagem de erro já preenchida em LoadOfflineBundle }
    Exit;
  end;

  { 1. Valida Assinatura RSA-2048 do Cache Local }
  if not VerifySignatureRSA2048(LPayloadJson, LSignatureBase64) then
    raise EB2PermissaoInvalidSignatureException.Create(
      'ALERTA DE SEGURANÇA: O arquivo local de permissões (.b2perm) foi adulterado externamente!');

  { 2. Carrega Sessão em RAM }
  FSession.LoadFromPayloadJSON(LPayloadJson, LSignatureBase64);

  { 3. Confere Hardware Lock (Machine Hash) contra cópia do arquivo .b2perm para outro PC }
  if (FSession.MachineHash <> '') and (FSession.MachineHash <> 'UNBOUND_DEV_STATION') then
  begin
    if FSession.MachineHash <> LMachineHash then
      raise EB2PermissaoHardwareMismatchException.Create(
        'VIOLAÇÃO DE LICENÇA: O arquivo de permissões pertence a outro computador e não pode ser copiado.');
  end;

  { 4. Confere Trava de Relógio (Anti-Clock-Rollback) }
  VerifyOfflineClockIntegrity(FSession.IssuedAt, AMaxFirebirdDate);

  { 5. Confere Validade Temporal do Cache Offline }
  LNowSec := DateTimeToUnix(Now, False);
  if LNowSec > FSession.OfflineExpiresAt then
    raise EB2PermissaoOfflineExpiredException.Create(
      'O período de contingência offline deste terminal expirou. Conecte-se à internet para renovar o acesso.');

  { 6. Confere Usuário e Senha Digitada contra o PBKDF2 assinado }
  if LowerCase(Trim(FSession.Usuario.Login)) <> LowerCase(Trim(AUsuario)) then
  begin
    FLastErrorMessage := 'O usuário informado não confere com o último usuário armazenado em cache offline.';
    Exit;
  end;

  if not VerifyOfflinePassword(ASenha, FSession.Usuario.OfflineVerifier) then
  begin
    FLastErrorMessage := 'Senha incorreta para contingência offline.';
    Exit;
  end;

  Result := True;
end;

function TB2PermissaoClient.HasPermission(const AChaveItem: string; const AAcao: string): Boolean;
begin
  Result := FSession.HasPermission(AChaveItem, AAcao);
end;

function TB2PermissaoClient.IsTabAllowed(const ATabSlug: string): Boolean;
begin
  Result := FSession.IsTabAllowed(ATabSlug);
end;

procedure TB2PermissaoClient.ApplyToForm(AForm: TForm);
var
  i: Integer;
  LComp: TComponent;
  LAction: TCustomAction;
  LMenuItem: TMenuItem;
  LControl: TControl;
  LChave: string;
  LPermitido: Boolean;
begin
  if not Assigned(AForm) then Exit;

  { Varre componentes do Form e aplica segurança por Action, MenuItem e Control }
  for i := 0 to AForm.ComponentCount - 1 do
  begin
    LComp := AForm.Components[i];

    { 1. TCustomAction / TAction }
    if LComp is TCustomAction then
    begin
      LAction := TCustomAction(LComp);
      { Se o TagString ou Name estiver registrado nas permissões }
      LChave := LAction.Category;
      if LChave = '' then LChave := LAction.Name;

      if FSession.Permissoes.ContainsKey(LChave) then
      begin
        LPermitido := FSession.HasPermission(LChave, 'ler');
        LAction.Visible := LPermitido;
        LAction.Enabled := LPermitido and (FSession.HasPermission(LChave, 'editar') or FSession.HasPermission(LChave, 'criar'));
      end;
    end
    { 2. TMenuItem }
    else if LComp is TMenuItem then
    begin
      LMenuItem := TMenuItem(LComp);
      LChave := LMenuItem.Name;
      if FSession.Permissoes.ContainsKey(LChave) then
      begin
        LPermitido := FSession.HasPermission(LChave, 'ler');
        LMenuItem.Visible := LPermitido;
        LMenuItem.Enabled := LPermitido;
      end;
    end
    { 3. TControl com Hint ou Tag formatado }
    else if LComp is TControl then
    begin
      LControl := TControl(LComp);
      LChave := LControl.Name;
      if FSession.Permissoes.ContainsKey(LChave) then
      begin
        LPermitido := FSession.HasPermission(LChave, 'ler');
        LControl.Visible := LPermitido;
        LControl.Enabled := LPermitido;
      end;
    end;
  end;
end;

function TB2PermissaoClient.SyncFormCatalog(AForm: TForm): Boolean;
var
  LBody: TJSONObject;
  LItensArray: TJSONArray;
  LItemObj: TJSONObject;
  i: Integer;
  LComp: TComponent;
  LAction: TCustomAction;
  LMenuItem: TMenuItem;
  LResponseStr: string;
  LStatusCode: Integer;
begin
  Result := False;
  if not Assigned(AForm) then Exit;

  LBody := TJSONObject.Create;
  try
    LItensArray := TJSONArray.Create;
    LBody.AddPair('itens', LItensArray);

    for i := 0 to AForm.ComponentCount - 1 do
    begin
      LComp := AForm.Components[i];

      if LComp is TCustomAction then
      begin
        LAction := TCustomAction(LComp);
        LItemObj := TJSONObject.Create;
        LItemObj.AddPair('modulo', LAction.Category);
        LItemObj.AddPair('chaveItem', LAction.Name);
        LItemObj.AddPair('titulo', LAction.Caption);
        LItemObj.AddPair('delphiComponent', LAction.Name);
        LItensArray.AddElement(LItemObj);
      end
      else if LComp is TMenuItem then
      begin
        LMenuItem := TMenuItem(LComp);
        if (LMenuItem.Caption <> '-') and (LMenuItem.Name <> '') then
        begin
          LItemObj := TJSONObject.Create;
          LItemObj.AddPair('modulo', AForm.Caption);
          LItemObj.AddPair('chaveItem', LMenuItem.Name);
          LItemObj.AddPair('titulo', LMenuItem.Caption);
          LItemObj.AddPair('delphiComponent', LMenuItem.Name);
          LItensArray.AddElement(LItemObj);
        end;
      end;
    end;

    Result := PostHttp('/api/v1/b2permissao/sistemas/' + FSystemUID + '/sync-catalogo',
      LBody, LResponseStr, LStatusCode);
  finally
    LBody.Free;
  end;
end;

end.
