diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index aa500ca..1eb2653 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -104,7 +104,7 @@ jobs: with: php-version: '8.4' coverage: none - extensions: curl, dom, fileinfo, mbstring, openssl, pdo_sqlite, sqlite3, xml, zip + extensions: curl, dom, fileinfo, mbstring, openssl, pdo_sqlite, sodium, sqlite3, xml, zip tools: composer:v2 - uses: actions/setup-node@v4 with: diff --git a/.github/workflows/php-ci.yml b/.github/workflows/php-ci.yml index f5e6c7b..ec99fd4 100644 --- a/.github/workflows/php-ci.yml +++ b/.github/workflows/php-ci.yml @@ -22,7 +22,7 @@ jobs: - uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} - extensions: curl, dom, fileinfo, mbstring, openssl, pdo_sqlite, sqlite3, xml, zip + extensions: curl, dom, fileinfo, mbstring, openssl, pdo_sqlite, sodium, sqlite3, xml, zip coverage: none tools: composer:v2 - name: Verify dependencies and install without side effects diff --git a/app/AutomaticKimai/LocalStore.php b/app/AutomaticKimai/LocalStore.php index 576415a..abc74d7 100644 --- a/app/AutomaticKimai/LocalStore.php +++ b/app/AutomaticKimai/LocalStore.php @@ -156,6 +156,8 @@ public function disconnectNextcloud(): void 'NEXTCLOUD_URL','NEXTCLOUD_USERNAME','NEXTCLOUD_LOGIN_NAME','NEXTCLOUD_APP_PASSWORD' ]); $this->write('nextcloud-login.json',[]); + $this->write('settings-sync-state.json',['enabled'=>false,'state'=>'disabled']); + $this->write('settings-sync-key.json',[]); } public function sources(): array diff --git a/app/AutomaticKimai/MadelineTelegramAdapter.php b/app/AutomaticKimai/MadelineTelegramAdapter.php index e7c2548..6a5c547 100644 --- a/app/AutomaticKimai/MadelineTelegramAdapter.php +++ b/app/AutomaticKimai/MadelineTelegramAdapter.php @@ -42,7 +42,7 @@ public function __construct(string $sessionPath,int $apiId,string $apiHash) throw new RuntimeException('MadelineProto session not imported; run the controlled migration first'); } if (is_link($sessionPath))throw new RuntimeException('Symlinked Telegram session forbidden'); - $this->api=new API($sessionPath,self::settings($apiId,$apiHash,dirname($sessionPath).'/telegram-user.log')); + $this->api=new API($sessionPath); $me=$this->api->getSelf(); if (!is_array($me)||($me['bot']??false)) { throw new RuntimeException('Authorized individual Telegram user session required'); diff --git a/app/AutomaticKimai/NextcloudSettingsDav.php b/app/AutomaticKimai/NextcloudSettingsDav.php new file mode 100644 index 0000000..d528e60 --- /dev/null +++ b/app/AutomaticKimai/NextcloudSettingsDav.php @@ -0,0 +1,173 @@ +fake=$fake; + $this->checkIdentity=$checkIdentity; + } + + public static function scope(array $credentials): string + { + [$base,$uid]=self::address($credentials); + return hash('sha256',$base."\n".$uid); + } + + private static function address(array $creds): array + { + $base=NextcloudLoginFlow::normalizeServer((string)($creds['NEXTCLOUD_URL']??'')); + $uid=(string)($creds['NEXTCLOUD_USERNAME']??''); + $login=(string)($creds['NEXTCLOUD_LOGIN_NAME']??$uid); + $password=(string)($creds['NEXTCLOUD_APP_PASSWORD']??''); + if ($uid==='' || strlen($uid)>200 || strpbrk($uid,"/\\\r\n")!==false || + $login==='' || str_contains($login,':') || $password==='') { + throw new RuntimeException('Conecte sua conta Nextcloud neste computador primeiro.'); + } + return [$base,$uid,[$login,$password]]; + } + + private function endpoints(array $creds): array + { + [$base,$uid,$auth]=self::address($creds); + $dir=$base.'/remote.php/dav/files/'.rawurlencode($uid).'/Automatic%20Kimai'; + return [$dir,$dir.'/settings-v1.encrypted',$auth]; + } + + private function verified(array $creds): void + { + if ($this->checkIdentity!==null) { + $account=($this->checkIdentity)($creds); + } else { + $account=(new NextcloudIdentity(new HttpTransport()))->profile($creds); + } + if (!is_array($account) || + ($account['username']??null)!==($creds['NEXTCLOUD_USERNAME']??null)) { + throw new RuntimeException('A conta Nextcloud autenticada não corresponde ao backup.'); + } + } + + private static function etag(mixed $etag): string + { + if (!is_string($etag) || + !preg_match('/^"[A-Za-z0-9._:-]{1,160}"$/D',$etag)) { + throw new RuntimeException('O servidor não forneceu um ETag forte e seguro.'); + } + return $etag; + } + + private function request(string $method,string $url,array $headers,array $auth,?string $body=null): array + { + if (!in_array($method,['GET','PUT','MKCOL'],true) || + !str_starts_with($url,'https://') || strlen($url)>800) { + throw new RuntimeException('Operação WebDAV inválida.'); + } + if ($this->fake!==null) { + $response=($this->fake)($method,$url,$headers,$body,$auth); + } else { + $curl=curl_init($url); + if (!$curl)throw new RuntimeException('Conexão WebDAV indisponível.'); + $content=''; + $headerMap=[]; + $opts=[ + CURLOPT_CUSTOMREQUEST=>$method, + CURLOPT_RETURNTRANSFER=>false, + CURLOPT_CONNECTTIMEOUT=>5,CURLOPT_TIMEOUT=>20, + CURLOPT_FOLLOWLOCATION=>false,CURLOPT_MAXREDIRS=>0, + CURLOPT_SSL_VERIFYPEER=>true,CURLOPT_SSL_VERIFYHOST=>2, + CURLOPT_PROXY=>'',CURLOPT_HTTPAUTH=>CURLAUTH_BASIC, + CURLOPT_USERPWD=>$auth[0].':'.$auth[1], + CURLOPT_HTTPHEADER=>array_merge(['Accept: application/octet-stream'],$headers), + CURLOPT_WRITEFUNCTION=>static function($handle,string $chunk) use (&$content): int { + if (strlen($content)+strlen($chunk)>self::MAX_RESPONSE)return 0; + $content.=$chunk; + return strlen($chunk); + }, + CURLOPT_HEADERFUNCTION=>static function($handle,string $line) use (&$headerMap): int { + if (str_starts_with(strtolower($line),'etag:')) { + $headerMap['etag']=trim(substr($line,5)); + } + return strlen($line); + }, + ]; + if ($method==='PUT' && $body!==null)$opts[CURLOPT_POSTFIELDS]=$body; + curl_setopt_array($curl,$opts); + $result=curl_exec($curl); + $status=(int)curl_getinfo($curl,CURLINFO_RESPONSE_CODE); + curl_close($curl); + if ($result===false || strlen($content)>self::MAX_RESPONSE) { + throw new RuntimeException('Falha de transferência WebDAV.'); + } + $response=['status'=>$status,'body'=>$content,'headers'=>$headerMap]; + } + if (!is_array($response)||!is_int($response['status']??null) || + !is_string($response['body']??null) || + strlen($response['body'])>self::MAX_RESPONSE) { + throw new RuntimeException('Resposta WebDAV inválida.'); + } + return $response; + } + + /** @return array{etag:string,raw:string}|null */ + public function read(array $credentials): ?array + { + $this->verified($credentials); + [, $file, $auth]=$this->endpoints($credentials); + $response=$this->request('GET',$file,[],$auth); + if ($response['status']===404)return null; + if ($response['status']!==200)throw new RuntimeException('Não foi possível ler o backup do Nextcloud.'); + return [ + 'etag'=>self::etag($response['headers']['etag']??null), + 'raw'=>$response['body'], + ]; + } + + /** + * Precondition prevents clobbering a backup modified by another device. + * When the first backup is created, If-None-Match:* prevents races. + */ + public function write(array $credentials,string $encrypted,?string $expectedEtag): array + { + if (strlen($encrypted)>self::MAX_RESPONSE)throw new RuntimeException('Backup muito grande.'); + $this->verified($credentials); + [$dir,$file,$auth]=$this->endpoints($credentials); + if ($expectedEtag===null) { + $folder=$this->request('MKCOL',$dir,[],$auth); + if (!in_array($folder['status'],[201,405],true)) { + throw new RuntimeException('Não foi possível preparar a pasta de backup.'); + } + $condition='If-None-Match: *'; + } else { + $condition='If-Match: '.self::etag($expectedEtag); + } + $response=$this->request('PUT',$file,[ + 'Content-Type: application/octet-stream', + $condition, + ],$auth,$encrypted); + if (in_array($response['status'],[409,412,423],true)) { + throw new SettingsSyncConflict('Outro dispositivo modificou o backup. Revise o conflito.'); + } + if (!in_array($response['status'],[200,201,204],true)) { + throw new RuntimeException('O Nextcloud não aceitou a gravação condicionada.'); + } + $current=$this->read($credentials); + if ($current===null || !hash_equals($encrypted,$current['raw'])) { + throw new SettingsSyncConflict('O backup mudou durante a gravação; nenhum estado foi confirmado.'); + } + return $current; + } +} diff --git a/app/AutomaticKimai/SettingsSnapshot.php b/app/AutomaticKimai/SettingsSnapshot.php new file mode 100644 index 0000000..637d41a --- /dev/null +++ b/app/AutomaticKimai/SettingsSnapshot.php @@ -0,0 +1,170 @@ +profile()?->toArray(); + if ($profile!==null) { + foreach (self::LOCAL_PROFILE as $key)unset($profile[$key]); + $profile['sync_mode']='review_only'; + $profile['allow_auto_nonbillable_preview']=false; + } + $sources=array_intersect_key($store->sources(),array_flip(self::SOURCES)); + $sources['telegram_setup']=$sources['telegram_setup']??false; + $credentials=$includeSecrets?array_intersect_key( + $store->credentials(),array_flip(self::SHARED_CREDENTIALS) + ):[]; + return [ + 'schema'=>1,'include_credentials'=>$includeSecrets, + 'profile'=>$profile,'sources'=>$sources,'credentials'=>$credentials, + ]; + } + + /** Check remote shape BEFORE any local state changes. */ + public static function validated(array $raw,bool $includeSecrets): array + { + if (count($raw)!==5 || array_diff(array_keys($raw),['schema','include_credentials','profile','sources','credentials'])!==[] || + $raw['schema']!==1 || $raw['include_credentials']!==$includeSecrets || + !is_array($raw['sources']) || !is_array($raw['credentials']) || + ($raw['profile']!==null && !is_array($raw['profile']))) { + throw new InvalidArgumentException('O backup não corresponde às opções de compartilhamento autorizadas.'); + } + if (array_diff(array_keys($raw['sources']),self::SOURCES)!==[] || + array_diff(array_keys($raw['credentials']),self::SHARED_CREDENTIALS)!==[]) { + throw new InvalidArgumentException('Backup contém configurações não suportadas.'); + } + foreach ($raw['sources'] as $enabled) { + if (!is_bool($enabled))throw new InvalidArgumentException('Fonte de dados inválida.'); + } + // The collector is a mandatory invariant. Reject the entire backup + // before touching credentials/profile to avoid partial restoration. + if (($raw['sources']['activitywatch']??true)!==true) { + throw new InvalidArgumentException('Backup contém fontes incompatíveis.'); + } + foreach ($raw['credentials'] as $value) { + if (!is_string($value) || $value==='' || strlen($value)>1200) { + throw new InvalidArgumentException('Credencial importada inválida.'); + } + } + if (!$includeSecrets && $raw['credentials']!==[]) { + throw new InvalidArgumentException('Credenciais não autorizadas no backup.'); + } + $profile=$raw['profile']; + if ($profile!==null) { + foreach (self::LOCAL_PROFILE as $key) { + if (array_key_exists($key,$profile)) { + throw new InvalidArgumentException('Backup contém dados exclusivos de outro dispositivo.'); + } + } + $profile['sync_mode']='review_only'; + $profile['allow_auto_nonbillable_preview']=false; + // Restore per-device Telegram group selection only after a new authorization. + // Validate through Profile but retain only portable fields from the + // encrypted document. Adding Profile defaults would change the + // canonical remote digest on every read and create false conflicts. + new Profile(array_replace($profile,[ + 'work_messenger_dialog_ids'=>[], + 'work_messenger_group_titles'=>[], + 'work_messenger_labels'=>[], + 'work_messenger_classification_labels'=>[], + 'work_messenger_recommendations_reviewed'=>false, + ])); + } + return [ + 'schema'=>1,'include_credentials'=>$includeSecrets, + 'profile'=>$profile,'sources'=>$raw['sources'], + 'credentials'=>$raw['credentials'], + ]; + } + + public static function digest(array $data): string + { + return CanonicalJson::digest($data,false); + } + + public static function hasLocalConfiguration(LocalStore $store): bool + { + if ($store->profile()!==null)return true; + $credentials=$store->credentials(); + foreach (self::SHARED_CREDENTIALS as $key) { + if (!empty($credentials[$key]))return true; + } + $sources=$store->sources(); + foreach (self::SOURCES as $key) { + if (($sources[$key]??false)===true && !in_array($key,[ + 'activitywatch','chatgpt_browser','claude_browser', + ],true))return true; + } + return false; + } + + /** Token changes on another device must not silently replace an active login. */ + public static function wouldReplaceActiveCredentials(LocalStore $store,array $snapshot): bool + { + $local=$store->credentials(); + $telegramActive=$store->sources()['telegram']??false; + foreach ($snapshot['credentials'] as $key=>$remoteValue) { + if (empty($local[$key]) || $local[$key]===$remoteValue)continue; + if (in_array($key,['GITHUB_TOKEN','KIMAI_API_TOKEN','KIMAI_BASE_URL'],true)) { + return true; + } + if ($telegramActive && in_array($key,['TELEGRAM_API_ID','TELEGRAM_API_HASH'],true)) { + return true; + } + } + return false; + } + + public static function restore(LocalStore $store,array $snapshot): void + { + $profile=$snapshot['profile']; + $credentials=$snapshot['credentials']; + $sources=$snapshot['sources']; + // Do not alter active Telegram session or its per-device consent. + $oldSources=$store->sources(); + unset($sources['telegram']); + if ($oldSources['telegram']??false) { + $sources['telegram_setup']=true; + // This device already owns a distinct MTProto session. Importing + // a different app API identity could invalidate its IPC state. + unset($credentials['TELEGRAM_API_ID'],$credentials['TELEGRAM_API_HASH']); + } + if ($profile!==null) { + $existing=$store->profile()?->toArray()??[]; + foreach (self::LOCAL_PROFILE as $key) { + if (array_key_exists($key,$existing))$profile[$key]=$existing[$key]; + } + $profile=new Profile($profile); + } + $updates=$sources; + if ($credentials!==[])$store->saveCredentials(array_replace($credentials,[ + 'KIMAI_WRITE_ENABLED'=>'false','KIMAI_AUTO_PREVIEW_OPT_IN'=>'false', + 'KIMAI_MANUAL_PREVIEW_ENABLED'=>'false', + ])); + if ($profile!==null)$store->saveProfile($profile); + $store->setSources($updates); + } +} diff --git a/app/AutomaticKimai/SettingsSyncConflict.php b/app/AutomaticKimai/SettingsSyncConflict.php new file mode 100644 index 0000000..9dc269b --- /dev/null +++ b/app/AutomaticKimai/SettingsSyncConflict.php @@ -0,0 +1,8 @@ +store->read(self::STATE,['enabled'=>false]); + return [ + 'enabled'=>$state['enabled']??false, + 'state'=>$state['state']??'disabled', + 'synced_at'=>$state['synced_at']??null, + 'include_credentials'=>$state['include_credentials']??false, + ]; + } + + private function credentials(): array + { + $creds=$this->store->credentials(); + NextcloudSettingsDav::scope($creds); + return $creds; + } + + private function saveKey(string $key,string $salt): void + { + $this->store->write(self::KEY,[ + 'wrapped'=>Crypt::encryptString(base64_encode($key)), + 'salt'=>base64_encode($salt), + ]); + } + + private function key(): array + { + $raw=$this->store->read(self::KEY); + if (!is_string($raw['wrapped']??null)||!is_string($raw['salt']??null)) { + throw new RuntimeException('Ative a sincronização com sua senha de recuperação.'); + } + try { + $key=base64_decode(Crypt::decryptString($raw['wrapped']),true); + $salt=base64_decode($raw['salt'],true); + } catch (Throwable) { + throw new RuntimeException('A chave local do backup não está disponível.'); + } + if (!is_string($key)||strlen($key)!==32 || + !is_string($salt)||strlen($salt)!==SODIUM_CRYPTO_PWHASH_SALTBYTES) { + throw new RuntimeException('Chave local inválida; reative o backup.'); + } + return [$key,$salt]; + } + + private function withLock(callable $callback): mixed + { + $path=$this->store->root().'/settings-sync.lock'; + if (is_link($path))throw new RuntimeException('Arquivo de lock inseguro.'); + $handle=fopen($path,'c'); + if ($handle===false)throw new RuntimeException('Não foi possível abrir lock do backup.'); + chmod($path,0600); + if (!flock($handle,LOCK_EX|LOCK_NB)) { + fclose($handle); + throw new RuntimeException('Outra operação de sincronização está em andamento.'); + } + try {return $callback();} + finally {flock($handle,LOCK_UN);fclose($handle);} + } + + private static function saved(array $state,string $label, + ?string $localDigest=null,?string $remoteDigest=null, + ?string $etag=null): array + { + $state['state']=$label; + if ($localDigest!==null)$state['last_local_digest']=$localDigest; + if ($remoteDigest!==null)$state['last_remote_digest']=$remoteDigest; + if ($etag!==null)$state['remote_etag']=$etag; + if ($label==='synced')$state['synced_at']=gmdate('c'); + return $state; + } + + /** + * First device creates encrypted backup. Subsequent device decrypts it, + * and restores only when no existing local configuration would be replaced. + */ + public function enable(string $passphrase,bool $includeSecrets): string + { + return $this->withLock(function() use ($passphrase,$includeSecrets): string { + $creds=$this->credentials(); + $scope=NextcloudSettingsDav::scope($creds); + $state=$this->store->read(self::STATE); + if ($state['enabled']??false) { + throw new RuntimeException('Desative primeiro para trocar a chave ou as opções do backup.'); + } + $remote=$this->dav->read($creds); + $local=SettingsSnapshot::fromStore($this->store,$includeSecrets); + if ($remote===null) { + $salt=SettingsVault::generateSalt(); + $key=SettingsVault::derive($passphrase,$salt); + $encrypted=SettingsVault::seal($local,$key,$salt,$scope); + $created=$this->dav->write($creds,$encrypted,null); + $etag=$created['etag']; + $digest=SettingsSnapshot::digest($local); + $label='created'; + $state=self::saved([ + 'enabled'=>true,'include_credentials'=>$includeSecrets, + 'scope'=>$scope, + ],'synced',$digest,$digest,$etag); + } else { + [$raw,$key,$salt]=SettingsVault::unlock($remote['raw'],$passphrase,$scope); + $snapshot=SettingsSnapshot::validated($raw,$includeSecrets); + $digest=SettingsSnapshot::digest($snapshot); + $state=[ + 'enabled'=>true,'include_credentials'=>$includeSecrets, + 'scope'=>$scope,'remote_etag'=>$remote['etag'], + ]; + if (SettingsSnapshot::hasLocalConfiguration($this->store)) { + $label='needs_resolution'; + $state=self::saved($state,$label); + } else { + SettingsSnapshot::restore($this->store,$snapshot); + $localDigest=SettingsSnapshot::digest( + SettingsSnapshot::fromStore($this->store,$includeSecrets) + ); + $label='restored'; + $state=self::saved($state,'synced',$localDigest,$digest,$remote['etag']); + } + } + $this->saveKey($key,$salt); + sodium_memzero($key); + $this->store->write(self::STATE,$state); + return $label; + }); + } + + /** Use explicitly when local/remote started from different settings. */ + public function resolve(string $decision): string + { + if (!in_array($decision,['remote','local'],true)) { + throw new RuntimeException('Escolha inválida de resolução.'); + } + return $this->withLock(function() use ($decision): string { + [$state,$creds,$scope,$key,$salt]=$this->context(); + try { + $remote=$this->dav->read($creds); + if ($remote===null)throw new RuntimeException('Backup remoto ausente; operação cancelada.'); + $snapshot=SettingsSnapshot::validated( + SettingsVault::open($remote['raw'],$key,$scope), + $state['include_credentials'] + ); + // Even an explicit resolve must not silently use a newer + // remote version that arrived after the conflict was displayed. + if ($remote['etag']!==($state['remote_etag']??null)) { + $this->store->write(self::STATE, + self::saved($state,'conflict',etag:$remote['etag'])); + throw new SettingsSyncConflict('Backup remoto mudou; revise o conflito novamente.'); + } + if ($decision==='local') { + $local=SettingsSnapshot::fromStore($this->store,$state['include_credentials']); + $written=$this->dav->write( + $creds,SettingsVault::seal($local,$key,$salt,$scope),$remote['etag'] + ); + $digest=SettingsSnapshot::digest($local); + $state=self::saved($state,'synced',$digest,$digest,$written['etag']); + } else { + SettingsSnapshot::restore($this->store,$snapshot); + $localDigest=SettingsSnapshot::digest( + SettingsSnapshot::fromStore($this->store,$state['include_credentials']) + ); + $state=self::saved($state,'synced',$localDigest, + SettingsSnapshot::digest($snapshot),$remote['etag']); + } + $this->store->write(self::STATE,$state); + return $decision==='local'?'uploaded':'restored'; + } finally {sodium_memzero($key);} + }); + } + + private function context(): array + { + $state=$this->store->read(self::STATE); + if (!($state['enabled']??false) || !is_bool($state['include_credentials']??null)) { + throw new RuntimeException('Sincronização desativada.'); + } + $creds=$this->credentials(); + $scope=NextcloudSettingsDav::scope($creds); + if (!is_string($state['scope']??null) || !hash_equals($state['scope'],$scope)) { + throw new RuntimeException('A conexão Nextcloud mudou; desative e reconfigure o backup.'); + } + [$key,$salt]=$this->key(); + return [$state,$creds,$scope,$key,$salt]; + } + + public function synchronize(): string + { + return $this->withLock(function(): string { + [$state,$creds,$scope,$key,$salt]=$this->context(); + try { + if (($state['state']??null)==='needs_resolution' || + ($state['state']??null)==='conflict')return 'needs_resolution'; + $remote=$this->dav->read($creds); + if ($remote===null)throw new RuntimeException('Backup remoto ausente; não será recriado automaticamente.'); + if (!is_string($state['last_local_digest']??null)|| + !is_string($state['last_remote_digest']??null)) { + throw new RuntimeException('Histórico de sincronização incompleto.'); + } + $remotePayload=SettingsSnapshot::validated( + SettingsVault::open($remote['raw'],$key,$scope), + $state['include_credentials'] + ); + $local=SettingsSnapshot::fromStore($this->store,$state['include_credentials']); + $localHash=SettingsSnapshot::digest($local); + $remoteHash=SettingsSnapshot::digest($remotePayload); + $localChanged=$localHash!==$state['last_local_digest']; + $remoteChanged=$remoteHash!==$state['last_remote_digest']; + if ($localChanged && $remoteChanged) { + $state=self::saved($state,'conflict',etag:$remote['etag']); + $this->store->write(self::STATE,$state); + return 'conflict'; + } + if ($remoteChanged && + SettingsSnapshot::wouldReplaceActiveCredentials($this->store,$remotePayload)) { + $state=self::saved($state,'conflict',etag:$remote['etag']); + $this->store->write(self::STATE,$state); + return 'conflict'; + } + if ($remoteChanged) { + SettingsSnapshot::restore($this->store,$remotePayload); + $localHash=SettingsSnapshot::digest( + SettingsSnapshot::fromStore($this->store,$state['include_credentials']) + ); + $label='restored'; + $state=self::saved($state,'synced',$localHash,$remoteHash,$remote['etag']); + } elseif ($localChanged) { + $written=$this->dav->write( + $creds,SettingsVault::seal($local,$key,$salt,$scope),$remote['etag'] + ); + $label='uploaded'; + $state=self::saved($state,'synced',$localHash,$localHash,$written['etag']); + } else { + $label='unchanged'; + $state=self::saved($state,'synced',$localHash,$remoteHash,$remote['etag']); + } + $this->store->write(self::STATE,$state); + return $label; + } catch (SettingsSyncConflict) { + $state=self::saved($state,'conflict'); + $this->store->write(self::STATE,$state); + return 'conflict'; + } finally {sodium_memzero($key);} + }); + } + + /** Stops the local sync and forgets its cached key; remote backup remains. */ + public function disable(): void + { + $this->withLock(function(): void { + $this->store->write(self::STATE,['enabled'=>false,'state'=>'disabled']); + $this->store->write(self::KEY,[]); + }); + } +} diff --git a/app/AutomaticKimai/SettingsVault.php b/app/AutomaticKimai/SettingsVault.php new file mode 100644 index 0000000..f29c0f1 --- /dev/null +++ b/app/AutomaticKimai/SettingsVault.php @@ -0,0 +1,131 @@ +1024) { + throw new RuntimeException('Use uma senha de recuperação exclusiva com pelo menos 16 caracteres.'); + } + if (strlen($salt)!==SODIUM_CRYPTO_PWHASH_SALTBYTES) { + throw new RuntimeException('Formato de backup inválido.'); + } + return sodium_crypto_pwhash( + SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES, + $passphrase,$salt,self::OPS,self::MEM,SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13 + ); + } + + private static function aad(string $scope): string + { + if (strlen($scope)!==64 || !ctype_xdigit($scope))throw new RuntimeException('Identidade Nextcloud inválida.'); + return self::CONTEXT.':'.strtolower($scope); + } + + public static function seal(array $settings,string $key,string $salt,string $scope): string + { + if (strlen($key)!==SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES || + strlen($salt)!==SODIUM_CRYPTO_PWHASH_SALTBYTES) { + throw new RuntimeException('Chave do backup inválida.'); + } + $plaintext=CanonicalJson::encode($settings,false); + if (strlen($plaintext)>100_000)throw new RuntimeException('Configuração excede o limite de backup.'); + $nonce=random_bytes(SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES); + $encrypted=sodium_crypto_aead_xchacha20poly1305_ietf_encrypt( + $plaintext,self::aad($scope),$nonce,$key + ); + $envelope=[ + 'version'=>self::VERSION,'algorithm'=>'xchacha20poly1305-ietf', + 'kdf'=>'argon2id-v1','salt'=>base64_encode($salt), + 'nonce'=>base64_encode($nonce),'ciphertext'=>base64_encode($encrypted), + ]; + $json=json_encode($envelope,JSON_UNESCAPED_SLASHES|JSON_THROW_ON_ERROR); + if (strlen($json)>self::MAX_BYTES)throw new RuntimeException('Backup excede o limite.'); + return $json; + } + + public static function salt(string $raw): string + { + $envelope=self::envelope($raw); + return $envelope['salt']; + } + + private static function envelope(string $raw): array + { + if (strlen($raw)>self::MAX_BYTES)throw new RuntimeException('Backup remoto excede o limite.'); + try {$doc=json_decode($raw,true,16,JSON_THROW_ON_ERROR);} + catch (\Throwable) {throw new RuntimeException('Backup criptografado inválido.');} + if (!is_array($doc) || array_keys($doc)!==[ + 'version','algorithm','kdf','salt','nonce','ciphertext' + ] || ($doc['version']??null)!==self::VERSION || + ($doc['algorithm']??null)!=='xchacha20poly1305-ietf' || + ($doc['kdf']??null)!=='argon2id-v1') { + throw new RuntimeException('Formato ou versão de backup não suportado.'); + } + foreach (['salt','nonce','ciphertext'] as $field) { + if (!is_string($doc[$field])||strlen($doc[$field])>self::MAX_BYTES) { + throw new RuntimeException('Backup criptografado inválido.'); + } + $decoded=base64_decode($doc[$field],true); + if ($decoded===false)throw new RuntimeException('Backup criptografado inválido.'); + $doc[$field]=$decoded; + } + if (strlen($doc['salt'])!==SODIUM_CRYPTO_PWHASH_SALTBYTES || + strlen($doc['nonce'])!==SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES || + strlen($doc['ciphertext'])store->root().'/telegram-user.log' - )); + $api=new API($session); $me=$api->getSelf(); $valid=$api->getAuthorization()===API::LOGGED_IN && is_array($me)?self::publicAccount($me):null; @@ -166,10 +162,7 @@ public function avatar(?object $client=null): ?array $own=$client===null; $old=umask(0077); try { - $client??=new API($session,MadelineTelegramAdapter::settings( - (int)$credentials['TELEGRAM_API_ID'],(string)$credentials['TELEGRAM_API_HASH'], - $this->store->root().'/telegram-user.log' - )); + $client??=new API($session); $self=$client->getSelf(); if (!is_array($self)||self::publicAccount($self)===null) return null; $list=$client->photos->getUserPhotos( diff --git a/app/AutomaticKimai/WeeklyCalendar.php b/app/AutomaticKimai/WeeklyCalendar.php new file mode 100644 index 0000000..13f9726 --- /dev/null +++ b/app/AutomaticKimai/WeeklyCalendar.php @@ -0,0 +1,130 @@ +modify('-'.((int)$date->format('N')-1).' days'); + $days=[]; + for ($i=0;$i<7;$i++)$days[]=$monday->modify('+'.$i.' days')->format('Y-m-d'); + return [ + 'days'=>$days, + 'start'=>$days[0], + 'end'=>$days[6], + 'previous'=>$monday->modify('-7 days')->format('Y-m-d'), + 'next'=>$monday->modify('+7 days')->format('Y-m-d'), + 'today'=>(new DateTimeImmutable('now',$zone))->format('Y-m-d'), + ]; + } + + private static function entity(mixed $value): string + { + if (is_array($value))return (string)($value['name']??''); + return ''; + } + + public static function entries(array $remote, array $report, array $days, DateTimeZone $zone): array + { + if ($days===[])return []; + $weekStart=TimeMath::dayStart($days[0],$zone); + $weekEnd=TimeMath::dayStart(end($days),$zone)->modify('+1 day'); + $events=[]; + $add=static function(string $type,string $start,string $end,string $title,string $details='') use (&$events,$zone,$weekStart,$weekEnd): void { + try { + $a=(new DateTimeImmutable($start,$zone))->setTimezone($zone); + $b=(new DateTimeImmutable($end,$zone))->setTimezone($zone); + } catch (Throwable) {return;} + if ($b <= $a || $b <= $weekStart || $a >= $weekEnd)return; + if ($a < $weekStart)$a=$weekStart; + if ($b > $weekEnd)$b=$weekEnd; + // Split midnight-crossing entries, accounting for local DST boundaries. + while ($a < $b) { + $midnight=TimeMath::dayStart($a->modify('+1 day')->format('Y-m-d'),$zone); + $stop=$b < $midnight ? $b : $midnight; + if ($stop <= $a)break; + $day=$a->format('Y-m-d'); + $minutes=(int)$a->format('H')*60+(int)$a->format('i'); + $finish=$stop===$midnight ? 1440 : (int)$stop->format('H')*60+(int)$stop->format('i'); + if ($stop->format('Y-m-d')!==$day)$finish=1440; + $events[]=[ + 'type'=>$type,'day'=>$day,'start'=>$a->format('H:i'), + 'end'=>$stop->format('Y-m-d')!==$day?'24:00':$stop->format('H:i'), + 'title'=>$title,'details'=>$details, + 'top'=>round($minutes/1440*100,4), + 'height'=>round(max(1,$finish-$minutes)/1440*100,4), + 'seconds'=>(int)($stop->getTimestamp()-$a->getTimestamp()), + 'start_ts'=>$a->getTimestamp(),'end_ts'=>$stop->getTimestamp(), + ]; + $a=$stop; + } + }; + foreach ($remote as $entry) { + if (!is_array($entry) || !is_string($entry['begin']??null))continue; + $end=$entry['end']??null; + if (!is_string($end)||$end==='')continue; // Running timer cannot be presented as a completed interval. + $project=self::entity($entry['project']??null); + $activity=self::entity($entry['activity']??null); + $customer=self::entity($entry['customer']??null); + $title=trim($project.' · '.$activity,' ·') ?: 'Atividade registrada'; + $detail=trim($customer.' — '.(string)($entry['description']??''),' —'); + $add('registered',$entry['begin'],$end,$title,$detail); + } + foreach ($report['days']??[] as $day) { + if (!is_array($day)||!in_array($day['day']??null,$days,true))continue; + foreach ($day['review_intervals']??[] as $row) { + if (is_string($row['start']??null)&&is_string($row['end']??null)) + $add('observed',$row['start'],$row['end'],'Atividade observada','Duração de trabalho não confirmada'); + } + foreach ($day['calendar_gap_alerts']??[] as $row) { + if (is_string($row['start']??null)&&is_string($row['end']??null)) + $add('scheduled',$row['start'],$row['end'],'Sinal de agenda','Compromisso previsto; presença não comprovada'); + } + } + usort($events,static fn($x,$y)=>[$x['start_ts'],$x['type']]<=>[$y['start_ts'],$y['type']]); + return $events; + } + + public static function decorate(array $calendar): array + { + $total=0; + $counts=['registered'=>0,'observed'=>0,'scheduled'=>0]; + $daily=[]; + foreach ($calendar['days'] as $day) { + $spans=[];$seen=['registered'=>0,'observed'=>0,'scheduled'=>0]; + foreach ($calendar['events'] as $event) { + if ($event['day']!==$day)continue; + $seen[$event['type']]++; + if ($event['type']==='registered')$spans[]=[$event['start_ts'],$event['end_ts']]; + } + usort($spans,static fn($a,$b)=>$a[0]<=>$b[0]); + $merged=[]; + foreach ($spans as [$a,$b]) { + $i=count($merged)-1; + if ($i<0||$a>$merged[$i][1])$merged[]=[$a,$b]; + elseif ($b>$merged[$i][1])$merged[$i][1]=$b; + } + $seconds=array_sum(array_map(static fn($v)=>$v[1]-$v[0],$merged)); + $total+=$seconds; + foreach ($seen as $key=>$value)$counts[$key]+=$value; + $daily[$day]=['seconds'=>$seconds,'counts'=>$seen]; + } + $calendar['total_seconds']=$total; + $calendar['counts']=$counts; + $calendar['daily']=$daily; + return $calendar; + } + + public static function hours(int $seconds): string + { + return sprintf('%dh%02d',intdiv($seconds,3600),intdiv($seconds%3600,60)); + } +} diff --git a/app/Console/Commands/AutomaticKimaiSettingsSync.php b/app/Console/Commands/AutomaticKimaiSettingsSync.php new file mode 100644 index 0000000..ede409b --- /dev/null +++ b/app/Console/Commands/AutomaticKimaiSettingsSync.php @@ -0,0 +1,30 @@ +status()['enabled']??false))return self::SUCCESS; + try { + $result=$sync->synchronize(); + if (in_array($result,['needs_resolution','conflict'],true)) { + $this->warn('SETTINGS_SYNC_CONFLICT: review required in local settings'); + } + return self::SUCCESS; + } catch (Throwable) { + // Do not log remote URLs, user names, provider responses or tokens. + $this->warn('SETTINGS_SYNC_UNAVAILABLE: local settings remain intact'); + return self::FAILURE; + } + } +} diff --git a/app/Http/Controllers/AutomaticKimaiController.php b/app/Http/Controllers/AutomaticKimaiController.php index cb28fff..9668e77 100644 --- a/app/Http/Controllers/AutomaticKimaiController.php +++ b/app/Http/Controllers/AutomaticKimaiController.php @@ -5,6 +5,7 @@ use App\AutomaticKimai\ActivityWatchClient; use App\AutomaticKimai\KimaiClient; +use App\AutomaticKimai\WeeklyCalendar; use App\AutomaticKimai\LocalStore; use App\AutomaticKimai\NextcloudDesktopDiscovery; use App\AutomaticKimai\NextcloudLoginFlow; @@ -33,18 +34,20 @@ private function local(Request $request): void } } - public function home(Request $request): View + public function home(Request $request): View|RedirectResponse { $this->local($request); $view=(string)$request->query('view','overview'); if ($view==='settings')$view='kimai'; // Existing bookmarks. + if ($view==='attendance')return redirect()->route('kimai.home',['view'=>'manual']); // Old bookmarks. if ($view==='about')$view='overview'; // Old migration-page links. $titles=[ 'overview'=>'Visão geral', 'review'=>'Conciliação de horas', - 'attendance'=>'Trabalho presencial', + 'calendar'=>'Calendário semanal', 'manual'=>'Informar horas', 'kimai'=>'Conta Kimai', + 'settings_sync'=>'Backup e sincronização', 'sources'=>'Fontes de dados', 'integrations'=>'Conexões', 'nextcloud'=>'Nextcloud', @@ -54,9 +57,10 @@ public function home(Request $request): View $hints=[ 'overview'=>'Acompanhe seu monitoramento e veja o que precisa de atenção.', 'review'=>'Acompanhe horas reconciliadas e observações monitoradas automaticamente.', - 'attendance'=>'Revise compromissos presenciais e desconte as pausas.', + 'calendar'=>'Compare lançamentos confirmados e evidências que ainda precisam de revisão.', 'manual'=>'Informe atividades realizadas fora da coleta automática.', 'kimai'=>'Visualize sua conta e altere a conexão apenas se necessário.', + 'settings_sync'=>'Proteja suas configurações com criptografia e sincronize entre computadores.', 'sources'=>'Controle quais informações o aplicativo pode consultar.', 'integrations'=>'Conecte cada serviço separadamente.', 'nextcloud'=>'Autorize o acesso no navegador sem usar sua senha principal.', @@ -75,7 +79,7 @@ public function home(Request $request): View 'telegram'=>$sources['telegram_setup']||$sources['telegram'], ]; $hiddenConnection=null; - if (array_key_exists($view,$connectionVisibility) && !$connectionVisibility[$view]) { + if (array_key_exists($view,$connectionVisibility) && !$connectionVisibility[$view] && $view!=='nextcloud') { $hiddenConnection=$titles[$view]; $view='sources'; } @@ -105,8 +109,43 @@ public function home(Request $request): View try {$reviewRows=$queue->rows();} finally {$queue->close();} } + $calendar=null; + if ($view==='calendar') { + $day=(string)$request->query('week',''); + if ($day!=='' && !preg_match('/^\d{4}-\d{2}-\d{2}$/D',$day)) { + abort(422,'Semana inválida'); + } + $profile=$this->store->profile(); + $zone=new \DateTimeZone((string)($profile?->get('timezone')??'UTC')); + try { + $calendar=WeeklyCalendar::week($day==='' ? (new DateTimeImmutable('now',$zone))->format('Y-m-d') : $day,$zone); + } catch (\Throwable) {abort(422,'Semana inválida');} + $calendar['events']=[]; + $calendar['error']=null; + $calendar['outdated']=false; + if ($profile===null) { + $calendar['error']='Conecte uma conta Kimai para consultar as horas registradas.'; + } else { + try { + $creds=$this->store->credentials(); + $api=new KimaiClient($creds['KIMAI_BASE_URL']??'', $creds['KIMAI_API_TOKEN']??''); + $me=$api->me(); + if (!is_int($me['id']??null))throw new RuntimeException('Conta Kimai sem identificação'); + $remote=$api->timesheets($me['id'],$calendar['days'],$zone); + $calendar['events']=WeeklyCalendar::entries($remote,$this->store->report(),$calendar['days'],$zone); + } catch (Throwable) { + $calendar['error']='Não foi possível consultar os lançamentos do Kimai. Confira a conexão e tente novamente.'; + $calendar['outdated']=true; + $calendar['events']=WeeklyCalendar::entries([],$this->store->report(),$calendar['days'],$zone); + } + } + $calendar=WeeklyCalendar::decorate($calendar); + } return view('automatic-kimai.dashboard',[ 'reviewRows'=>$reviewRows, + 'calendar'=>$calendar, + 'settingsSyncStatus'=>$view==='settings_sync' ? + $this->store->read('settings-sync-state.json',['enabled'=>false]) : [], 'view'=>$view, 'statusLabel'=>$statusLabel, 'lastAnalysis'=>$lastAnalysis, @@ -229,12 +268,9 @@ public function connectors(Request $request): RedirectResponse $manual=isset($input['nextcloud_url']) || isset($input['nextcloud_user']) || isset($input['nextcloud_password']); if ($manual) { - $enabled=$this->store->sources(); - if (!$enabled['nextcloud_calendar'] && !$enabled['nextcloud_talk'] && - !$enabled['nextcloud_activity'] && !$enabled['nextcloud_mail'] && - empty($this->store->credentials()['NEXTCLOUD_APP_PASSWORD'])) { - throw new RuntimeException('Ative ao menos um aplicativo Nextcloud antes de conectar.'); - } + // Authorization for encrypted backups is independent from + // consent to inspect any Nextcloud source (Talk, Mail, etc.). + // The manually provided app password is still verified by OCS. $existing=$this->store->credentials(); $server=NextcloudLoginFlow::normalizeServer((string)($input['nextcloud_url']??'')); $login=trim((string)($input['nextcloud_user']??'')); @@ -361,6 +397,8 @@ public function manual(Request $request): RedirectResponse 'start'=>'required|date_format:H:i', 'end'=>'required|date_format:H:i', 'task'=>'required|string|min:3|max:64', + 'pause_start'=>'nullable|date_format:H:i|required_with:pause_end', + 'pause_end'=>'nullable|date_format:H:i|required_with:pause_start', 'confirmed'=>'accepted', ]); $profile=$this->store->profile(); @@ -372,11 +410,24 @@ public function manual(Request $request): RedirectResponse if (!is_int($user)||$user<1)throw new RuntimeException('Kimai account unavailable'); \App\AutomaticKimai\PublicationGate::assertManualReady( $this->store,$profile,$creds,$user); - $result=(new ManualTime())->submit($profile,$api,$this->store->ledgerFile(), - true, - $data['day'],$data['start'],$data['end'],$data['task'],true, - new DateTimeImmutable('now',$profile->zone)); - return back()->with('ok','Kimai worklog entry #'.$result['remote_id'].' verified.'); + $now=new DateTimeImmutable('now',$profile->zone); + $segments=[[$data['start'],$data['end']]]; + if (!empty($data['pause_start']) && !empty($data['pause_end'])) { + $segments=ManualTime::attendanceSegments($profile,[ + 'day'=>$data['day'],'start'=>$data['start'],'end'=>$data['end'], + 'label'=>$data['task'], + 'breaks'=>[[$data['pause_start'],$data['pause_end']]], + 'schedule_source'=>'Horários declarados pelo usuário', + 'attendance_attested'=>true, + ],$now); + } + $ids=[];$manual=new ManualTime(); + foreach ($segments as [$start,$end]) { + $result=$manual->submit($profile,$api,$this->store->ledgerFile(), + true,$data['day'],$start,$end,$data['task'],true,$now); + $ids[]=(int)$result['remote_id']; + } + return back()->with('ok','Horas registradas no Kimai. IDs: '.implode(', ',$ids)); } catch(Throwable $e) { return back()->withErrors(['manual'=>$e->getMessage()]); } diff --git a/app/Http/Controllers/NextcloudLoginController.php b/app/Http/Controllers/NextcloudLoginController.php index 3e6bae4..97c2127 100644 --- a/app/Http/Controllers/NextcloudLoginController.php +++ b/app/Http/Controllers/NextcloudLoginController.php @@ -27,16 +27,6 @@ private function requireLocal(Request $request): void } } - private function requireSelectedSource(): void - { - $sources=$this->store->sources(); - if (!$sources['nextcloud_calendar'] && !$sources['nextcloud_talk'] && - !$sources['nextcloud_activity'] && !$sources['nextcloud_mail'] && - empty($this->store->credentials()['NEXTCLOUD_APP_PASSWORD'])) { - abort(403,'Habilite ao menos uma fonte Nextcloud antes de conectar.'); - } - } - private static function reply(array $payload,int $status=200): JsonResponse { return response()->json($payload,$status) @@ -49,14 +39,12 @@ private static function reply(array $payload,int $status=200): JsonResponse public function status(Request $request): JsonResponse { $this->requireLocal($request); - $this->requireSelectedSource(); return self::reply($this->flow->status()); } public function start(Request $request): JsonResponse { $this->requireLocal($request); - $this->requireSelectedSource(); $data=$request->validate(['url'=>'required|string|max:250']); try { return self::reply($this->flow->start($data['url'])); } catch (Throwable $exception) { @@ -130,7 +118,6 @@ public function avatar(Request $request): \Illuminate\Http\Response public function poll(Request $request): JsonResponse { $this->requireLocal($request); - $this->requireSelectedSource(); try {return self::reply($this->flow->poll());} catch (Throwable $exception) { return self::reply(['status'=>'error','message'=>$exception->getMessage()],422); diff --git a/app/Http/Controllers/SettingsSyncController.php b/app/Http/Controllers/SettingsSyncController.php new file mode 100644 index 0000000..9aa9b75 --- /dev/null +++ b/app/Http/Controllers/SettingsSyncController.php @@ -0,0 +1,102 @@ +getHost()),['localhost','127.0.0.1','::1'],true)|| + !in_array($request->ip(),['127.0.0.1','::1'],true)) { + abort(403,'Somente no aplicativo local.'); + } + } + + private static function message(string $action): string + { + return match ($action) { + 'created'=>'Backup criptografado criado na sua conta Nextcloud.', + 'restored'=>'Configurações restauradas. Autorize o Telegram separadamente neste dispositivo.', + 'needs_resolution','conflict'=>'Conflito identificado. Escolha qual configuração deverá prevalecer.', + 'uploaded'=>'Suas configurações foram enviadas de forma criptografada.', + 'unchanged'=>'As configurações já estão sincronizadas.', + default=>'Operação concluída.', + }; + } + + public function enable(Request $request): RedirectResponse + { + self::local($request); + $data=$request->validate([ + 'recovery_password'=>'required|string|min:16|max:1024', + 'include_credentials'=>'sometimes|boolean', + 'confirmed'=>'accepted', + ]); + try { + $result=$this->sync->enable( + $data['recovery_password'],(bool)($data['include_credentials']??false) + ); + return redirect()->route('kimai.home',['view'=>'settings_sync'])->with('ok',self::message($result)); + } catch (Throwable $e) { + return redirect()->route('kimai.home',['view'=>'settings_sync']) + ->withErrors(['backup'=>self::safeError($e)]); + } + } + + public function synchronize(Request $request): RedirectResponse + { + self::local($request); + try {$result=$this->sync->synchronize();} + catch (Throwable $e) { + return redirect()->route('kimai.home',['view'=>'settings_sync']) + ->withErrors(['backup'=>self::safeError($e)]); + } + return redirect()->route('kimai.home',['view'=>'settings_sync'])->with('ok',self::message($result)); + } + + public function resolve(Request $request): RedirectResponse + { + self::local($request); + $data=$request->validate([ + 'decision'=>'required|in:remote,local', + 'confirmed'=>'accepted', + ]); + try {$result=$this->sync->resolve($data['decision']);} + catch (Throwable $e) { + return redirect()->route('kimai.home',['view'=>'settings_sync']) + ->withErrors(['backup'=>self::safeError($e)]); + } + return redirect()->route('kimai.home',['view'=>'settings_sync'])->with('ok',self::message($result)); + } + + public function disable(Request $request): RedirectResponse + { + self::local($request); + $request->validate(['confirmed'=>'accepted']); + try {$this->sync->disable();} + catch (Throwable $e) { + return redirect()->route('kimai.home',['view'=>'settings_sync']) + ->withErrors(['backup'=>self::safeError($e)]); + } + return redirect()->route('kimai.home',['view'=>'settings_sync']) + ->with('ok','Sincronização desativada neste dispositivo. O backup remoto foi preservado.'); + } + + private static function safeError(Throwable $error): string + { + // Only messages from our domain code are safe to show. Never expose + // cURL/auth/SQL exceptions that may include private hosts or tokens. + return $error instanceof \RuntimeException || $error instanceof \InvalidArgumentException + ? $error->getMessage() + : 'Operação indisponível. Confira a conexão e tente novamente.'; + } +} diff --git a/composer.json b/composer.json index c2c846e..3a676e3 100644 --- a/composer.json +++ b/composer.json @@ -14,6 +14,7 @@ "license": "GPL-3.0-or-later", "require": { "php": "^8.4", + "ext-sodium": "*", "danog/madelineproto": "^8.21", "laravel/framework": "^12.0", "laravel/tinker": "^2.10.1", diff --git a/composer.lock b/composer.lock index b9d71d5..8008e74 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "29958f6eb2525de1c370c9e13c6f20ff", + "content-hash": "ec55a9afa5ba6de7ad4170fe7543fe8b", "packages": [ { "name": "amphp/amp", @@ -14117,7 +14117,8 @@ "prefer-stable": true, "prefer-lowest": false, "platform": { - "php": "^8.4" + "php": "^8.4", + "ext-sodium": "*" }, "platform-dev": {}, "plugin-api-version": "2.11.0" diff --git a/docs/GETTING_STARTED.md b/docs/GETTING_STARTED.md index 4238856..4b26af8 100644 --- a/docs/GETTING_STARTED.md +++ b/docs/GETTING_STARTED.md @@ -46,7 +46,7 @@ credenciais diretamente no serviço de origem se não forem mais necessárias. ## Acompanhar suas horas -Na **Visão geral**, execute **Atualizar análise**. Abra **Conciliação de horas** +Na **Visão geral**, execute **Atualizar análise**. Na tela **Calendário semanal** (prova de conceito somente leitura), navegue entre semanas para visualizar os horários confirmados no Kimai ao lado das observações locais; blocos de agenda e atividade observada não são somados às horas registradas. Utilize **Atualizar do Kimai** para consultar novamente os lançamentos da semana e selecione blocos, inclusive os curtos, para visualizar seus horários e detalhes. Abra **Conciliação de horas** para ver três situações distintas: - **Já registrado:** o Kimai possui um lançamento correspondente; a @@ -58,8 +58,7 @@ para ver três situações distintas: uma aprovação que tenha perdido validade pode exigir tratamento específico. Uma fila de revisão vazia não garante que toda a jornada foi registrada. -Para trabalho comprovado fora do computador, utilize **Trabalho presencial** -ou **Informar horas**, com horários reais e pausas. A publicação em servidor +Para trabalho comprovado fora do computador, utilize **Informar horas**, com data, horários reais e descrição. Se houver pausa, abra **Informar pausa (opcional)** para descontá-la. A publicação em servidor depende da política autorizada para a instalação. ## Problemas comuns diff --git a/docs/SETTINGS_SYNC.md b/docs/SETTINGS_SYNC.md new file mode 100644 index 0000000..d9bced3 --- /dev/null +++ b/docs/SETTINGS_SYNC.md @@ -0,0 +1,70 @@ +# Sincronização criptografada de configurações + +O Automatic Kimai pode usar o **Files/WebDAV do Nextcloud** como armazenamento de +backup pessoal. Não depende de aplicativo extra no servidor. O recurso é +**desativado por padrão** e exige autorização por dispositivo. + +## Primeiro dispositivo + +1. Conecte seu próprio Nextcloud pelo Login Flow v2, sem reutilizar credenciais + do cliente de sincronização nem a senha principal. +2. Abra **Preferências → Backup e sincronização**. +3. Crie uma senha de recuperação exclusiva com pelo menos 16 caracteres. +4. Escolha explicitamente se deseja exportar tokens individuais do Kimai e + GitHub e os identificadores da API Telegram (criptografados). +5. Ative o recurso. O sistema cria um único arquivo criptografado em + **Arquivos → Automatic Kimai**, sob a conta Nextcloud autenticada. + +A senha de recuperação não é gravada. A chave derivada é guardada **somente +no dispositivo**, protegida pela chave da aplicação local. O arquivo do Nextcloud é +cifrado com Argon2id (64 MiB, três operações) e +XChaCha20-Poly1305, com nonce novo em cada versão e identidade Nextcloud +como AAD (dados autenticados). + +## Segundo dispositivo + +1. Instale o aplicativo e autorize **a mesma conta Nextcloud** neste dispositivo. +2. Ative o backup com a **mesma senha de recuperação** e a **mesma opção de + credenciais** escolhida na criação. +3. Se não houver configuração local, a restauração é automática. Se já houver, + o programa para e pergunta qual configuração deve prevalecer. +4. O Kimai e o GitHub podem recuperar seus tokens **apenas se o usuário + explicitamente optou por compartilhá-los**. Cada integração deve ser + revalidada caso o provedor revogue ou restrinja o token. +5. A sessão **Telegram não é copiável** com segurança: autorize-a + separadamente (QR/2FA) no segundo dispositivo. Lista de grupos/consentimento + para leitura também exige aprovação local. + +## Proteção contra perda de dados + +- Somente configurações portáteis são transferidas. Não são enviados SQLite, + logs, arquivos de trabalho, dados de ActivityWatch, documentos, sessões + MadelineProto, cookies, senha do Nextcloud ou a chave da aplicação Laravel. +- Permissões de publicação automática no Kimai **nunca são restauradas**: + o perfil importado fica em modo de revisão. +- Alterações concorrentes geram um **conflito**, sem substituição automática. + O usuário precisa decidir explicitamente qual versão prevalece. +- Gravações WebDAV usam If-Match com ETag forte, ou If-None-Match: * + na criação. Uma falha ou alteração concorrente cancela a escrita. +- A sincronização ocorre pelo scheduler a cada cinco minutos enquanto o + aplicativo estiver em execução. O botão **Sincronizar agora** antecipa o ciclo. +- Desconectar a conta Nextcloud apaga apenas a chave de sincronização local; + o backup cifrado permanece no armazenamento remoto. +- Se a senha for perdida, a aplicação não consegue descriptografar o backup. + Isso é intencional. A revogação de credenciais precisa ser feita no provedor. + +Não compartilhe a pasta com terceiros, mesmo que seu conteúdo seja cifrado. +Nunca armazene a senha de recuperação junto ao arquivo de backup. + +## Revisão técnica + +Camadas independentes: +- SettingsSnapshot: allowlist para dados portáteis; +- SettingsVault: cifra autenticada e derivação de chave; +- NextcloudSettingsDav: WebDAV autenticado, HTTPS e ETag; +- SettingsSyncService: comparação de alterações e conflito de escrita; +- SettingsSyncController: ações locais com CSRF, validação e opt-in; +- comando agendado automatic-kimai:settings-sync. + +Os testes de unidade utilizam transporte WebDAV fictício. Não devem escrever +em arquivos ou contas Nextcloud reais da pessoa desenvolvedora. diff --git a/docs/images/calendar-week-poc.png b/docs/images/calendar-week-poc.png new file mode 100644 index 0000000..fe54d5b Binary files /dev/null and b/docs/images/calendar-week-poc.png differ diff --git a/public/css/automatic-kimai.css b/public/css/automatic-kimai.css index 8313516..7647cea 100644 --- a/public/css/automatic-kimai.css +++ b/public/css/automatic-kimai.css @@ -611,3 +611,88 @@ a.button:hover { background:var(--primary-hover); } .updates-actions button { margin: 0; } .updates-panel progress { width: 100%; height: 12px; margin: 6px 0 14px; } .updates-note { font-size: 12px; margin: 14px 0 0; } + +/* Weekly read-only calendar POC */ +.calendar-toolbar{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;flex-wrap:wrap} +.calendar-toolbar h2{margin:0 0 .35rem} +.calendar-controls,.calendar-legend,.calendar-actions{display:flex;align-items:center;flex-wrap:wrap;gap:.55rem} +.calendar-controls a{min-width:2.6rem;text-align:center;text-decoration:none} +.calendar-summary{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:.7rem;margin:1.3rem 0} +.calendar-summary>div{border:1px solid var(--line);border-radius:12px;padding:.8rem;display:flex;flex-direction:column;gap:.5rem} +.calendar-summary strong{font-size:1.35rem} +.calendar-legend{gap:1.2rem;margin:.7rem 0 1rem;font-size:.9rem} +.calendar-legend>span{display:flex;align-items:center;gap:.35rem} +.calendar-dot{display:inline-block;width:11px;height:11px;border-radius:3px;background:#2563eb} +.calendar-dot.observed{background:#d97706} +.calendar-dot.scheduled{background:#64748b} +.calendar-scroller{overflow-x:auto;border:1px solid var(--line);border-radius:13px} +.calendar-grid{display:grid;grid-template-columns:64px repeat(7,minmax(126px,1fr));min-width:960px} +.calendar-axis,.calendar-day{min-width:0;border-right:1px solid var(--line)} +.calendar-day:last-child{border-right:0} +.calendar-axis-title,.calendar-day-heading{height:61px;display:flex;flex-direction:column;justify-content:center;padding:.45rem .55rem;border-bottom:1px solid var(--line);background:var(--raised)} +.calendar-day-heading small{font-size:.72rem;opacity:.78;margin-top:.25rem} +.calendar-day.today .calendar-day-heading{box-shadow:inset 0 3px #2563eb} +.calendar-axis-body,.calendar-day-body{height:960px;position:relative} +.calendar-axis-body span{position:absolute;left:.6rem;transform:translateY(-50%);font-size:.73rem;opacity:.68} +.calendar-hour{position:absolute;left:0;right:0;border-top:1px solid var(--line);opacity:.43} +.calendar-event{position:absolute;z-index:1;left:3px;right:3px;min-height:2px;padding:3px 5px;border-radius:5px;overflow:hidden;display:flex;flex-direction:column;gap:2px;line-height:1.25;font-size:.73rem;box-sizing:border-box;box-shadow:0 1px 2px #0002} +.calendar-event.registered{background:#dbeafe;color:#163879;border-left:3px solid #2563eb;z-index:3} +.calendar-event.observed{background:repeating-linear-gradient(135deg,#fef3c7,#fef3c7 7px,#fffbeb 7px,#fffbeb 14px);color:#78350f;border-left:3px solid #d97706;z-index:2;right:8%} +.calendar-event.scheduled{background:rgba(100,116,139,.14);color:var(--fg);border-left:3px dashed #64748b;z-index:1;left:8%;box-shadow:none} +.calendar-event span{overflow-wrap:anywhere} +.calendar-footnote{margin:1rem 0} +@media(max-width:720px){.calendar-summary{grid-template-columns:repeat(2,minmax(0,1fr))}.calendar-grid{min-width:900px}} +[data-theme="dark"] .calendar-event.registered{background:#17335a;color:#e4f0ff} +[data-theme="dark"] .calendar-event.observed{background:#584219;color:#ffedbd} +[data-theme="dark"] .calendar-event.scheduled{background:#334155;color:#e2e8f0} + +.calendar-summary>div{background:var(--raised)} +.calendar-day-body{background:var(--card)} +.calendar-legend{color:var(--fg)} +.calendar-event:focus-visible{outline:3px solid var(--focus);outline-offset:1px} + +/* Match system dark mode when no explicit theme preference is stored. */ +@media (prefers-color-scheme: dark) { + :root:not([data-theme]) .calendar-event.registered{background:#17335a;color:#e4f0ff} + :root:not([data-theme]) .calendar-event.observed{background:#584219;color:#ffedbd} + :root:not([data-theme]) .calendar-event.scheduled{background:rgba(148,163,184,.16);color:var(--fg)} +} + + +/* Compact calendar entries: retain real start position and elapsed time, but + give 1–15 minute entries a readable click/focus target. */ +.calendar-event{cursor:pointer;text-align:left;align-items:flex-start;justify-content:flex-start;font-family:inherit;font-weight:400;margin:0} +.calendar-event:focus-visible{outline:3px solid var(--focus);outline-offset:2px} +.calendar-event-short{min-height:30px!important;flex-direction:row;align-items:center;justify-content:flex-start;gap:4px;font-size:.7rem;padding:3px 4px;overflow:hidden;z-index:5} +.calendar-event-short b{white-space:nowrap;font-variant-numeric:tabular-nums} +.calendar-event-short .calendar-event-name{display:none} +.calendar-event:hover{filter:brightness(.94)} +.calendar-dialog-close{float:right} +.calendar-detail-dialog{width:min(92vw,450px);max-height:80vh;padding:22px;border-radius:16px;border:1px solid var(--line);background:var(--card);color:var(--fg);box-shadow:0 24px 60px #0005} +.calendar-detail-dialog::backdrop{background:rgba(8,15,26,.55)} +.calendar-detail-dialog h3{font-size:1.1rem;clear:both} +.calendar-detail-time{font-weight:750;font-variant-numeric:tabular-nums} +.calendar-detail-dialog form{margin:0} +.calendar-refresh{display:inline-flex;align-items:center;gap:7px} +.calendar-refresh .icon{width:17px;height:17px} +.page-loading-overlay[hidden]{display:none!important} +.page-loading-overlay{position:fixed;inset:0;background:rgba(9,22,42,.45);backdrop-filter:blur(2px);z-index:1000;display:grid;place-items:center;padding:18px} +.page-loading-card{display:flex;flex-direction:column;align-items:center;gap:11px;min-width:min(92vw,270px);max-width:380px;text-align:center;background:var(--card);color:var(--fg);padding:28px 32px;border-radius:18px;box-shadow:0 18px 50px #0005;border:1px solid var(--line)} +.page-loading-card strong{font-size:1rem;line-height:1.35} +.page-loading-card small{font-size:.8rem} +.page-loading-spinner{width:43px;height:43px;border:4px solid var(--line);border-top-color:var(--focus);border-radius:50%;animation:calendar-spin .75s linear infinite} +@keyframes calendar-spin{to{transform:rotate(360deg)}} +@media(prefers-reduced-motion:reduce){.page-loading-spinner{animation-duration:2.5s}} + +/* Encrypted Nextcloud configuration backup (independent of collection sources). */ +.settings-sync-content{display:grid;gap:1rem;max-width:960px} +.settings-sync-content>section{min-width:0} +.settings-sync-content h2,.settings-sync-content h3{margin-top:0} +.settings-sync-form{display:grid;gap:1rem} +.settings-sync-checkbox{display:flex;align-items:flex-start;gap:.75rem;padding:.65rem 0;line-height:1.45;cursor:pointer} +.settings-sync-checkbox input{width:18px;height:18px;flex-shrink:0;margin-top:.25rem;accent-color:var(--primary-bg)} +.settings-sync-conflict{border:2px solid var(--warn,#d97706);border-radius:13px;padding:1.15rem} +.settings-sync-conflict-actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1.5rem} +.settings-sync-conflict-actions form{padding:1rem;border:1px solid var(--line);border-radius:10px} +.settings-sync-overview .notice p{margin-bottom:0} +@media(max-width:760px){.settings-sync-conflict-actions{grid-template-columns:1fr}} diff --git a/public/icons/lucide.svg b/public/icons/lucide.svg index abd2cd9..12c5d33 100644 --- a/public/icons/lucide.svg +++ b/public/icons/lucide.svg @@ -59,4 +59,4 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/resources/views/automatic-kimai/dashboard.blade.php b/resources/views/automatic-kimai/dashboard.blade.php index ce066b7..6d22f29 100644 --- a/resources/views/automatic-kimai/dashboard.blade.php +++ b/resources/views/automatic-kimai/dashboard.blade.php @@ -15,7 +15,7 @@ } } catch (_error) { /* Browser storage is optional. */ } - +
@@ -69,18 +69,21 @@ @if($view==='overview') @include('automatic-kimai.sections.overview') @endif +@if($view==='calendar') +@include('automatic-kimai.sections.calendar') +@endif @if($view==='review') @include('automatic-kimai.sections.review') @endif -@if($view==='attendance') -@include('automatic-kimai.sections.attendance') -@endif @if($view==='manual') @include('automatic-kimai.sections.manual') @endif @if($view==='kimai') @include('automatic-kimai.sections.kimai') @endif +@if($view==='settings_sync') +@include('automatic-kimai.sections.settings-sync') +@endif @if($view==='sources') @include('automatic-kimai.sections.sources') @endif @@ -96,16 +99,27 @@ @if($view==='github') @include('automatic-kimai.sections.github') @endif +
Automatic Kimai · dados locais e privados · informações não equivalem a aprovação financeira.