Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/desktop-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/php-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions app/AutomaticKimai/LocalStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion app/AutomaticKimai/MadelineTelegramAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
173 changes: 173 additions & 0 deletions app/AutomaticKimai/NextcloudSettingsDav.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
<?php
declare(strict_types=1);

namespace App\AutomaticKimai;

use RuntimeException;

/**
* Personal Nextcloud Files WebDAV folder: one encrypted, versioned document.
* Only conditional writes are permitted; concurrent device changes never
* silently overwrite each other. No server-side Nextcloud app is necessary.
*/
final class NextcloudSettingsDav
{
private const MAX_RESPONSE=250_000;
private $fake;
private $checkIdentity;

public function __construct(?callable $fake=null,?callable $checkIdentity=null)
{
$this->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;
}
}
170 changes: 170 additions & 0 deletions app/AutomaticKimai/SettingsSnapshot.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
<?php
declare(strict_types=1);

namespace App\AutomaticKimai;

use InvalidArgumentException;

/** Explicit portable allowlists, never entire storage directories. */
final class SettingsSnapshot
{
private const SHARED_CREDENTIALS=[
'KIMAI_BASE_URL','KIMAI_API_TOKEN','GITHUB_TOKEN',
'TELEGRAM_API_ID','TELEGRAM_API_HASH',
];
private const SOURCES=[
'activitywatch','github','nextcloud_calendar','nextcloud_talk',
'nextcloud_activity','nextcloud_mail','telegram_setup',
'chatgpt_browser','claude_browser',
];
private const LOCAL_PROFILE=[
'work_messenger_dialog_ids','work_messenger_group_titles',
'work_messenger_labels','work_messenger_classification_labels',
'work_messenger_recommendations_reviewed',
'cache_dir','state_dir',
];

public static function fromStore(LocalStore $store,bool $includeSecrets): array
{
$profile=$store->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);
}
}
8 changes: 8 additions & 0 deletions app/AutomaticKimai/SettingsSyncConflict.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php
declare(strict_types=1);

namespace App\AutomaticKimai;

use RuntimeException;

final class SettingsSyncConflict extends RuntimeException {}
Loading
Loading