sg-send-cli 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. sg_send_cli-0.3.0/LICENSE +201 -0
  2. sg_send_cli-0.3.0/PKG-INFO +47 -0
  3. sg_send_cli-0.3.0/README.md +25 -0
  4. sg_send_cli-0.3.0/pyproject.toml +48 -0
  5. sg_send_cli-0.3.0/sg_send_cli/__init__.py +1 -0
  6. sg_send_cli-0.3.0/sg_send_cli/_version.py +1 -0
  7. sg_send_cli-0.3.0/sg_send_cli/api/Vault__API.py +83 -0
  8. sg_send_cli-0.3.0/sg_send_cli/api/__init__.py +0 -0
  9. sg_send_cli-0.3.0/sg_send_cli/cli/__init__.py +189 -0
  10. sg_send_cli-0.3.0/sg_send_cli/crypto/Vault__Crypto.py +106 -0
  11. sg_send_cli-0.3.0/sg_send_cli/crypto/__init__.py +0 -0
  12. sg_send_cli-0.3.0/sg_send_cli/safe_types/Enum__Sync_State.py +11 -0
  13. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_Str__Access_Token.py +10 -0
  14. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_Str__File_Id.py +16 -0
  15. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_Str__File_Path.py +10 -0
  16. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_Str__SHA256.py +16 -0
  17. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_Str__Transfer_Id.py +15 -0
  18. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_Str__Vault_Id.py +16 -0
  19. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_Str__Vault_Key.py +14 -0
  20. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_Str__Vault_Name.py +10 -0
  21. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_Str__Vault_Passphrase.py +14 -0
  22. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_Str__Write_Key.py +16 -0
  23. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_UInt__File_Size.py +6 -0
  24. sg_send_cli-0.3.0/sg_send_cli/safe_types/Safe_UInt__Vault_Version.py +4 -0
  25. sg_send_cli-0.3.0/sg_send_cli/safe_types/__init__.py +0 -0
  26. sg_send_cli-0.3.0/sg_send_cli/schemas/Schema__Transfer_File.py +13 -0
  27. sg_send_cli-0.3.0/sg_send_cli/schemas/Schema__Vault_Config.py +11 -0
  28. sg_send_cli-0.3.0/sg_send_cli/schemas/Schema__Vault_Index.py +10 -0
  29. sg_send_cli-0.3.0/sg_send_cli/schemas/Schema__Vault_Index_Entry.py +16 -0
  30. sg_send_cli-0.3.0/sg_send_cli/schemas/Schema__Vault_Meta.py +12 -0
  31. sg_send_cli-0.3.0/sg_send_cli/schemas/__init__.py +0 -0
  32. sg_send_cli-0.3.0/sg_send_cli/sync/Vault__Sync.py +286 -0
  33. sg_send_cli-0.3.0/sg_send_cli/sync/__init__.py +0 -0
  34. sg_send_cli-0.3.0/sg_send_cli/version +1 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.1
2
+ Name: sg-send-cli
3
+ Version: 0.3.0
4
+ Summary: CLI tool for syncing encrypted vaults with SG/Send Transfer API
5
+ Home-page: https://github.com/the-cyber-boardroom/SG_Send__CLI
6
+ License: Apache-2.0
7
+ Keywords: sg-send,vault,encryption,cli,sync
8
+ Author: The Cyber Boardroom
9
+ Requires-Python: >=3.11
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Security :: Cryptography
17
+ Requires-Dist: cryptography (>=43.0.0)
18
+ Requires-Dist: osbot-utils (>=3.70.0)
19
+ Project-URL: Repository, https://github.com/the-cyber-boardroom/SG_Send__CLI
20
+ Description-Content-Type: text/markdown
21
+
22
+ # SG_Send__CLI
23
+
24
+ CLI tool for syncing encrypted vaults with SG/Send Transfer API.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install sg-send-cli
30
+ ```
31
+
32
+ ## Development
33
+
34
+ ```bash
35
+ pip install -e ".[dev]"
36
+ pytest
37
+ ```
38
+
39
+ ## Architecture
40
+
41
+ - `sg_send_cli/safe_types/` — Domain-specific Safe_* types (zero raw primitives)
42
+ - `sg_send_cli/schemas/` — Pure data Type_Safe schemas
43
+ - `sg_send_cli/crypto/` — AES-256-GCM encrypt/decrypt, PBKDF2, HKDF
44
+ - `sg_send_cli/sync/` — Local ↔ remote vault sync (planned)
45
+ - `sg_send_cli/api/` — SG/Send Transfer API client (planned)
46
+ - `sg_send_cli/cli/` — CLI commands (planned)
47
+
@@ -0,0 +1,25 @@
1
+ # SG_Send__CLI
2
+
3
+ CLI tool for syncing encrypted vaults with SG/Send Transfer API.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install sg-send-cli
9
+ ```
10
+
11
+ ## Development
12
+
13
+ ```bash
14
+ pip install -e ".[dev]"
15
+ pytest
16
+ ```
17
+
18
+ ## Architecture
19
+
20
+ - `sg_send_cli/safe_types/` — Domain-specific Safe_* types (zero raw primitives)
21
+ - `sg_send_cli/schemas/` — Pure data Type_Safe schemas
22
+ - `sg_send_cli/crypto/` — AES-256-GCM encrypt/decrypt, PBKDF2, HKDF
23
+ - `sg_send_cli/sync/` — Local ↔ remote vault sync (planned)
24
+ - `sg_send_cli/api/` — SG/Send Transfer API client (planned)
25
+ - `sg_send_cli/cli/` — CLI commands (planned)
@@ -0,0 +1,48 @@
1
+ [tool.poetry]
2
+ name = "sg-send-cli"
3
+ version = "v0.3.0"
4
+ description = "CLI tool for syncing encrypted vaults with SG/Send Transfer API"
5
+ readme = "README.md"
6
+ license = "Apache-2.0"
7
+ authors = ["The Cyber Boardroom"]
8
+ keywords = ["sg-send", "vault", "encryption", "cli", "sync"]
9
+ homepage = "https://github.com/the-cyber-boardroom/SG_Send__CLI"
10
+ repository = "https://github.com/the-cyber-boardroom/SG_Send__CLI"
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Topic :: Security :: Cryptography",
17
+ ]
18
+ packages = [{ include = "sg_send_cli" }]
19
+
20
+ [tool.poetry.dependencies]
21
+ python = ">=3.11"
22
+ osbot-utils = ">=3.70.0"
23
+ cryptography = ">=43.0.0"
24
+
25
+ [tool.poetry.group.dev.dependencies]
26
+ pytest = ">=8.0"
27
+ pytest-cov = ">=5.0"
28
+
29
+ [tool.poetry.scripts]
30
+ sg-send-cli = "sg_send_cli.cli:main"
31
+
32
+ [build-system]
33
+ requires = ["poetry-core>=1.9.1"]
34
+ build-backend = "poetry.core.masonry.api"
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
38
+ addopts = "-v --tb=short"
39
+ python_files = "test_*.py"
40
+ python_classes = "Test_*"
41
+ python_functions = "test_*"
42
+
43
+ [tool.coverage.run]
44
+ source = ["sg_send_cli"]
45
+ omit = ["tests/*"]
46
+
47
+ [tool.coverage.report]
48
+ show_missing = true
@@ -0,0 +1 @@
1
+ from sg_send_cli._version import VERSION
@@ -0,0 +1 @@
1
+ VERSION = 'v0.1.0'
@@ -0,0 +1,83 @@
1
+ import json
2
+ from urllib.request import Request, urlopen
3
+ from urllib.error import HTTPError
4
+ from osbot_utils.type_safe.Type_Safe import Type_Safe
5
+
6
+ DEFAULT_BASE_URL = 'https://send.sgraph.ai'
7
+
8
+
9
+ class Vault__API(Type_Safe):
10
+ base_url : str
11
+ access_token : str
12
+
13
+ def setup(self):
14
+ if not self.base_url:
15
+ self.base_url = DEFAULT_BASE_URL
16
+ return self
17
+
18
+ def write(self, vault_id: str, file_id: str, write_key: str, payload: bytes) -> dict:
19
+ url = f'{self.base_url}/api/vault/write/{vault_id}/{file_id}'
20
+ headers = {'Content-Type' : 'application/octet-stream',
21
+ 'x-sgraph-access-token': self.access_token,
22
+ 'x-sgraph-vault-write-key' : write_key}
23
+ return self._request('PUT', url, headers, payload)
24
+
25
+ def read(self, vault_id: str, file_id: str) -> bytes:
26
+ url = f'{self.base_url}/api/vault/read/{vault_id}/{file_id}'
27
+ return self._request_bytes('GET', url)
28
+
29
+ def delete(self, vault_id: str, file_id: str, write_key: str) -> dict:
30
+ url = f'{self.base_url}/api/vault/delete/{vault_id}/{file_id}'
31
+ headers = {'x-sgraph-access-token': self.access_token,
32
+ 'x-sgraph-vault-write-key' : write_key}
33
+ return self._request('DELETE', url, headers)
34
+
35
+ def _request(self, method: str, url: str, headers: dict = None, data: bytes = None) -> dict:
36
+ req = Request(url, data=data, method=method)
37
+ if headers:
38
+ for key, value in headers.items():
39
+ req.add_header(key, value)
40
+ try:
41
+ with urlopen(req) as response:
42
+ body = response.read()
43
+ if body:
44
+ return json.loads(body)
45
+ return {}
46
+ except HTTPError as e:
47
+ raise self._api_error(method, url, headers, e, data_size=len(data) if data else 0)
48
+
49
+ def _request_bytes(self, method: str, url: str, headers: dict = None) -> bytes:
50
+ req = Request(url, method=method)
51
+ if headers:
52
+ for key, value in headers.items():
53
+ req.add_header(key, value)
54
+ try:
55
+ with urlopen(req) as response:
56
+ return response.read()
57
+ except HTTPError as e:
58
+ raise self._api_error(method, url, headers, e)
59
+
60
+ def _api_error(self, method: str, url: str, headers: dict, error: HTTPError, data_size: int = 0) -> Exception:
61
+ response_body = ''
62
+ try:
63
+ response_body = error.read().decode('utf-8', errors='replace')
64
+ except Exception:
65
+ pass
66
+
67
+ masked_headers = {}
68
+ for k, v in (headers or {}).items():
69
+ if 'token' in k.lower() or 'key' in k.lower():
70
+ masked_headers[k] = f'{v[:8]}...({len(v)} chars)'
71
+ else:
72
+ masked_headers[k] = v
73
+
74
+ lines = [f'API Error: HTTP {error.code} {error.reason}',
75
+ f' Request: {method} {url}',
76
+ f' Headers: {json.dumps(masked_headers, indent=2)}']
77
+ if data_size:
78
+ lines.append(f' Payload: {data_size} bytes')
79
+ if response_body:
80
+ lines.append(f' Response: {response_body}')
81
+
82
+ message = '\n'.join(lines)
83
+ return RuntimeError(message)
File without changes
@@ -0,0 +1,189 @@
1
+ import argparse
2
+ import os
3
+ import sys
4
+ from sg_send_cli.crypto.Vault__Crypto import Vault__Crypto
5
+ from sg_send_cli.api.Vault__API import Vault__API
6
+ from sg_send_cli.sync.Vault__Sync import Vault__Sync
7
+
8
+ TOKEN_FILE = 'token'
9
+
10
+
11
+ def _resolve_token(token: str, directory: str) -> str:
12
+ if token:
13
+ _save_token(token, directory)
14
+ return token
15
+ return _load_token(directory)
16
+
17
+
18
+ def _save_token(token: str, directory: str):
19
+ sg_vault_dir = os.path.join(directory, '.sg_vault')
20
+ if os.path.isdir(sg_vault_dir):
21
+ token_path = os.path.join(sg_vault_dir, TOKEN_FILE)
22
+ with open(token_path, 'w') as f:
23
+ f.write(token)
24
+
25
+
26
+ def _load_token(directory: str) -> str:
27
+ token_path = os.path.join(directory, '.sg_vault', TOKEN_FILE)
28
+ if os.path.isfile(token_path):
29
+ with open(token_path, 'r') as f:
30
+ return f.read().strip()
31
+ return ''
32
+
33
+
34
+ def create_sync(base_url: str = None, access_token: str = None) -> Vault__Sync:
35
+ api = Vault__API(base_url=base_url or '', access_token=access_token or '')
36
+ api.setup()
37
+ return Vault__Sync(crypto=Vault__Crypto(), api=api)
38
+
39
+
40
+ def cmd_clone(args):
41
+ sync = create_sync(args.base_url, args.token)
42
+ directory = sync.clone(args.vault_key, args.directory)
43
+ if args.token:
44
+ _save_token(args.token, directory)
45
+ print(f'Cloned vault to {directory}/')
46
+
47
+
48
+ def cmd_pull(args):
49
+ token = _resolve_token(args.token, args.directory)
50
+ sync = create_sync(args.base_url, token)
51
+ result = sync.pull(args.directory)
52
+ added = len(result['added'])
53
+ modified = len(result['modified'])
54
+ deleted = len(result['deleted'])
55
+ if added + modified + deleted == 0:
56
+ print('Already up to date.')
57
+ else:
58
+ for f in result['added']:
59
+ print(f' + {f}')
60
+ for f in result['modified']:
61
+ print(f' ~ {f}')
62
+ for f in result['deleted']:
63
+ print(f' - {f}')
64
+ print(f'Pulled: {added} added, {modified} modified, {deleted} deleted')
65
+
66
+
67
+ def cmd_push(args):
68
+ token = _resolve_token(args.token, args.directory)
69
+ sync = create_sync(args.base_url, token)
70
+ result = sync.push(args.directory)
71
+ added = len(result['added'])
72
+ modified = len(result['modified'])
73
+ deleted = len(result['deleted'])
74
+ if added + modified + deleted == 0:
75
+ print('Nothing to push — vault is up to date.')
76
+ else:
77
+ if added:
78
+ for f in sorted(result['added']):
79
+ print(f' + {f}')
80
+ if modified:
81
+ for f in sorted(result['modified']):
82
+ print(f' ~ {f}')
83
+ if deleted:
84
+ for f in sorted(result['deleted']):
85
+ print(f' - {f}')
86
+ print(f'Pushed: {added} added, {modified} modified, {deleted} deleted')
87
+
88
+
89
+ def cmd_status(args):
90
+ sync = Vault__Sync(crypto=Vault__Crypto(), api=Vault__API())
91
+ result = sync.status(args.directory)
92
+ if result['clean']:
93
+ print('Vault is clean — no local changes.')
94
+ else:
95
+ for f in result['added']:
96
+ print(f' + {f}')
97
+ for f in result['modified']:
98
+ print(f' ~ {f}')
99
+ for f in result['deleted']:
100
+ print(f' - {f}')
101
+
102
+
103
+ def cmd_remote_status(args):
104
+ token = _resolve_token(args.token, args.directory)
105
+ sync = create_sync(args.base_url, token)
106
+ result = sync.remote_status(args.directory)
107
+
108
+ remote_changes = result['remote_added'] or result['remote_modified'] or result['remote_deleted']
109
+ local_changes = result['local_added'] or result['local_modified'] or result['local_deleted']
110
+
111
+ print(f'Local version: {result["local_version"]}')
112
+ print(f'Remote version: {result["remote_version"]}')
113
+ print()
114
+
115
+ if remote_changes:
116
+ print('Remote changes (not yet pulled):')
117
+ for f in result['remote_added']:
118
+ print(f' + {f}')
119
+ for f in result['remote_modified']:
120
+ print(f' ~ {f}')
121
+ for f in result['remote_deleted']:
122
+ print(f' - {f}')
123
+ else:
124
+ print('Remote: up to date.')
125
+
126
+ if local_changes:
127
+ print('Local changes (not yet pushed):')
128
+ for f in result['local_added']:
129
+ print(f' + {f}')
130
+ for f in result['local_modified']:
131
+ print(f' ~ {f}')
132
+ for f in result['local_deleted']:
133
+ print(f' - {f}')
134
+ else:
135
+ print('Local: clean.')
136
+
137
+
138
+ def cmd_derive_keys(args):
139
+ crypto = Vault__Crypto()
140
+ keys = crypto.derive_keys_from_vault_key(args.vault_key)
141
+ print(f'vault_id: {keys["vault_id"]}')
142
+ print(f'read_key: {keys["read_key"]}')
143
+ print(f'write_key: {keys["write_key"]}')
144
+ print(f'tree_file_id: {keys["tree_file_id"]}')
145
+ print(f'settings_file_id: {keys["settings_file_id"]}')
146
+
147
+
148
+ def main():
149
+ parser = argparse.ArgumentParser(prog='sg-send-cli',
150
+ description='CLI tool for syncing encrypted vaults with SG/Send')
151
+ parser.add_argument('--base-url', default=None, help='API base URL (default: https://send.sgraph.ai)')
152
+ parser.add_argument('--token', default=None, help='SG/Send access token')
153
+
154
+ subparsers = parser.add_subparsers(dest='command', help='Available commands')
155
+
156
+ clone_parser = subparsers.add_parser('clone', help='Clone a remote vault to a local directory')
157
+ clone_parser.add_argument('vault_key', help='Vault key ({passphrase}:{vault_id})')
158
+ clone_parser.add_argument('directory', nargs='?', default=None, help='Target directory (default: vault_id)')
159
+ clone_parser.set_defaults(func=cmd_clone)
160
+
161
+ pull_parser = subparsers.add_parser('pull', help='Pull remote changes to local directory')
162
+ pull_parser.add_argument('directory', nargs='?', default='.', help='Vault directory (default: .)')
163
+ pull_parser.set_defaults(func=cmd_pull)
164
+
165
+ push_parser = subparsers.add_parser('push', help='Push local changes to the remote vault')
166
+ push_parser.add_argument('directory', nargs='?', default='.', help='Vault directory (default: .)')
167
+ push_parser.set_defaults(func=cmd_push)
168
+
169
+ status_parser = subparsers.add_parser('status', help='Show local changes vs vault tree')
170
+ status_parser.add_argument('directory', nargs='?', default='.', help='Vault directory (default: .)')
171
+ status_parser.set_defaults(func=cmd_status)
172
+
173
+ remote_status_parser = subparsers.add_parser('remote-status', help='Compare local vault against remote')
174
+ remote_status_parser.add_argument('directory', nargs='?', default='.', help='Vault directory (default: .)')
175
+ remote_status_parser.set_defaults(func=cmd_remote_status)
176
+
177
+ keys_parser = subparsers.add_parser('derive-keys', help='Derive and display vault keys (debug)')
178
+ keys_parser.add_argument('vault_key', help='Vault key ({passphrase}:{vault_id})')
179
+ keys_parser.set_defaults(func=cmd_derive_keys)
180
+
181
+ args = parser.parse_args()
182
+ if not args.command:
183
+ parser.print_help()
184
+ sys.exit(1)
185
+ try:
186
+ args.func(args)
187
+ except RuntimeError as e:
188
+ print(str(e), file=sys.stderr)
189
+ sys.exit(1)
@@ -0,0 +1,106 @@
1
+ import hashlib
2
+ import hmac
3
+ import os
4
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
5
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
6
+ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
7
+ from cryptography.hazmat.primitives import hashes
8
+ from osbot_utils.type_safe.Type_Safe import Type_Safe
9
+
10
+ PBKDF2_ITERATIONS = 600_000
11
+ AES_KEY_BYTES = 32
12
+ GCM_IV_BYTES = 12
13
+ GCM_TAG_BYTES = 16
14
+ HKDF_INFO_PREFIX = b'sg-send-file-key'
15
+
16
+ SALT_PREFIX = 'sg-vault-v1'
17
+ WRITE_SALT_PREFIX = 'sg-vault-v1:write'
18
+ TREE_DOMAIN = 'sg-vault-v1:file-id:tree'
19
+ SETTINGS_DOMAIN = 'sg-vault-v1:file-id:settings'
20
+
21
+
22
+ class Vault__Crypto(Type_Safe):
23
+
24
+ def parse_vault_key(self, vault_key: str) -> tuple:
25
+ parts = vault_key.rsplit(':', 1)
26
+ if len(parts) != 2 or not parts[0] or not parts[1]:
27
+ raise ValueError(f'Invalid vault key format: expected {{passphrase}}:{{vault_id}}')
28
+ passphrase = parts[0]
29
+ vault_id = parts[1]
30
+ return passphrase, vault_id
31
+
32
+ def derive_read_key(self, passphrase: str, vault_id: str) -> bytes:
33
+ salt = f'{SALT_PREFIX}:{vault_id}'.encode()
34
+ return self.derive_key_from_passphrase(passphrase.encode(), salt)
35
+
36
+ def derive_write_key(self, passphrase: str, vault_id: str) -> bytes:
37
+ salt = f'{WRITE_SALT_PREFIX}:{vault_id}'.encode()
38
+ return self.derive_key_from_passphrase(passphrase.encode(), salt)
39
+
40
+ def derive_file_id(self, read_key: bytes, domain_string: str) -> str:
41
+ mac = hmac.new(read_key, domain_string.encode(), hashlib.sha256).hexdigest()
42
+ return mac[:12]
43
+
44
+ def derive_tree_file_id(self, read_key: bytes, vault_id: str) -> str:
45
+ domain = f'{TREE_DOMAIN}:{vault_id}'
46
+ return self.derive_file_id(read_key, domain)
47
+
48
+ def derive_settings_file_id(self, read_key: bytes, vault_id: str) -> str:
49
+ domain = f'{SETTINGS_DOMAIN}:{vault_id}'
50
+ return self.derive_file_id(read_key, domain)
51
+
52
+ def derive_keys(self, passphrase: str, vault_id: str) -> dict:
53
+ read_key_bytes = self.derive_read_key(passphrase, vault_id)
54
+ write_key_bytes = self.derive_write_key(passphrase, vault_id)
55
+ tree_file_id = self.derive_tree_file_id(read_key_bytes, vault_id)
56
+ settings_file_id = self.derive_settings_file_id(read_key_bytes, vault_id)
57
+ return dict(read_key_bytes = read_key_bytes,
58
+ read_key = read_key_bytes.hex(),
59
+ write_key_bytes = write_key_bytes,
60
+ write_key = write_key_bytes.hex(),
61
+ tree_file_id = tree_file_id,
62
+ settings_file_id = settings_file_id,
63
+ passphrase = passphrase,
64
+ vault_id = vault_id)
65
+
66
+ def derive_keys_from_vault_key(self, vault_key: str) -> dict:
67
+ passphrase, vault_id = self.parse_vault_key(vault_key)
68
+ return self.derive_keys(passphrase, vault_id)
69
+
70
+ # --- low-level primitives ---
71
+
72
+ def derive_key_from_passphrase(self, passphrase: bytes, salt: bytes) -> bytes:
73
+ kdf = PBKDF2HMAC(algorithm = hashes.SHA256(),
74
+ length = AES_KEY_BYTES,
75
+ salt = salt,
76
+ iterations = PBKDF2_ITERATIONS)
77
+ return kdf.derive(passphrase)
78
+
79
+ def derive_file_key(self, vault_key: bytes, file_context: bytes) -> bytes:
80
+ hkdf = HKDF(algorithm = hashes.SHA256(),
81
+ length = AES_KEY_BYTES,
82
+ salt = None,
83
+ info = HKDF_INFO_PREFIX + file_context)
84
+ return hkdf.derive(vault_key)
85
+
86
+ def encrypt(self, key: bytes, plaintext: bytes, iv: bytes = None) -> bytes:
87
+ if iv is None:
88
+ iv = os.urandom(GCM_IV_BYTES)
89
+ aesgcm = AESGCM(key)
90
+ ciphertext = aesgcm.encrypt(iv, plaintext, None)
91
+ return iv + ciphertext
92
+
93
+ def decrypt(self, key: bytes, data: bytes) -> bytes:
94
+ iv = data[:GCM_IV_BYTES]
95
+ ciphertext = data[GCM_IV_BYTES:]
96
+ aesgcm = AESGCM(key)
97
+ return aesgcm.decrypt(iv, ciphertext, None)
98
+
99
+ def hash_data(self, data: bytes) -> str:
100
+ return hashlib.sha256(data).hexdigest()
101
+
102
+ def generate_salt(self) -> bytes:
103
+ return os.urandom(16)
104
+
105
+ def generate_iv(self) -> bytes:
106
+ return os.urandom(GCM_IV_BYTES)
File without changes
@@ -0,0 +1,11 @@
1
+ from enum import Enum
2
+
3
+ class Enum__Sync_State(Enum):
4
+ SYNCED = 'synced'
5
+ MODIFIED_LOCALLY = 'modified_locally'
6
+ MODIFIED_REMOTELY = 'modified_remotely'
7
+ CONFLICT = 'conflict'
8
+ ADDED_LOCALLY = 'added_locally'
9
+ ADDED_REMOTELY = 'added_remotely'
10
+ DELETED_LOCALLY = 'deleted_locally'
11
+ DELETED_REMOTELY = 'deleted_remotely'
@@ -0,0 +1,10 @@
1
+ import re
2
+ from osbot_utils.type_safe.primitives.core.Safe_Str import Safe_Str
3
+
4
+ ACCESS_TOKEN__REGEX = re.compile(r'[^a-zA-Z0-9\-_.]')
5
+ ACCESS_TOKEN__MAX_LENGTH = 2048
6
+
7
+ class Safe_Str__Access_Token(Safe_Str):
8
+ regex = ACCESS_TOKEN__REGEX
9
+ max_length = ACCESS_TOKEN__MAX_LENGTH
10
+ allow_empty = True
@@ -0,0 +1,16 @@
1
+ import re
2
+ from osbot_utils.type_safe.primitives.core.Safe_Str import Safe_Str
3
+ from osbot_utils.type_safe.primitives.core.enums.Enum__Safe_Str__Regex_Mode import Enum__Safe_Str__Regex_Mode
4
+
5
+ FILE_ID__REGEX = re.compile(r'^[0-9a-f]{12}$')
6
+ FILE_ID__MAX_LENGTH = 12
7
+
8
+ class Safe_Str__File_Id(Safe_Str):
9
+ regex = FILE_ID__REGEX
10
+ regex_mode = Enum__Safe_Str__Regex_Mode.MATCH
11
+ max_length = FILE_ID__MAX_LENGTH
12
+ exact_length = True
13
+ allow_empty = True
14
+ trim_whitespace = True
15
+ to_lower_case = True
16
+ strict_validation = True
@@ -0,0 +1,10 @@
1
+ import re
2
+ from osbot_utils.type_safe.primitives.core.Safe_Str import Safe_Str
3
+
4
+ FILE_PATH__REGEX = re.compile(r'[^a-zA-Z0-9/\\_.\- ]')
5
+ FILE_PATH__MAX_LENGTH = 4096
6
+
7
+ class Safe_Str__File_Path(Safe_Str):
8
+ regex = FILE_PATH__REGEX
9
+ max_length = FILE_PATH__MAX_LENGTH
10
+ allow_empty = True
@@ -0,0 +1,16 @@
1
+ import re
2
+ from osbot_utils.type_safe.primitives.core.Safe_Str import Safe_Str
3
+ from osbot_utils.type_safe.primitives.core.enums.Enum__Safe_Str__Regex_Mode import Enum__Safe_Str__Regex_Mode
4
+
5
+ SHA256__REGEX = re.compile(r'^[0-9a-f]{64}$')
6
+ SHA256__MAX_LENGTH = 64
7
+
8
+ class Safe_Str__SHA256(Safe_Str):
9
+ regex = SHA256__REGEX
10
+ regex_mode = Enum__Safe_Str__Regex_Mode.MATCH
11
+ max_length = SHA256__MAX_LENGTH
12
+ exact_length = True
13
+ allow_empty = True
14
+ trim_whitespace = True
15
+ to_lower_case = True
16
+ strict_validation = True
@@ -0,0 +1,15 @@
1
+ import re
2
+ from osbot_utils.type_safe.primitives.core.Safe_Str import Safe_Str
3
+ from osbot_utils.type_safe.primitives.core.enums.Enum__Safe_Str__Regex_Mode import Enum__Safe_Str__Regex_Mode
4
+
5
+ TRANSFER_ID__REGEX = re.compile(r'^[a-zA-Z0-9]{12}$')
6
+ TRANSFER_ID__MAX_LENGTH = 12
7
+
8
+ class Safe_Str__Transfer_Id(Safe_Str):
9
+ regex = TRANSFER_ID__REGEX
10
+ regex_mode = Enum__Safe_Str__Regex_Mode.MATCH
11
+ max_length = TRANSFER_ID__MAX_LENGTH
12
+ exact_length = True
13
+ allow_empty = True
14
+ trim_whitespace = True
15
+ strict_validation = True
@@ -0,0 +1,16 @@
1
+ import re
2
+ from osbot_utils.type_safe.primitives.core.Safe_Str import Safe_Str
3
+ from osbot_utils.type_safe.primitives.core.enums.Enum__Safe_Str__Regex_Mode import Enum__Safe_Str__Regex_Mode
4
+
5
+ VAULT_ID__REGEX = re.compile(r'^[0-9a-f]{8}$')
6
+ VAULT_ID__MAX_LENGTH = 8
7
+
8
+ class Safe_Str__Vault_Id(Safe_Str):
9
+ regex = VAULT_ID__REGEX
10
+ regex_mode = Enum__Safe_Str__Regex_Mode.MATCH
11
+ max_length = VAULT_ID__MAX_LENGTH
12
+ exact_length = True
13
+ allow_empty = True
14
+ trim_whitespace = True
15
+ to_lower_case = True
16
+ strict_validation = True
@@ -0,0 +1,14 @@
1
+ import re
2
+ from osbot_utils.type_safe.primitives.core.Safe_Str import Safe_Str
3
+ from osbot_utils.type_safe.primitives.core.enums.Enum__Safe_Str__Regex_Mode import Enum__Safe_Str__Regex_Mode
4
+
5
+ VAULT_KEY__REGEX = re.compile(r'^[\x20-\x7E]+:[0-9a-f]{8}$')
6
+ VAULT_KEY__MAX_LENGTH = 268
7
+
8
+ class Safe_Str__Vault_Key(Safe_Str):
9
+ regex = VAULT_KEY__REGEX
10
+ regex_mode = Enum__Safe_Str__Regex_Mode.MATCH
11
+ max_length = VAULT_KEY__MAX_LENGTH
12
+ allow_empty = True
13
+ trim_whitespace = True
14
+ strict_validation = True
@@ -0,0 +1,10 @@
1
+ import re
2
+ from osbot_utils.type_safe.primitives.core.Safe_Str import Safe_Str
3
+
4
+ VAULT_NAME__REGEX = re.compile(r'[^a-zA-Z0-9 _\-.]')
5
+ VAULT_NAME__MAX_LENGTH = 128
6
+
7
+ class Safe_Str__Vault_Name(Safe_Str):
8
+ regex = VAULT_NAME__REGEX
9
+ max_length = VAULT_NAME__MAX_LENGTH
10
+ allow_empty = True
@@ -0,0 +1,14 @@
1
+ import re
2
+ from osbot_utils.type_safe.primitives.core.Safe_Str import Safe_Str
3
+ from osbot_utils.type_safe.primitives.core.enums.Enum__Safe_Str__Regex_Mode import Enum__Safe_Str__Regex_Mode
4
+
5
+ VAULT_PASSPHRASE__REGEX = re.compile(r'^[\x20-\x7E]{1,256}$')
6
+ VAULT_PASSPHRASE__MAX_LENGTH = 256
7
+
8
+ class Safe_Str__Vault_Passphrase(Safe_Str):
9
+ regex = VAULT_PASSPHRASE__REGEX
10
+ regex_mode = Enum__Safe_Str__Regex_Mode.MATCH
11
+ max_length = VAULT_PASSPHRASE__MAX_LENGTH
12
+ allow_empty = False
13
+ trim_whitespace = False
14
+ strict_validation = True
@@ -0,0 +1,16 @@
1
+ import re
2
+ from osbot_utils.type_safe.primitives.core.Safe_Str import Safe_Str
3
+ from osbot_utils.type_safe.primitives.core.enums.Enum__Safe_Str__Regex_Mode import Enum__Safe_Str__Regex_Mode
4
+
5
+ WRITE_KEY__REGEX = re.compile(r'^[0-9a-f]{64}$')
6
+ WRITE_KEY__MAX_LENGTH = 64
7
+
8
+ class Safe_Str__Write_Key(Safe_Str):
9
+ regex = WRITE_KEY__REGEX
10
+ regex_mode = Enum__Safe_Str__Regex_Mode.MATCH
11
+ max_length = WRITE_KEY__MAX_LENGTH
12
+ exact_length = True
13
+ allow_empty = True
14
+ trim_whitespace = True
15
+ to_lower_case = True
16
+ strict_validation = True
@@ -0,0 +1,6 @@
1
+ from osbot_utils.type_safe.primitives.core.Safe_UInt import Safe_UInt
2
+
3
+ MAX_FILE_SIZE = 100 * 1024 * 1024
4
+
5
+ class Safe_UInt__File_Size(Safe_UInt):
6
+ max_value = MAX_FILE_SIZE
@@ -0,0 +1,4 @@
1
+ from osbot_utils.type_safe.primitives.core.Safe_UInt import Safe_UInt
2
+
3
+ class Safe_UInt__Vault_Version(Safe_UInt):
4
+ max_value = 999999
File without changes
@@ -0,0 +1,13 @@
1
+ from osbot_utils.type_safe.Type_Safe import Type_Safe
2
+ from sg_send_cli.safe_types.Safe_Str__Transfer_Id import Safe_Str__Transfer_Id
3
+ from sg_send_cli.safe_types.Safe_Str__SHA256 import Safe_Str__SHA256
4
+ from sg_send_cli.safe_types.Safe_Str__File_Path import Safe_Str__File_Path
5
+ from sg_send_cli.safe_types.Safe_UInt__File_Size import Safe_UInt__File_Size
6
+
7
+
8
+ class Schema__Transfer_File(Type_Safe):
9
+ transfer_id : Safe_Str__Transfer_Id = None
10
+ file_path : Safe_Str__File_Path = None
11
+ file_hash : Safe_Str__SHA256 = None
12
+ file_size : Safe_UInt__File_Size
13
+ content_type : Safe_Str__File_Path = None
@@ -0,0 +1,11 @@
1
+ from osbot_utils.type_safe.Type_Safe import Type_Safe
2
+ from sg_send_cli.safe_types.Safe_Str__Vault_Id import Safe_Str__Vault_Id
3
+ from sg_send_cli.safe_types.Safe_Str__Access_Token import Safe_Str__Access_Token
4
+ from sg_send_cli.safe_types.Safe_Str__File_Path import Safe_Str__File_Path
5
+
6
+
7
+ class Schema__Vault_Config(Type_Safe):
8
+ vault_id : Safe_Str__Vault_Id = None
9
+ endpoint_url : Safe_Str__File_Path = None
10
+ access_token : Safe_Str__Access_Token = None
11
+ local_path : Safe_Str__File_Path = None
@@ -0,0 +1,10 @@
1
+ from osbot_utils.type_safe.Type_Safe import Type_Safe
2
+ from sg_send_cli.safe_types.Safe_Str__Vault_Id import Safe_Str__Vault_Id
3
+ from sg_send_cli.safe_types.Safe_UInt__Vault_Version import Safe_UInt__Vault_Version
4
+ from sg_send_cli.schemas.Schema__Vault_Index_Entry import Schema__Vault_Index_Entry
5
+
6
+
7
+ class Schema__Vault_Index(Type_Safe):
8
+ vault_id : Safe_Str__Vault_Id = None
9
+ version : Safe_UInt__Vault_Version
10
+ entries : list[Schema__Vault_Index_Entry]
@@ -0,0 +1,16 @@
1
+ from osbot_utils.type_safe.Type_Safe import Type_Safe
2
+ from sg_send_cli.safe_types.Safe_Str__SHA256 import Safe_Str__SHA256
3
+ from sg_send_cli.safe_types.Safe_Str__Transfer_Id import Safe_Str__Transfer_Id
4
+ from sg_send_cli.safe_types.Safe_Str__File_Path import Safe_Str__File_Path
5
+ from sg_send_cli.safe_types.Safe_UInt__File_Size import Safe_UInt__File_Size
6
+ from sg_send_cli.safe_types.Enum__Sync_State import Enum__Sync_State
7
+
8
+
9
+ class Schema__Vault_Index_Entry(Type_Safe):
10
+ file_path : Safe_Str__File_Path = None
11
+ local_hash : Safe_Str__SHA256 = None
12
+ local_size : Safe_UInt__File_Size
13
+ remote_transfer_id : Safe_Str__Transfer_Id = None
14
+ remote_hash : Safe_Str__SHA256 = None
15
+ remote_size : Safe_UInt__File_Size
16
+ state : Enum__Sync_State = Enum__Sync_State.SYNCED
@@ -0,0 +1,12 @@
1
+ from osbot_utils.type_safe.Type_Safe import Type_Safe
2
+ from sg_send_cli.safe_types.Safe_Str__Vault_Id import Safe_Str__Vault_Id
3
+ from sg_send_cli.safe_types.Safe_Str__Vault_Name import Safe_Str__Vault_Name
4
+ from sg_send_cli.safe_types.Safe_Str__Vault_Key import Safe_Str__Vault_Key
5
+ from sg_send_cli.safe_types.Safe_UInt__Vault_Version import Safe_UInt__Vault_Version
6
+
7
+
8
+ class Schema__Vault_Meta(Type_Safe):
9
+ vault_id : Safe_Str__Vault_Id = None
10
+ name : Safe_Str__Vault_Name = None
11
+ version : Safe_UInt__Vault_Version
12
+ vault_key: Safe_Str__Vault_Key = None
File without changes
@@ -0,0 +1,286 @@
1
+ import json
2
+ import os
3
+ from datetime import datetime, timezone
4
+ from osbot_utils.type_safe.Type_Safe import Type_Safe
5
+ from sg_send_cli.crypto.Vault__Crypto import Vault__Crypto
6
+ from sg_send_cli.api.Vault__API import Vault__API
7
+
8
+ SG_VAULT_DIR = '.sg_vault'
9
+ HEAD_FILE = 'HEAD'
10
+ TREE_FILE = 'tree.json'
11
+ SETTINGS_FILE = 'settings.json'
12
+
13
+
14
+ class Vault__Sync(Type_Safe):
15
+ crypto : Vault__Crypto
16
+ api : Vault__API
17
+
18
+ def clone(self, vault_key: str, directory: str = None) -> str:
19
+ keys = self.crypto.derive_keys_from_vault_key(vault_key)
20
+ vault_id = keys['vault_id']
21
+ read_key = keys['read_key_bytes']
22
+
23
+ if directory is None:
24
+ directory = vault_id
25
+ os.makedirs(directory, exist_ok=True)
26
+
27
+ settings = self._download_and_decrypt(vault_id, keys['settings_file_id'], read_key)
28
+ tree = self._download_and_decrypt(vault_id, keys['tree_file_id'], read_key)
29
+
30
+ settings_data = json.loads(settings)
31
+ tree_data = json.loads(tree)
32
+
33
+ file_map = self._flatten_tree(tree_data.get('tree', {}))
34
+ for file_path, file_info in file_map.items():
35
+ file_id = file_info['file_id']
36
+ encrypted_data = self.api.read(vault_id, file_id)
37
+ plaintext = self.crypto.decrypt(read_key, encrypted_data)
38
+ full_path = os.path.join(directory, file_path)
39
+ os.makedirs(os.path.dirname(full_path), exist_ok=True)
40
+ with open(full_path, 'wb') as f:
41
+ f.write(plaintext)
42
+
43
+ sg_vault_dir = os.path.join(directory, SG_VAULT_DIR)
44
+ os.makedirs(sg_vault_dir, exist_ok=True)
45
+ with open(os.path.join(sg_vault_dir, HEAD_FILE), 'w') as f:
46
+ f.write(vault_key)
47
+ with open(os.path.join(sg_vault_dir, TREE_FILE), 'w') as f:
48
+ json.dump(tree_data, f, indent=2)
49
+ with open(os.path.join(sg_vault_dir, SETTINGS_FILE), 'w') as f:
50
+ json.dump(settings_data, f, indent=2)
51
+
52
+ return directory
53
+
54
+ def pull(self, directory: str = '.') -> dict:
55
+ vault_key = self._read_head(directory)
56
+ keys = self.crypto.derive_keys_from_vault_key(vault_key)
57
+ vault_id = keys['vault_id']
58
+ read_key = keys['read_key_bytes']
59
+
60
+ settings = self._download_and_decrypt(vault_id, keys['settings_file_id'], read_key)
61
+ tree = self._download_and_decrypt(vault_id, keys['tree_file_id'], read_key)
62
+ settings_data = json.loads(settings)
63
+ tree_data = json.loads(tree)
64
+
65
+ old_tree_data = self._read_local_tree(directory)
66
+ old_file_map = self._flatten_tree(old_tree_data.get('tree', {}))
67
+ new_file_map = self._flatten_tree(tree_data.get('tree', {}))
68
+
69
+ old_paths = set(old_file_map.keys())
70
+ new_paths = set(new_file_map.keys())
71
+
72
+ added = new_paths - old_paths
73
+ deleted = old_paths - new_paths
74
+ modified = set()
75
+ for path in old_paths & new_paths:
76
+ if old_file_map[path].get('file_id') != new_file_map[path].get('file_id'):
77
+ modified.add(path)
78
+
79
+ for path in added | modified:
80
+ file_id = new_file_map[path]['file_id']
81
+ encrypted_data = self.api.read(vault_id, file_id)
82
+ plaintext = self.crypto.decrypt(read_key, encrypted_data)
83
+ full_path = os.path.join(directory, path)
84
+ os.makedirs(os.path.dirname(full_path), exist_ok=True)
85
+ with open(full_path, 'wb') as f:
86
+ f.write(plaintext)
87
+
88
+ for path in deleted:
89
+ full_path = os.path.join(directory, path)
90
+ if os.path.exists(full_path):
91
+ os.remove(full_path)
92
+
93
+ sg_vault_dir = os.path.join(directory, SG_VAULT_DIR)
94
+ with open(os.path.join(sg_vault_dir, TREE_FILE), 'w') as f:
95
+ json.dump(tree_data, f, indent=2)
96
+ with open(os.path.join(sg_vault_dir, SETTINGS_FILE), 'w') as f:
97
+ json.dump(settings_data, f, indent=2)
98
+
99
+ return dict(added=sorted(added), modified=sorted(modified), deleted=sorted(deleted))
100
+
101
+ def push(self, directory: str = '.') -> dict:
102
+ vault_key = self._read_head(directory)
103
+ keys = self.crypto.derive_keys_from_vault_key(vault_key)
104
+ vault_id = keys['vault_id']
105
+ read_key = keys['read_key_bytes']
106
+ write_key = keys['write_key']
107
+
108
+ old_tree_data = self._read_local_tree(directory)
109
+ old_file_map = self._flatten_tree(old_tree_data.get('tree', {}))
110
+ new_file_map = self._scan_local_directory(directory)
111
+
112
+ old_paths = set(old_file_map.keys())
113
+ new_paths = set(new_file_map.keys())
114
+
115
+ added = new_paths - old_paths
116
+ deleted = old_paths - new_paths
117
+ common = old_paths & new_paths
118
+ modified = set()
119
+
120
+ for path in common:
121
+ local_file = os.path.join(directory, path)
122
+ with open(local_file, 'rb') as f:
123
+ content = f.read()
124
+ if len(content) != old_file_map[path].get('size', -1):
125
+ modified.add(path)
126
+
127
+ uploaded = {}
128
+ for path in added | modified:
129
+ local_file = os.path.join(directory, path)
130
+ with open(local_file, 'rb') as f:
131
+ content = f.read()
132
+ file_id = os.urandom(6).hex()
133
+ encrypted = self.crypto.encrypt(read_key, content)
134
+ self.api.write(vault_id, file_id, write_key, encrypted)
135
+ uploaded[path] = dict(file_id=file_id, size=len(content))
136
+
137
+ for path in deleted:
138
+ file_id = old_file_map[path]['file_id']
139
+ self.api.delete(vault_id, file_id, write_key)
140
+
141
+ new_tree_data = self._build_tree_json(old_tree_data, old_file_map, uploaded, deleted)
142
+
143
+ tree_json = json.dumps(new_tree_data).encode()
144
+ encrypted_tree = self.crypto.encrypt(read_key, tree_json)
145
+ self.api.write(vault_id, keys['tree_file_id'], write_key, encrypted_tree)
146
+
147
+ settings_data = self._read_local_settings(directory)
148
+ settings_json = json.dumps(settings_data).encode()
149
+ encrypted_settings = self.crypto.encrypt(read_key, settings_json)
150
+ self.api.write(vault_id, keys['settings_file_id'], write_key, encrypted_settings)
151
+
152
+ sg_vault_dir = os.path.join(directory, SG_VAULT_DIR)
153
+ with open(os.path.join(sg_vault_dir, TREE_FILE), 'w') as f:
154
+ json.dump(new_tree_data, f, indent=2)
155
+
156
+ return dict(added=list(added), modified=list(modified), deleted=list(deleted))
157
+
158
+ def status(self, directory: str = '.') -> dict:
159
+ old_tree_data = self._read_local_tree(directory)
160
+ old_file_map = self._flatten_tree(old_tree_data.get('tree', {}))
161
+ new_file_map = self._scan_local_directory(directory)
162
+
163
+ old_paths = set(old_file_map.keys())
164
+ new_paths = set(new_file_map.keys())
165
+
166
+ added = sorted(new_paths - old_paths)
167
+ deleted = sorted(old_paths - new_paths)
168
+ common = old_paths & new_paths
169
+ modified = []
170
+
171
+ for path in sorted(common):
172
+ local_file = os.path.join(directory, path)
173
+ with open(local_file, 'rb') as f:
174
+ content = f.read()
175
+ if len(content) != old_file_map[path].get('size', -1):
176
+ modified.append(path)
177
+
178
+ return dict(added=added, modified=modified, deleted=deleted,
179
+ clean=not added and not modified and not deleted)
180
+
181
+ def remote_status(self, directory: str = '.') -> dict:
182
+ vault_key = self._read_head(directory)
183
+ keys = self.crypto.derive_keys_from_vault_key(vault_key)
184
+ vault_id = keys['vault_id']
185
+ read_key = keys['read_key_bytes']
186
+
187
+ remote_tree_raw = self._download_and_decrypt(vault_id, keys['tree_file_id'], read_key)
188
+ remote_tree_data = json.loads(remote_tree_raw)
189
+ remote_file_map = self._flatten_tree(remote_tree_data.get('tree', {}))
190
+
191
+ local_tree_data = self._read_local_tree(directory)
192
+ local_file_map = self._flatten_tree(local_tree_data.get('tree', {}))
193
+
194
+ remote_paths = set(remote_file_map.keys())
195
+ local_paths = set(local_file_map.keys())
196
+
197
+ remote_added = sorted(remote_paths - local_paths)
198
+ remote_deleted = sorted(local_paths - remote_paths)
199
+ remote_modified = []
200
+ for path in sorted(remote_paths & local_paths):
201
+ if remote_file_map[path].get('file_id') != local_file_map[path].get('file_id'):
202
+ remote_modified.append(path)
203
+
204
+ local_status = self.status(directory)
205
+
206
+ return dict(remote_version = remote_tree_data.get('version'),
207
+ local_version = local_tree_data.get('version'),
208
+ remote_added = remote_added,
209
+ remote_modified= remote_modified,
210
+ remote_deleted = remote_deleted,
211
+ local_added = local_status['added'],
212
+ local_modified = local_status['modified'],
213
+ local_deleted = local_status['deleted'])
214
+
215
+ # --- internal helpers ---
216
+
217
+ def _download_and_decrypt(self, vault_id: str, file_id: str, read_key: bytes) -> bytes:
218
+ encrypted = self.api.read(vault_id, file_id)
219
+ return self.crypto.decrypt(read_key, encrypted)
220
+
221
+ def _read_head(self, directory: str) -> str:
222
+ head_path = os.path.join(directory, SG_VAULT_DIR, HEAD_FILE)
223
+ with open(head_path, 'r') as f:
224
+ return f.read().strip()
225
+
226
+ def _read_local_tree(self, directory: str) -> dict:
227
+ tree_path = os.path.join(directory, SG_VAULT_DIR, TREE_FILE)
228
+ with open(tree_path, 'r') as f:
229
+ return json.load(f)
230
+
231
+ def _read_local_settings(self, directory: str) -> dict:
232
+ settings_path = os.path.join(directory, SG_VAULT_DIR, SETTINGS_FILE)
233
+ with open(settings_path, 'r') as f:
234
+ return json.load(f)
235
+
236
+ def _flatten_tree(self, tree: dict, prefix: str = '') -> dict:
237
+ result = {}
238
+ for name, node in tree.items():
239
+ if name == '/':
240
+ result.update(self._flatten_tree(node.get('children', {}), prefix))
241
+ elif node.get('type') == 'folder':
242
+ child_prefix = f'{prefix}{name}/' if prefix else f'{name}/'
243
+ result.update(self._flatten_tree(node.get('children', {}), child_prefix))
244
+ elif node.get('type') == 'file':
245
+ path = f'{prefix}{name}'
246
+ result[path] = node
247
+ return result
248
+
249
+ def _scan_local_directory(self, directory: str) -> dict:
250
+ result = {}
251
+ for root, dirs, files in os.walk(directory):
252
+ dirs[:] = [d for d in dirs if d != SG_VAULT_DIR and not d.startswith('.')]
253
+ for filename in files:
254
+ if filename.startswith('.'):
255
+ continue
256
+ full_path = os.path.join(root, filename)
257
+ rel_path = os.path.relpath(full_path, directory)
258
+ rel_path = rel_path.replace(os.sep, '/')
259
+ result[rel_path] = dict(size=os.path.getsize(full_path))
260
+ return result
261
+
262
+ def _build_tree_json(self, old_tree_data: dict, old_file_map: dict,
263
+ uploaded: dict, deleted: set) -> dict:
264
+ now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.000Z')
265
+ all_files = {}
266
+ for path, info in old_file_map.items():
267
+ if path not in deleted:
268
+ all_files[path] = info
269
+ for path, info in uploaded.items():
270
+ all_files[path] = dict(type = 'file',
271
+ file_id = info['file_id'],
272
+ size = info['size'],
273
+ uploaded= now)
274
+
275
+ tree = {'/': {'type': 'folder', 'children': {}}}
276
+ for path, info in sorted(all_files.items()):
277
+ parts = path.split('/')
278
+ current = tree['/']['children']
279
+ for part in parts[:-1]:
280
+ if part not in current:
281
+ current[part] = {'type': 'folder', 'children': {}}
282
+ current = current[part]['children']
283
+ current[parts[-1]] = info
284
+
285
+ version = old_tree_data.get('version', 0) + 1
286
+ return dict(version=version, updated=now, tree=tree)
File without changes
@@ -0,0 +1 @@
1
+ v0.3.0