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.
- socialcli-0.3.0.dist-info/METADATA +168 -0
- socialcli-0.3.0.dist-info/RECORD +224 -0
- socialcli-0.3.0.dist-info/WHEEL +4 -0
- socialcli-0.3.0.dist-info/entry_points.txt +3 -0
- socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
- socialctl/__init__.py +0 -0
- socialctl/__main__.py +6 -0
- socialctl/adapters/__init__.py +6 -0
- socialctl/adapters/base.py +68 -0
- socialctl/adapters/errores.py +56 -0
- socialctl/adapters/facebook.py +180 -0
- socialctl/adapters/instagram.py +442 -0
- socialctl/adapters/tiktok.py +535 -0
- socialctl/adapters/youtube.py +331 -0
- socialctl/agent_errors.py +176 -0
- socialctl/agent_guide.py +23 -0
- socialctl/approval_cli.py +27 -0
- socialctl/auth.py +139 -0
- socialctl/authflow.py +344 -0
- socialctl/brands.py +194 -0
- socialctl/capabilities.py +57 -0
- socialctl/capabilities.yml +5945 -0
- socialctl/cli.py +1766 -0
- socialctl/connection_service/__init__.py +0 -0
- socialctl/connection_service/__main__.py +33 -0
- socialctl/connection_service/app.py +496 -0
- socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
- socialctl/connection_service/assets/connection.css +75 -0
- socialctl/connection_service/assets/facebook.webp +0 -0
- socialctl/connection_service/assets/instagram.svg +194 -0
- socialctl/connection_service/assets/socialcli-logo.png +0 -0
- socialctl/connection_service/assets/tiktok.png +0 -0
- socialctl/connection_service/assets/youtube.svg +1 -0
- socialctl/connection_service/landing.py +146 -0
- socialctl/connection_service/legacy.py +48 -0
- socialctl/connection_service/peer.py +13 -0
- socialctl/connection_service/providers.py +324 -0
- socialctl/connection_service/settings.py +76 -0
- socialctl/connection_service/store.py +124 -0
- socialctl/connections/__init__.py +0 -0
- socialctl/connections/account_cli.py +438 -0
- socialctl/connections/cli.py +379 -0
- socialctl/connections/client.py +126 -0
- socialctl/connections/credential_cli.py +224 -0
- socialctl/connections/credential_store.py +49 -0
- socialctl/connections/file_store.py +193 -0
- socialctl/connections/keychain.py +78 -0
- socialctl/connections/meta_user.py +81 -0
- socialctl/connections/rotation_cli.py +116 -0
- socialctl/connections/saas_client.py +91 -0
- socialctl/connections/temporary_media.py +62 -0
- socialctl/delivery_options.py +70 -0
- socialctl/engagement.py +200 -0
- socialctl/engagement_cli.py +50 -0
- socialctl/executor.py +135 -0
- socialctl/formatter.py +291 -0
- socialctl/hosted_media.py +152 -0
- socialctl/identity.py +200 -0
- socialctl/inbox.py +298 -0
- socialctl/inbox_cli.py +46 -0
- socialctl/inventory.py +155 -0
- socialctl/inventory_cli.py +171 -0
- socialctl/inventory_sources.py +101 -0
- socialctl/management/__init__.py +1 -0
- socialctl/management/batch_cli.py +115 -0
- socialctl/management/batches.py +325 -0
- socialctl/management/changes.py +485 -0
- socialctl/management/cli.py +227 -0
- socialctl/management/comments_cli.py +352 -0
- socialctl/management/community_batch_cli.py +63 -0
- socialctl/management/community_batches.py +294 -0
- socialctl/management/community_changes.py +370 -0
- socialctl/management/community_cli.py +142 -0
- socialctl/management/community_schema.py +119 -0
- socialctl/management/facebook_groups.py +1118 -0
- socialctl/management/groups_cli.py +274 -0
- socialctl/management/inbox_readers.py +87 -0
- socialctl/management/meta_changes.py +197 -0
- socialctl/management/meta_cli.py +342 -0
- socialctl/management/meta_client.py +631 -0
- socialctl/management/meta_comment_inbox.py +565 -0
- socialctl/management/meta_comments.py +587 -0
- socialctl/management/meta_errors.py +59 -0
- socialctl/management/meta_pagination.py +52 -0
- socialctl/management/meta_schema.py +128 -0
- socialctl/management/meta_webhooks.py +147 -0
- socialctl/management/metadata_parts.py +144 -0
- socialctl/management/owned_assets.py +85 -0
- socialctl/management/owned_changes.py +470 -0
- socialctl/management/owned_cli.py +128 -0
- socialctl/management/owned_reorder.py +62 -0
- socialctl/management/owned_schema.py +368 -0
- socialctl/management/reply_context.py +24 -0
- socialctl/management/reply_evidence.py +80 -0
- socialctl/management/resource_changes.py +407 -0
- socialctl/management/resource_cli.py +136 -0
- socialctl/management/snippet_readback.py +26 -0
- socialctl/management/stories.py +713 -0
- socialctl/management/stories_cli.py +172 -0
- socialctl/management/youtube.py +323 -0
- socialctl/management/youtube_community.py +326 -0
- socialctl/management/youtube_metadata.py +122 -0
- socialctl/management/youtube_owned.py +259 -0
- socialctl/management/youtube_resources.py +305 -0
- socialctl/media.py +269 -0
- socialctl/media_cli.py +183 -0
- socialctl/media_ingress.py +211 -0
- socialctl/media_preflight.py +114 -0
- socialctl/media_registry.py +301 -0
- socialctl/media_requirements.py +52 -0
- socialctl/metricas/__init__.py +6 -0
- socialctl/metricas/almacen.py +133 -0
- socialctl/metricas/analytics_changes.py +295 -0
- socialctl/metricas/analytics_cli.py +191 -0
- socialctl/metricas/analytics_client.py +304 -0
- socialctl/metricas/analytics_ingest.py +260 -0
- socialctl/metricas/analytics_schema.py +174 -0
- socialctl/metricas/base.py +147 -0
- socialctl/metricas/facebook.py +418 -0
- socialctl/metricas/insights.py +227 -0
- socialctl/metricas/instagram.py +133 -0
- socialctl/metricas/modelos.py +87 -0
- socialctl/metricas/piezas.py +134 -0
- socialctl/metricas/reach.py +94 -0
- socialctl/metricas/reporting_client.py +112 -0
- socialctl/metricas/resumen.py +251 -0
- socialctl/metricas/slugs.py +89 -0
- socialctl/metricas/tiktok.py +185 -0
- socialctl/metricas/youtube.py +403 -0
- socialctl/migration_cli.py +60 -0
- socialctl/migration_files.py +68 -0
- socialctl/models.py +150 -0
- socialctl/native_schedule/__init__.py +13 -0
- socialctl/native_schedule/api_delivery.py +15 -0
- socialctl/native_schedule/api_reconcile.py +40 -0
- socialctl/native_schedule/approval.py +160 -0
- socialctl/native_schedule/cadence.py +73 -0
- socialctl/native_schedule/cli.py +510 -0
- socialctl/native_schedule/dispatcher.py +120 -0
- socialctl/native_schedule/facebook.py +112 -0
- socialctl/native_schedule/facebook_reels.py +140 -0
- socialctl/native_schedule/first_comment.py +181 -0
- socialctl/native_schedule/handoff.py +193 -0
- socialctl/native_schedule/instagram_delivery.py +224 -0
- socialctl/native_schedule/instagram_runtime.py +66 -0
- socialctl/native_schedule/inventory.py +70 -0
- socialctl/native_schedule/migration.py +310 -0
- socialctl/native_schedule/models.py +103 -0
- socialctl/native_schedule/reconcile.py +83 -0
- socialctl/native_schedule/remote_data.py +177 -0
- socialctl/native_schedule/report.py +151 -0
- socialctl/native_schedule/store.py +560 -0
- socialctl/native_schedule/verification.py +32 -0
- socialctl/native_schedule/youtube.py +339 -0
- socialctl/operation_output.py +87 -0
- socialctl/plantillas/accounts.yml +33 -0
- socialctl/plantillas/brand.md +95 -0
- socialctl/plantillas/estrategia.md +64 -0
- socialctl/postfile.py +240 -0
- socialctl/preflight.py +73 -0
- socialctl/publication_policy.py +34 -0
- socialctl/publication_status.py +75 -0
- socialctl/publication_steps.py +398 -0
- socialctl/publish_output.py +96 -0
- socialctl/publisher.py +445 -0
- socialctl/queue_migration.py +302 -0
- socialctl/read_budget.py +224 -0
- socialctl/read_reports.py +91 -0
- socialctl/rutas.py +103 -0
- socialctl/saas/__init__.py +1 -0
- socialctl/saas/access.py +75 -0
- socialctl/saas/auth.py +213 -0
- socialctl/saas/backup.py +124 -0
- socialctl/saas/billing.py +327 -0
- socialctl/saas/billing_enrollment.py +1237 -0
- socialctl/saas/billing_enrollment_schema.py +519 -0
- socialctl/saas/billing_inventory.py +775 -0
- socialctl/saas/billing_reconcile.py +127 -0
- socialctl/saas/billing_routes.py +27 -0
- socialctl/saas/budget.py +66 -0
- socialctl/saas/connections.py +374 -0
- socialctl/saas/consent.py +52 -0
- socialctl/saas/lifecycle.py +341 -0
- socialctl/saas/mail.py +89 -0
- socialctl/saas/maintenance.py +68 -0
- socialctl/saas/meta_user.py +298 -0
- socialctl/saas/meta_webhooks.py +358 -0
- socialctl/saas/migration.py +107 -0
- socialctl/saas/models.py +8 -0
- socialctl/saas/operations.py +102 -0
- socialctl/saas/pages.py +126 -0
- socialctl/saas/pairing.py +158 -0
- socialctl/saas/permissions.py +57 -0
- socialctl/saas/reminders.py +128 -0
- socialctl/saas/renewal.py +74 -0
- socialctl/saas/restore_guard.py +229 -0
- socialctl/saas/revocation.py +97 -0
- socialctl/saas/rotation.py +114 -0
- socialctl/saas/routes.py +221 -0
- socialctl/saas/settings.py +34 -0
- socialctl/saas/store.py +106 -0
- socialctl/saas/temporary_media.py +245 -0
- socialctl/saas/webhooks.py +76 -0
- socialctl/schedule_remote.py +262 -0
- socialctl/schedule_sqlite.py +44 -0
- socialctl/scheduler.py +581 -0
- socialctl/scheduler_launchd.py +319 -0
- socialctl/scheduler_systemd.py +167 -0
- socialctl/source_links.py +119 -0
- socialctl/ui/__init__.py +1 -0
- socialctl/ui/assets/agent-manual.md +850 -0
- socialctl/ui/assets/agents.md +27 -0
- socialctl/ui/assets/components.css +20 -0
- socialctl/ui/assets/connection-layout.css +53 -0
- socialctl/ui/assets/otp.template.html +10 -0
- socialctl/ui/assets/tokens.css +1 -0
- socialctl/ui/assets/trial.template.html +11 -0
- socialctl/ui/assets/web-layout.css +38 -0
- socialctl/ui/email/otp.html +10 -0
- socialctl/ui/email/trial.html +11 -0
- socialctl/upload_consent.py +13 -0
- socialctl/workspace.py +8 -0
- socialctl/youtube_data.py +471 -0
- socialctl/youtube_data_service.py +225 -0
socialctl/saas/pages.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Escaped server-rendered account views using the approved SocialCli shell."""
|
|
2
|
+
from html import escape
|
|
3
|
+
from socialctl.saas import consent
|
|
4
|
+
from socialctl.connection_service.landing import _page, connection_symbols, PROVIDERS
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def page(title,content,*,platform=None):
|
|
8
|
+
if platform in PROVIDERS:
|
|
9
|
+
content = connection_symbols(platform) + content
|
|
10
|
+
return _page(title,content,platform=platform).replace('ACCOUNT CONNECTION','YOUR SOCIALCLI ACCOUNT').replace(
|
|
11
|
+
'<main id="main-content">','<a class="skip-link" href="#main-content">Skip to content</a><main id="main-content">')
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def hidden(name,value):
|
|
15
|
+
return f'<input type="hidden" name="{escape(name,quote=True)}" value="{escape(value,quote=True)}">'
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def notice(message, *, field=None):
|
|
19
|
+
identifier = f' id="{escape(field, quote=True)}-error"' if field else ''
|
|
20
|
+
return f'<p{identifier} class="status-notice" role="alert">{escape(message)}</p>' if message else ''
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def login(csrf,next_path,message='',*,input_error=False):
|
|
24
|
+
invalid = ' aria-invalid="true" aria-describedby="email-error"' if input_error and message else ''
|
|
25
|
+
return page('Sign in',f'''<p class="eyebrow">WELCOME TO SOCIALCLI</p>
|
|
26
|
+
<h1 id="page-title">Your social accounts.<br>Your AI assistants.</h1>
|
|
27
|
+
<p class="description">Sign in with a code sent to your email. No password needed.</p>{notice(message, field="email" if invalid else None)}
|
|
28
|
+
<form method="post" action="/account/login" class="form-stack">{hidden('csrf',csrf)}{hidden('next',next_path)}
|
|
29
|
+
<div><label for="email">Email address</label><input id="email" name="email" type="email" autocomplete="email" maxlength="254" required{invalid}></div>
|
|
30
|
+
{privacy_choice_html(required=False)}
|
|
31
|
+
<button class="primary-button" type="submit">Send sign-in code</button></form>
|
|
32
|
+
<p class="expiry-note">14 days free from your first connection. Then USD 10/month.</p>''')
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def verify(csrf,attempt,email,message='',*,input_error=False):
|
|
36
|
+
invalid = ' aria-invalid="true" aria-describedby="code-error"' if input_error and message else ''
|
|
37
|
+
return page('Check your email',f'''<p class="eyebrow">CHECK YOUR EMAIL</p><h1 id="page-title">Enter your sign-in code</h1>
|
|
38
|
+
<p class="description">We sent a code to {escape(email)}. It expires in 10 minutes.</p>{notice(message, field="code" if invalid else None)}
|
|
39
|
+
<form method="post" action="/account/verify" class="form-stack">{hidden('csrf',csrf)}{hidden('attempt',attempt)}
|
|
40
|
+
<div><label for="code">One-time code</label><input id="code" name="code" type="text" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{{6,8}}" minlength="6" maxlength="8" required{invalid}></div>
|
|
41
|
+
<button class="primary-button" type="submit">Sign in</button></form>
|
|
42
|
+
<a class="text-link" href="/account/login">Send a new code</a>''')
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def account(user,csrf,details=''):
|
|
46
|
+
return page('Your account',f'''<p class="eyebrow">YOUR ACCOUNT</p><h1 id="page-title">Welcome to SocialCli</h1>
|
|
47
|
+
<p class="description">{escape(user.email)}</p>{details}
|
|
48
|
+
<p class="quiet-notice">Connecting an account never approves publishing. You stay in control.</p>
|
|
49
|
+
<form method="post" action="/account/logout" class="form-stack">{hidden('csrf',csrf)}<button class="secondary-button" type="submit">Sign out</button></form>''')
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def error(message):
|
|
53
|
+
return page('Please try again',f'<h1 id="page-title">Let\'s try that again</h1>{notice(message)}<a class="secondary-button" href="/account/login">Back to sign in</a>')
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def utc_date(value):
|
|
57
|
+
from datetime import datetime, timezone
|
|
58
|
+
return datetime.fromtimestamp(value,timezone.utc).strftime('%b %d, %Y at %H:%M UTC')
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def subscription(decision,entitlement,billing,csrf,*,enabled,processing=False):
|
|
62
|
+
reason=decision.reason
|
|
63
|
+
action='';message='';heading='Your plan'
|
|
64
|
+
if reason=='trial_not_started':
|
|
65
|
+
message='Your 14 free days start when you connect your first social account. No card required.'
|
|
66
|
+
elif reason=='trial':
|
|
67
|
+
message='Your free trial ends '+utc_date(entitlement['trial_end'])+'.'
|
|
68
|
+
ongoing=entitlement['subscription_status'] not in ('','canceled','incomplete_expired')
|
|
69
|
+
if ongoing:
|
|
70
|
+
message+=' Your subscription is arranged. The first USD 10 monthly payment is due when your trial ends.'
|
|
71
|
+
if billing and billing['cancel_at_period_end']:
|
|
72
|
+
message+=' Cancellation is scheduled; check Manage billing for the final date.'
|
|
73
|
+
elif enabled:
|
|
74
|
+
message+=' Subscribe now to keep access. Your first USD 10 payment is due at the end of your trial, then monthly. Cancel anytime.'
|
|
75
|
+
action=f'<form method="post" action="/account/billing/checkout" class="form-stack">{hidden("csrf",csrf)}<button type="submit" class="primary-button">Subscribe — USD 10/month</button></form>'
|
|
76
|
+
elif reason=='paid':
|
|
77
|
+
heading='Subscription active'
|
|
78
|
+
ending=billing and billing['cancel_at_period_end'] or entitlement['subscription_status']=='canceled'
|
|
79
|
+
message=('Will not renew. Access ends ' if ending else 'Your paid access ends ')+utc_date(decision.access_until)+'.'
|
|
80
|
+
if not ending:message+=' Renews monthly at USD 10.'
|
|
81
|
+
elif reason in {'suspended','account_unavailable'}:
|
|
82
|
+
heading='Account unavailable';message='Contact support for help with access.'
|
|
83
|
+
if enabled and billing and billing['customer_id']:message+=' You can still manage your billing.'
|
|
84
|
+
else:
|
|
85
|
+
heading='Your free trial has ended' if reason=='trial_expired' else 'Subscription required'
|
|
86
|
+
message='Subscribe to continue using your connected accounts. USD 10 is charged when you confirm, then monthly. Cancel anytime.'
|
|
87
|
+
ongoing=entitlement and entitlement['subscription_status'] not in ('','canceled','incomplete_expired')
|
|
88
|
+
if ongoing:
|
|
89
|
+
heading='Subscription needs attention'
|
|
90
|
+
message='Your subscription needs attention. Open Manage billing to check your payment and restore access.'
|
|
91
|
+
elif enabled:
|
|
92
|
+
action=f'<form method="post" action="/account/billing/checkout" class="form-stack">{hidden("csrf",csrf)}<button type="submit" class="primary-button">Subscribe — USD 10/month</button></form>'
|
|
93
|
+
checking=processing and enabled and reason in {'trial','trial_expired','subscription_required'}
|
|
94
|
+
if checking:
|
|
95
|
+
heading='Checking your payment'
|
|
96
|
+
message='Payment confirmation can take a few minutes. Check your account status before trying to subscribe again. If access is still unavailable, check Manage billing when available or contact support.'
|
|
97
|
+
action='<a class="secondary-button" href="/account/">Check account status</a>'
|
|
98
|
+
if enabled and billing and billing['customer_id']:
|
|
99
|
+
action+=f'<form method="post" action="/account/billing/portal" class="form-stack">{hidden("csrf",csrf)}<button type="submit" class="secondary-button">Manage billing</button></form>'
|
|
100
|
+
if not enabled:message+=' Subscription checkout is not available yet.'
|
|
101
|
+
status=' role="status"' if checking else ''
|
|
102
|
+
return f'<section aria-label="Subscription"><h2>{escape(heading)}</h2><p class="description">USD 10/month · One brand · Four social platforms</p><p class="status-notice"{status}>{escape(message)}</p>{action}</section>'
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def privacy_choice_html(*, required=True):
|
|
106
|
+
needed=' required' if required else ''
|
|
107
|
+
return f'''{hidden('privacy_version',consent.PRIVACY_VERSION)}
|
|
108
|
+
<label for="privacy-accept"><input id="privacy-accept" type="checkbox" name="privacy_accept" value="1"{needed}> I have read and agree to the <a href="https://socialcli.app/privacy.html" target="_blank" rel="noopener">Privacy Policy</a>.</label>
|
|
109
|
+
<p class="expiry-note">Only the account owner may accept. Acceptance is required to enable features. You can sign in to delete your account or sign out without accepting.</p>'''
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def privacy_review(csrf,next_path,account_csrf):
|
|
113
|
+
return page('Review the Privacy Policy',f'''<p class="eyebrow">PRIVACY REVIEW</p><h1 id="page-title">Review the Privacy Policy</h1>
|
|
114
|
+
<p class="description">Before using SocialCli features, review how we access, use, share and retain your account data. A material policy change requires a new owner acceptance.</p>
|
|
115
|
+
<form method="post" action="/account/privacy" class="form-stack">{hidden('csrf',csrf)}{hidden('next',next_path)}{privacy_choice_html()}<button class="primary-button" type="submit">Accept and continue</button></form>
|
|
116
|
+
<a class="text-link" href="/account/delete">Delete my account</a>
|
|
117
|
+
<form method="post" action="/account/logout">{hidden('csrf',account_csrf)}<button class="secondary-button" type="submit">Sign out</button></form>''')
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def assistant_choice_html():
|
|
121
|
+
return f'''<fieldset class="permission-options"><legend>Assistant data access</legend>
|
|
122
|
+
<p>This installation receives SocialCli output and may obtain provider access tokens for the selected accounts. Output can include Google/YouTube account details, videos, comments and analytics. Tokens may allow direct provider access with all granted permissions.</p>
|
|
123
|
+
<p>Customer-controlled software runs under your control. If you use a third-party AI service, data you give it also goes to that provider under its terms and settings. Use Google data only for the features you explicitly request. Do not use Google data for model training or advertising. Human access requires specific consent permitted by the applicable Google policy.</p>
|
|
124
|
+
<p>Before continuing, choose a provider and configuration that restrict use and transfer to your requested features, disables training and advertising, and controls retention and human access. If these settings cannot be verified, do not link this installation. SocialCli does not certify every advertised assistant or provider configuration and cannot enforce third-party settings after data or tokens are delivered.</p>
|
|
125
|
+
{hidden('assistant_version',consent.ASSISTANT_VERSION)}
|
|
126
|
+
<label for="assistant-accept"><input id="assistant-accept" type="checkbox" name="assistant_accept" value="1" required> I am the account owner, understand this transfer, and have selected suitable software or provider settings for my requested features.</label></fieldset>'''
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Thirty-minute human-approved pairing with retry-safe, scoped capabilities."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import hmac
|
|
4
|
+
import re
|
|
5
|
+
import secrets
|
|
6
|
+
from html import escape
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
from socialctl.connection_service.peer import client_ip
|
|
9
|
+
from fastapi import HTTPException, Request
|
|
10
|
+
from fastapi.responses import HTMLResponse, RedirectResponse
|
|
11
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
12
|
+
from socialctl.saas.auth import digest
|
|
13
|
+
from socialctl.saas.routes import read_form
|
|
14
|
+
from socialctl.saas import pages, permissions, consent
|
|
15
|
+
|
|
16
|
+
PAIR_SECONDS=1800
|
|
17
|
+
INSTALLATION_SECONDS=90*86400
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PairRequest(BaseModel):
|
|
21
|
+
model_config=ConfigDict(extra='forbid')
|
|
22
|
+
label:str=Field(min_length=1,max_length=80)
|
|
23
|
+
poll_challenge:str=Field(pattern='^[0-9a-f]{64}$')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def proof(request):
|
|
27
|
+
value=request.headers.get('authorization','')
|
|
28
|
+
if not value.startswith('Bearer ') or not 16<=len(value[7:])<=512:
|
|
29
|
+
return ''
|
|
30
|
+
return digest(value[7:])
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Installations:
|
|
34
|
+
def __init__(self,metadata,clock):
|
|
35
|
+
self.metadata,self.vault,self.clock=metadata,metadata.vault,clock
|
|
36
|
+
|
|
37
|
+
def require(self,db,installation_id,request):
|
|
38
|
+
record=self.vault.get(db,'saas-installation',installation_id)
|
|
39
|
+
if record is None or record['expires']<=self.clock() or not hmac.compare_digest(record['credential_hash'],proof(request)):
|
|
40
|
+
raise HTTPException(401,'installation_expired: Sign in to SocialCli again.')
|
|
41
|
+
user=self.metadata.user(db,record['payload']['user_id'])
|
|
42
|
+
if user is None or user['deleting']:
|
|
43
|
+
raise HTTPException(401,'installation_revoked: Sign in to SocialCli again.')
|
|
44
|
+
if request.method!='DELETE':
|
|
45
|
+
consent.require_privacy(self.metadata,db,user['id'])
|
|
46
|
+
consent.require_assistant(record['payload'])
|
|
47
|
+
return record
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def install_pairing_routes(app,settings,metadata,sessions,clock):
|
|
51
|
+
vault=metadata.vault
|
|
52
|
+
installations=Installations(metadata,clock)
|
|
53
|
+
app.state.saas_installations=installations
|
|
54
|
+
csrf=app.state.saas_csrf
|
|
55
|
+
valid_form=app.state.saas_valid_form
|
|
56
|
+
|
|
57
|
+
def pairing(db,pair_id,request=None):
|
|
58
|
+
record=vault.get(db,'saas-pair',pair_id)
|
|
59
|
+
if record is None or record['expires']<=clock() or request is not None and not hmac.compare_digest(record['credential_hash'],proof(request)):
|
|
60
|
+
raise HTTPException(404,'pairing_expired: Request a new SocialCli sign-in link.')
|
|
61
|
+
return record
|
|
62
|
+
|
|
63
|
+
@app.get('/api/saas/v1/capabilities')
|
|
64
|
+
def capabilities():
|
|
65
|
+
return {'version':1,'service':'socialcli-saas','minimum_client':'0.3.0',
|
|
66
|
+
'pairing_seconds':PAIR_SECONDS,'oauth_seconds':600,'browser_account_selection':True,
|
|
67
|
+
'installation_platform_expansion':True,
|
|
68
|
+
'currency':'usd','monthly_amount':1000,'trial_days':14,
|
|
69
|
+
'platforms':sorted(settings.providers)}
|
|
70
|
+
|
|
71
|
+
@app.post('/api/saas/v1/installations/pair',status_code=201)
|
|
72
|
+
def start(body:PairRequest,request:Request):
|
|
73
|
+
pair_id=secrets.token_urlsafe(24)
|
|
74
|
+
with vault.transaction() as db:
|
|
75
|
+
peer=client_ip(request,settings)
|
|
76
|
+
if not metadata.admit(db,'pair-peer:'+peer,clock(),limit=60):
|
|
77
|
+
raise HTTPException(429,'Too many sign-in links. Please wait a minute.')
|
|
78
|
+
active=db.execute("SELECT count(*) FROM records WHERE kind='saas-pair' AND expires>?",(clock(),)).fetchone()[0]
|
|
79
|
+
if active>=1000:
|
|
80
|
+
raise HTTPException(503,'Sign-in is busy. Please try again.')
|
|
81
|
+
vault.put(db,'saas-pair',pair_id,{'label':body.label,'status':'pending'},
|
|
82
|
+
expires=clock()+PAIR_SECONDS,credential_hash=body.poll_challenge)
|
|
83
|
+
return {'version':1,'pairing_id':pair_id,'browser_url':settings.public_url+'/account/pair/'+pair_id,
|
|
84
|
+
'expires_in':PAIR_SECONDS,'poll_interval':2}
|
|
85
|
+
|
|
86
|
+
@app.get('/account/pair/{pair_id}',response_class=HTMLResponse)
|
|
87
|
+
def approve_page(pair_id:str,request:Request):
|
|
88
|
+
with vault.read_transaction() as db:
|
|
89
|
+
record=pairing(db,pair_id)
|
|
90
|
+
if record['payload']['status']!='pending':
|
|
91
|
+
raise HTTPException(409,'This assistant has already been linked.')
|
|
92
|
+
try:
|
|
93
|
+
sessions.require_user(request)
|
|
94
|
+
except HTTPException as exc:
|
|
95
|
+
if exc.status_code!=401: raise
|
|
96
|
+
return RedirectResponse('/account/login?next='+quote('/account/pair/'+pair_id,safe=''),status_code=303)
|
|
97
|
+
label=escape(record['payload']['label'])
|
|
98
|
+
content=f'''<p class="eyebrow">LINK AN ASSISTANT</p><h1 id="page-title">Allow {label}?</h1>
|
|
99
|
+
<p class="description">Choose which SocialCli connections this installation may access. Only approve an assistant you recognize. Provider credentials can include permissions for linked accounts and actions. This selection controls access to SocialCli connections; it does not narrow provider permissions.</p>
|
|
100
|
+
<div class="status-notice">You can revoke this installation from your account at any time. Previously issued provider tokens may remain usable until they expire or are revoked at the provider. Linking does not approve any publication.</div>
|
|
101
|
+
<form method="post" action="/account/pair/{escape(pair_id,quote=True)}" class="form-stack">{pages.hidden('csrf',csrf(request,'pair:'+pair_id))}{permissions.selection_html()}{pages.assistant_choice_html()}<button class="primary-button" type="submit">Allow {label}</button></form>
|
|
102
|
+
<a class="text-link" href="/account/">Cancel and return to account</a>'''
|
|
103
|
+
return HTMLResponse(pages.page('Link an assistant',content))
|
|
104
|
+
|
|
105
|
+
@app.post('/account/pair/{pair_id}',response_class=HTMLResponse)
|
|
106
|
+
async def approve(pair_id:str,request:Request):
|
|
107
|
+
data=await read_form(request,settings.public_url)
|
|
108
|
+
valid_form(request,data,'pair:'+pair_id)
|
|
109
|
+
assistant_consent=consent.assistant_choice(data,clock())
|
|
110
|
+
platform_access=permissions.from_form({k:v for k,v in data.items() if k not in {'assistant_accept','assistant_version'}})
|
|
111
|
+
user=await asyncio.to_thread(sessions.require_user,request)
|
|
112
|
+
def commit():
|
|
113
|
+
with vault.transaction() as db:
|
|
114
|
+
record=pairing(db,pair_id)
|
|
115
|
+
if record['payload']['status']!='pending':
|
|
116
|
+
raise HTTPException(409,'This assistant has already been linked.')
|
|
117
|
+
row=metadata.user(db,user.id)
|
|
118
|
+
if row is None or row['deleting']:
|
|
119
|
+
raise HTTPException(401,'Sign in to SocialCli again.')
|
|
120
|
+
consent.require_privacy(metadata,db,user.id)
|
|
121
|
+
installation_id,secret=secrets.token_urlsafe(24),secrets.token_urlsafe(32)
|
|
122
|
+
vault.put(db,'saas-installation',installation_id,{'user_id':user.id,'label':record['payload']['label'],
|
|
123
|
+
'created_at':clock(),'platform_access':platform_access,'assistant_consent':assistant_consent},expires=clock()+INSTALLATION_SECONDS,credential_hash=digest(secret))
|
|
124
|
+
record['payload'].update(status='approved',user_id=user.id,installation_id=installation_id,installation_secret=secret)
|
|
125
|
+
vault.put(db,'saas-pair',pair_id,record['payload'],expires=record['expires'],credential_hash=record['credential_hash'])
|
|
126
|
+
await asyncio.to_thread(commit)
|
|
127
|
+
return HTMLResponse(pages.page('Assistant linked','<p class="eyebrow">ALL SET</p><h1 id="page-title">Assistant linked</h1><p class="description">Return to your assistant to continue. No social account has been connected by this step.</p><a class="secondary-button" href="/account/">Your account</a>'))
|
|
128
|
+
|
|
129
|
+
@app.post('/api/saas/v1/pairings/{pair_id}/poll')
|
|
130
|
+
def poll(pair_id:str,request:Request):
|
|
131
|
+
with vault.read_transaction() as db:
|
|
132
|
+
payload=pairing(db,pair_id,request)['payload']
|
|
133
|
+
return {'version':1,**{k:v for k,v in payload.items() if k in {'status','installation_id','installation_secret'}}}
|
|
134
|
+
|
|
135
|
+
@app.post('/api/saas/v1/pairings/{pair_id}/ack')
|
|
136
|
+
def ack(pair_id:str,request:Request):
|
|
137
|
+
with vault.transaction() as db:
|
|
138
|
+
record=pairing(db,pair_id,request)
|
|
139
|
+
if record['payload']['status'] not in {'approved','consumed'}:
|
|
140
|
+
raise HTTPException(409,'Pairing is not approved.')
|
|
141
|
+
record['payload'].pop('installation_secret',None)
|
|
142
|
+
record['payload']['status']='consumed'
|
|
143
|
+
vault.put(db,'saas-pair',pair_id,record['payload'],expires=min(record['expires'],clock()+600),credential_hash=record['credential_hash'])
|
|
144
|
+
return {'version':1,'status':'consumed'}
|
|
145
|
+
|
|
146
|
+
@app.get('/api/saas/v1/installations/{installation_id}')
|
|
147
|
+
def status(installation_id:str,request:Request):
|
|
148
|
+
with vault.read_transaction() as db:
|
|
149
|
+
record=installations.require(db,installation_id,request)
|
|
150
|
+
return {'version':1,'installation_id':installation_id,'label':record['payload']['label'],'expires_at':record['expires'],
|
|
151
|
+
'platform_access':permissions.describe(record['payload'])}
|
|
152
|
+
|
|
153
|
+
@app.delete('/api/saas/v1/installations/{installation_id}')
|
|
154
|
+
def revoke(installation_id:str,request:Request):
|
|
155
|
+
with vault.transaction() as db:
|
|
156
|
+
installations.require(db,installation_id,request)
|
|
157
|
+
vault.delete(db,'saas-installation',installation_id)
|
|
158
|
+
return {'version':1,'status':'revoked','provider_authorization_revoked':False}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Server-side installation/platform boundaries, not provider action attenuation."""
|
|
2
|
+
from html import escape
|
|
3
|
+
from fastapi import HTTPException
|
|
4
|
+
|
|
5
|
+
PLATFORMS = {'youtube': 'YouTube', 'facebook': 'Facebook', 'instagram': 'Instagram', 'tiktok': 'TikTok'}
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def policy(platforms, *, source='owner_selection'):
|
|
9
|
+
return {'version': 1, 'platforms': sorted(platforms), 'source': source}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def approved(payload):
|
|
13
|
+
value = payload.get('platform_access')
|
|
14
|
+
if not isinstance(value, dict) or type(value.get('version')) is not int or value['version'] != 1:
|
|
15
|
+
raise ValueError('invalid platform policy')
|
|
16
|
+
names = value.get('platforms')
|
|
17
|
+
if (not isinstance(names, list) or any(not isinstance(p, str) or p not in PLATFORMS for p in names)
|
|
18
|
+
or len(set(names)) != len(names)):
|
|
19
|
+
raise ValueError('invalid platform policy')
|
|
20
|
+
return sorted(names)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def require(payload, platform):
|
|
24
|
+
try:
|
|
25
|
+
names = approved(payload)
|
|
26
|
+
except ValueError:
|
|
27
|
+
raise HTTPException(403, 'installation_permissions_invalid: Ask the owner to revoke and link this assistant again.') from None
|
|
28
|
+
if platform not in names:
|
|
29
|
+
raise HTTPException(403, 'platform_not_allowed: This assistant was not approved for this social platform.')
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def describe(payload):
|
|
33
|
+
try:
|
|
34
|
+
names = approved(payload)
|
|
35
|
+
except ValueError:
|
|
36
|
+
return {'version': 1, 'status': 'invalid', 'platforms': [], 'action_restrictions_enforced': False, 'provider_scope_restrictions_enforced': False, 'enforcement': 'connection_broker'}
|
|
37
|
+
return {'version': 1, 'status': 'approved', 'platforms': names, 'action_restrictions_enforced': False, 'provider_scope_restrictions_enforced': False, 'enforcement': 'connection_broker'}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def from_form(data):
|
|
41
|
+
if (data.get('platform_access_version') != '1'
|
|
42
|
+
or set(data) - {'csrf', 'platform_access_version', *(f'allow_{p}' for p in PLATFORMS)}
|
|
43
|
+
or any(value != '1' for key, value in data.items() if key.startswith('allow_'))):
|
|
44
|
+
raise HTTPException(400, 'Review the social platforms on this page and submit again.')
|
|
45
|
+
return policy([p for p in PLATFORMS if data.get('allow_' + p) == '1'])
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def selection_html():
|
|
49
|
+
choices = ''.join(f'<label for="allow-{p}"><input id="allow-{p}" type="checkbox" name="allow_{p}" value="1" checked> {escape(label)}</label>' for p, label in PLATFORMS.items())
|
|
50
|
+
return '<fieldset class="permission-options"><legend>SocialCli connections this assistant may access</legend>' + choices + '</fieldset><input type="hidden" name="platform_access_version" value="1">'
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def summary_html(payload):
|
|
54
|
+
value = describe(payload)
|
|
55
|
+
names = ', '.join(PLATFORMS[p] for p in value['platforms']) or 'None'
|
|
56
|
+
return '<p>Approved social platforms: ' + escape(names) + '</p>' + (
|
|
57
|
+
'<p class="status-notice">Permissions unavailable. Revoke and link this assistant again.</p>' if value['status'] == 'invalid' else '')
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Leased trial-email outbox. SMTP uncertainty is terminal, never auto-replayed."""
|
|
2
|
+
import secrets
|
|
3
|
+
from email.message import EmailMessage
|
|
4
|
+
from email.policy import SMTP
|
|
5
|
+
from email.utils import formatdate
|
|
6
|
+
from html import escape
|
|
7
|
+
from importlib.resources import files
|
|
8
|
+
from string import Template
|
|
9
|
+
|
|
10
|
+
from socialctl.saas.access import AccessControl
|
|
11
|
+
from socialctl.saas.pages import utc_date
|
|
12
|
+
from socialctl.saas.mail import mailbox
|
|
13
|
+
from socialctl.saas.budget import using_budget
|
|
14
|
+
|
|
15
|
+
DAY=86400
|
|
16
|
+
LEASE_SECONDS=300
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def message_for(job,recipient,public_url,now):
|
|
20
|
+
mailbox(recipient)
|
|
21
|
+
deadline=utc_date(job['trial_end'])
|
|
22
|
+
link=public_url+'/account/'
|
|
23
|
+
message=EmailMessage(policy=SMTP)
|
|
24
|
+
message['From']='SocialCli <access@socialcli.app>'
|
|
25
|
+
message['To']=recipient
|
|
26
|
+
message['Subject']='Your SocialCli free trial ends soon'
|
|
27
|
+
message['Date']=formatdate(now,usegmt=True)
|
|
28
|
+
message['Message-ID']=f"<socialcli.trial.{job['id']}@socialcli.app>"
|
|
29
|
+
message.set_content(f'Your SocialCli free trial ends {deadline}.\n\n'
|
|
30
|
+
'Subscribe now for USD 10/month without losing your remaining free days. The first charge is due at the original trial end '
|
|
31
|
+
'to continue using your connected accounts. Cancel anytime.\n\n'
|
|
32
|
+
f'Manage your account: {link}\n\nYour accounts. Your permissions. Your choice.\n')
|
|
33
|
+
template=files('socialctl.ui').joinpath('email/trial.html').read_text()
|
|
34
|
+
message.add_alternative(Template(template).substitute(deadline=escape(deadline),account_url=escape(link,quote=True)),subtype='html')
|
|
35
|
+
return message
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Reminders:
|
|
39
|
+
def __init__(self,metadata,clock,public_url):
|
|
40
|
+
self.metadata,self.vault,self.clock,self.public_url=metadata,metadata.vault,clock,public_url
|
|
41
|
+
self.access=AccessControl(metadata)
|
|
42
|
+
|
|
43
|
+
def eligible(self,db,job,now):
|
|
44
|
+
entitlement=db.execute('SELECT trial_end,subscription_status FROM saas_entitlements WHERE user_id=?',(job['user_id'],)).fetchone()
|
|
45
|
+
if (entitlement is None or entitlement['trial_end']!=job['trial_end']
|
|
46
|
+
or entitlement['subscription_status'] not in ('','canceled','incomplete_expired')
|
|
47
|
+
or self.access.decision(db,job['user_id'],now).reason!='trial'):
|
|
48
|
+
return False
|
|
49
|
+
end=job['trial_end']
|
|
50
|
+
return end-job['milestone']*DAY<=now<(end-DAY if job['milestone']==3 else end)
|
|
51
|
+
|
|
52
|
+
def prepare(self):
|
|
53
|
+
now=self.clock()
|
|
54
|
+
with self.vault.transaction() as db:
|
|
55
|
+
# A crashed worker before DATA can be reclaimed; after DATA starts it cannot.
|
|
56
|
+
db.execute("UPDATE saas_reminders SET state='pending',lease=NULL WHERE state='preparing' AND lease_until<=?",(now,))
|
|
57
|
+
db.execute("UPDATE saas_reminders SET state='uncertain' WHERE state='sending' AND lease_until<=?",(now,))
|
|
58
|
+
rows=db.execute("""SELECT e.user_id,e.trial_end FROM saas_entitlements e
|
|
59
|
+
JOIN saas_users u ON u.id=e.user_id WHERE e.trial_end>? AND u.deleting=0 AND u.suspended=0
|
|
60
|
+
AND (SELECT count(*) FROM saas_reminders r WHERE r.user_id=e.user_id AND r.trial_end=e.trial_end)<2
|
|
61
|
+
ORDER BY e.trial_end LIMIT 100""",(now,)).fetchall()
|
|
62
|
+
for row in rows:
|
|
63
|
+
for milestone in (3,1):
|
|
64
|
+
db.execute('INSERT OR IGNORE INTO saas_reminders(id,user_id,trial_end,milestone,next_attempt) VALUES(?,?,?,?,?)',
|
|
65
|
+
(secrets.token_hex(24),row['user_id'],row['trial_end'],milestone,row['trial_end']-milestone*DAY))
|
|
66
|
+
db.execute("UPDATE saas_reminders SET state='cancelled',lease=NULL WHERE state IN ('pending','preparing') AND (trial_end<=? OR (milestone=3 AND trial_end-86400<=?))",(now,now))
|
|
67
|
+
# Retain minimal delivery receipts only briefly after the trial. No addresses.
|
|
68
|
+
db.execute('DELETE FROM saas_reminders WHERE trial_end<?',(now-30*DAY,))
|
|
69
|
+
|
|
70
|
+
def run(self,sender,limit=100,*,budget=None):
|
|
71
|
+
with using_budget(budget,sender):
|
|
72
|
+
return self._run(sender,limit,budget)
|
|
73
|
+
|
|
74
|
+
def _run(self,sender,limit,budget):
|
|
75
|
+
self.prepare()
|
|
76
|
+
accepted=0
|
|
77
|
+
with self.vault.transaction() as db:
|
|
78
|
+
jobs=([dict(row) for row in db.execute("SELECT * FROM saas_reminders WHERE state='pending' AND next_attempt<=? ORDER BY next_attempt,id LIMIT ?",(self.clock(),limit))]
|
|
79
|
+
if sender is not None else [])
|
|
80
|
+
for job in jobs:
|
|
81
|
+
if budget and budget.expired():break
|
|
82
|
+
lease=secrets.token_hex(24)
|
|
83
|
+
with self.vault.transaction() as db:
|
|
84
|
+
claimed=db.execute("UPDATE saas_reminders SET state='preparing',attempts=attempts+1,lease=?,lease_until=? WHERE id=? AND state='pending' AND next_attempt<=?",(lease,self.clock()+LEASE_SECONDS,job['id'],self.clock())).rowcount
|
|
85
|
+
if not claimed:continue
|
|
86
|
+
identity=self.vault.get(db,'saas-user',job['user_id'])
|
|
87
|
+
if identity is None or not self.eligible(db,job,self.clock()):
|
|
88
|
+
db.execute("UPDATE saas_reminders SET state='cancelled',lease=NULL WHERE id=?",(job['id'],))
|
|
89
|
+
continue
|
|
90
|
+
recipient=identity['payload']['email']
|
|
91
|
+
|
|
92
|
+
def before_send():
|
|
93
|
+
if budget and budget.expired():return False
|
|
94
|
+
with self.vault.transaction() as db:
|
|
95
|
+
row=db.execute('SELECT * FROM saas_reminders WHERE id=?',(job['id'],)).fetchone()
|
|
96
|
+
if row is None or row['lease']!=lease or row['state']!='preparing' or row['lease_until']<=self.clock():return False
|
|
97
|
+
identity=self.vault.get(db,'saas-user',job['user_id'])
|
|
98
|
+
if not self.eligible(db,job,self.clock()) or identity is None or identity['payload']['email']!=recipient:
|
|
99
|
+
db.execute("UPDATE saas_reminders SET state='cancelled',lease=NULL WHERE id=?",(job['id'],))
|
|
100
|
+
return False
|
|
101
|
+
if budget and budget.expired():return False
|
|
102
|
+
db.execute("UPDATE saas_reminders SET state='sending',lease_until=? WHERE id=?",(self.clock()+LEASE_SECONDS,job['id']))
|
|
103
|
+
return True
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
result=sender.send(recipient,message_for(job,recipient,self.public_url,self.clock()),before_send)
|
|
107
|
+
except ValueError:
|
|
108
|
+
result='rejected'
|
|
109
|
+
except Exception:
|
|
110
|
+
result='error'
|
|
111
|
+
with self.vault.transaction() as db:
|
|
112
|
+
row=db.execute('SELECT * FROM saas_reminders WHERE id=?',(job['id'],)).fetchone()
|
|
113
|
+
if row is None or row['lease']!=lease:continue
|
|
114
|
+
if row['state']=='cancelled':continue
|
|
115
|
+
if result=='accepted' and row['state'] in {'sending','uncertain'}:
|
|
116
|
+
state='accepted';accepted+=1
|
|
117
|
+
elif result=='rejected':state='rejected'
|
|
118
|
+
elif result=='retry':state='pending'
|
|
119
|
+
elif row['state'] in {'sending','uncertain'}:state='uncertain'
|
|
120
|
+
else:state='pending'
|
|
121
|
+
db.execute('UPDATE saas_reminders SET state=?,next_attempt=?,lease=NULL,lease_until=0 WHERE id=?',
|
|
122
|
+
(state,self.clock()+300,job['id']))
|
|
123
|
+
with self.vault.transaction() as db:
|
|
124
|
+
counts={row['state']:row['n'] for row in db.execute("SELECT state,count(*) AS n FROM saas_reminders WHERE (state='pending' AND next_attempt<=?) OR state IN ('uncertain','rejected','preparing','sending') GROUP BY state",(self.clock(),))}
|
|
125
|
+
retry_pending=db.execute("SELECT count(*) FROM saas_reminders WHERE state='pending' AND attempts>0").fetchone()[0]
|
|
126
|
+
return {'disabled':sender is None,'accepted':accepted,'retry_pending':retry_pending,'due':counts.get('pending',0),'uncertain':counts.get('uncertain',0),
|
|
127
|
+
'rejected':counts.get('rejected',0),'in_progress':counts.get('preparing',0)+counts.get('sending',0),
|
|
128
|
+
'budget_exhausted':bool(budget and budget.expired())}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Public renewal state derived from encrypted grant metadata; no token replay."""
|
|
2
|
+
from fastapi import HTTPException
|
|
3
|
+
|
|
4
|
+
PENDING_SECONDS=120
|
|
5
|
+
RETRY_SECONDS=30
|
|
6
|
+
CONFIG_RETRY_SECONDS=300
|
|
7
|
+
|
|
8
|
+
MESSAGES={
|
|
9
|
+
'renewal_required':'An explicitly authorized operation must renew this token.',
|
|
10
|
+
'renewal_pending':'Another renewal is pending. Try again later.',
|
|
11
|
+
'renewal_retryable':'The provider could not be reached. Keep this connection and try again later.',
|
|
12
|
+
'renewal_uncertain':'Renewal could not be confirmed. Review this connection in your SocialCli account.',
|
|
13
|
+
'provider_configuration':'Provider configuration needs attention. Keep this connection and try again after it is fixed.',
|
|
14
|
+
'provider_authorization_expired':'Provider authorization expired or was revoked. Reconnect this account explicitly.',
|
|
15
|
+
'provider_permissions_changed':'Provider permissions changed. Reconnect this account explicitly to review the required permissions.',
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def state(payload,now):
|
|
20
|
+
error=payload.get('refresh_error')
|
|
21
|
+
if error in {'provider_authorization_expired','provider_permissions_changed'}: return 'reconnect_required'
|
|
22
|
+
if error=='renewal_uncertain': return 'uncertain'
|
|
23
|
+
if payload.get('refresh_lease'):
|
|
24
|
+
started=payload.get('refresh_started_at')
|
|
25
|
+
return 'pending' if started is not None and now<started+PENDING_SECONDS else 'uncertain'
|
|
26
|
+
if error=='provider_configuration': return 'configuration_error'
|
|
27
|
+
if error=='renewal_retryable': return 'retryable'
|
|
28
|
+
grant=payload['grant']
|
|
29
|
+
if grant['expires_at']<=now+60:
|
|
30
|
+
if payload['platform'] not in {'youtube','tiktok'} or grant.get('refresh_expires_at',float('inf'))<=now:
|
|
31
|
+
return 'reconnect_required'
|
|
32
|
+
return 'required'
|
|
33
|
+
return 'ready'
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def reject(code):
|
|
37
|
+
status=409 if code in {'renewal_required','provider_authorization_expired','provider_permissions_changed'} else 503
|
|
38
|
+
raise HTTPException(status,code+': '+MESSAGES[code])
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def check(payload,now,refresh):
|
|
42
|
+
current=state(payload,now)
|
|
43
|
+
fatal={'uncertain':'renewal_uncertain','pending':'renewal_pending',
|
|
44
|
+
'reconnect_required':payload.get('refresh_error') or 'provider_authorization_expired'}
|
|
45
|
+
if current in fatal: reject(fatal[current])
|
|
46
|
+
if current in {'retryable','configuration_error'} and payload.get('refresh_retry_at',0)>now:
|
|
47
|
+
reject(payload['refresh_error'])
|
|
48
|
+
if current!='ready' and not refresh: reject('renewal_required')
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def clear(payload):
|
|
52
|
+
for key in ('refresh_lease','refresh_started_at','refresh_error','refresh_retry_at'):
|
|
53
|
+
payload.pop(key,None)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def record_failure(payload,code,now):
|
|
57
|
+
clear(payload)
|
|
58
|
+
payload['refresh_error']=code
|
|
59
|
+
if code in {'renewal_retryable','provider_configuration'}:
|
|
60
|
+
payload['refresh_retry_at']=now+(RETRY_SECONDS if code=='renewal_retryable' else CONFIG_RETRY_SECONDS)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def notice(payload,now):
|
|
64
|
+
current=state(payload,now)
|
|
65
|
+
if payload.get('refresh_error')=='provider_permissions_changed':
|
|
66
|
+
return 'Provider permissions changed. Ask your assistant to reconnect this account with your approval to review the required permissions.'
|
|
67
|
+
return {
|
|
68
|
+
'required':'Token renewal is due. An explicitly authorized operation can renew it.',
|
|
69
|
+
'pending':'Token renewal is in progress. Try again shortly.',
|
|
70
|
+
'retryable':'The provider could not be reached. Your connection is saved; try again later.',
|
|
71
|
+
'configuration_error':'The connection service needs a configuration fix. Your connection is saved.',
|
|
72
|
+
'uncertain':'Renewal could not be confirmed. Ask your assistant to review this connection. If access cannot be restored, approve a new connection.',
|
|
73
|
+
'reconnect_required':'Provider authorization expired or was revoked. Ask your assistant to reconnect this account with your approval.',
|
|
74
|
+
}.get(current,'')
|