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,379 @@
1
+ """Browser account connection with explicit binding and secure local capabilities."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import fcntl
6
+ import json
7
+ import os
8
+ import secrets
9
+ import sys
10
+ import math
11
+ import tempfile
12
+ import time
13
+ import webbrowser
14
+ from pathlib import Path
15
+
16
+ import httpx
17
+ import typer
18
+ import yaml
19
+
20
+ from socialctl.brands import cargar_brand
21
+ from socialctl.connections import keychain
22
+ from socialctl.connections.client import BrokerClient,DEFAULT_SERVICE,opaque,visible,broker_for
23
+ from socialctl.models import Platform
24
+ from socialctl.workspace import default_root
25
+
26
+
27
+ def interactive_terminal():
28
+ try:
29
+ return bool(sys.stdin.isatty())
30
+ except (AttributeError, ValueError, OSError):
31
+ return False
32
+
33
+
34
+ def http_client():
35
+ from socialctl.read_budget import LocalConfigurationError
36
+ try:
37
+ return httpx.Client(timeout=30,follow_redirects=False)
38
+ except (httpx.InvalidURL,ValueError,OSError,ImportError):
39
+ raise LocalConfigurationError('Check local proxy, CA and HTTP transport configuration; no request was sent.') from None
40
+
41
+
42
+ def atomic_bytes(path:Path,content:bytes,mode=0o600):
43
+ path.parent.mkdir(parents=True,exist_ok=True)
44
+ fd,name=tempfile.mkstemp(prefix='.'+path.name+'-',dir=path.parent)
45
+ try:
46
+ os.fchmod(fd,mode)
47
+ with os.fdopen(fd,'wb') as stream:
48
+ stream.write(content)
49
+ stream.flush()
50
+ os.fsync(stream.fileno())
51
+ os.replace(name,path)
52
+ finally:
53
+ Path(name).unlink(missing_ok=True)
54
+
55
+
56
+ def acquire_brand_lock(brand,*,allow_rotation=False,allow_recovery=False):
57
+ brand.dir_secretos.mkdir(exist_ok=True,mode=0o700)
58
+ brand.dir_secretos.chmod(0o700)
59
+ fd=os.open(brand.dir_secretos/'connection.lock',os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW,0o600)
60
+ try:
61
+ fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
62
+ except BaseException:
63
+ os.close(fd)
64
+ raise ValueError('another account connection is in progress for this brand') from None
65
+ if not allow_rotation and (brand.dir_secretos/'socialcli-rotation.json').exists():
66
+ os.close(fd)
67
+ raise ValueError('Credential rotation is pending. Run socialcli account rotate to resume.')
68
+ if not allow_recovery:
69
+ for platform in Platform:
70
+ if (brand.dir_secretos/('socialcli-recovery-'+platform.value+'.json')).exists():
71
+ os.close(fd)
72
+ raise ValueError('Connection recovery is pending. Run socialcli account recover '+platform.value+' before changing this brand.')
73
+ return fd
74
+
75
+
76
+ def validate_binding(brand,platform,account):
77
+ value=yaml.safe_load((brand.raiz/'accounts.yml').read_text()) or {}
78
+ current_page=(value.get('facebook') or {}).get('page_id')
79
+ requested=account.get('page_id') if platform is Platform.INSTAGRAM else account.get('id')
80
+ other=Platform.FACEBOOK if platform is Platform.INSTAGRAM else Platform.INSTAGRAM
81
+ if platform in (Platform.FACEBOOK,Platform.INSTAGRAM) and brand.leer_secreto(other) and str(current_page)!=str(requested):
82
+ raise ValueError('Facebook Page differs from an existing linked connection; disconnect that connection or use another brand')
83
+
84
+
85
+ def bind_account(brand,platform,account):
86
+ validate_binding(brand,platform,account)
87
+ path=brand.raiz/'accounts.yml'
88
+ text=path.read_text()
89
+ value=yaml.safe_load(text) or {}
90
+ if not isinstance(value,dict):
91
+ raise ValueError('brand account configuration is invalid')
92
+ field={'youtube':'channel_id','facebook':'page_id','instagram':'ig_user_id','tiktok':'open_id'}[platform.value]
93
+ updates={platform.value:{field:account['id']}}
94
+ if platform is Platform.INSTAGRAM:
95
+ updates['facebook']={'page_id':opaque(account.get('page_id'))}
96
+ if platform is Platform.TIKTOK:
97
+ updates['tiktok'].update(mode='inbox',auditada=False)
98
+ import re
99
+ # Rewrite only affected top-level sections; unrelated sections and their
100
+ # comments remain intact. Values from discovery are safely YAML-serialized.
101
+ for section,fields in updates.items():
102
+ current=value.get(section) or {}
103
+ if not isinstance(current,dict):
104
+ raise ValueError('brand account configuration is invalid')
105
+ current.update(fields)
106
+ pattern=re.compile(r'^'+re.escape(section)+r':[^\n]*\n(?:[ \t].*\n|\n|#[^\n]*\n)*',re.MULTILINE)
107
+ replacement=yaml.safe_dump({section:current},sort_keys=False)
108
+ match=pattern.search(text)
109
+ if match:
110
+ text=text[:match.start()]+replacement+text[match.end():]
111
+ else:
112
+ text+='\n'+replacement
113
+ atomic_bytes(path,text.encode(),path.stat().st_mode&0o777)
114
+
115
+
116
+ def fail(message):
117
+ typer.echo(message,err=True)
118
+ raise typer.Exit(1)
119
+
120
+
121
+ def register(app):
122
+ @app.command('connect')
123
+ def connect(platform:Platform,
124
+ brand_name:str=typer.Option(...,'--brand'),
125
+ root:Path=typer.Option(default_root(),'--root'),
126
+ service:str=typer.Option(DEFAULT_SERVICE,'--service',help='HTTPS connection service.'),
127
+ no_browser:bool=typer.Option(False,'--no-browser',help='AI agents: print the single-use login link without opening it; give it directly to the user.'),
128
+ account_id:str|None=typer.Option(None,'--account-id',help='Exact account ID to bind; required with --yes.'),
129
+ yes:bool=typer.Option(False,'--yes',help='Confirm only the explicitly authorized --account-id connection.'),
130
+ replace_independent:bool=typer.Option(False,'--replace-independent',help='Explicitly permit replacing independent credentials with --yes.'),
131
+ management:bool=typer.Option(False,'--management',help='YouTube: comment inbox and management (youtube.force-ssl); Facebook/Instagram: comments and webhook permissions.'),
132
+ analytics:bool=typer.Option(False,'--analytics',help='YouTube, Facebook or Instagram: request analytics read access.'),
133
+ timeout:float=typer.Option(600,'--timeout',min=1,max=600,help='Maximum browser connection wait in seconds.'),
134
+ dev_local:bool=typer.Option(False,'--dev-local',help='Development only: permit a loopback HTTP service.')):
135
+ """Connect your own social account in the browser without developer credentials."""
136
+ auth_id=None
137
+ connected=None
138
+ metadata=None
139
+ lock_fd=None
140
+ try:
141
+ brand=cargar_brand(root,brand_name)
142
+ lock_fd=acquire_brand_lock(brand)
143
+ if management and platform is Platform.TIKTOK:
144
+ raise ValueError('TikTok management permission is not available in this connection flow')
145
+ if analytics and platform is Platform.TIKTOK:
146
+ raise ValueError('TikTok analytics permission is not available in this connection flow')
147
+ from socialctl.connections.account_cli import metadata as account_metadata,connect_saas
148
+ if account_metadata(brand):
149
+ connect_saas(brand,platform,no_browser=no_browser,account_id=account_id,replace_independent=replace_independent,management=management,analytics=analytics,timeout=timeout)
150
+ return
151
+ previous=brand.leer_secreto(platform)
152
+ if previous.get('auth_mode')=='broker':
153
+ raise ValueError('this platform already has a connection; disconnect it before reconnecting')
154
+ if (yes and not account_id) or (not (yes and account_id) and not interactive_terminal()):
155
+ raise ValueError('Noninteractive connection requires --account-id ID and --yes after explicit user authorization')
156
+ if account_id is not None:
157
+ opaque(account_id)
158
+ if replace_independent and not yes:
159
+ raise ValueError('--replace-independent requires --account-id ID and --yes')
160
+ if previous and yes and not replace_independent:
161
+ raise ValueError('Replacing independent credentials requires explicit --replace-independent')
162
+ keychain.ensure_available(brand)
163
+ poll_secret=secrets.token_urlsafe(32)
164
+ with http_client() as transport:
165
+ broker=BrokerClient(service,transport,allow_http_local=dev_local)
166
+ start=broker.request('POST','/v1/authorizations',body={'platform':platform.value,
167
+ 'poll_challenge':hashlib.sha256(poll_secret.encode()).hexdigest(),
168
+ 'management':management,'analytics':analytics})
169
+ auth_id=opaque(start.get('authorization_id'))
170
+ expected_url=broker.origin+'/connect/'+auth_id
171
+ if start.get('browser_url')!=expected_url:
172
+ raise ValueError('invalid authorization browser URL')
173
+ if no_browser:
174
+ typer.echo(f'Give this single-use link directly to the user to connect {platform.value}: {expected_url}')
175
+ typer.echo('Do not open, fetch or preview this link. The user must open it and press Connect if shown. It expires in 10 minutes.')
176
+ typer.echo('Waiting for the user to authorize. Keep this command running. No content will be published.')
177
+ else:
178
+ typer.echo(f'Opening your browser to connect {platform.value}. No content will be published.')
179
+ typer.echo(f'If it does not open, visit: {expected_url}')
180
+ webbrowser.open(expected_url)
181
+ expiry=start.get('expires_in',600)
182
+ interval=start.get('poll_interval',2)
183
+ if (type(expiry) not in {int,float} or not math.isfinite(expiry) or not 0<expiry<=600
184
+ or type(interval) not in {int,float} or not math.isfinite(interval) or not 0<interval<=60):
185
+ raise ValueError('invalid authorization timing')
186
+ sys.stdout.flush()
187
+ deadline=time.monotonic()+expiry
188
+ while True:
189
+ result=broker.request('POST',f'/v1/authorizations/{auth_id}/poll',secret=poll_secret)
190
+ if result.get('status')=='ready':
191
+ break
192
+ if result.get('status') in {'denied','failed'}:
193
+ raise ValueError('authorization cancelled or incomplete; check permissions and retry')
194
+ if result.get('status') not in {'pending','exchanging'} or time.monotonic()>=deadline:
195
+ raise ValueError('authorization timed out; retry connecting your account')
196
+ time.sleep(min(interval,max(0,deadline-time.monotonic())))
197
+ accounts=result.get('accounts')
198
+ if not isinstance(accounts,list) or not 1<=len(accounts)<=500:
199
+ raise ValueError('no eligible authorized accounts were returned')
200
+ for index,account in enumerate(accounts,1):
201
+ opaque(account.get('id'))
202
+ typer.echo(f"{index}. {visible(account.get('name',''))} ({account['id']})")
203
+ if account_id is not None:
204
+ matches=[i for i,a in enumerate(accounts,1) if a['id']==account_id]
205
+ if len(matches)!=1:
206
+ raise ValueError('requested account was not uniquely returned by the provider; no connection installed')
207
+ selection=matches[0]
208
+ else:
209
+ selection=1 if len(accounts)==1 else typer.prompt('Choose an account number',type=int)
210
+ if not 1<=selection<=len(accounts):
211
+ raise ValueError('invalid account selection')
212
+ account=accounts[selection-1]
213
+ validate_binding(brand,platform,account)
214
+ if previous:
215
+ typer.echo('Confirming will replace the existing independent-app credentials for this platform.')
216
+ if platform is Platform.INSTAGRAM:
217
+ typer.echo(f"Linked Facebook Page: {opaque(account.get('page_id'))}")
218
+ if platform is Platform.TIKTOK:
219
+ typer.echo('This connection uses inbox mode; finish posting in TikTok.')
220
+ if not yes and not typer.confirm(f"Connect {visible(account.get('name',''))} ({account['id']}) to {visible(brand.nombre)}?",default=False):
221
+ broker.request('DELETE',f'/v1/authorizations/{auth_id}',secret=poll_secret,allow_missing=True)
222
+ auth_id=None
223
+ typer.echo('Connection cancelled. Existing credentials were preserved.')
224
+ return
225
+ connected=broker.request('POST',f'/v1/authorizations/{auth_id}/complete',secret=poll_secret,body={'account_id':account['id']})
226
+ auth_id=None
227
+ if connected.get('platform')!=platform.value or connected.get('account')!=account:
228
+ raise ValueError('completed account differs from the account you confirmed')
229
+ opaque(connected.get('connection_id'))
230
+ capability=connected.get('connection_secret')
231
+ if not isinstance(capability,str) or not 16<=len(capability)<=512:
232
+ raise ValueError('invalid connection credential')
233
+ metadata={'version':1,'auth_mode':'broker','service_url':broker.origin,
234
+ 'connection_id':connected['connection_id'],'account_id':account['id'],
235
+ 'account':account,'granted_scopes':connected.get('granted_scopes',[])}
236
+ if dev_local:
237
+ metadata['development_local']=True
238
+ config_path=brand.raiz/'accounts.yml'
239
+ secret_path=brand.dir_secretos/f'{platform.value}.json'
240
+ original_config=config_path.read_bytes()
241
+ original_secret=secret_path.read_bytes() if secret_path.exists() else None
242
+ try:
243
+ keychain.save(brand,platform,metadata,capability)
244
+ bind_account(brand,platform,account)
245
+ brand.dir_secretos.mkdir(exist_ok=True,mode=0o700)
246
+ brand.dir_secretos.chmod(0o700)
247
+ atomic_bytes(secret_path,json.dumps(metadata,indent=2).encode())
248
+ # Activate only after both keyring and local binding are durable.
249
+ # The returned provider token is discarded, never persisted.
250
+ broker.request('POST',f"/v1/connections/{metadata['connection_id']}/token",secret=capability)
251
+ except BaseException:
252
+ try:
253
+ atomic_bytes(config_path,original_config,config_path.stat().st_mode&0o777)
254
+ if original_secret is None:
255
+ secret_path.unlink(missing_ok=True)
256
+ else:
257
+ atomic_bytes(secret_path,original_secret)
258
+ except BaseException:
259
+ raise ValueError('Credential restoration could not be completed; restore the brand from your private backup before retrying') from None
260
+ raise
261
+ typer.echo(f'{platform.value} connected for {visible(brand.nombre)}. Credentials are held in your OS keyring.')
262
+ connected=None # Successfully installed: do not cancel in finally.
263
+ except (KeyboardInterrupt,typer.Abort):
264
+ fail('Connection cancelled.')
265
+ except ValueError as exc:
266
+ fail(str(exc))
267
+ except Exception:
268
+ fail('Could not connect safely; existing credentials were preserved.')
269
+ finally:
270
+ if auth_id or connected:
271
+ try:
272
+ with http_client() as transport:
273
+ cleanup=BrokerClient(service,transport,allow_http_local=dev_local)
274
+ if connected and connected.get('connection_id') and connected.get('connection_secret'):
275
+ cleanup.request('DELETE',f"/v1/connections/{opaque(connected['connection_id'])}",secret=connected['connection_secret'],allow_missing=True)
276
+ elif auth_id:
277
+ cleanup.request('DELETE',f'/v1/authorizations/{auth_id}',secret=poll_secret,allow_missing=True)
278
+ if metadata:
279
+ keychain.delete(brand,platform,metadata)
280
+ except Exception:
281
+ typer.echo('Cleanup could not be confirmed. Contact the service operator before retrying.',err=True)
282
+ if lock_fd is not None:
283
+ os.close(lock_fd)
284
+
285
+ @app.command('connections')
286
+ def connections(brand_name:str=typer.Option(...,'--brand'),
287
+ root:Path=typer.Option(default_root(),'--root'),
288
+ json_output:bool=typer.Option(False,'--json')):
289
+ """Read connection status without renewing provider tokens or publishing."""
290
+ from socialctl.agent_errors import error_document, emit_error
291
+ from socialctl.connections.saas_client import ServiceRejected
292
+ try:
293
+ brand=cargar_brand(root,brand_name)
294
+ rows=[]
295
+ errors=[]
296
+ with http_client() as transport:
297
+ for platform in Platform:
298
+ try:
299
+ metadata=brand.leer_secreto(platform)
300
+ if metadata.get('auth_mode')!='broker':
301
+ continue
302
+ broker=broker_for(metadata,transport)
303
+ secret=keychain.get(brand,platform,metadata)
304
+ status=broker.request('GET',f"/v1/connections/{opaque(metadata['connection_id'])}",secret=secret)
305
+ if status.get('platform')!=platform.value or status.get('account',{}).get('id')!=metadata['account_id']:
306
+ raise ValueError('connection account mismatch')
307
+ if platform is Platform.YOUTUBE and status.get('data_cleanup_required'):
308
+ from socialctl.youtube_data import request_youtube_purge
309
+ status['local_data_cleanup']=request_youtube_purge(brand.raiz)
310
+ rows.append(status)
311
+ except Exception as exc:
312
+ if platform is Platform.YOUTUBE and getattr(exc,'code',None) in {
313
+ 'provider_authorization_expired','provider_permissions_changed',
314
+ 'connection_inactive','connection_unavailable','installation_revoked','installation_expired'}:
315
+ from socialctl.youtube_data import request_youtube_purge
316
+ request_youtube_purge(brand.raiz)
317
+ detail={'platform':platform.value, **error_document(exc,read_only=True)}
318
+ if isinstance(exc,ServiceRejected): detail['http_status']=exc.status
319
+ errors.append(detail)
320
+ state='partial' if errors and rows else 'error' if errors else 'ok'
321
+ result={'version':1,'brand':brand.nombre,'status':state,'connections':rows,'errors':errors}
322
+ if json_output:
323
+ typer.echo(json.dumps(result,indent=2))
324
+ elif not rows and not errors:
325
+ typer.echo('No shared connections. Independent-app credentials use socialcli auth status.')
326
+ else:
327
+ for row in rows:
328
+ renewal_label={None:'connected','ready':'connected',
329
+ 'required':'renewal required by an explicitly authorized operation',
330
+ 'pending':'renewal pending; try later',
331
+ 'retryable':'provider unreachable; keep connection and retry later',
332
+ 'uncertain':'renewal uncertain; review your SocialCli account',
333
+ 'configuration_error':'service configuration needs attention',
334
+ 'reconnect_required':'reconnect required with your explicit approval'}
335
+ label=('reconnect required with your explicit approval' if row.get('needs_reconnect')
336
+ else renewal_label.get(row.get('renewal_status'),'review your SocialCli account'))
337
+ typer.echo(f"{row['platform']}: {visible(row['account']['name'])} ({row['account']['id']}) — {label}")
338
+ if not json_output:
339
+ for error in errors:
340
+ typer.echo(f"{error['platform']}: {error['code']} — {error['message']}",err=True)
341
+ except Exception as exc:
342
+ if json_output: emit_error(exc,read_only=True)
343
+ fail(str(exc) if isinstance(exc,ValueError) else 'Could not read connection status safely.')
344
+ if errors: raise typer.Exit(3 if rows else 1)
345
+
346
+ @app.command('disconnect')
347
+ def disconnect(platform:Platform,brand_name:str=typer.Option(...,'--brand'),root:Path=typer.Option(default_root(),'--root')):
348
+ """Delete a shared connection and its local capability after confirmation."""
349
+ lock_fd=None
350
+ try:
351
+ brand=cargar_brand(root,brand_name)
352
+ lock_fd=acquire_brand_lock(brand)
353
+ metadata=brand.leer_secreto(platform)
354
+ if metadata.get('auth_mode')!='broker':
355
+ raise ValueError('no shared connection exists for this platform')
356
+ if not typer.confirm(f'Disconnect {platform.value} from {visible(brand.nombre)}?',default=False):
357
+ return
358
+ secret=keychain.get(brand,platform,metadata)
359
+ with http_client() as transport:
360
+ broker=broker_for(metadata,transport)
361
+ disconnected=broker.request('DELETE',f"/v1/connections/{opaque(metadata['connection_id'])}",secret=secret,allow_missing=True)
362
+ keychain.delete(brand,platform,metadata)
363
+ (brand.dir_secretos/f'{platform.value}.json').unlink(missing_ok=True)
364
+ if platform is Platform.YOUTUBE:
365
+ from socialctl.youtube_data import request_youtube_purge
366
+ cleanup=request_youtube_purge(brand.raiz)
367
+ typer.echo('Disconnected. Google revocation: '+disconnected.get('provider_revocation_status','unconfirmed')+'.')
368
+ if not cleanup['complete']:
369
+ typer.echo('Local API data cleanup is pending; run data-cleanup for this brand and resolve its listed paths.',err=True)
370
+ else:
371
+ typer.echo('Disconnected. To also revoke provider authorization, remove SocialCli in the provider account settings.')
372
+ except ValueError as exc:
373
+ fail(str(exc))
374
+ except Exception:
375
+ fail('Could not confirm disconnection; retry after checking service and keyring availability.')
376
+
377
+ finally:
378
+ if lock_fd is not None:
379
+ os.close(lock_fd)
@@ -0,0 +1,126 @@
1
+ """Bounded HTTPS connection-service client; secrets never appear in diagnostics."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import math
6
+ import re
7
+ from urllib.parse import urlsplit
8
+
9
+ from socialctl.connections import keychain
10
+
11
+ DEFAULT_SERVICE = 'https://social.florentino.pro'
12
+
13
+
14
+ def service_origin(value: str, *, allow_http_local=False) -> str:
15
+ try:
16
+ p=urlsplit(value)
17
+ local=allow_http_local and p.hostname in {'localhost','127.0.0.1','::1'}
18
+ if (not p.hostname or p.scheme not in ({'http','https'} if local else {'https'})
19
+ or p.username or p.password or p.query or p.fragment or p.path not in {'','/'}
20
+ or p.port is not None and not 1<=p.port<=65535):
21
+ raise ValueError()
22
+ except Exception:
23
+ raise ValueError('connection service must use a fixed HTTPS origin') from None
24
+ return value.rstrip('/')
25
+
26
+
27
+ def opaque(value):
28
+ if not isinstance(value,str) or not re.fullmatch(r'[A-Za-z0-9_-]{1,256}',value):
29
+ raise ValueError('invalid connection response')
30
+ return value
31
+
32
+
33
+ def visible(value):
34
+ return ''.join(c if c.isprintable() else ' ' for c in str(value))[:256]
35
+
36
+
37
+ def account_id(brand,platform):
38
+ key={'youtube':'channel_id','facebook':'page_id','instagram':'ig_user_id','tiktok':'open_id'}[platform.value]
39
+ return (brand.cuentas.get(platform.value) or {}).get(key)
40
+
41
+
42
+ class BrokerClient:
43
+ def __init__(self,service,client,*,allow_http_local=False):
44
+ self.origin=service_origin(service,allow_http_local=allow_http_local)
45
+ self.client=client
46
+
47
+ def request(self,method,path,*,secret=None,body=None,allow_missing=False):
48
+ if not re.fullmatch(r'/v1/(?:authorizations|connections)(?:/[A-Za-z0-9_-]{1,256}(?:/(?:poll|complete|token))?)?(?:\?refresh=false)?',path):
49
+ raise ValueError('invalid connection endpoint')
50
+ headers={'Authorization':f'Bearer {secret}'} if secret else {}
51
+ try:
52
+ with self.client.stream(method,self.origin+path,headers=headers,json=body,
53
+ timeout=30,follow_redirects=False) as response:
54
+ if response.status_code==404 and allow_missing:
55
+ return {'version':1,'status':'disconnected'}
56
+ if response.status_code in {404,409}:
57
+ raise ValueError('connection expired or unavailable; reconnect your account')
58
+ if response.status_code==429:
59
+ raise ValueError('too many connection attempts; try again later')
60
+ if response.status_code==503:
61
+ raise ValueError('connection service or platform is not configured yet')
62
+ if not response.is_success:
63
+ raise ValueError('connection request was rejected')
64
+ raw=bytearray()
65
+ for chunk in response.iter_bytes():
66
+ raw.extend(chunk)
67
+ if len(raw)>65536:
68
+ raise ValueError('invalid connection response')
69
+ result=json.loads(raw)
70
+ if not isinstance(result,dict) or result.get('version')!=1:
71
+ raise ValueError('invalid connection response')
72
+ return result
73
+ except ValueError:
74
+ raise
75
+ except Exception:
76
+ raise ValueError('could not reach the connection service securely') from None
77
+
78
+
79
+ def broker_access_token(brand,platform,client,*,refresh=True,required_scopes=frozenset()):
80
+ if (brand.dir_secretos/'socialcli-rotation.json').exists():
81
+ raise ValueError('Credential rotation is pending. Run socialcli account rotate to resume.')
82
+ metadata=brand.leer_secreto(platform)
83
+ if metadata.get('auth_mode')!='broker' or metadata.get('version')!=1:
84
+ raise ValueError('invalid connection metadata')
85
+ broker=broker_for(metadata,client)
86
+ connection_id=opaque(metadata.get('connection_id'))
87
+ expected=opaque(metadata.get('account_id'))
88
+ if account_id(brand,platform)!=expected:
89
+ raise ValueError('brand account differs from its connection; reconnect explicitly')
90
+ secret=keychain.get(brand,platform,metadata)
91
+ if not isinstance(secret,str) or not 16<=len(secret)<=512:
92
+ raise ValueError('connection credential unavailable in the selected secure credential store')
93
+ try:
94
+ result=broker.request('POST',f'/v1/connections/{connection_id}/token'+('' if refresh else '?refresh=false'),secret=secret)
95
+ except ValueError as exc:
96
+ if platform.value=='youtube' and getattr(exc,'code',None) in {
97
+ 'provider_authorization_expired','provider_permissions_changed',
98
+ 'connection_inactive','connection_unavailable','installation_revoked','installation_expired'}:
99
+ from socialctl.youtube_data import request_youtube_purge
100
+ request_youtube_purge(brand.raiz)
101
+ raise
102
+ if result.get('platform')!=platform.value or result.get('account',{}).get('id')!=expected:
103
+ raise ValueError('connection account mismatch; reconnect explicitly')
104
+ if required_scopes:
105
+ granted=result.get('granted_scopes')
106
+ if (not isinstance(granted,list) or any(not isinstance(scope,str) for scope in granted)
107
+ or not set(required_scopes)<=set(granted)):
108
+ raise ValueError('Required granted provider permissions are missing or unknown')
109
+ expiry=result.get('expires_at')
110
+ if type(expiry) not in {int,float} or not math.isfinite(expiry) or expiry<=0:
111
+ raise ValueError('invalid connection expiration')
112
+ token=result.get('access_token')
113
+ if not isinstance(token,str) or not 1<=len(token)<=16384 or any(ord(c)<33 or ord(c)==127 for c in token):
114
+ raise ValueError('invalid connection credentials')
115
+ return token
116
+
117
+
118
+ def broker_for(metadata,client):
119
+ protocol=metadata.get('protocol')
120
+ if protocol not in {None,'saas-v1'}:
121
+ raise ValueError('Unsupported connection protocol. Update SocialCli.')
122
+ if protocol=='saas-v1':
123
+ from socialctl.connections.saas_client import SaaSClient
124
+ factory=SaaSClient
125
+ else:factory=BrokerClient
126
+ return factory(metadata.get('service_url',''),client,allow_http_local=metadata.get('development_local') is True)