-
-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathembedding.txt
More file actions
7214 lines (6044 loc) · 246 KB
/
Copy pathembedding.txt
File metadata and controls
7214 lines (6044 loc) · 246 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--- BEGIN FILE: SECURITY.md ---
# Security Policy
## Reporting Vulnerabilities
We take security seriously and appreciate your help in keeping **ctxsync** secure. If you discover a security vulnerability, please follow these guidelines:
1. **Public Disclosure:** If the issue can be safely disclosed, feel free to [open an issue](https://github.com/jahwag/ctxsync/issues).
2. **Private Disclosure:** If the issue should not be made public, please contact me directly via DM on Discord:
- **Discord:** [@jahwag](https://discord.gg/pR4qeMH4u4)
--- END FILE: SECURITY.md ---
--- BEGIN FILE: requirements.txt ---
click>=8.1.7
click_completion>=0.5.2
pathspec>=0.12.1
pytest>=8.3.2
python_crontab>=3.2.0
setuptools>=73.0.1
sseclient_py>=1.8.0
tqdm>=4.66.5
pytest-cov>=5.0.0
crontab>=1.0.1
python-crontab>=3.2.0
Brotli>=1.1.0
cryptography>=42.0.4
--- END FILE: requirements.txt ---
--- BEGIN FILE: pytest.ini ---
[pytest]
testpaths = tests
python_files = test_*.py
addopts = -v --cov=ctxsync --cov-report=term-missing
--- END FILE: pytest.ini ---
--- BEGIN FILE: README.md ---
# ctxsync
[](https://opensource.org/licenses/MIT)
[](https://pypi.org/project/ctxsync/)
[](https://github.com/jahwag/ctxsync/releases)
[](https://github.com/jahwag/ctxsync/actions/workflows/python-package.yml)
[](https://github.com/jahwag/ctxsync/issues)
[](https://github.com/psf/black)
[](https://github.com/jahwag/ctxsync/network/dependencies)
[](https://github.com/jahwag/ctxsync/commits/main)
[](https://github.com/sponsors/jahwag)
ctxsync (formerly known as ClaudeSync) bridges your local development environment with Claude.ai projects, enabling seamless synchronization to enhance your AI-powered workflow.
> **Renamed from ClaudeSync**: the `claudesync` PyPI package is deprecated — install `ctxsync` instead. Your existing configuration is picked up automatically: `~/.claudesync` is migrated on first run and project-local `.claudesync` directories keep working.

## ⚠️ Disclaimer
ctxsync is an independent, open-source project **not affiliated** with Anthropic or Claude.ai. By using ctxsync, you agree to:
1. Use it at your own risk.
2. Acknowledge potential violation of Anthropic's Terms of Service.
3. Assume responsibility for any consequences.
4. Understand that Anthropic does not support this tool.
Please review [Anthropic's Terms of Service](https://www.anthropic.com/legal/consumer-terms) before using ctxsync.
## 🌟 Features
- **File sync**: Synchronize local files with [Claude.ai projects](https://www.anthropic.com/news/projects).
- **Cross-Platform**: Compatible with [Windows, macOS, and Linux](https://github.com/jahwag/ctxsync/releases).
- **Configurable**: Plenty of [configuration options](https://github.com/jahwag/ctxsync/wiki/Quick-reference).
- **Integrate**: Designed to be easy to integrate into your pipelines.
- **Secure**: Ensures data privacy and security.
## ⚙️ Prerequisites
### 📄 Supported Claude.ai plans
| [Plan](https://www.anthropic.com/pricing) | Supported |
|--------|-----------|
| Pro | ✅ |
| Team | ✅ |
| Free | ❌ |
### 🔑 SSH Key
Ensure you have an SSH key for secure credential storage. Follow [GitHub's guide](https://docs.github.com/en/authentication/connecting-to-github-with-ssh) to generate and add your SSH key.
### 💻 Software
- **Python**: ≥ [3.10](https://www.python.org/downloads/)
- **pip**: [Python package installer](https://pip.pypa.io/en/stable/installation/)
## 🚀 Quick Start
1. **Install ctxsync**
```shell
pip install ctxsync
```
2. **Authenticate**
```shell
ctxsync auth login
```
3. **Create a Project**
```shell
ctxsync project create
```
4. **Start Syncing***
```shell
ctxsync push
```
**This is a one-way sync. Files not present locally will be removed from the Claude.ai project unless pruning is [disabled](https://github.com/jahwag/ctxsync/wiki/Quick-reference#pruning-remote).*
📚 [Detailed Guides & FAQs](https://github.com/jahwag/ctxsync/wiki)
## 🤝 Support & Contribute
Enjoying ctxsync? Support us by:
- ⭐ [Starring the Repository](https://github.com/jahwag/ctxsync)
- 🐛 [Reporting Issues](https://github.com/jahwag/ctxsync/issues)
- 🌍 [Contributing](CONTRIBUTING.md)
- 💬 [Join Our Discord](https://discord.gg/pR4qeMH4u4)
- 💖 [Sponsor Us](https://github.com/sponsors/jahwag)
Your contributions help improve ctxsync!
---
[Contributors](https://github.com/jahwag/ctxsync/graphs/contributors) • [License](https://github.com/jahwag/ctxsync/blob/master/LICENSE) • [Report Bug](https://github.com/jahwag/ctxsync/issues) • [Request Feature](https://github.com/jahwag/ctxsync/issues/new?labels=enhancement&template=feature_request.md)• [Sponsor](https://github.com/sponsors/jahwag)
--- END FILE: README.md ---
--- BEGIN FILE: CODEOWNERS ---
# Default owner for everything in the repo
* @jahwag
--- END FILE: CODEOWNERS ---
--- BEGIN FILE: LICENSE ---
MIT License
Copyright (c) 2024 Jahziah Wagner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--- END FILE: LICENSE ---
--- BEGIN FILE: .gitignore ---
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
.idea
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
**/*.egg-info
__pycache__
# claude
claude.sync
config.json
ctxsync.log
claude_chats
some_value
.ctxsync
ROADMAP.md
# legacy names from before the ClaudeSync -> ctxsync rename
claudesync.log
.claudesync
--- END FILE: .gitignore ---
--- BEGIN FILE: setup.py ---
from setuptools import setup, find_packages
setup(
packages=find_packages(where="src"),
package_dir={"": "src"},
)
--- END FILE: setup.py ---
--- BEGIN FILE: pyproject.toml ---
[project]
name = "ctxsync"
version = "0.8.0"
authors = [
{name = "Jahziah Wagner", email = "540380+jahwag@users.noreply.github.com"},
]
description = "A tool to synchronize local files with Claude.ai projects"
license = {file = "LICENSE"}
readme = "README.md"
requires-python = ">=3.10"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
dependencies = [
"click>=8.1.7",
"click_completion>=0.5.2",
"pathspec>=0.12.1",
"pytest>=8.3.2",
"python_crontab>=3.2.0",
"setuptools>=73.0.1",
"sseclient_py>=1.8.0",
"tqdm>=4.66.5",
"pytest-cov>=5.0.0",
"crontab>=1.0.1",
"python-crontab>=3.2.0",
"Brotli>=1.1.0",
"cryptography>=42.0.4",
]
keywords = [
"sync",
"files",
"Claude.ai",
"automation",
"synchronization",
"project management",
"file management",
"cloud sync",
"cli tool",
"command line",
"productivity",
"development tools",
"file synchronization",
"continuous integration",
"devops",
"version control"
]
[project.optional-dependencies]
test = [
"pytest>=8.2.2",
"pytest-cov>=5.0.0",
]
[project.urls]
"Homepage" = "https://github.com/jahwag/ctxsync"
"Bug Tracker" = "https://github.com/jahwag/ctxsync/issues"
[project.scripts]
ctxsync = "ctxsync.cli.main:cli"
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[tool.setuptools.packages.find]
where = ["src"]
include = ["ctxsync*"]
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = "test_*.py"
addopts = "-v --cov=ctxsync --cov-report=term-missing"
--- END FILE: pyproject.toml ---
--- BEGIN FILE: renovate.json ---
{
"extends": ["config:base"],
"pip_requirements": {
"enabled": true
},
"packageRules": [
{
"matchManagers": ["pip_requirements"],
"matchUpdateTypes": ["minor", "patch"],
"groupName": "All non-major Python updates"
},
{
"matchManagers": ["github-actions"],
"groupName": "GitHub Actions updates"
}
],
"automerge": false,
"timezone": "UTC",
"schedule": ["after 10pm and before 5am"],
"labels": ["dependencies", "renovate"],
"dependencyDashboard": true,
"prHourlyLimit": 5,
"prConcurrentLimit": 10
}
--- END FILE: renovate.json ---
--- BEGIN FILE: CONTRIBUTING.md ---
# Contributing to ctxsync
We're excited that you're interested in contributing to ctxsync! This document outlines the process for contributing to this project.
## Getting Started
1. Fork the repository on GitHub.
2. Clone your fork locally:
```
git clone https://github.com/your-username/ctxsync.git
```
3. Create a new branch for your feature or bug fix:
```
git checkout -b feature/your-feature-name
```
## Setting Up the Development Environment
1. Ensure you have Python 3.10 or later installed.
2. Install the development dependencies:
```
pip install -r requirements.txt
```
3. Install linting tools (required by CI but not in requirements.txt):
```
pip install black flake8
```
4. Install the package in editable mode:
```
pip install -e .
```
## Making Changes
1. Make your changes in your feature branch.
2. Add or update tests as necessary.
3. Run the tests to ensure they pass:
```
python -m unittest discover tests
```
4. Update the documentation if you've made changes to the API or added new features.
## Code Style
We use [Black](https://black.readthedocs.io/) for formatting and [flake8](https://flake8.pycqa.org/) for linting. Run both locally before pushing:
```
black .
flake8 . --max-line-length=127 --extend-ignore=E203,E701 --max-complexity=10
```
These flags match the CI configuration exactly. The build will fail if either check fails.
Use `logging`/`logger` for all output — do **not** use `print()`.
## Version Bump
Every PR must include a version bump in `pyproject.toml`:
```toml
[project]
version = "x.y.z"
```
Increment the patch version for bug fixes, the minor version for new features, and the major version for breaking changes. PRs without a version bump cannot be released.
## Signed Commits
All commits require **both**:
- `-s` — DCO sign-off, certifying you wrote or have the right to submit the code
- `-S` — cryptographic signature (GPG or SSH), producing a verified badge on GitHub
```
git commit -s -S -am "Add a brief description of your changes"
```
Set up commit signing: https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits
PRs with unverified commits will not be merged.
## PR Checklist
Before submitting a pull request, confirm all of the following:
- [ ] Tests pass: `python -m unittest discover tests`
- [ ] Black check passes: `black --check .`
- [ ] flake8 passes: `flake8 . --max-line-length=127 --extend-ignore=E203,E701 --max-complexity=10`
- [ ] Version bumped in `pyproject.toml`
- [ ] All commits signed off and cryptographically signed (`git commit -s -S`)
- [ ] No `print()` calls — use `logger` instead
## Submitting Changes
1. Commit your changes:
```
git commit -s -S -am "Add a brief description of your changes"
```
2. Push to your fork:
```
git push origin feature/your-feature-name
```
3. Submit a pull request through the GitHub website.
## Reporting Bugs
If you find a bug, please open an issue on the GitHub repository using our bug report template. To do this:
1. Go to the [Issues](https://github.com/jahwag/ctxsync/issues) page of the ctxsync repository.
2. Click on "New Issue".
3. Select the "Bug Report" template.
4. Fill out the template with as much detail as possible.
When reporting a bug, please include:
- A clear and concise description of the bug
- Steps to reproduce the behavior
- Expected behavior
- Any error messages or stack traces
- Your environment details (OS, Python version, ctxsync version)
- Your ctxsync configuration (use `ctxsync config list`)
- Any relevant logs (you can increase log verbosity with `ctxsync config set log_level DEBUG`)
The more information you provide, the easier it will be for us to reproduce and fix the bug.
## Requesting Features
If you have an idea for a new feature, please open an issue on the GitHub repository. Describe the feature and why you think it would be useful for the project.
## Questions
If you have any questions about contributing, feel free to open an issue for discussion.
Thank you for your interest in improving ctxsync!
--- END FILE: CONTRIBUTING.md ---
--- BEGIN FILE: src/ctxsync/session_key_manager.py ---
import subprocess
import base64
import logging
from pathlib import Path
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
class SessionKeyManager:
def __init__(self, ssh_key_path=None):
self.logger = logging.getLogger(__name__)
# Allow config-provided ssh_key_path to guide key discovery
self.ssh_key_path = self._find_ssh_key(ssh_key_path)
def _find_ssh_key(self, configured_path=None):
"""
Locate an SSH private key for session encryption.
Priority:
1. If configured_path points to a specific file, check it first
2. If configured_path is a directory, search it alongside ~/.ssh
3. Fall back to ~/.ssh with default key names
4. Prompt the user as a last resort
"""
default_ssh_dir = Path.home() / ".ssh"
key_names = ["id_ed25519", "id_ecdsa"]
search_dirs = [default_ssh_dir]
if configured_path:
configured = Path(configured_path)
if configured.is_file():
# Config points directly to a key file — use it immediately
return str(configured)
if configured.is_dir():
# Config is a directory — search it in addition to ~/.ssh
if configured != default_ssh_dir:
search_dirs.insert(0, configured)
else:
# Path doesn't exist — warn and fall through to defaults
self.logger.warning(
"Configured ssh_key_path not found: %s", configured_path
)
# Search all candidate directories for supported key names
for search_dir in search_dirs:
for key_name in key_names:
key_path = search_dir / key_name
if key_path.exists():
return str(key_path)
# If no supported key is found, prompt the user to generate an Ed25519 key
self.logger.warning(
"* No supported SSH key found. RSA keys are no longer supported."
)
self.logger.warning(
"* Please generate an Ed25519 key using the following command:"
)
self.logger.warning(' ssh-keygen -t ed25519 -C "your_email@example.com"')
self.logger.warning(
"* If you have NOT specified a custom ssh_key_path in config,"
)
self.logger.warning("* have created a key, and are still seeing this message,")
self.logger.warning(
" be sure to name your key 'id_ed25519' or 'id_ecdsa' so it's found automatically."
)
self.logger.warning(
"* Or set ssh_key_path with the full key name in your .ctxsync/config.local.json"
)
return input("Enter the full path to your new Ed25519 private key: ")
def _get_key_type(self):
try:
result = subprocess.run(
["ssh-keygen", "-l", "-f", self.ssh_key_path],
capture_output=True,
text=True,
check=True,
)
output = result.stdout.lower()
if "ecdsa" in output:
return "ecdsa"
elif "ed25519" in output:
return "ed25519"
else:
raise ValueError(f"Unsupported key type for {self.ssh_key_path}")
except subprocess.CalledProcessError as e:
self.logger.error(f"Failed to determine key type: {e}")
raise RuntimeError(
"Failed to determine SSH key type. Make sure the key file is valid and accessible."
)
def _derive_key_from_ssh_key(self):
with open(self.ssh_key_path, "rb") as key_file:
ssh_key_data = key_file.read()
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=b"ctxsync", # Using a fixed salt; consider using a secure random salt in production
iterations=100000,
)
key = base64.urlsafe_b64encode(kdf.derive(ssh_key_data))
return key
def encrypt_session_key(self, provider, session_key):
self._get_key_type()
return self._encrypt_symmetric(session_key)
def _encrypt_symmetric(self, session_key):
key = self._derive_key_from_ssh_key()
f = Fernet(key)
encrypted_session_key = f.encrypt(session_key.encode()).decode()
return encrypted_session_key, "symmetric"
def decrypt_session_key(self, provider, encryption_method, encrypted_session_key):
if not encrypted_session_key or not encryption_method:
return None
if encryption_method == "symmetric":
return self._decrypt_symmetric(encrypted_session_key)
else:
raise ValueError(f"Unknown encryption method: {encryption_method}")
def _decrypt_symmetric(self, encrypted_session_key):
key = self._derive_key_from_ssh_key()
f = Fernet(key)
return f.decrypt(encrypted_session_key.encode()).decode()
--- END FILE: src/ctxsync/session_key_manager.py ---
--- BEGIN FILE: src/ctxsync/syncmanager.py ---
import functools
import os
import time
import logging
from datetime import datetime, timezone
import io
from tqdm import tqdm
from ctxsync.utils import compute_md5_hash
from ctxsync.exceptions import ProviderError
from .compression import compress_content, decompress_content
logger = logging.getLogger(__name__)
def retry_on_403(max_retries=3, delay=1):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0] if len(args) > 0 else None
for attempt in range(max_retries):
try:
return func(*args, **kwargs)
except ProviderError as e:
if "403 Forbidden" in str(e) and attempt < max_retries - 1:
if self and hasattr(self, "logger"):
self.logger.warning(
f"Received 403 error. Retrying in {delay} seconds... (Attempt {attempt + 1}/{max_retries})"
)
else:
logger.warning(
f"Received 403 error. Retrying in {delay} seconds... (Attempt {attempt + 1}/{max_retries})"
)
time.sleep(delay)
else:
raise
return wrapper
return decorator
class SyncManager:
def __init__(self, provider, config, local_path):
self.provider = provider
self.config = config
self.active_organization_id = config.get("active_organization_id")
self.active_project_id = config.get("active_project_id")
self.local_path = local_path
self.upload_delay = config.get("upload_delay", 0.5)
self.two_way_sync = config.get("two_way_sync", False)
self.max_retries = 3
self.retry_delay = 1
self.compression_algorithm = config.get("compression_algorithm", "none")
self.synced_files = {}
def sync(self, local_files, remote_files):
self.synced_files = {} # Reset synced files at the start of sync
if self.compression_algorithm == "none":
self._sync_without_compression(local_files, remote_files)
else:
self._sync_with_compression(local_files, remote_files)
def _sync_without_compression(self, local_files, remote_files):
remote_files_to_delete = set(rf["file_name"] for rf in remote_files)
synced_files = set()
with tqdm(total=len(local_files), desc="Local → Remote") as pbar:
for local_file, local_checksum in local_files.items():
remote_file = next(
(rf for rf in remote_files if rf["file_name"] == local_file), None
)
if remote_file:
self.update_existing_file(
local_file,
local_checksum,
remote_file,
remote_files_to_delete,
synced_files,
)
else:
self.upload_new_file(local_file, synced_files)
pbar.update(1)
self.update_local_timestamps(remote_files, synced_files)
if self.two_way_sync:
with tqdm(total=len(remote_files), desc="Local ← Remote") as pbar:
for remote_file in remote_files:
self.sync_remote_to_local(
remote_file, remote_files_to_delete, synced_files
)
pbar.update(1)
self.prune_remote_files(remote_files, remote_files_to_delete)
def _sync_with_compression(self, local_files, remote_files):
packed_content = self._pack_files(local_files)
compressed_content = compress_content(
packed_content, self.compression_algorithm
)
remote_file_name = (
f"ctxsync_packed_{datetime.now().strftime('%Y%m%d%H%M%S')}.dat"
)
self._upload_compressed_file(compressed_content, remote_file_name)
if self.two_way_sync:
remote_compressed_content = self._download_compressed_file()
if remote_compressed_content:
remote_packed_content = decompress_content(
remote_compressed_content, self.compression_algorithm
)
self._unpack_files(remote_packed_content)
self._cleanup_old_remote_files(remote_files)
def _pack_files(self, local_files):
packed_content = io.StringIO()
for file_path, file_hash in local_files.items():
full_path = os.path.join(self.local_path, file_path)
with open(full_path, "r", encoding="utf-8") as f:
content = f.read()
packed_content.write(f"--- BEGIN FILE: {file_path} ---\n")
packed_content.write(content)
packed_content.write(f"\n--- END FILE: {file_path} ---\n")
return packed_content.getvalue()
@retry_on_403()
def _upload_compressed_file(self, compressed_content, file_name):
logger.debug(f"Uploading compressed file {file_name} to remote...")
self.provider.upload_file(
self.active_organization_id,
self.active_project_id,
file_name,
compressed_content,
)
time.sleep(self.upload_delay)
@retry_on_403()
def _download_compressed_file(self):
logger.debug("Downloading latest compressed file from remote...")
remote_files = self.provider.list_files(
self.active_organization_id, self.active_project_id
)
compressed_files = [
rf for rf in remote_files if rf["file_name"].startswith("ctxsync_packed_")
]
if compressed_files:
latest_file = max(compressed_files, key=lambda x: x["file_name"])
return latest_file["content"]
return None
def _unpack_files(self, packed_content):
current_file = None
current_content = io.StringIO()
for line in packed_content.splitlines():
if line.startswith("--- BEGIN FILE:"):
if current_file:
self._write_file(current_file, current_content.getvalue())
current_content = io.StringIO()
current_file = line.split("--- BEGIN FILE:")[1].strip()
elif line.startswith("--- END FILE:"):
if current_file:
self._write_file(current_file, current_content.getvalue())
current_file = None
current_content = io.StringIO()
else:
current_content.write(line + "\n")
if current_file:
self._write_file(current_file, current_content.getvalue())
def _write_file(self, file_path, content):
full_path = os.path.join(self.local_path, file_path)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
with open(full_path, "w", encoding="utf-8") as f:
f.write(content)
def _cleanup_old_remote_files(self, remote_files):
for remote_file in remote_files:
if remote_file["file_name"].startswith("ctxsync_packed_"):
self.provider.delete_file(
self.active_organization_id,
self.active_project_id,
remote_file["uuid"],
)
@retry_on_403()
def update_existing_file(
self,
local_file,
local_checksum,
remote_file,
remote_files_to_delete,
synced_files,
):
remote_content = remote_file["content"]
remote_checksum = compute_md5_hash(remote_content)
if local_checksum != remote_checksum:
logger.debug(f"Updating {local_file} on remote...")
with tqdm(total=2, desc=f"Updating {local_file}", leave=False) as pbar:
self.provider.delete_file(
self.active_organization_id,
self.active_project_id,
remote_file["uuid"],
)
pbar.update(1)
with open(
os.path.join(self.local_path, local_file), "r", encoding="utf-8"
) as file:
content = file.read()
self.provider.upload_file(
self.active_organization_id,
self.active_project_id,
local_file,
content,
)
pbar.update(1)
time.sleep(self.upload_delay)
synced_files.add(local_file)
remote_files_to_delete.remove(local_file)
@retry_on_403()
def upload_new_file(self, local_file, synced_files):
logger.debug(f"Uploading new file {local_file} to remote...")
with open(
os.path.join(self.local_path, local_file), "r", encoding="utf-8"
) as file:
content = file.read()
with tqdm(total=1, desc=f"Uploading {local_file}", leave=False) as pbar:
self.provider.upload_file(
self.active_organization_id, self.active_project_id, local_file, content
)
pbar.update(1)
time.sleep(self.upload_delay)
synced_files.add(local_file)
def update_local_timestamps(self, remote_files, synced_files):
for remote_file in remote_files:
if remote_file["file_name"] in synced_files:
local_file_path = os.path.join(
self.local_path, remote_file["file_name"]
)
if os.path.exists(local_file_path):
remote_timestamp = datetime.fromisoformat(
remote_file["created_at"].replace("Z", "+00:00")
).timestamp()
os.utime(local_file_path, (remote_timestamp, remote_timestamp))
logger.debug(f"Updated timestamp on local file {local_file_path}")
def sync_remote_to_local(self, remote_file, remote_files_to_delete, synced_files):
local_file_path = os.path.join(self.local_path, remote_file["file_name"])
if os.path.exists(local_file_path):
self.update_existing_local_file(
local_file_path, remote_file, remote_files_to_delete, synced_files
)
else:
self.create_new_local_file(
local_file_path, remote_file, remote_files_to_delete, synced_files
)
def update_existing_local_file(
self, local_file_path, remote_file, remote_files_to_delete, synced_files
):
local_mtime = datetime.fromtimestamp(
os.path.getmtime(local_file_path), tz=timezone.utc
)