socialcli 0.3.0__py3-none-any.whl

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.

Potentially problematic release.


This version of socialcli might be problematic. Click here for more details.

Files changed (224) hide show
  1. socialcli-0.3.0.dist-info/METADATA +168 -0
  2. socialcli-0.3.0.dist-info/RECORD +224 -0
  3. socialcli-0.3.0.dist-info/WHEEL +4 -0
  4. socialcli-0.3.0.dist-info/entry_points.txt +3 -0
  5. socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
  6. socialctl/__init__.py +0 -0
  7. socialctl/__main__.py +6 -0
  8. socialctl/adapters/__init__.py +6 -0
  9. socialctl/adapters/base.py +68 -0
  10. socialctl/adapters/errores.py +56 -0
  11. socialctl/adapters/facebook.py +180 -0
  12. socialctl/adapters/instagram.py +442 -0
  13. socialctl/adapters/tiktok.py +535 -0
  14. socialctl/adapters/youtube.py +331 -0
  15. socialctl/agent_errors.py +176 -0
  16. socialctl/agent_guide.py +23 -0
  17. socialctl/approval_cli.py +27 -0
  18. socialctl/auth.py +139 -0
  19. socialctl/authflow.py +344 -0
  20. socialctl/brands.py +194 -0
  21. socialctl/capabilities.py +57 -0
  22. socialctl/capabilities.yml +5945 -0
  23. socialctl/cli.py +1766 -0
  24. socialctl/connection_service/__init__.py +0 -0
  25. socialctl/connection_service/__main__.py +33 -0
  26. socialctl/connection_service/app.py +496 -0
  27. socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
  28. socialctl/connection_service/assets/connection.css +75 -0
  29. socialctl/connection_service/assets/facebook.webp +0 -0
  30. socialctl/connection_service/assets/instagram.svg +194 -0
  31. socialctl/connection_service/assets/socialcli-logo.png +0 -0
  32. socialctl/connection_service/assets/tiktok.png +0 -0
  33. socialctl/connection_service/assets/youtube.svg +1 -0
  34. socialctl/connection_service/landing.py +146 -0
  35. socialctl/connection_service/legacy.py +48 -0
  36. socialctl/connection_service/peer.py +13 -0
  37. socialctl/connection_service/providers.py +324 -0
  38. socialctl/connection_service/settings.py +76 -0
  39. socialctl/connection_service/store.py +124 -0
  40. socialctl/connections/__init__.py +0 -0
  41. socialctl/connections/account_cli.py +438 -0
  42. socialctl/connections/cli.py +379 -0
  43. socialctl/connections/client.py +126 -0
  44. socialctl/connections/credential_cli.py +224 -0
  45. socialctl/connections/credential_store.py +49 -0
  46. socialctl/connections/file_store.py +193 -0
  47. socialctl/connections/keychain.py +78 -0
  48. socialctl/connections/meta_user.py +81 -0
  49. socialctl/connections/rotation_cli.py +116 -0
  50. socialctl/connections/saas_client.py +91 -0
  51. socialctl/connections/temporary_media.py +62 -0
  52. socialctl/delivery_options.py +70 -0
  53. socialctl/engagement.py +200 -0
  54. socialctl/engagement_cli.py +50 -0
  55. socialctl/executor.py +135 -0
  56. socialctl/formatter.py +291 -0
  57. socialctl/hosted_media.py +152 -0
  58. socialctl/identity.py +200 -0
  59. socialctl/inbox.py +298 -0
  60. socialctl/inbox_cli.py +46 -0
  61. socialctl/inventory.py +155 -0
  62. socialctl/inventory_cli.py +171 -0
  63. socialctl/inventory_sources.py +101 -0
  64. socialctl/management/__init__.py +1 -0
  65. socialctl/management/batch_cli.py +115 -0
  66. socialctl/management/batches.py +325 -0
  67. socialctl/management/changes.py +485 -0
  68. socialctl/management/cli.py +227 -0
  69. socialctl/management/comments_cli.py +352 -0
  70. socialctl/management/community_batch_cli.py +63 -0
  71. socialctl/management/community_batches.py +294 -0
  72. socialctl/management/community_changes.py +370 -0
  73. socialctl/management/community_cli.py +142 -0
  74. socialctl/management/community_schema.py +119 -0
  75. socialctl/management/facebook_groups.py +1118 -0
  76. socialctl/management/groups_cli.py +274 -0
  77. socialctl/management/inbox_readers.py +87 -0
  78. socialctl/management/meta_changes.py +197 -0
  79. socialctl/management/meta_cli.py +342 -0
  80. socialctl/management/meta_client.py +631 -0
  81. socialctl/management/meta_comment_inbox.py +565 -0
  82. socialctl/management/meta_comments.py +587 -0
  83. socialctl/management/meta_errors.py +59 -0
  84. socialctl/management/meta_pagination.py +52 -0
  85. socialctl/management/meta_schema.py +128 -0
  86. socialctl/management/meta_webhooks.py +147 -0
  87. socialctl/management/metadata_parts.py +144 -0
  88. socialctl/management/owned_assets.py +85 -0
  89. socialctl/management/owned_changes.py +470 -0
  90. socialctl/management/owned_cli.py +128 -0
  91. socialctl/management/owned_reorder.py +62 -0
  92. socialctl/management/owned_schema.py +368 -0
  93. socialctl/management/reply_context.py +24 -0
  94. socialctl/management/reply_evidence.py +80 -0
  95. socialctl/management/resource_changes.py +407 -0
  96. socialctl/management/resource_cli.py +136 -0
  97. socialctl/management/snippet_readback.py +26 -0
  98. socialctl/management/stories.py +713 -0
  99. socialctl/management/stories_cli.py +172 -0
  100. socialctl/management/youtube.py +323 -0
  101. socialctl/management/youtube_community.py +326 -0
  102. socialctl/management/youtube_metadata.py +122 -0
  103. socialctl/management/youtube_owned.py +259 -0
  104. socialctl/management/youtube_resources.py +305 -0
  105. socialctl/media.py +269 -0
  106. socialctl/media_cli.py +183 -0
  107. socialctl/media_ingress.py +211 -0
  108. socialctl/media_preflight.py +114 -0
  109. socialctl/media_registry.py +301 -0
  110. socialctl/media_requirements.py +52 -0
  111. socialctl/metricas/__init__.py +6 -0
  112. socialctl/metricas/almacen.py +133 -0
  113. socialctl/metricas/analytics_changes.py +295 -0
  114. socialctl/metricas/analytics_cli.py +191 -0
  115. socialctl/metricas/analytics_client.py +304 -0
  116. socialctl/metricas/analytics_ingest.py +260 -0
  117. socialctl/metricas/analytics_schema.py +174 -0
  118. socialctl/metricas/base.py +147 -0
  119. socialctl/metricas/facebook.py +418 -0
  120. socialctl/metricas/insights.py +227 -0
  121. socialctl/metricas/instagram.py +133 -0
  122. socialctl/metricas/modelos.py +87 -0
  123. socialctl/metricas/piezas.py +134 -0
  124. socialctl/metricas/reach.py +94 -0
  125. socialctl/metricas/reporting_client.py +112 -0
  126. socialctl/metricas/resumen.py +251 -0
  127. socialctl/metricas/slugs.py +89 -0
  128. socialctl/metricas/tiktok.py +185 -0
  129. socialctl/metricas/youtube.py +403 -0
  130. socialctl/migration_cli.py +60 -0
  131. socialctl/migration_files.py +68 -0
  132. socialctl/models.py +150 -0
  133. socialctl/native_schedule/__init__.py +13 -0
  134. socialctl/native_schedule/api_delivery.py +15 -0
  135. socialctl/native_schedule/api_reconcile.py +40 -0
  136. socialctl/native_schedule/approval.py +160 -0
  137. socialctl/native_schedule/cadence.py +73 -0
  138. socialctl/native_schedule/cli.py +510 -0
  139. socialctl/native_schedule/dispatcher.py +120 -0
  140. socialctl/native_schedule/facebook.py +112 -0
  141. socialctl/native_schedule/facebook_reels.py +140 -0
  142. socialctl/native_schedule/first_comment.py +181 -0
  143. socialctl/native_schedule/handoff.py +193 -0
  144. socialctl/native_schedule/instagram_delivery.py +224 -0
  145. socialctl/native_schedule/instagram_runtime.py +66 -0
  146. socialctl/native_schedule/inventory.py +70 -0
  147. socialctl/native_schedule/migration.py +310 -0
  148. socialctl/native_schedule/models.py +103 -0
  149. socialctl/native_schedule/reconcile.py +83 -0
  150. socialctl/native_schedule/remote_data.py +177 -0
  151. socialctl/native_schedule/report.py +151 -0
  152. socialctl/native_schedule/store.py +560 -0
  153. socialctl/native_schedule/verification.py +32 -0
  154. socialctl/native_schedule/youtube.py +339 -0
  155. socialctl/operation_output.py +87 -0
  156. socialctl/plantillas/accounts.yml +33 -0
  157. socialctl/plantillas/brand.md +95 -0
  158. socialctl/plantillas/estrategia.md +64 -0
  159. socialctl/postfile.py +240 -0
  160. socialctl/preflight.py +73 -0
  161. socialctl/publication_policy.py +34 -0
  162. socialctl/publication_status.py +75 -0
  163. socialctl/publication_steps.py +398 -0
  164. socialctl/publish_output.py +96 -0
  165. socialctl/publisher.py +445 -0
  166. socialctl/queue_migration.py +302 -0
  167. socialctl/read_budget.py +224 -0
  168. socialctl/read_reports.py +91 -0
  169. socialctl/rutas.py +103 -0
  170. socialctl/saas/__init__.py +1 -0
  171. socialctl/saas/access.py +75 -0
  172. socialctl/saas/auth.py +213 -0
  173. socialctl/saas/backup.py +124 -0
  174. socialctl/saas/billing.py +327 -0
  175. socialctl/saas/billing_enrollment.py +1237 -0
  176. socialctl/saas/billing_enrollment_schema.py +519 -0
  177. socialctl/saas/billing_inventory.py +775 -0
  178. socialctl/saas/billing_reconcile.py +127 -0
  179. socialctl/saas/billing_routes.py +27 -0
  180. socialctl/saas/budget.py +66 -0
  181. socialctl/saas/connections.py +374 -0
  182. socialctl/saas/consent.py +52 -0
  183. socialctl/saas/lifecycle.py +341 -0
  184. socialctl/saas/mail.py +89 -0
  185. socialctl/saas/maintenance.py +68 -0
  186. socialctl/saas/meta_user.py +298 -0
  187. socialctl/saas/meta_webhooks.py +358 -0
  188. socialctl/saas/migration.py +107 -0
  189. socialctl/saas/models.py +8 -0
  190. socialctl/saas/operations.py +102 -0
  191. socialctl/saas/pages.py +126 -0
  192. socialctl/saas/pairing.py +158 -0
  193. socialctl/saas/permissions.py +57 -0
  194. socialctl/saas/reminders.py +128 -0
  195. socialctl/saas/renewal.py +74 -0
  196. socialctl/saas/restore_guard.py +229 -0
  197. socialctl/saas/revocation.py +97 -0
  198. socialctl/saas/rotation.py +114 -0
  199. socialctl/saas/routes.py +221 -0
  200. socialctl/saas/settings.py +34 -0
  201. socialctl/saas/store.py +106 -0
  202. socialctl/saas/temporary_media.py +245 -0
  203. socialctl/saas/webhooks.py +76 -0
  204. socialctl/schedule_remote.py +262 -0
  205. socialctl/schedule_sqlite.py +44 -0
  206. socialctl/scheduler.py +581 -0
  207. socialctl/scheduler_launchd.py +319 -0
  208. socialctl/scheduler_systemd.py +167 -0
  209. socialctl/source_links.py +119 -0
  210. socialctl/ui/__init__.py +1 -0
  211. socialctl/ui/assets/agent-manual.md +850 -0
  212. socialctl/ui/assets/agents.md +27 -0
  213. socialctl/ui/assets/components.css +20 -0
  214. socialctl/ui/assets/connection-layout.css +53 -0
  215. socialctl/ui/assets/otp.template.html +10 -0
  216. socialctl/ui/assets/tokens.css +1 -0
  217. socialctl/ui/assets/trial.template.html +11 -0
  218. socialctl/ui/assets/web-layout.css +38 -0
  219. socialctl/ui/email/otp.html +10 -0
  220. socialctl/ui/email/trial.html +11 -0
  221. socialctl/upload_consent.py +13 -0
  222. socialctl/workspace.py +8 -0
  223. socialctl/youtube_data.py +471 -0
  224. socialctl/youtube_data_service.py +225 -0
@@ -0,0 +1,224 @@
1
+ """Explicit secure-store setup, verified migration and recoverable key rotation."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+ import typer
7
+
8
+ from socialctl.brands import cargar_brand
9
+ from socialctl.connections.credential_store import store_for, KeyringStore, configuration_path
10
+ from socialctl.connections.file_store import EncryptedFileStore, protected_parent, read_file, replace_file
11
+ from socialctl.models import Platform
12
+ from socialctl.workspace import default_root
13
+
14
+ credentials_app = typer.Typer(help='Setup order: brand new, credentials generate-key/configure, account login, then connect. Headless: encrypted-file requires a Fernet key, generated with generate-key; never use a password or hex string.')
15
+
16
+
17
+ def write_configuration(brand, config):
18
+ path=configuration_path(brand)
19
+ path.parent.mkdir(mode=0o700,exist_ok=True)
20
+ with protected_parent(path) as (parent,name):
21
+ replace_file(parent,name,json.dumps(config,sort_keys=True).encode())
22
+
23
+
24
+ def external_paths(store_file,key_file,workspace=None):
25
+ if store_file is None or key_file is None:
26
+ raise ValueError('encrypted-file requires --store-file and --key-file')
27
+ paths=[Path(store_file).absolute(),Path(key_file).absolute()]
28
+ if paths[1] in {paths[0],paths[0].with_name(paths[0].name+'.lock'),paths[0].with_name(paths[0].name+'.before-rotation')}:
29
+ raise ValueError('key must not alias the encrypted store, lock or recovery file')
30
+ for path in paths:
31
+ if workspace is not None and path.is_relative_to(Path(workspace).resolve()):
32
+ raise ValueError('credential key and store must be outside the creator workspace')
33
+ if any((parent/'.git').exists() for parent in path.parents):
34
+ raise ValueError('credential key and store must be outside Git repositories')
35
+ with protected_parent(path):
36
+ pass
37
+ if paths[0] == paths[1]:
38
+ raise ValueError('key and store must be different files')
39
+ if all(p.exists() for p in paths) and paths[0].samefile(paths[1]):
40
+ raise ValueError('key and store must not alias the same file')
41
+ return paths
42
+
43
+
44
+ def destination(backend,store_file=None,key_file=None,workspace=None):
45
+ if backend=='keyring':
46
+ return KeyringStore(),{'version':1,'backend':'keyring'}
47
+ if backend!='encrypted-file':
48
+ raise ValueError('backend must be keyring or encrypted-file')
49
+ path,key=external_paths(store_file,key_file,workspace)
50
+ store=EncryptedFileStore(path,key)
51
+ store.ensure_available()
52
+ return store,{'version':1,'backend':backend,'store_file':str(path),'key_file':str(key)}
53
+
54
+
55
+ def confirm(yes,message):
56
+ typer.echo(message)
57
+ if not yes and not typer.confirm('Apply this credential-store change?',default=False):
58
+ raise typer.Exit(1)
59
+
60
+
61
+ def fail(exc):
62
+ # Backend errors must never include capabilities or key material.
63
+ typer.echo('Secure credential operation failed. Existing source credentials remain available; check protected paths, backend configuration and recovery backup.',err=True)
64
+ raise typer.Exit(1)
65
+
66
+
67
+ def require_backend_options(backend, store_file, key_file):
68
+ """Report missing CLI inputs before opening any credential backend."""
69
+ if backend == 'encrypted-file':
70
+ missing = [flag for flag, value in (('--store-file', store_file), ('--key-file', key_file))
71
+ if value is None]
72
+ if missing:
73
+ raise typer.BadParameter('Required for encrypted-file storage. Provide both --store-file and --key-file.',
74
+ param_hint=', '.join(missing))
75
+
76
+
77
+ @credentials_app.command('status')
78
+ def status(brand:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root')):
79
+ try:
80
+ selected=cargar_brand(root,brand)
81
+ store=store_for(selected)
82
+ store.ensure_available()
83
+ value={'version':1,'backend':'encrypted-file' if isinstance(store,EncryptedFileStore) else 'keyring','available':True}
84
+ if isinstance(store,EncryptedFileStore):
85
+ value.update(store_file=str(store.path),key_file=str(store.key_path))
86
+ typer.echo(json.dumps(value))
87
+ except Exception as exc: fail(exc)
88
+
89
+
90
+ def stable_credentials(brand):
91
+ from socialctl.connections.account_cli import Slot,metadata,recovery_path
92
+ if ((brand.dir_secretos/'socialcli-pairing.json').exists()
93
+ or any(recovery_path(brand,p).exists() for p in Platform)):
94
+ raise ValueError('Finish pending sign-in or connection recovery before changing credential backends.')
95
+ records=[]
96
+ installation=metadata(brand)
97
+ if installation:records.append((Slot.ACCOUNT,installation))
98
+ for platform in Platform:
99
+ meta=brand.leer_secreto(platform)
100
+ if meta.get('auth_mode')=='broker':records.append((platform,meta))
101
+ return records
102
+
103
+
104
+ @credentials_app.command('configure')
105
+ def configure(backend:str=typer.Option(...,'--backend'),store_file:Path|None=typer.Option(None,'--store-file',help='Required for encrypted-file: external encrypted credential store path.'),key_file:Path|None=typer.Option(None,'--key-file',help='Required for encrypted-file: external Fernet key (32 bytes in URL-safe base64). Create it with credentials generate-key.'),brand:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root'),yes:bool=typer.Option(False,'--yes')):
106
+ require_backend_options(backend, store_file, key_file)
107
+ try:
108
+ from socialctl.connections.cli import acquire_brand_lock
109
+ import os
110
+ selected=cargar_brand(root,brand)
111
+ fd=acquire_brand_lock(selected)
112
+ try:
113
+ if stable_credentials(selected):
114
+ raise ValueError('existing connections require credentials migrate')
115
+ dest,config=destination(backend,store_file,key_file,selected.raiz.parent)
116
+ dest.ensure_available()
117
+ confirm(yes,'Select '+backend+' capability storage. Keep the external key separate from backups and Git; losing it makes capabilities unrecoverable.')
118
+ if isinstance(dest,EncryptedFileStore): dest.claim(selected)
119
+ write_configuration(selected,config)
120
+ finally: os.close(fd)
121
+ typer.echo('Credential store configured. No account authorization or publication occurred.')
122
+ except (OSError,ValueError) as exc: fail(exc)
123
+
124
+
125
+ @credentials_app.command('migrate')
126
+ def migrate(to:str=typer.Option(...,'--to'),store_file:Path|None=typer.Option(None,'--store-file'),key_file:Path|None=typer.Option(None,'--key-file',help='External Fernet key file: 32 bytes in URL-safe base64. Create it with credentials generate-key.'),brand:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root'),yes:bool=typer.Option(False,'--yes')):
127
+ require_backend_options(to, store_file, key_file)
128
+ try:
129
+ from socialctl.connections.cli import acquire_brand_lock
130
+ import os
131
+ selected=cargar_brand(root,brand)
132
+ fd=acquire_brand_lock(selected)
133
+ try:
134
+ bindings=stable_credentials(selected)
135
+ source=store_for(selected)
136
+ dest,config=destination(to,store_file,key_file,selected.raiz.parent)
137
+ if type(source) is type(dest):
138
+ raise ValueError('use rotate for keys; migration requires another backend')
139
+ source.ensure_available();dest.ensure_available()
140
+ records=[]
141
+ for p,meta in bindings:
142
+ capability=source.get(selected,p,meta)
143
+ if not capability: raise ValueError('source capability missing')
144
+ records.append((p,meta,capability))
145
+ confirm(yes,f'Migrate {len(records)} connection capabilities to {to}; verify destination before switching or removing source.')
146
+ if isinstance(dest,EncryptedFileStore): dest.claim(selected)
147
+ for p,meta,capability in records:
148
+ existing = dest.get(selected,p,meta)
149
+ if existing is not None and existing != capability: raise ValueError('destination capability conflicts with source')
150
+ dest.save(selected,p,meta,capability)
151
+ if dest.get(selected,p,meta)!=capability: raise ValueError('destination verification failed')
152
+ write_configuration(selected,config)
153
+ cleanup_failed=False
154
+ for p,meta,_ in records:
155
+ try: source.delete(selected,p,meta)
156
+ except ValueError: cleanup_failed=True
157
+ finally: os.close(fd)
158
+ typer.echo('Migration verified; destination is active.' + (' Source cleanup incomplete; remove redundant source capabilities after confirming destination.' if cleanup_failed else ' Source capabilities removed.'))
159
+ except (OSError,ValueError) as exc: fail(exc)
160
+
161
+
162
+ @credentials_app.command('rotate')
163
+ def rotate(new_key_file:Path=typer.Option(...,'--new-key-file'),brand:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root'),yes:bool=typer.Option(False,'--yes')):
164
+ try:
165
+ from socialctl.connections.cli import acquire_brand_lock
166
+ import os
167
+ selected=cargar_brand(root,brand)
168
+ fd=acquire_brand_lock(selected)
169
+ try:
170
+ old=store_for(selected)
171
+ if not isinstance(old,EncryptedFileStore): raise ValueError('rotation requires encrypted-file')
172
+ path,key=external_paths(old.path,new_key_file,selected.raiz.parent)
173
+ if key==old.key_path or key.samefile(old.key_path): raise ValueError('rotation requires a different key file')
174
+ new=EncryptedFileStore(path,key)
175
+ new_cipher=new.cipher()
176
+ old_cipher=old.cipher()
177
+ confirm(yes,'Rotate all encrypted capabilities. Retain the old key and protected .before-rotation backup until recovery is no longer needed.')
178
+ with old.locked() as (parent,name):
179
+ data=old.bind_data(old._load(parent,name,old_cipher), selected)
180
+ config_path=configuration_path(selected)
181
+ with protected_parent(config_path) as (config_parent,config_name):
182
+ original_config=read_file(config_parent,config_name)
183
+ original=read_file(parent,name)
184
+ backup=name+'.before-rotation'
185
+ try:
186
+ # Do not overwrite an earlier recovery generation.
187
+ read_file(parent,backup)
188
+ except FileNotFoundError: pass
189
+ else: raise ValueError('previous rotation backup must be archived before another rotation')
190
+ replace_file(parent,backup,original)
191
+ try:
192
+ new._write(parent,name,data,new_cipher)
193
+ if new._load(parent,name,new_cipher)!=data: raise ValueError('rotation verification failed')
194
+ write_configuration(selected,{'version':1,'backend':'encrypted-file','store_file':str(path),'key_file':str(key)})
195
+ except BaseException:
196
+ replace_file(parent,name,original)
197
+ with protected_parent(config_path) as (config_parent,config_name):
198
+ replace_file(config_parent,config_name,original_config)
199
+ os.unlink(backup,dir_fd=parent)
200
+ raise
201
+ finally: os.close(fd)
202
+ typer.echo('Key rotation verified. Protected recovery backup retained; keep the old key separately.')
203
+ except (OSError,ValueError) as exc: fail(exc)
204
+
205
+
206
+ @credentials_app.command('generate-key')
207
+ def generate_key(key_file:Path=typer.Option(...,'--key-file',help='New external key file in an existing private directory (0700).'),root:Path=typer.Option(default_root(),'--root')):
208
+ """Create a Fernet key (32 random bytes encoded as URL-safe base64), without displaying it."""
209
+ import os
210
+ try:
211
+ from cryptography.fernet import Fernet
212
+ path=key_file.absolute()
213
+ external_paths(path.with_name(path.name+'.store-check'),path,root)
214
+ with protected_parent(path) as (parent,name):
215
+ fd=os.open(name,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600,dir_fd=parent)
216
+ with os.fdopen(fd,'wb') as stream:
217
+ stream.write(Fernet.generate_key())
218
+ stream.flush()
219
+ os.fsync(stream.fileno())
220
+ os.fsync(parent)
221
+ except (OSError,ValueError,ImportError):
222
+ typer.echo('Key not created. Use a new file outside the workspace and Git, in an existing directory owned by you with mode 0700; install socialcli[headless-credentials]. Existing files are never overwritten.',err=True)
223
+ raise typer.Exit(1)
224
+ typer.echo('Fernet key created with mode 0600. Keep it private and separate from backups; use this file with credentials configure --key-file.')
@@ -0,0 +1,49 @@
1
+ """Explicit capability-store selection; no fallback when a backend fails."""
2
+ from __future__ import annotations
3
+ import json
4
+ from typing import Protocol
5
+
6
+
7
+ class CapabilityStore(Protocol):
8
+ def ensure_available(self): ...
9
+ def get(self, brand, platform, metadata): ...
10
+ def save(self, brand, platform, metadata, secret): ...
11
+ def delete(self, brand, platform, metadata): ...
12
+
13
+
14
+ class KeyringStore:
15
+ def ensure_available(self):
16
+ from socialctl.connections.keychain import _backend
17
+ _backend()
18
+ def get(self, *args):
19
+ from socialctl.connections.keychain import _os_get
20
+ return _os_get(*args)
21
+ def save(self, *args):
22
+ from socialctl.connections.keychain import _os_save
23
+ return _os_save(*args)
24
+ def delete(self, *args):
25
+ from socialctl.connections.keychain import _os_delete
26
+ return _os_delete(*args)
27
+
28
+
29
+ def configuration_path(brand):
30
+ return brand.dir_secretos/'credential-store.json'
31
+
32
+
33
+ def store_for(brand) -> CapabilityStore:
34
+ path = configuration_path(brand)
35
+ if not path.exists() and not path.is_symlink():
36
+ return KeyringStore()
37
+ try:
38
+ from socialctl.connections.file_store import protected_parent, read_file, EncryptedFileStore
39
+ with protected_parent(path) as (parent,name):
40
+ config = json.loads(read_file(parent,name))
41
+ if config == {'version':1,'backend':'keyring'}:
42
+ return KeyringStore()
43
+ if config.get('version') != 1 or config.get('backend') != 'encrypted-file' or set(config) != {'version','backend','store_file','key_file'}:
44
+ raise ValueError()
45
+ from socialctl.connections.credential_cli import external_paths
46
+ path,key=external_paths(config['store_file'],config['key_file'],brand.raiz.parent)
47
+ return EncryptedFileStore(path,key)
48
+ except Exception:
49
+ raise ValueError('secure credential store configuration is invalid or unsafe') from None
@@ -0,0 +1,193 @@
1
+ """Explicit authenticated capability storage for Linux/macOS headless clients."""
2
+ from __future__ import annotations
3
+
4
+ import fcntl
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import secrets
9
+ import stat
10
+ from contextlib import contextmanager
11
+ from pathlib import Path
12
+
13
+ LIMIT = 4 * 1024 * 1024
14
+
15
+
16
+ @contextmanager
17
+ def protected_parent(path):
18
+ """Walk without following symlinks; pin the protected immediate directory."""
19
+ path = Path(path)
20
+ if not path.is_absolute() or '..' in path.parts:
21
+ raise ValueError('credential paths must be absolute without parent traversal')
22
+ fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY)
23
+ try:
24
+ for part in path.parent.parts[1:]:
25
+ child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
26
+ os.close(fd)
27
+ fd = child
28
+ info = os.fstat(fd)
29
+ if info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) & 0o777 != 0o700:
30
+ raise ValueError('credential parent directory must be owned by this user with owner permissions 0700 and no group/other access')
31
+ yield fd, path.name
32
+ finally:
33
+ os.close(fd)
34
+
35
+
36
+ def checked_fd(parent, name, *, create=False):
37
+ if create:
38
+ try:
39
+ fd = os.open(name, os.O_RDWR | os.O_NOFOLLOW | os.O_CREAT | os.O_EXCL, 0o600, dir_fd=parent)
40
+ except FileExistsError:
41
+ fd = os.open(name, os.O_RDWR | os.O_NOFOLLOW, dir_fd=parent)
42
+ else:
43
+ fd = os.open(name, os.O_RDWR | os.O_NOFOLLOW, dir_fd=parent)
44
+ try:
45
+ info = os.fstat(fd)
46
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1:
47
+ raise ValueError('credential files must be regular, owned by this user, mode 0600 and not hard-linked')
48
+ return fd
49
+ except BaseException:
50
+ os.close(fd)
51
+ raise
52
+
53
+
54
+ def read_file(parent, name):
55
+ fd = checked_fd(parent, name)
56
+ try:
57
+ raw = os.read(fd, LIMIT + 1)
58
+ if len(raw) > LIMIT:
59
+ raise ValueError('credential file exceeds size limit')
60
+ return raw
61
+ finally:
62
+ os.close(fd)
63
+
64
+
65
+ def replace_file(parent, name, raw):
66
+ # Check existing destination without following aliases before replacement.
67
+ try:
68
+ fd = checked_fd(parent, name)
69
+ except FileNotFoundError:
70
+ pass
71
+ else:
72
+ os.close(fd)
73
+ temporary = '.' + name + '-' + secrets.token_hex(12)
74
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
75
+ try:
76
+ with os.fdopen(fd, 'wb') as stream:
77
+ stream.write(raw)
78
+ stream.flush()
79
+ os.fsync(stream.fileno())
80
+ os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
81
+ os.fsync(parent)
82
+ finally:
83
+ try: os.unlink(temporary, dir_fd=parent)
84
+ except FileNotFoundError: pass
85
+
86
+
87
+ class EncryptedFileStore:
88
+ def __init__(self, path, key_path):
89
+ self.path, self.key_path = Path(path), Path(key_path)
90
+ if self.path == self.key_path:
91
+ raise ValueError('master key and encrypted store must be different files')
92
+
93
+ def cipher(self):
94
+ try:
95
+ from cryptography.fernet import Fernet
96
+ with protected_parent(self.key_path) as (parent, name):
97
+ return Fernet(read_file(parent, name).strip())
98
+ except Exception:
99
+ raise ValueError('encrypted credentials require a protected valid external key and the headless-credentials extra') from None
100
+
101
+ @contextmanager
102
+ def locked(self):
103
+ try:
104
+ with protected_parent(self.path) as (parent, name):
105
+ fd = checked_fd(parent, name+'.lock', create=True)
106
+ try:
107
+ fcntl.flock(fd, fcntl.LOCK_EX)
108
+ yield parent, name
109
+ finally:
110
+ os.close(fd)
111
+ except Exception:
112
+ raise ValueError('secure encrypted credential store unavailable, unsafe or corrupt') from None
113
+
114
+ def _load(self, parent, name, cipher):
115
+ try:
116
+ raw = read_file(parent, name)
117
+ except FileNotFoundError:
118
+ return {'version':1, 'records':{}}
119
+ envelope = json.loads(raw)
120
+ if envelope.get('version') != 1:
121
+ raise ValueError('unsupported encrypted credential version')
122
+ data = json.loads(cipher.decrypt(envelope['ciphertext'].encode()))
123
+ if data.get('version') != 1 or not isinstance(data.get('records'), dict):
124
+ raise ValueError('invalid encrypted credential envelope')
125
+ return data
126
+
127
+ def _write(self, parent, name, data, cipher):
128
+ raw = json.dumps({'version':1,'ciphertext':cipher.encrypt(json.dumps(data,sort_keys=True).encode()).decode()}).encode()
129
+ if len(raw) > LIMIT:
130
+ raise ValueError('credential store exceeds size limit')
131
+ replace_file(parent, name, raw)
132
+
133
+ def ensure_available(self):
134
+ cipher = self.cipher()
135
+ with self.locked() as (parent,name):
136
+ self._load(parent,name,cipher)
137
+
138
+ @staticmethod
139
+ def bind_data(data, brand):
140
+ root = str(brand.raiz.resolve())
141
+ if data.get('brand_root') not in {None, root} or any(
142
+ record.get('binding', {}).get('brand') != root for record in data['records'].values()):
143
+ raise ValueError('one encrypted store belongs to exactly one brand; use a different store file')
144
+ data['brand_root'] = root
145
+ return data
146
+
147
+ def claim(self, brand):
148
+ cipher = self.cipher()
149
+ with self.locked() as (parent,name):
150
+ data = self.bind_data(self._load(parent,name,cipher), brand)
151
+ self._write(parent,name,data,cipher)
152
+
153
+ @staticmethod
154
+ def binding(brand, platform, metadata):
155
+ return {'version':1, 'brand':str(brand.raiz.resolve()), 'platform':platform.value,
156
+ 'service_url':metadata['service_url'], 'connection_id':metadata['connection_id'],
157
+ 'account_id':(None if platform.value in {'socialcli_account','socialcli_pair','socialcli_rotation'}
158
+ else metadata['account_id'])}
159
+
160
+ def _record(self, brand, platform, metadata):
161
+ binding = self.binding(brand,platform,metadata)
162
+ return hashlib.sha256(json.dumps(binding,sort_keys=True).encode()).hexdigest(), binding
163
+
164
+ def get(self, brand, platform, metadata):
165
+ key, binding = self._record(brand,platform,metadata)
166
+ cipher = self.cipher()
167
+ with self.locked() as (parent,name):
168
+ record = self.bind_data(self._load(parent,name,cipher), brand)['records'].get(key)
169
+ if record is None:
170
+ return None
171
+ if record.get('binding') != binding or not isinstance(record.get('secret'), str):
172
+ raise ValueError('credential binding mismatch')
173
+ return record['secret']
174
+
175
+ def save(self, brand, platform, metadata, secret):
176
+ if not isinstance(secret,str) or not secret or len(secret) > 8192:
177
+ raise ValueError('invalid connection capability')
178
+ key, binding = self._record(brand,platform,metadata)
179
+ cipher = self.cipher()
180
+ with self.locked() as (parent,name):
181
+ data = self.bind_data(self._load(parent,name,cipher), brand)
182
+ data['records'][key] = {'binding':binding,'secret':secret}
183
+ self._write(parent,name,data,cipher)
184
+ if self._load(parent,name,cipher) != data:
185
+ raise ValueError('credential save verification failed')
186
+
187
+ def delete(self, brand, platform, metadata):
188
+ key, _ = self._record(brand,platform,metadata)
189
+ cipher = self.cipher()
190
+ with self.locked() as (parent,name):
191
+ data = self.bind_data(self._load(parent,name,cipher), brand)
192
+ data['records'].pop(key,None)
193
+ self._write(parent,name,data,cipher)
@@ -0,0 +1,78 @@
1
+ """Connection capabilities live only in supported OS credential stores."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+
6
+ import keyring
7
+
8
+ SECURE_MODULES = {'keyring.backends.macOS', 'keyring.backends.Windows',
9
+ 'keyring.backends.SecretService', 'keyring.backends.libsecret',
10
+ 'keyring.backends.kwallet'}
11
+
12
+
13
+ def _backend():
14
+ try:
15
+ backend = keyring.get_keyring()
16
+ candidates = backend.backends if type(backend).__module__ == 'keyring.backends.chainer' else [backend]
17
+ for candidate in candidates:
18
+ if type(candidate).__module__ in SECURE_MODULES and candidate.priority > 0:
19
+ return candidate
20
+ except Exception:
21
+ pass
22
+ raise ValueError('a secure OS keyring is required; unlock or configure your system credential store')
23
+
24
+
25
+ def ensure_available(brand=None):
26
+ if brand is None:
27
+ _backend()
28
+ else:
29
+ from socialctl.connections.credential_store import store_for
30
+ store_for(brand).ensure_available()
31
+
32
+
33
+ def _key(brand, platform, metadata):
34
+ root_hash = hashlib.sha256(str(brand.raiz.resolve()).encode()).hexdigest()
35
+ return f'socialcli:{root_hash}', f"{platform.value}:{metadata['service_url']}:{metadata['connection_id']}"
36
+
37
+
38
+ def _os_get(brand, platform, metadata):
39
+ try:
40
+ return _backend().get_password(*_key(brand,platform,metadata))
41
+ except Exception:
42
+ raise ValueError('connection credential unavailable in the secure OS keyring') from None
43
+
44
+
45
+ def _os_save(brand, platform, metadata, secret):
46
+ try:
47
+ backend = _backend()
48
+ key = _key(brand,platform,metadata)
49
+ backend.set_password(*key,secret)
50
+ if backend.get_password(*key) != secret:
51
+ raise ValueError()
52
+ except Exception:
53
+ raise ValueError('could not save the connection in the secure OS keyring') from None
54
+
55
+
56
+ def _os_delete(brand, platform, metadata):
57
+ try:
58
+ backend = _backend()
59
+ key = _key(brand,platform,metadata)
60
+ if backend.get_password(*key) is not None:
61
+ backend.delete_password(*key)
62
+ except Exception:
63
+ raise ValueError('could not delete the connection from the secure OS keyring') from None
64
+
65
+
66
+ def get(brand, platform, metadata):
67
+ from socialctl.connections.credential_store import store_for
68
+ return store_for(brand).get(brand, platform, metadata)
69
+
70
+
71
+ def save(brand, platform, metadata, secret):
72
+ from socialctl.connections.credential_store import store_for
73
+ return store_for(brand).save(brand, platform, metadata, secret)
74
+
75
+
76
+ def delete(brand, platform, metadata):
77
+ from socialctl.connections.credential_store import store_for
78
+ return store_for(brand).delete(brand, platform, metadata)
@@ -0,0 +1,81 @@
1
+ """Owned Instagram User operations through SaaS; User tokens never leave it."""
2
+ from socialctl.connections.client import broker_for, opaque, account_id
3
+ from socialctl.connections import keychain
4
+ from socialctl.connections.saas_client import ServiceRejected
5
+ from socialctl.management.meta_schema import MetaError, MetaRejected, MetaUncertain, meta_id
6
+
7
+ NO_WRITE_CODES = {
8
+ 'operation_rejected', 'operation_conflict', 'user_authorization_required',
9
+ 'provider_authorization_expired', 'provider_permissions_changed',
10
+ 'connection_inactive', 'connection_unavailable', 'connection_replaced',
11
+ 'connection_changed', 'platform_not_allowed', 'installation_revoked',
12
+ 'installation_expired', 'privacy_acceptance_required',
13
+ 'assistant_consent_required', 'subscription_required', 'activation_required',
14
+ 'capability_not_enabled',
15
+ }
16
+
17
+
18
+ class RemoteMetaUser:
19
+ def __init__(self, brand, platform, client):
20
+ self.brand, self.platform, self.client = brand, platform, client
21
+
22
+ def request(self, phase, edit=None, *, change=None, mention=None):
23
+ writing = phase == 'mutate'
24
+ try:
25
+ if (self.brand.dir_secretos / 'socialcli-rotation.json').exists():
26
+ raise MetaError('Credential rotation is pending; finish it before management operations.')
27
+ metadata = self.brand.leer_secreto(self.platform)
28
+ expected = opaque(metadata.get('account_id'))
29
+ if (metadata.get('auth_mode') != 'broker' or metadata.get('protocol') != 'saas-v1'
30
+ or expected != account_id(self.brand, self.platform)):
31
+ raise MetaError('Instagram management connection does not match the selected account.')
32
+ connection = opaque(metadata.get('connection_id'))
33
+ secret = keychain.get(self.brand, self.platform, metadata)
34
+ if not isinstance(secret, str) or not 16 <= len(secret) <= 512:
35
+ raise MetaError('Connection credential unavailable in the selected secure store.')
36
+ body = mention if mention is not None else {'phase': phase, 'edit': edit.model_dump(exclude_none=True)}
37
+ if phase in {'mutate', 'status'}:
38
+ if change is None:
39
+ raise MetaError('Remote mutation requires the approved durable ChangeSet.')
40
+ body.update(operation_id=change.id, expected_identity=change.identity, expected_before=change.before)
41
+ result = broker_for(metadata, self.client).request('POST',
42
+ f'/v1/connections/{connection}/' + ('instagram-mention-inspect' if mention is not None else 'instagram-management'), secret=secret, body=body)
43
+ identity = result.get('identity')
44
+ page_id = (self.brand.cuentas.get('facebook') or {}).get('page_id')
45
+ if (result.get('platform') != 'instagram' or result.get('account', {}).get('id') != expected
46
+ or not isinstance(identity, dict) or set(identity) != {'actor_id', 'token_mode', 'page_id', 'account_id'}
47
+ or identity.get('token_mode') != 'facebook_user' or identity.get('account_id') != expected
48
+ or identity.get('page_id') != page_id):
49
+ raise ValueError('Account mismatch')
50
+ meta_id(identity['actor_id'])
51
+ if phase == 'inspect' and not isinstance(result.get('before'), dict):
52
+ raise ValueError('Missing observation')
53
+ if phase in {'mutate', 'status'}:
54
+ if identity != change.identity:
55
+ raise ValueError('Receipt identity does not match the approved operation')
56
+ receipt = result.get('receipt')
57
+ if (phase == 'status' and edit.action == 'comment-moderate'
58
+ and result.get('reconciliation') == 'verified_readback'
59
+ and receipt is None):
60
+ expected = dict(change.before, hidden=edit.hide)
61
+ if result.get('before') != expected or expected == change.before:
62
+ raise ValueError('Invalid independent moderation readback')
63
+ elif edit.action in {'media-delete','comment-moderate'}:
64
+ if receipt != {'success': True, 'target_id': edit.comment_id or edit.target_id}:
65
+ raise ValueError('Invalid receipt')
66
+ elif not isinstance(receipt, dict) or set(receipt) != {'id', 'accepted'} or receipt['accepted'] is not True:
67
+ raise ValueError('Invalid receipt')
68
+ else:
69
+ meta_id(receipt['id'])
70
+ return result
71
+ except MetaError:
72
+ raise
73
+ except ServiceRejected as exc:
74
+ definitive = exc.status in {400, 401, 402, 403, 404, 409, 422} and exc.code in NO_WRITE_CODES
75
+ error = (MetaRejected if definitive else MetaUncertain) if writing else MetaError
76
+ failure = error(str(exc))
77
+ failure._socialcli_error_code = exc.code
78
+ raise failure from None
79
+ except Exception:
80
+ raise (MetaUncertain if writing else MetaError)(
81
+ 'Instagram management response unavailable or invalid; no automatic retry.') from None