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,438 @@
1
+ """Installation sign-in and safe connection installation for terminal AI agents."""
2
+ import base64
3
+ from enum import Enum
4
+ import hashlib
5
+ import json
6
+ import math
7
+ import os
8
+ from pathlib import Path
9
+ import secrets
10
+ import time
11
+ import webbrowser
12
+ import httpx
13
+ import typer
14
+ from socialctl.brands import cargar_brand
15
+ from socialctl.connections import keychain
16
+ from socialctl.connections.client import opaque,visible,service_origin
17
+ from socialctl.connections.saas_client import SaaSClient,ServiceRejected,TransportFailure
18
+ from socialctl.connections.cli import atomic_bytes,acquire_brand_lock,bind_account,validate_binding
19
+ from socialctl.models import Platform
20
+ from socialctl.workspace import default_root
21
+
22
+ DEFAULT_SAAS='https://socialcli.app'
23
+ account_app=typer.Typer(help='Sign in to SocialCli and manage this agent installation.')
24
+ Slot=Enum('Slot',{'ACCOUNT':'socialcli_account','PAIR':'socialcli_pair'})
25
+
26
+
27
+ def http_client():
28
+ from socialctl.read_budget import LocalConfigurationError
29
+ try:
30
+ return httpx.Client(timeout=30,follow_redirects=False)
31
+ except (httpx.InvalidURL,ValueError,OSError,ImportError):
32
+ raise LocalConfigurationError('Check local proxy, CA and HTTP transport configuration; no request was sent.') from None
33
+
34
+
35
+ def metadata(brand):
36
+ path=brand.dir_secretos/'socialcli-account.json'
37
+ data=json.loads(path.read_text()) if path.exists() else {}
38
+ if data and (data.get('version')!=1 or data.get('auth_mode')!='saas-installation'):
39
+ raise ValueError('Invalid SocialCli installation metadata.')
40
+ return data
41
+
42
+
43
+ def handoff(url,*,no_browser,seconds):
44
+ typer.echo('Give this link directly to the user: '+url,err=True)
45
+ typer.echo(f'Do not open, fetch or preview it. Keep this command running. The user has {seconds//60} minutes to approve. No content will be published.',err=True)
46
+ if not no_browser: webbrowser.open(url)
47
+
48
+
49
+ def wait(client,path,secret,seconds,interval,ready):
50
+ if type(seconds) not in {int,float} or not math.isfinite(seconds) or not 0<seconds<=1800 or type(interval) not in {int,float} or not math.isfinite(interval) or not 0<interval<=60:
51
+ raise ValueError('Invalid SocialCli authorization timing.')
52
+ deadline=time.monotonic()+seconds
53
+ while time.monotonic()<deadline:
54
+ result=client.request('POST',path,secret=secret)
55
+ if result.get('status') in ready: return result
56
+ if result.get('status') in {'failed','denied','cancelled','consumed'}:
57
+ raise ValueError('Authorization was cancelled or unavailable. Request a new link.')
58
+ time.sleep(min(interval,max(0,deadline-time.monotonic())))
59
+ raise ValueError('Authorization timed out. Request a new link.')
60
+
61
+
62
+ def output(value,json_output):
63
+ if json_output: typer.echo(json.dumps(value))
64
+ else: typer.echo(value['status'].replace('_',' ').capitalize()+'.')
65
+
66
+
67
+ def finish_pending_pair(client,brand,installation_id):
68
+ """Finish delivery cleanup only after this durable installation is verified."""
69
+ path=brand.dir_secretos/'socialcli-pairing.json'
70
+ if not path.exists():return
71
+ pending=json.loads(path.read_text())
72
+ if pending['service_url']!=client.origin:
73
+ raise ValueError('A pairing is pending for another service.')
74
+ secret=keychain.get(brand,Slot.PAIR,pending)
75
+ if secret is not None:
76
+ pair_id=opaque(pending['connection_id'])
77
+ try:
78
+ result=client.request('POST','/api/saas/v1/pairings/'+pair_id+'/poll',secret=secret)
79
+ if result.get('installation_id')!=installation_id or result.get('status') not in {'approved','consumed'}:
80
+ raise ValueError('Pending pairing does not match the saved installation.')
81
+ client.request('POST','/api/saas/v1/pairings/'+pair_id+'/ack',secret=secret)
82
+ except ServiceRejected as exc:
83
+ if exc.status!=404:raise # Expired delivery cannot be replayed.
84
+ # Missing proof can result from a crash between secret deletion and unlink.
85
+ # The installation itself was authenticated; no new grant is inferred here.
86
+ keychain.delete(brand,Slot.PAIR,pending)
87
+ path.unlink(missing_ok=True)
88
+
89
+
90
+ @account_app.command('login')
91
+ def login(brand_name:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root'),
92
+ service:str=typer.Option(DEFAULT_SAAS,'--service'),label:str=typer.Option('AI assistant','--label'),
93
+ no_browser:bool=typer.Option(False,'--no-browser'),json_output:bool=typer.Option(False,'--json'),
94
+ timeout:float=typer.Option(1800,'--timeout',min=1,max=1800),
95
+ dev_local:bool=typer.Option(False,'--dev-local')):
96
+ """Link this installation after the user signs in and approves in their browser."""
97
+ lock=None
98
+ try:
99
+ brand=cargar_brand(root,brand_name);lock=acquire_brand_lock(brand);keychain.ensure_available(brand)
100
+ with http_client() as transport:
101
+ client=SaaSClient(service,transport,allow_http_local=dev_local)
102
+ previous=metadata(brand)
103
+ if previous:
104
+ if previous['service_url']!=client.origin:
105
+ raise ValueError('Sign out of the existing SocialCli service before changing services.')
106
+ try:
107
+ status=client.request('GET','/api/saas/v1/installations/'+opaque(previous['connection_id']),secret=keychain.get(brand,Slot.ACCOUNT,previous))
108
+ except ServiceRejected as exc:
109
+ if exc.status!=401: raise
110
+ else:
111
+ finish_pending_pair(client,brand,status['installation_id'])
112
+ output({'version':1,'status':'signed_in','installation_id':status['installation_id']},json_output);return
113
+ pending_path=brand.dir_secretos/'socialcli-pairing.json'
114
+ pending=json.loads(pending_path.read_text()) if pending_path.exists() else None
115
+ if pending and pending['service_url']!=client.origin: raise ValueError('A pairing is pending for another service.')
116
+ if pending:
117
+ poll_secret=keychain.get(brand,Slot.PAIR,pending)
118
+ pair_id=opaque(pending['connection_id']);start=pending['start']
119
+ else:
120
+ poll_secret=secrets.token_urlsafe(32)
121
+ start=client.request('POST','/api/saas/v1/installations/pair',body={'label':label,'poll_challenge':hashlib.sha256(poll_secret.encode()).hexdigest()})
122
+ pair_id=opaque(start.get('pairing_id'))
123
+ pending={'version':1,'service_url':client.origin,'connection_id':pair_id,'start':start}
124
+ keychain.save(brand,Slot.PAIR,pending,poll_secret)
125
+ atomic_bytes(pending_path,json.dumps(pending).encode())
126
+ expected=client.origin+'/account/pair/'+pair_id
127
+ if start.get('browser_url')!=expected: raise ValueError('Invalid SocialCli sign-in URL.')
128
+ handoff(expected,no_browser=no_browser,seconds=1800)
129
+ try:
130
+ result=wait(client,'/api/saas/v1/pairings/'+pair_id+'/poll',poll_secret,min(timeout,start['expires_in']),start['poll_interval'],{'approved'})
131
+ except ServiceRejected as exc:
132
+ if exc.status==404:
133
+ pending_path.unlink(missing_ok=True);keychain.delete(brand,Slot.PAIR,pending)
134
+ raise
135
+ installation_id=opaque(result.get('installation_id'));secret=result.get('installation_secret')
136
+ if not isinstance(secret,str) or not 16<=len(secret)<=512: raise ValueError('Invalid installation credential.')
137
+ saved={'version':1,'auth_mode':'saas-installation','service_url':client.origin,'connection_id':installation_id}
138
+ if dev_local:saved['development_local']=True
139
+ keychain.save(brand,Slot.ACCOUNT,saved,secret)
140
+ atomic_bytes(brand.dir_secretos/'socialcli-account.json',json.dumps(saved).encode())
141
+ # Credentials and metadata are durable before acknowledging delivery.
142
+ client.request('POST','/api/saas/v1/pairings/'+pair_id+'/ack',secret=poll_secret)
143
+ keychain.delete(brand,Slot.PAIR,pending);pending_path.unlink(missing_ok=True)
144
+ if previous and previous['connection_id']!=installation_id:keychain.delete(brand,Slot.ACCOUNT,previous)
145
+ output({'version':1,'status':'signed_in','installation_id':installation_id},json_output)
146
+ except (KeyboardInterrupt,typer.Abort):
147
+ typer.echo('Sign-in interrupted. Run the same command to resume.',err=True);raise typer.Exit(1)
148
+ except Exception as exc:
149
+ if json_output:
150
+ from socialctl.agent_errors import emit_error
151
+ emit_error(exc, read_only=False)
152
+ typer.echo(str(exc) if isinstance(exc,ValueError) else 'Could not sign in safely. Your pending sign-in can be resumed.',err=True);raise typer.Exit(1)
153
+ finally:
154
+ if lock is not None:os.close(lock)
155
+
156
+
157
+ @account_app.command('status')
158
+ def status(brand_name:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root'),json_output:bool=typer.Option(False,'--json')):
159
+ """Read this installation without refreshing provider tokens."""
160
+ try:
161
+ brand=cargar_brand(root,brand_name);saved=metadata(brand)
162
+ if not saved: raise ValueError('Not signed in. Run socialcli account login.')
163
+ with http_client() as transport:
164
+ client=SaaSClient(saved['service_url'],transport,allow_http_local=saved.get('development_local') is True)
165
+ result=client.request('GET','/api/saas/v1/installations/'+opaque(saved['connection_id']),secret=keychain.get(brand,Slot.ACCOUNT,saved))
166
+ output({**result,'status':'signed_in'},json_output)
167
+ except Exception as exc:
168
+ if json_output:
169
+ from socialctl.agent_errors import emit_error
170
+ emit_error(exc, read_only=True)
171
+ typer.echo(str(exc) if isinstance(exc,ValueError) else 'Could not read SocialCli installation status.',err=True);raise typer.Exit(1)
172
+
173
+
174
+ @account_app.command('permissions')
175
+ def permissions(brand_name:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root'),
176
+ no_browser:bool=typer.Option(False,'--no-browser'),json_output:bool=typer.Option(False,'--json')):
177
+ """Give the owner a link to add platforms without replacing this installation."""
178
+ try:
179
+ brand=cargar_brand(root,brand_name);saved=metadata(brand)
180
+ if not saved:raise ValueError('Not signed in. Run socialcli account login.')
181
+ with http_client() as transport:
182
+ client=SaaSClient(saved['service_url'],transport,allow_http_local=saved.get('development_local') is True)
183
+ installation_id=opaque(saved['connection_id'])
184
+ result=client.request('GET','/api/saas/v1/installations/'+installation_id,secret=keychain.get(brand,Slot.ACCOUNT,saved))
185
+ supported=client.request('GET','/api/saas/v1/capabilities')
186
+ if supported.get('installation_platform_expansion') is not True:
187
+ raise ValueError('This SocialCli service needs an update to add platforms. Keep existing connections; do not log out.')
188
+ url=client.origin+'/account/installations/'+installation_id+'/platforms'
189
+ typer.echo('Give this link directly to the owner: '+url,err=True)
190
+ typer.echo('The owner must open it and approve additional platforms. Existing connections stay active. After approval, run connect for the new platform. Do not open or approve it for the owner.',err=True)
191
+ if json_output:
192
+ typer.echo(json.dumps({'version':1,'status':'owner_action_required','browser_url':url,
193
+ 'platform_access':result.get('platform_access')}))
194
+ if not no_browser:webbrowser.open(url)
195
+ except Exception as exc:
196
+ if json_output:
197
+ from socialctl.agent_errors import emit_error
198
+ emit_error(exc,read_only=True)
199
+ typer.echo(str(exc) if isinstance(exc,ValueError) else 'Could not read SocialCli permissions.',err=True);raise typer.Exit(1)
200
+
201
+
202
+ @account_app.command('logout')
203
+ def logout(brand_name:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root')):
204
+ """Revoke this agent installation; other installations keep their access."""
205
+ lock=None
206
+ try:
207
+ brand=cargar_brand(root,brand_name);lock=acquire_brand_lock(brand);saved=metadata(brand)
208
+ if not saved: raise ValueError('Not signed in.')
209
+ with http_client() as transport:
210
+ client=SaaSClient(saved['service_url'],transport,allow_http_local=saved.get('development_local') is True)
211
+ try:client.request('DELETE','/api/saas/v1/installations/'+opaque(saved['connection_id']),secret=keychain.get(brand,Slot.ACCOUNT,saved))
212
+ except ServiceRejected as exc:
213
+ if exc.status!=401:raise
214
+ keychain.delete(brand,Slot.ACCOUNT,saved);(brand.dir_secretos/'socialcli-account.json').unlink(missing_ok=True)
215
+ from socialctl.youtube_data import request_youtube_purge
216
+ cleanup=request_youtube_purge(brand.raiz)
217
+ if not cleanup['complete']:
218
+ typer.echo('Local YouTube data cleanup is pending; run data-cleanup for this brand.',err=True)
219
+ typer.echo('Signed out. This installation can no longer obtain social tokens.')
220
+ except Exception as exc:
221
+ typer.echo(str(exc) if isinstance(exc,ValueError) else 'Could not confirm sign-out. Keep your credentials and retry.',err=True);raise typer.Exit(1)
222
+ finally:
223
+ if lock is not None:os.close(lock)
224
+
225
+
226
+ def recovery_slot(platform):
227
+ return Enum('RecoverySlot',{'VALUE':'socialcli_recovery_'+platform.value}).VALUE
228
+
229
+
230
+ def recovery_path(brand,platform):
231
+ return brand.dir_secretos/('socialcli-recovery-'+platform.value+'.json')
232
+
233
+
234
+ def finalize_local(brand,platform,client,result):
235
+ account=result.get('account',{});opaque(account.get('id'));connection_id=opaque(result.get('connection_id'))
236
+ if result.get('platform')!=platform.value:raise ValueError('Connection platform mismatch.')
237
+ secret=result.get('connection_secret')
238
+ if not isinstance(secret,str) or not 16<=len(secret)<=512:raise ValueError('Invalid connection credential.')
239
+ validate_binding(brand,platform,account)
240
+ saved={'version':1,'auth_mode':'broker','protocol':'saas-v1','service_url':client.origin,
241
+ 'connection_id':connection_id,'account_id':account['id'],'account':account,'granted_scopes':result.get('granted_scopes',[])}
242
+ if client.origin.startswith('http://'):saved['development_local']=True
243
+ path=brand.dir_secretos/(platform.value+'.json');config=brand.raiz/'accounts.yml'
244
+ old=brand.leer_secreto(platform)
245
+ journal={'metadata':saved,'previous_config':base64.b64encode(config.read_bytes()).decode(),
246
+ 'previous_secret':base64.b64encode(path.read_bytes()).decode() if path.exists() else None,'previous_metadata':old}
247
+ keychain.save(brand,platform,saved,secret)
248
+ keychain.save(brand,recovery_slot(platform),saved,json.dumps(journal))
249
+ atomic_bytes(recovery_path(brand,platform),json.dumps(saved).encode())
250
+ activation_started=False
251
+ try:
252
+ bind_account(brand,platform,account);atomic_bytes(path,json.dumps(saved).encode())
253
+ activation_started=True
254
+ client.request('POST','/api/saas/v1/connections/'+connection_id+'/activate',secret=secret)
255
+ except BaseException as exc:
256
+ if activation_started and (not isinstance(exc,ServiceRejected) or exc.status>=500):
257
+ raise ValueError('Activation could not be confirmed. Run socialcli account recover '+platform.value+' before any other connection change.') from None
258
+ restore_local(brand,platform,journal)
259
+ keychain.delete(brand,platform,saved)
260
+ forget_recovery(brand,platform,saved)
261
+ raise
262
+ clear_recovery(brand,platform,journal)
263
+ return saved
264
+
265
+
266
+ def restore_local(brand,platform,journal):
267
+ config=brand.raiz/'accounts.yml';atomic_bytes(config,base64.b64decode(journal['previous_config']),config.stat().st_mode&0o777)
268
+ path=brand.dir_secretos/(platform.value+'.json')
269
+ if journal['previous_secret'] is None:path.unlink(missing_ok=True)
270
+ else:atomic_bytes(path,base64.b64decode(journal['previous_secret']))
271
+
272
+
273
+ def clear_recovery(brand,platform,journal):
274
+ saved=journal['metadata'];old=journal['previous_metadata']
275
+ if old.get('auth_mode')=='broker' and old.get('connection_id')!=saved['connection_id']:
276
+ keychain.delete(brand,platform,old)
277
+ forget_recovery(brand,platform,saved)
278
+
279
+
280
+ def forget_recovery(brand,platform,saved):
281
+ # Keep the journal available until its pointer is durably gone. A failed
282
+ # unlink must remain recoverable; a leftover unreferenced secret is harmless.
283
+ path=recovery_path(brand,platform)
284
+ path.unlink(missing_ok=True)
285
+ directory=os.open(path.parent,os.O_RDONLY)
286
+ try:os.fsync(directory)
287
+ finally:os.close(directory)
288
+ keychain.delete(brand,recovery_slot(platform),saved)
289
+
290
+
291
+ @account_app.command('recover')
292
+ def recover(platform:Platform,brand_name:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root')):
293
+ """Resolve an interrupted local install without repeating OAuth or publication."""
294
+ lock=None
295
+ try:
296
+ brand=cargar_brand(root,brand_name);lock=acquire_brand_lock(brand,allow_recovery=True)
297
+ saved=json.loads(recovery_path(brand,platform).read_text())
298
+ journal=json.loads(keychain.get(brand,recovery_slot(platform),saved));secret=keychain.get(brand,platform,saved)
299
+ with http_client() as transport:
300
+ client=SaaSClient(saved['service_url'],transport,allow_http_local=saved.get('development_local') is True)
301
+ try:client.request('POST','/api/saas/v1/connections/'+opaque(saved['connection_id'])+'/activate',secret=secret)
302
+ except ServiceRejected as exc:
303
+ if exc.status>=500: raise
304
+ restore_local(brand,platform,journal);keychain.delete(brand,platform,saved)
305
+ forget_recovery(brand,platform,saved)
306
+ typer.echo('Pending activation was rejected. Previous local credentials restored.');return
307
+ bind_account(brand,platform,saved['account']);atomic_bytes(brand.dir_secretos/(platform.value+'.json'),json.dumps(saved).encode())
308
+ clear_recovery(brand,platform,journal);typer.echo('Connection recovered. No OAuth or publication was repeated.')
309
+ except Exception as exc:
310
+ typer.echo(str(exc) if isinstance(exc,ValueError) else 'Could not confirm recovery. Keep the pending records and retry.',err=True);raise typer.Exit(1)
311
+ finally:
312
+ if lock is not None:os.close(lock)
313
+
314
+
315
+ def connect_saas(brand,platform,*,no_browser,account_id=None,replace_independent=False,management=False,analytics=False,timeout=600):
316
+ if recovery_path(brand,platform).exists():raise ValueError('A connection recovery is pending. Run socialcli account recover '+platform.value+'.')
317
+ saved=metadata(brand);previous=brand.leer_secreto(platform)
318
+ if previous and previous.get('auth_mode')!='broker' and not replace_independent:
319
+ raise ValueError('Replacing independent credentials requires explicit --replace-independent and browser approval.')
320
+ keychain.ensure_available(brand)
321
+ with http_client() as transport:
322
+ client=SaaSClient(saved['service_url'],transport,allow_http_local=saved.get('development_local') is True)
323
+ secret=keychain.get(brand,Slot.ACCOUNT,saved);installation_id=opaque(saved['connection_id'])
324
+ poll_secret=secrets.token_urlsafe(32)
325
+ start=client.request('POST','/api/saas/v1/installations/'+installation_id+'/authorizations',secret=secret,
326
+ body={'platform':platform.value,'brand':brand.nombre,'poll_challenge':hashlib.sha256(poll_secret.encode()).hexdigest(),
327
+ 'management':management,'analytics':analytics})
328
+ auth_id=opaque(start.get('authorization_id'));expected=client.origin+'/connect/'+auth_id
329
+ if start.get('browser_url')!=expected:raise ValueError('Invalid account authorization URL.')
330
+ handoff(expected,no_browser=no_browser,seconds=600)
331
+ result=wait(client,'/api/saas/v1/authorizations/'+auth_id+'/poll',poll_secret,min(timeout,start['expires_in']),start['poll_interval'],{'selected'})
332
+ if account_id is not None and result.get('account',{}).get('id')!=account_id:raise ValueError('Browser-selected account differs from the explicitly requested ID. No connection was installed.')
333
+ finalize_local(brand,platform,client,result)
334
+ typer.echo(platform.value+' connected for '+visible(brand.nombre)+'. No content was published.')
335
+
336
+
337
+ @account_app.command('attach')
338
+ def attach(platform:Platform,brand_name:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root')):
339
+ """Use an existing owner-approved account in this installation without OAuth."""
340
+ lock=None
341
+ try:
342
+ brand=cargar_brand(root,brand_name);lock=acquire_brand_lock(brand)
343
+ if recovery_path(brand,platform).exists():raise ValueError('Resolve pending connection recovery first.')
344
+ previous=brand.leer_secreto(platform)
345
+ saved=metadata(brand)
346
+ if not saved:raise ValueError('Run socialcli account login first.')
347
+ if previous and (previous.get('auth_mode')!='broker' or previous.get('protocol')!='saas-v1'
348
+ or previous.get('service_url')!=saved['service_url']):
349
+ raise ValueError('A local connection already exists. Review it before replacing it.')
350
+ keychain.ensure_available(brand)
351
+ with http_client() as transport:
352
+ client=SaaSClient(saved['service_url'],transport,allow_http_local=saved.get('development_local') is True)
353
+ if previous:
354
+ try:
355
+ client.request('GET','/api/saas/v1/connections/'+opaque(previous['connection_id']),
356
+ secret=keychain.get(brand,platform,previous))
357
+ except ServiceRejected as exc:
358
+ # Browser revocation removes capabilities, so their status
359
+ # becomes 404. This explicit attach still authenticates the
360
+ # current installation, requires its owner-approved platform
361
+ # and existing grant, and checks the exact old account below.
362
+ if (exc.status,exc.code) not in {
363
+ (401,'installation_revoked'),(401,'installation_expired'),
364
+ (404,'connection_unavailable')}:
365
+ raise
366
+ else:raise ValueError('A local connection already exists. Review it before replacing it.')
367
+ result=client.request('POST','/api/saas/v1/installations/'+opaque(saved['connection_id'])+'/attach',
368
+ secret=keychain.get(brand,Slot.ACCOUNT,saved),body={'platform':platform.value,'brand':brand.nombre})
369
+ if previous and result.get('account',{}).get('id')!=previous.get('account_id'):
370
+ raise ValueError('The approved account changed. Review it before replacing this local connection.')
371
+ finalize_local(brand,platform,client,result)
372
+ typer.echo(platform.value+' attached for '+visible(brand.nombre)+'. No OAuth or publication was repeated.')
373
+ except Exception as exc:
374
+ typer.echo(str(exc) if isinstance(exc,ValueError) else 'Could not attach safely. Check your SocialCli account.',err=True);raise typer.Exit(1)
375
+ finally:
376
+ if lock is not None:os.close(lock)
377
+
378
+
379
+ def migration_origin_allowed(old,new,*,allow_http_local=False):
380
+ source=service_origin(old,allow_http_local=allow_http_local)
381
+ target=service_origin(new,allow_http_local=allow_http_local)
382
+ # The only cross-origin transfer approved for this distribution. Never
383
+ # accept aliases supplied by the destination service itself.
384
+ return source==target or (source,target)==('https://social.florentino.pro','https://socialcli.app')
385
+
386
+
387
+ @account_app.command('migrate')
388
+ def migrate(platform:Platform,brand_name:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root'),
389
+ no_browser:bool=typer.Option(False,'--no-browser'),timeout:float=typer.Option(600,'--timeout',min=1,max=600)):
390
+ """Move an existing legacy connection after its owner confirms in the browser."""
391
+ lock=None
392
+ try:
393
+ brand=cargar_brand(root,brand_name);lock=acquire_brand_lock(brand)
394
+ if recovery_path(brand,platform).exists():raise ValueError('Resolve pending connection recovery first.')
395
+ saved=metadata(brand);old=brand.leer_secreto(platform)
396
+ if not saved:raise ValueError('Run socialcli account login first.')
397
+ if old.get('auth_mode')!='broker' or old.get('protocol')=='saas-v1':
398
+ raise ValueError('This command requires an existing legacy broker connection.')
399
+ keychain.ensure_available(brand)
400
+ with http_client() as transport:
401
+ client=SaaSClient(saved['service_url'],transport,allow_http_local=saved.get('development_local') is True)
402
+ if not migration_origin_allowed(old['service_url'],client.origin,allow_http_local=saved.get('development_local') is True and old.get('development_local') is True):
403
+ raise ValueError('Legacy connection belongs to another service. Its credential cannot be transferred to this destination.')
404
+ poll_secret=secrets.token_urlsafe(32)
405
+ start=client.request('POST','/api/saas/v1/installations/'+opaque(saved['connection_id'])+'/migrations',
406
+ secret=keychain.get(brand,Slot.ACCOUNT,saved),legacy_secret=keychain.get(brand,platform,old),
407
+ body={'platform':platform.value,'brand':brand.nombre,'legacy_id':opaque(old['connection_id']),
408
+ 'poll_challenge':hashlib.sha256(poll_secret.encode()).hexdigest()})
409
+ migration_id=opaque(start.get('migration_id'));expected=client.origin+'/account/migrate/'+migration_id
410
+ if start.get('browser_url')!=expected:raise ValueError('Invalid SocialCli migration URL.')
411
+ handoff(expected,no_browser=no_browser,seconds=600)
412
+ result=wait(client,'/api/saas/v1/migrations/'+migration_id+'/poll',poll_secret,
413
+ min(timeout,start['expires_in']),start['poll_interval'],{'selected'})
414
+ if result.get('account',{}).get('id')!=old.get('account_id'):
415
+ raise ValueError('The migration account does not match the local connection.')
416
+ finalize_local(brand,platform,client,result)
417
+ typer.echo(platform.value+' migrated for '+visible(brand.nombre)+'. No OAuth or publication was repeated.')
418
+ except Exception as exc:
419
+ typer.echo(str(exc) if isinstance(exc,ValueError) else 'Could not confirm migration. Keep local credentials and check account recovery.',err=True);raise typer.Exit(1)
420
+ finally:
421
+ if lock is not None:os.close(lock)
422
+
423
+
424
+ @account_app.command('rotate')
425
+ def rotate(brand_name:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root'),
426
+ cancel:bool=typer.Option(False,'--cancel')):
427
+ """Renew this installation before expiry; rerun to recover an interruption."""
428
+ lock=None
429
+ try:
430
+ brand=cargar_brand(root,brand_name);lock=acquire_brand_lock(brand,allow_rotation=True)
431
+ from socialctl.connections.rotation_cli import rotate_local
432
+ typer.echo(rotate_local(brand,cancel=cancel))
433
+ except Exception as exc:
434
+ message=str(exc) if isinstance(exc,ValueError) else 'Credential rotation could not be confirmed.'
435
+ typer.echo(message+' Run socialcli account rotate with the same brand to resume; use --cancel only to cancel an uncommitted rotation.',err=True)
436
+ raise typer.Exit(1)
437
+ finally:
438
+ if lock is not None:os.close(lock)