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/routes.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Browser-bound email sign-in with local session revocation and bounded forms."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import hmac
|
|
4
|
+
import re
|
|
5
|
+
import secrets
|
|
6
|
+
from urllib.parse import parse_qs, urlencode
|
|
7
|
+
from socialctl.connection_service.peer import client_ip
|
|
8
|
+
from fastapi import HTTPException, Request
|
|
9
|
+
from fastapi.responses import HTMLResponse, RedirectResponse
|
|
10
|
+
from socialctl.connection_service.landing import LandingTokens
|
|
11
|
+
from socialctl.saas.auth import SupabaseAuth, WebSessions, IdentityError, IdentityUnavailable, digest
|
|
12
|
+
from socialctl.saas.store import SaaSStore
|
|
13
|
+
from socialctl.saas import pages, consent
|
|
14
|
+
|
|
15
|
+
PREAUTH='socialcli-browser'
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
async def read_form(request,origin):
|
|
19
|
+
if request.headers.get('origin')!=origin:
|
|
20
|
+
raise HTTPException(403,'Reload the page and try again.')
|
|
21
|
+
if request.headers.get('content-type','').split(';')[0]!='application/x-www-form-urlencoded':
|
|
22
|
+
raise HTTPException(403,'Reload the page and try again.')
|
|
23
|
+
content=bytearray()
|
|
24
|
+
try:
|
|
25
|
+
async with asyncio.timeout(5):
|
|
26
|
+
async for chunk in request.stream():
|
|
27
|
+
content.extend(chunk)
|
|
28
|
+
if len(content)>8192:
|
|
29
|
+
raise HTTPException(413,'This form is too large.')
|
|
30
|
+
values=parse_qs(content.decode('utf-8'),max_num_fields=12,strict_parsing=True,keep_blank_values=True)
|
|
31
|
+
if any(len(v)!=1 for v in values.values()):
|
|
32
|
+
raise ValueError()
|
|
33
|
+
return {k:v[0] for k,v in values.items()}
|
|
34
|
+
except (UnicodeError,ValueError,TimeoutError):
|
|
35
|
+
raise HTTPException(403,'Reload the page and try again.') from None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def safe_next(value):
|
|
39
|
+
# Only exact local handoff paths; never arbitrary URLs or query strings.
|
|
40
|
+
return value if value=='/account/' or re.fullmatch(r'(?:/(?:connect|account/(?:pair|migrate|connect))/[A-Za-z0-9_-]{16,64}|/account/installations/[A-Za-z0-9_-]{16,64}/platforms)',value or '') else '/account/'
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def connection_sign_in(path):
|
|
44
|
+
return RedirectResponse('/account/login?' + urlencode({'next':safe_next(path)}),status_code=303)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def install_account_routes(app,settings,vault,identity_client,clock):
|
|
48
|
+
metadata=SaaSStore(vault,settings.encryption_keys)
|
|
49
|
+
identity=SupabaseAuth(settings.saas,identity_client)
|
|
50
|
+
sessions=WebSessions(metadata,identity,clock)
|
|
51
|
+
tokens=LandingTokens(settings.encryption_keys)
|
|
52
|
+
app.state.saas=metadata
|
|
53
|
+
app.state.saas_sessions=sessions
|
|
54
|
+
|
|
55
|
+
def csrf(request,purpose,*,authenticated=True):
|
|
56
|
+
cookie=sessions.cookie if authenticated else PREAUTH
|
|
57
|
+
return tokens.issue(purpose,request.cookies.get(cookie,''),clock()+900)
|
|
58
|
+
|
|
59
|
+
def valid_form(request,data,purpose,*,authenticated=True):
|
|
60
|
+
cookie=sessions.cookie if authenticated else PREAUTH
|
|
61
|
+
if not tokens.valid(data.get('csrf',''),purpose,request.cookies.get(cookie,''),clock()):
|
|
62
|
+
raise HTTPException(403,'This form expired. Reload the page and try again.')
|
|
63
|
+
|
|
64
|
+
def response_cookie(response,secret,name=PREAUTH,lifetime=1800):
|
|
65
|
+
response.set_cookie(name,secret,secure=not settings.allow_http_local,httponly=True,
|
|
66
|
+
samesite='lax',max_age=int(lifetime),path='/')
|
|
67
|
+
return response
|
|
68
|
+
|
|
69
|
+
@app.get('/account/login',response_class=HTMLResponse)
|
|
70
|
+
def login_page(request:Request):
|
|
71
|
+
secret=request.cookies.get(PREAUTH,'')
|
|
72
|
+
if not 16<=len(secret)<=512:
|
|
73
|
+
secret=secrets.token_urlsafe(32)
|
|
74
|
+
token=tokens.issue('saas-login',secret,clock()+900)
|
|
75
|
+
return response_cookie(HTMLResponse(pages.login(token,safe_next(request.query_params.get('next','')))),secret)
|
|
76
|
+
|
|
77
|
+
@app.post('/account/login',response_class=HTMLResponse)
|
|
78
|
+
async def send_code(request:Request):
|
|
79
|
+
data=await read_form(request,settings.public_url)
|
|
80
|
+
valid_form(request,data,'saas-login',authenticated=False)
|
|
81
|
+
accepted=consent.privacy_choice(data,required=False)
|
|
82
|
+
email=data.get('email','').strip().casefold()
|
|
83
|
+
if len(email)>254 or not re.fullmatch(r'[^\s@]+@[^\s@]+\.[^\s@]+',email):
|
|
84
|
+
return HTMLResponse(pages.login(csrf(request,'saas-login',authenticated=False),safe_next(data.get('next','')),'Enter a valid email address.',input_error=True),status_code=400)
|
|
85
|
+
def prepare():
|
|
86
|
+
with vault.transaction() as db:
|
|
87
|
+
limits=[('email-minute:'+email,3,60),('email-hour:'+email,10,3600),
|
|
88
|
+
('browser:'+request.cookies[PREAUTH],5,60),
|
|
89
|
+
('login-peer:'+(client_ip(request,settings)),120,60)]
|
|
90
|
+
if not all(metadata.admit(db,key,clock(),limit=limit,seconds=period) for key,limit,period in limits):
|
|
91
|
+
return None
|
|
92
|
+
attempt=secrets.token_urlsafe(24)
|
|
93
|
+
vault.put(db,'saas-login',attempt,{'email':email,'browser':digest(request.cookies[PREAUTH]),
|
|
94
|
+
'next':safe_next(data.get('next','')),'tries':0,'status':'pending',
|
|
95
|
+
'privacy_version':consent.PRIVACY_VERSION if accepted else None},expires=clock()+600)
|
|
96
|
+
return attempt
|
|
97
|
+
attempt=await asyncio.to_thread(prepare)
|
|
98
|
+
if attempt is None:
|
|
99
|
+
raise HTTPException(429,'Too many codes requested. Wait a minute and try again.')
|
|
100
|
+
try:
|
|
101
|
+
await asyncio.to_thread(identity.send_code,email)
|
|
102
|
+
except (IdentityError,IdentityUnavailable) as exc:
|
|
103
|
+
def cancel():
|
|
104
|
+
with vault.transaction() as db:
|
|
105
|
+
vault.delete(db,'saas-login',attempt)
|
|
106
|
+
await asyncio.to_thread(cancel)
|
|
107
|
+
if isinstance(exc,IdentityError):
|
|
108
|
+
return HTMLResponse(pages.login(csrf(request,'saas-login',authenticated=False),safe_next(data.get('next','')),'Enter a valid email address.',input_error=True),status_code=400)
|
|
109
|
+
return HTMLResponse(pages.error('Email delivery is temporarily unavailable. Please try again.'),status_code=503)
|
|
110
|
+
return HTMLResponse(pages.verify(csrf(request,attempt,authenticated=False),attempt,email))
|
|
111
|
+
|
|
112
|
+
@app.post('/account/verify',response_class=HTMLResponse)
|
|
113
|
+
async def verify_code(request:Request):
|
|
114
|
+
data=await read_form(request,settings.public_url)
|
|
115
|
+
attempt=data.get('attempt','')
|
|
116
|
+
valid_form(request,data,attempt,authenticated=False)
|
|
117
|
+
def reserve():
|
|
118
|
+
with vault.transaction() as db:
|
|
119
|
+
record=vault.get(db,'saas-login',attempt)
|
|
120
|
+
if record is None or record['expires']<=clock() or not hmac.compare_digest(record['payload']['browser'],digest(request.cookies.get(PREAUTH,''))):
|
|
121
|
+
raise HTTPException(403,'This code expired. Request a new sign-in code.')
|
|
122
|
+
payload=record['payload']
|
|
123
|
+
if payload['status']!='pending':
|
|
124
|
+
raise HTTPException(409,'This code has already been used.')
|
|
125
|
+
if payload['tries']>=5:
|
|
126
|
+
return None
|
|
127
|
+
payload['tries']+=1
|
|
128
|
+
vault.put(db,'saas-login',attempt,payload,expires=record['expires'])
|
|
129
|
+
return payload
|
|
130
|
+
payload=await asyncio.to_thread(reserve)
|
|
131
|
+
if payload is None:
|
|
132
|
+
raise HTTPException(429,'Too many attempts. Request a new sign-in code.')
|
|
133
|
+
code=data.get('code','')
|
|
134
|
+
try:
|
|
135
|
+
if not re.fullmatch(r'[0-9]{6,8}',code):
|
|
136
|
+
raise IdentityError()
|
|
137
|
+
user,access,lifetime,refresh_token=await asyncio.to_thread(identity.verify,payload['email'],code)
|
|
138
|
+
except IdentityError:
|
|
139
|
+
return HTMLResponse(pages.verify(csrf(request,attempt,authenticated=False),attempt,payload['email'],'That code is invalid or expired. Please try again.',input_error=True),status_code=400)
|
|
140
|
+
except IdentityUnavailable:
|
|
141
|
+
return HTMLResponse(pages.verify(csrf(request,attempt,authenticated=False),attempt,payload['email'],'Sign-in is temporarily unavailable. Please try again.'),status_code=503)
|
|
142
|
+
def commit():
|
|
143
|
+
with vault.transaction() as db:
|
|
144
|
+
current=vault.get(db,'saas-login',attempt)
|
|
145
|
+
if current is None or current['expires']<=clock() or current['payload']['status']!='pending':
|
|
146
|
+
raise HTTPException(409,'This code has already been used or expired.')
|
|
147
|
+
current['payload']['status']='consumed'
|
|
148
|
+
vault.put(db,'saas-login',attempt,current['payload'],expires=current['expires'])
|
|
149
|
+
metadata.ensure_user(db,user,clock())
|
|
150
|
+
if payload.get('privacy_version')==consent.PRIVACY_VERSION:
|
|
151
|
+
consent.accept_privacy(metadata,db,user.id,clock())
|
|
152
|
+
previous=request.cookies.get(sessions.cookie,'')
|
|
153
|
+
if previous:
|
|
154
|
+
vault.delete(db,'saas-session',digest(previous))
|
|
155
|
+
return sessions.create(db,user,access,lifetime,refresh_token)
|
|
156
|
+
secret=await asyncio.to_thread(commit)
|
|
157
|
+
return response_cookie(RedirectResponse(payload['next'],status_code=303),secret,sessions.cookie,sessions.max_lifetime)
|
|
158
|
+
|
|
159
|
+
@app.get('/account/',response_class=HTMLResponse)
|
|
160
|
+
def account_page(request:Request):
|
|
161
|
+
try:
|
|
162
|
+
user=sessions.require_user(request,privacy=False)
|
|
163
|
+
except HTTPException as exc:
|
|
164
|
+
if exc.status_code!=401:
|
|
165
|
+
raise
|
|
166
|
+
return RedirectResponse('/account/login',status_code=303)
|
|
167
|
+
with vault.read_transaction() as db:
|
|
168
|
+
accepted=consent.privacy_accepted(metadata,db,user.id)
|
|
169
|
+
if not accepted:
|
|
170
|
+
return HTMLResponse(pages.privacy_review(csrf(request,'saas-privacy'),'/account/',csrf(request,'saas-account')))
|
|
171
|
+
from socialctl.saas.access import AccessControl
|
|
172
|
+
with vault.read_transaction() as db:
|
|
173
|
+
decision=AccessControl(metadata).decision(db,user.id,clock())
|
|
174
|
+
entitlement=db.execute('SELECT * FROM saas_entitlements WHERE user_id=?',(user.id,)).fetchone()
|
|
175
|
+
billing=db.execute('SELECT * FROM saas_billing WHERE user_id=?',(user.id,)).fetchone()
|
|
176
|
+
token=csrf(request,'saas-account')
|
|
177
|
+
details=pages.subscription(decision,entitlement,billing,token,
|
|
178
|
+
enabled=hasattr(app.state,'saas_billing'),processing=request.query_params.get('payment')=='processing' and not decision.allowed)
|
|
179
|
+
details+=app.state.saas_lifecycle.panel(user.id,token)
|
|
180
|
+
response=HTMLResponse(pages.account(user,token,details))
|
|
181
|
+
response.headers['Content-Security-Policy']="default-src 'none'; style-src 'self'; img-src 'self'; form-action 'self' https://checkout.stripe.com https://billing.stripe.com; frame-ancestors 'none'; base-uri 'none'"
|
|
182
|
+
return response
|
|
183
|
+
|
|
184
|
+
@app.get('/account/privacy',response_class=HTMLResponse)
|
|
185
|
+
def privacy_page(request:Request):
|
|
186
|
+
sessions.require_user(request,privacy=False)
|
|
187
|
+
return HTMLResponse(pages.privacy_review(csrf(request,'saas-privacy'),
|
|
188
|
+
safe_next(request.query_params.get('next','')),csrf(request,'saas-account')))
|
|
189
|
+
|
|
190
|
+
@app.post('/account/privacy')
|
|
191
|
+
async def accept_privacy(request:Request):
|
|
192
|
+
data=await read_form(request,settings.public_url)
|
|
193
|
+
valid_form(request,data,'saas-privacy')
|
|
194
|
+
user=await asyncio.to_thread(sessions.require_user,request,privacy=False)
|
|
195
|
+
consent.privacy_choice(data)
|
|
196
|
+
def commit():
|
|
197
|
+
with vault.transaction() as db:
|
|
198
|
+
row=metadata.user(db,user.id)
|
|
199
|
+
if row is None or row['deleting']:
|
|
200
|
+
raise HTTPException(401,'Sign in to SocialCli again.')
|
|
201
|
+
consent.accept_privacy(metadata,db,user.id,clock())
|
|
202
|
+
await asyncio.to_thread(commit)
|
|
203
|
+
return RedirectResponse(safe_next(data.get('next','')),status_code=303)
|
|
204
|
+
|
|
205
|
+
@app.post('/account/logout')
|
|
206
|
+
async def logout(request:Request):
|
|
207
|
+
data=await read_form(request,settings.public_url)
|
|
208
|
+
valid_form(request,data,'saas-account')
|
|
209
|
+
await asyncio.to_thread(sessions.require_user,request,privacy=False)
|
|
210
|
+
await asyncio.to_thread(sessions.revoke,request)
|
|
211
|
+
response=RedirectResponse('/account/login',status_code=303)
|
|
212
|
+
response.delete_cookie(sessions.cookie,path='/',secure=not settings.allow_http_local,httponly=True,samesite='lax')
|
|
213
|
+
return response
|
|
214
|
+
|
|
215
|
+
app.state.saas_csrf=csrf
|
|
216
|
+
app.state.saas_valid_form=valid_form
|
|
217
|
+
from socialctl.saas.pairing import install_pairing_routes
|
|
218
|
+
install_pairing_routes(app,settings,metadata,sessions,clock)
|
|
219
|
+
from socialctl.saas.lifecycle import install_lifecycle_routes
|
|
220
|
+
install_lifecycle_routes(app,settings,metadata,sessions,clock)
|
|
221
|
+
return metadata,sessions
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Explicit SaaS configuration, separate from provider and local CLI credentials."""
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from urllib.parse import urlsplit
|
|
4
|
+
import os
|
|
5
|
+
from socialctl.saas.billing import BillingSettings
|
|
6
|
+
from socialctl.saas.mail import MailSettings
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class SaaSSettings:
|
|
11
|
+
auth_url: str
|
|
12
|
+
auth_key: str = field(default='', repr=False)
|
|
13
|
+
allow_internal_auth: bool = False
|
|
14
|
+
billing: BillingSettings | None = None
|
|
15
|
+
auth_admin_key: str = field(default='',repr=False)
|
|
16
|
+
mail: MailSettings | None = None
|
|
17
|
+
|
|
18
|
+
def __post_init__(self):
|
|
19
|
+
url = urlsplit(self.auth_url)
|
|
20
|
+
if (not url.hostname or url.username or url.password or url.query or url.fragment
|
|
21
|
+
or url.scheme != 'https' and not (self.allow_internal_auth and url.scheme == 'http')):
|
|
22
|
+
raise ValueError('Auth requires an HTTPS URL or explicit private-network HTTP configuration')
|
|
23
|
+
object.__setattr__(self, 'auth_url', self.auth_url.rstrip('/'))
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def from_environment(cls):
|
|
27
|
+
if os.environ.get('SOCIALCLI_SAAS_ENABLED') != '1':
|
|
28
|
+
return None
|
|
29
|
+
return cls(auth_url=os.environ.get('SOCIALCLI_AUTH_URL',''),
|
|
30
|
+
auth_key=os.environ.get('SOCIALCLI_AUTH_KEY',''),
|
|
31
|
+
allow_internal_auth=os.environ.get('SOCIALCLI_AUTH_INTERNAL_HTTP') == '1',
|
|
32
|
+
billing=BillingSettings.from_environment(),
|
|
33
|
+
auth_admin_key=os.environ.get('SOCIALCLI_AUTH_ADMIN_KEY',''),
|
|
34
|
+
mail=MailSettings.from_environment())
|
socialctl/saas/store.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Versioned metadata alongside the existing encrypted credential vault.
|
|
2
|
+
|
|
3
|
+
Only small local transactions here. HTTP requests belong outside these scopes.
|
|
4
|
+
Email and provider credentials live in encrypted records, never plain SQL rows.
|
|
5
|
+
"""
|
|
6
|
+
import hashlib
|
|
7
|
+
from socialctl.connection_service.store import Store
|
|
8
|
+
from socialctl.saas.access import AccessControl
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SaaSStore:
|
|
12
|
+
def __init__(self, vault: Store, eligibility_keys: list[bytes]):
|
|
13
|
+
self.vault = vault
|
|
14
|
+
self.eligibility_keys = eligibility_keys
|
|
15
|
+
with vault.transaction() as db:
|
|
16
|
+
if db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='saas_restore_guard'").fetchone():
|
|
17
|
+
guard=db.execute('SELECT state FROM saas_restore_guard WHERE singleton=1').fetchone()
|
|
18
|
+
if guard is None or guard['state']!='ready':
|
|
19
|
+
raise ValueError('The restored database is quarantined; complete current-authority and identity cleanup before startup.')
|
|
20
|
+
db.execute('CREATE TABLE IF NOT EXISTS saas_schema (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)')
|
|
21
|
+
version = db.execute('SELECT coalesce(max(version),0) FROM saas_schema').fetchone()[0]
|
|
22
|
+
if version > 10:
|
|
23
|
+
raise ValueError('SaaS database is newer than this release; keep commercial access closed')
|
|
24
|
+
if version < 1:
|
|
25
|
+
db.execute('CREATE TABLE saas_users (id TEXT PRIMARY KEY, created REAL NOT NULL, suspended INTEGER NOT NULL DEFAULT 0, deleting INTEGER NOT NULL DEFAULT 0, session_version INTEGER NOT NULL DEFAULT 0)')
|
|
26
|
+
db.execute('CREATE TABLE saas_rates (key TEXT PRIMARY KEY, bucket INTEGER NOT NULL, count INTEGER NOT NULL)')
|
|
27
|
+
db.execute('INSERT INTO saas_schema(version) VALUES(1)')
|
|
28
|
+
if version < 2:
|
|
29
|
+
db.execute("CREATE TABLE saas_entitlements (user_id TEXT PRIMARY KEY,trial_start REAL,trial_end REAL,subscription_status TEXT NOT NULL DEFAULT '',paid_until REAL NOT NULL DEFAULT 0)")
|
|
30
|
+
db.execute('CREATE TABLE saas_trial_markers (marker TEXT PRIMARY KEY,trial_start REAL NOT NULL,trial_end REAL NOT NULL,retain_until REAL NOT NULL)')
|
|
31
|
+
db.execute('INSERT INTO saas_schema(version) VALUES(2)')
|
|
32
|
+
if version < 3:
|
|
33
|
+
db.execute('CREATE TABLE saas_brands (user_id TEXT PRIMARY KEY,id TEXT NOT NULL UNIQUE,label TEXT NOT NULL)')
|
|
34
|
+
db.execute('CREATE TABLE saas_slots (user_id TEXT NOT NULL,platform TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,PRIMARY KEY(user_id,platform))')
|
|
35
|
+
db.execute('INSERT INTO saas_schema(version) VALUES(3)')
|
|
36
|
+
if version < 4:
|
|
37
|
+
db.execute("CREATE TABLE saas_billing (user_id TEXT PRIMARY KEY,customer_id TEXT UNIQUE,subscription_id TEXT UNIQUE,customer_key TEXT NOT NULL,customer_started REAL NOT NULL,checkout_id TEXT,attempt TEXT,attempt_started REAL,lease TEXT,lease_until REAL NOT NULL DEFAULT 0,sync_due REAL NOT NULL DEFAULT 0,cancel_at_period_end INTEGER NOT NULL DEFAULT 0,review TEXT NOT NULL DEFAULT '')")
|
|
38
|
+
db.execute("CREATE TABLE saas_billing_events (account_id TEXT NOT NULL,mode TEXT NOT NULL,event_id TEXT NOT NULL,body_hash TEXT NOT NULL,customer_id TEXT,type TEXT NOT NULL,state TEXT NOT NULL DEFAULT 'pending',received REAL NOT NULL,next_attempt REAL NOT NULL DEFAULT 0,PRIMARY KEY(account_id,mode,event_id))")
|
|
39
|
+
db.execute('INSERT INTO saas_schema(version) VALUES(4)')
|
|
40
|
+
if version < 5:
|
|
41
|
+
db.execute("CREATE TABLE saas_deletions (user_id TEXT PRIMARY KEY,requested REAL NOT NULL,state TEXT NOT NULL DEFAULT 'pending',billing_done INTEGER NOT NULL DEFAULT 0,next_attempt REAL NOT NULL DEFAULT 0,lease TEXT,lease_until REAL NOT NULL DEFAULT 0)")
|
|
42
|
+
db.execute('INSERT INTO saas_schema(version) VALUES(5)')
|
|
43
|
+
if version < 6:
|
|
44
|
+
db.execute("CREATE TABLE saas_reminders (id TEXT PRIMARY KEY,user_id TEXT NOT NULL,trial_end REAL NOT NULL,milestone INTEGER NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,state TEXT NOT NULL DEFAULT 'pending',next_attempt REAL NOT NULL DEFAULT 0,lease TEXT,lease_until REAL NOT NULL DEFAULT 0,UNIQUE(user_id,trial_end,milestone))")
|
|
45
|
+
db.execute('CREATE INDEX saas_reminders_due ON saas_reminders(state,next_attempt,trial_end)')
|
|
46
|
+
db.execute('INSERT INTO saas_schema(version) VALUES(6)')
|
|
47
|
+
if version < 7:
|
|
48
|
+
from socialctl.saas.permissions import policy, PLATFORMS
|
|
49
|
+
for row in db.execute("SELECT id FROM records WHERE kind='saas-installation'").fetchall():
|
|
50
|
+
record = self.vault.get(db, 'saas-installation', row['id'])
|
|
51
|
+
if 'platform_access' not in record['payload']:
|
|
52
|
+
record['payload']['platform_access'] = policy(PLATFORMS, source='legacy_approval')
|
|
53
|
+
self.vault.put(db, 'saas-installation', row['id'], record['payload'],
|
|
54
|
+
expires=record['expires'], credential_hash=record['credential_hash'])
|
|
55
|
+
db.execute('INSERT INTO saas_schema(version) VALUES(7)')
|
|
56
|
+
|
|
57
|
+
if version < 8:
|
|
58
|
+
db.execute('CREATE TABLE IF NOT EXISTS saas_media_allocations (id TEXT PRIMARY KEY,user_id TEXT NOT NULL,size INTEGER NOT NULL,expires REAL NOT NULL)')
|
|
59
|
+
db.execute('CREATE INDEX IF NOT EXISTS saas_media_allocations_owner ON saas_media_allocations(user_id,expires)')
|
|
60
|
+
for row in db.execute("SELECT kind,id FROM records WHERE kind LIKE 'saas-%' OR kind='authorization'").fetchall():
|
|
61
|
+
record = vault.get(db, row['kind'], row['id'])
|
|
62
|
+
vault.index_owner(db, row['kind'], row['id'], record['payload'])
|
|
63
|
+
db.execute("ALTER TABLE saas_billing_events ADD COLUMN semantic_hash TEXT NOT NULL DEFAULT ''")
|
|
64
|
+
from socialctl.saas.webhooks import semantic_hash
|
|
65
|
+
for event in db.execute('SELECT account_id,mode,event_id FROM saas_billing_events').fetchall():
|
|
66
|
+
record=vault.get(db,'saas-stripe-event',':'.join(event))
|
|
67
|
+
if record:
|
|
68
|
+
db.execute('UPDATE saas_billing_events SET semantic_hash=? WHERE account_id=? AND mode=? AND event_id=?',(semantic_hash(record['payload']),*event))
|
|
69
|
+
state=db.execute('SELECT state,received FROM saas_billing_events WHERE account_id=? AND mode=? AND event_id=?',tuple(event)).fetchone()
|
|
70
|
+
if state['state'] in {'done','ignored'}:
|
|
71
|
+
vault.delete(db,'saas-stripe-event',':'.join(event))
|
|
72
|
+
else:
|
|
73
|
+
vault.put(db,'saas-stripe-event',':'.join(event),record['payload'],expires=min(record['expires'],state['received']+7*86400))
|
|
74
|
+
db.execute('ALTER TABLE saas_rates ADD COLUMN expires REAL NOT NULL DEFAULT 0')
|
|
75
|
+
db.execute('INSERT INTO saas_schema(version) VALUES(8)')
|
|
76
|
+
if version < 9:
|
|
77
|
+
# One-time backfill; request paths only use these indexed relations.
|
|
78
|
+
for row in db.execute("SELECT kind,id FROM records WHERE kind IN ('saas-pair','saas-capability','saas-user','saas-login')").fetchall():
|
|
79
|
+
record=vault.get(db,row['kind'],row['id'])
|
|
80
|
+
vault.index_owner(db,row['kind'],row['id'],record['payload'])
|
|
81
|
+
db.execute('INSERT INTO saas_schema(version) VALUES(9)')
|
|
82
|
+
|
|
83
|
+
if version < 10:
|
|
84
|
+
db.execute("CREATE TABLE IF NOT EXISTS saas_google_revocations (id TEXT PRIMARY KEY,user_id TEXT NOT NULL,requested REAL NOT NULL,state TEXT NOT NULL DEFAULT 'pending',next_attempt REAL NOT NULL DEFAULT 0,attempts INTEGER NOT NULL DEFAULT 0,lease TEXT,lease_until REAL NOT NULL DEFAULT 0)")
|
|
85
|
+
db.execute('CREATE INDEX IF NOT EXISTS saas_google_revocations_due ON saas_google_revocations(state,next_attempt,lease_until)')
|
|
86
|
+
db.execute('CREATE TABLE IF NOT EXISTS saas_deletion_tombstones (kind TEXT NOT NULL,id TEXT NOT NULL,requested REAL NOT NULL,PRIMARY KEY(kind,id))')
|
|
87
|
+
db.execute('INSERT INTO saas_schema(version) VALUES(10)')
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def user(self, db, user_id):
|
|
91
|
+
return db.execute('SELECT * FROM saas_users WHERE id=?',(user_id,)).fetchone()
|
|
92
|
+
|
|
93
|
+
def ensure_user(self, db, user, now):
|
|
94
|
+
db.execute('INSERT OR IGNORE INTO saas_users(id,created) VALUES(?,?)',(user.id,now))
|
|
95
|
+
self.vault.put(db,'saas-user',user.id,{'email':user.email},expires=253402300799)
|
|
96
|
+
AccessControl(self).restore_trial(db,user.id,user.email,now)
|
|
97
|
+
|
|
98
|
+
def admit(self, db, key, now, *, limit, seconds=60):
|
|
99
|
+
hashed = hashlib.sha256(key.encode()).hexdigest()
|
|
100
|
+
bucket = int(now // seconds)
|
|
101
|
+
row = db.execute('SELECT bucket,count FROM saas_rates WHERE key=?',(hashed,)).fetchone()
|
|
102
|
+
count = row['count'] if row and row['bucket'] == bucket else 0
|
|
103
|
+
if count >= limit:
|
|
104
|
+
return False
|
|
105
|
+
db.execute('INSERT OR REPLACE INTO saas_rates VALUES(?,?,?,?)',(hashed,bucket,count+1,(bucket+1)*seconds))
|
|
106
|
+
return True
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""Private, quota-bound staging for Instagram. URLs expire 15 minutes after reservation.
|
|
2
|
+
|
|
3
|
+
Only opaque filenames live here, outside database backups. Both the application
|
|
4
|
+
janitor and a host timer remove expired files, including interrupted uploads.
|
|
5
|
+
"""
|
|
6
|
+
import asyncio
|
|
7
|
+
import hashlib
|
|
8
|
+
import hmac
|
|
9
|
+
import math
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import re
|
|
13
|
+
import secrets
|
|
14
|
+
import shutil
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
from fastapi import HTTPException, Request
|
|
18
|
+
from fastapi.responses import Response, StreamingResponse
|
|
19
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
20
|
+
|
|
21
|
+
TTL = 900
|
|
22
|
+
MAX_FILE = 512 * 1024 * 1024
|
|
23
|
+
MAX_TOTAL = 2 * 1024 * 1024 * 1024
|
|
24
|
+
MAX_OWNER = 512 * 1024 * 1024
|
|
25
|
+
KINDS = {'image/jpeg': '.jpg', 'video/mp4': '.mp4', 'video/quicktime': '.mov'}
|
|
26
|
+
FILE = re.compile(r'([0-9]+)-([A-Za-z0-9_-]{32})\.(part|data)\Z')
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Reservation(BaseModel):
|
|
30
|
+
model_config = ConfigDict(extra='forbid', strict=True)
|
|
31
|
+
size: int = Field(gt=0, le=MAX_FILE)
|
|
32
|
+
sha256: str = Field(pattern=r'^[0-9a-f]{64}$')
|
|
33
|
+
content_type: str = Field(pattern=r'^(image/jpeg|video/mp4|video/quicktime)$')
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def cleanup_directory(root, now=None):
|
|
37
|
+
"""Does not need vault keys or a running container; safe across restarts."""
|
|
38
|
+
now = time.time() if now is None else now
|
|
39
|
+
removed = 0
|
|
40
|
+
for path in Path(root).iterdir():
|
|
41
|
+
match = FILE.fullmatch(path.name)
|
|
42
|
+
if match and int(match[1]) <= now:
|
|
43
|
+
path.unlink(missing_ok=True)
|
|
44
|
+
removed += 1
|
|
45
|
+
return removed
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class TemporaryMedia:
|
|
49
|
+
def __init__(self, metadata, root, clock=time.time):
|
|
50
|
+
self.metadata, self.vault, self.clock = metadata, metadata.vault, clock
|
|
51
|
+
self.root = Path(root)
|
|
52
|
+
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
53
|
+
if self.root.is_symlink():
|
|
54
|
+
raise ValueError('Temporary media must use a private real directory')
|
|
55
|
+
self.root.chmod(0o700)
|
|
56
|
+
self.cleanup()
|
|
57
|
+
|
|
58
|
+
def cleanup(self):
|
|
59
|
+
return cleanup_directory(self.root, self.clock())
|
|
60
|
+
|
|
61
|
+
def path(self, media_id, expiry, suffix='data'):
|
|
62
|
+
if not re.fullmatch(r'[A-Za-z0-9_-]{32}', media_id):
|
|
63
|
+
raise HTTPException(404, 'Temporary media unavailable.')
|
|
64
|
+
return self.root / f'{int(expiry)}-{media_id}.{suffix}'
|
|
65
|
+
|
|
66
|
+
def reserve(self, db, connection_id, owner, body):
|
|
67
|
+
# Allocation accounting survives credential deletion and cancelled uploads.
|
|
68
|
+
# Keep reservations charged until expiry even after early deletion, so an
|
|
69
|
+
# unlinked but still open upload FD cannot bypass disk admission.
|
|
70
|
+
db.execute('DELETE FROM saas_media_allocations WHERE expires<=?',(self.clock(),))
|
|
71
|
+
total=db.execute('SELECT coalesce(sum(size),0) FROM saas_media_allocations').fetchone()[0]
|
|
72
|
+
own,count=db.execute('SELECT coalesce(sum(size),0),count(*) FROM saas_media_allocations WHERE user_id=?',(owner['user_id'],)).fetchone()
|
|
73
|
+
if count>=10 or own+body.size>MAX_OWNER:
|
|
74
|
+
raise HTTPException(429,'media_quota: Wait for your temporary files to expire.')
|
|
75
|
+
if total+body.size>MAX_TOTAL or shutil.disk_usage(self.root).free < body.size+256*1024*1024:
|
|
76
|
+
raise HTTPException(503,'media_capacity: Temporary media storage is busy.')
|
|
77
|
+
media_id=secrets.token_urlsafe(24);download=secrets.token_urlsafe(32)
|
|
78
|
+
expiry=math.floor(self.clock())+TTL
|
|
79
|
+
payload=body.model_dump() | {'user_id':owner['user_id'],'connection_id':connection_id,
|
|
80
|
+
'grant_id':owner['grant_id'],'installation_id':owner['installation_id'],
|
|
81
|
+
'download_hash':hashlib.sha256(download.encode()).hexdigest(),'state':'reserved'}
|
|
82
|
+
db.execute('INSERT INTO saas_media_allocations VALUES(?,?,?,?)',(media_id,owner['user_id'],body.size,expiry))
|
|
83
|
+
self.vault.put(db,'saas-media',media_id,payload,expires=expiry)
|
|
84
|
+
return media_id,download,expiry
|
|
85
|
+
|
|
86
|
+
def checked(self, db, media_id, connection_id=None):
|
|
87
|
+
record=self.vault.get(db,'saas-media',media_id)
|
|
88
|
+
if record is None or record['expires']<=self.clock():
|
|
89
|
+
raise HTTPException(404,'Temporary media expired or unavailable.')
|
|
90
|
+
if connection_id and record['payload']['connection_id']!=connection_id:
|
|
91
|
+
raise HTTPException(404,'Temporary media unavailable.')
|
|
92
|
+
return record
|
|
93
|
+
|
|
94
|
+
def remove(self,media_id,expiry):
|
|
95
|
+
for suffix in ('part','data'):
|
|
96
|
+
self.path(media_id,expiry,suffix).unlink(missing_ok=True)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
async def settled_thread(function, *args):
|
|
100
|
+
"""Cancellation cannot outlive a worker touching an upload FD or transaction."""
|
|
101
|
+
task=asyncio.create_task(asyncio.to_thread(function,*args))
|
|
102
|
+
cancelled=None
|
|
103
|
+
while True:
|
|
104
|
+
try:
|
|
105
|
+
result=await asyncio.shield(task)
|
|
106
|
+
break
|
|
107
|
+
except asyncio.CancelledError as exc:
|
|
108
|
+
cancelled=exc
|
|
109
|
+
if task.done():
|
|
110
|
+
# Retrieve a worker exception even when cancellation won the race.
|
|
111
|
+
try:task.result()
|
|
112
|
+
except BaseException:pass
|
|
113
|
+
raise cancelled
|
|
114
|
+
except BaseException:
|
|
115
|
+
if cancelled is not None:raise cancelled
|
|
116
|
+
raise
|
|
117
|
+
if cancelled is not None:raise cancelled
|
|
118
|
+
return result
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def install_media_routes(app, service, connections, origin):
|
|
122
|
+
vault=service.vault
|
|
123
|
+
app.state.temporary_media=service
|
|
124
|
+
|
|
125
|
+
def owner(db,connection_id,request,*,require_subscription=True):
|
|
126
|
+
record=connections.capability(db,connection_id,request)
|
|
127
|
+
if require_subscription:connections.allowed(db,record['payload']['user_id'])
|
|
128
|
+
if record['payload']['platform']!='instagram':
|
|
129
|
+
raise HTTPException(403,'Temporary hosting is available for Instagram connections only.')
|
|
130
|
+
return record['payload']
|
|
131
|
+
|
|
132
|
+
@app.post('/api/saas/v1/connections/{connection_id}/media',status_code=201)
|
|
133
|
+
def reserve(connection_id:str,body:Reservation,request:Request):
|
|
134
|
+
service.cleanup()
|
|
135
|
+
with vault.transaction() as db:
|
|
136
|
+
data=owner(db,connection_id,request)
|
|
137
|
+
if not service.metadata.admit(db,'media:'+data['user_id'],service.clock(),limit=20):
|
|
138
|
+
raise HTTPException(429,'Too many temporary uploads. Wait a minute.')
|
|
139
|
+
ident,secret,expiry=service.reserve(db,connection_id,data,body)
|
|
140
|
+
return {'version':1,'media_id':ident,'expires_at':expiry,
|
|
141
|
+
'upload_url':f'{origin}/api/saas/v1/connections/{connection_id}/media/{ident}',
|
|
142
|
+
'download_url':f'{origin}/media/{ident}/{secret}'}
|
|
143
|
+
|
|
144
|
+
@app.put('/api/saas/v1/connections/{connection_id}/media/{media_id}')
|
|
145
|
+
async def upload(connection_id:str,media_id:str,request:Request):
|
|
146
|
+
record=None
|
|
147
|
+
def claim():
|
|
148
|
+
nonlocal record
|
|
149
|
+
with vault.transaction() as db:
|
|
150
|
+
owner(db,connection_id,request)
|
|
151
|
+
candidate=service.checked(db,media_id,connection_id)
|
|
152
|
+
if candidate['payload']['state']!='reserved':
|
|
153
|
+
raise HTTPException(409,'Upload already attempted. Reserve a new temporary file.')
|
|
154
|
+
record=candidate
|
|
155
|
+
record['payload']['state']='uploading'
|
|
156
|
+
vault.put(db,'saas-media',media_id,record['payload'],expires=record['expires'])
|
|
157
|
+
return record
|
|
158
|
+
try:
|
|
159
|
+
await settled_thread(claim)
|
|
160
|
+
partial=service.path(media_id,record['expires'],'part')
|
|
161
|
+
complete=service.path(media_id,record['expires'])
|
|
162
|
+
payload=record['payload'];size=0;digest=hashlib.sha256()
|
|
163
|
+
async with asyncio.timeout(min(300,max(0,record['expires']-service.clock()))):
|
|
164
|
+
fd=os.open(partial,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
|
|
165
|
+
with os.fdopen(fd,'wb') as output:
|
|
166
|
+
async for chunk in request.stream():
|
|
167
|
+
size+=len(chunk)
|
|
168
|
+
if size>payload['size'] or service.clock()>=record['expires']:
|
|
169
|
+
raise HTTPException(413,'Temporary upload exceeded its size or time limit.')
|
|
170
|
+
digest.update(chunk)
|
|
171
|
+
for offset in range(0,len(chunk),65536):
|
|
172
|
+
if service.clock()>=record['expires']:
|
|
173
|
+
raise HTTPException(408,'Temporary upload expired.')
|
|
174
|
+
await settled_thread(output.write,chunk[offset:offset+65536])
|
|
175
|
+
if size!=payload['size'] or digest.hexdigest()!=payload['sha256']:
|
|
176
|
+
raise HTTPException(400,'Temporary upload does not match its declared bytes.')
|
|
177
|
+
def finish():
|
|
178
|
+
with vault.transaction() as db:
|
|
179
|
+
owner(db,connection_id,request)
|
|
180
|
+
current=service.checked(db,media_id,connection_id)
|
|
181
|
+
if current['payload']['state']!='uploading':raise HTTPException(409,'Upload changed.')
|
|
182
|
+
os.replace(partial,complete)
|
|
183
|
+
current['payload']['state']='ready'
|
|
184
|
+
vault.put(db,'saas-media',media_id,current['payload'],expires=current['expires'])
|
|
185
|
+
await settled_thread(finish)
|
|
186
|
+
except BaseException:
|
|
187
|
+
if record is not None:
|
|
188
|
+
def discard():
|
|
189
|
+
# All our workers and the writer FD have settled. Serialize
|
|
190
|
+
# with DELETE/finish, remove paths first, then release charge.
|
|
191
|
+
with vault.transaction() as db:
|
|
192
|
+
service.remove(media_id,record['expires'])
|
|
193
|
+
vault.delete(db,'saas-media',media_id)
|
|
194
|
+
db.execute('DELETE FROM saas_media_allocations WHERE id=?',(media_id,))
|
|
195
|
+
await settled_thread(discard)
|
|
196
|
+
raise
|
|
197
|
+
return {'version':1,'status':'ready','expires_at':record['expires']}
|
|
198
|
+
|
|
199
|
+
@app.delete('/api/saas/v1/connections/{connection_id}/media/{media_id}')
|
|
200
|
+
def delete(connection_id:str,media_id:str,request:Request):
|
|
201
|
+
with vault.transaction() as db:
|
|
202
|
+
owner(db,connection_id,request,require_subscription=False)
|
|
203
|
+
record=service.checked(db,media_id,connection_id)
|
|
204
|
+
service.remove(media_id,record['expires'])
|
|
205
|
+
vault.delete(db,'saas-media',media_id)
|
|
206
|
+
return {'version':1,'status':'deleted'}
|
|
207
|
+
|
|
208
|
+
@app.api_route('/media/{media_id}/{download}',methods=['GET','HEAD'])
|
|
209
|
+
def download(media_id:str,download:str,request:Request):
|
|
210
|
+
with vault.read_transaction() as db:
|
|
211
|
+
record=service.checked(db,media_id);data=record['payload']
|
|
212
|
+
grant=vault.get(db,'saas-grant',data['grant_id'])
|
|
213
|
+
installation=vault.get(db,'saas-installation',data['installation_id'])
|
|
214
|
+
if not connections.access.decision(db,data['user_id'],service.clock()).allowed:
|
|
215
|
+
raise HTTPException(404,'Temporary media unavailable.')
|
|
216
|
+
if (data['state']!='ready' or not hmac.compare_digest(data['download_hash'],hashlib.sha256(download.encode()).hexdigest())
|
|
217
|
+
or grant is None or grant['expires']<=service.clock()
|
|
218
|
+
or installation is None or installation['expires']<=service.clock()):
|
|
219
|
+
raise HTTPException(404,'Temporary media unavailable.')
|
|
220
|
+
path=service.path(media_id,record['expires'])
|
|
221
|
+
if not path.is_file() or path.is_symlink():raise HTTPException(404,'Temporary media unavailable.')
|
|
222
|
+
size=data['size'];start=0;end=size-1;status=200
|
|
223
|
+
headers={'Accept-Ranges':'bytes','Content-Disposition':'inline; filename="media'+KINDS[data['content_type']]+'"'}
|
|
224
|
+
requested=request.headers.get('range')
|
|
225
|
+
if requested:
|
|
226
|
+
match=re.fullmatch(r'bytes=([0-9]*)-([0-9]*)',requested)
|
|
227
|
+
if not match or not any(match.groups()):raise HTTPException(416,'Invalid media range.',headers={'Content-Range':f'bytes */{size}'})
|
|
228
|
+
if match[1]:start=int(match[1]);end=min(int(match[2]),end) if match[2] else end
|
|
229
|
+
else:start=max(0,size-int(match[2]))
|
|
230
|
+
if start>end:raise HTTPException(416,'Invalid media range.',headers={'Content-Range':f'bytes */{size}'})
|
|
231
|
+
status=206;headers['Content-Range']=f'bytes {start}-{end}/{size}'
|
|
232
|
+
headers['Content-Length']=str(end-start+1)
|
|
233
|
+
if request.method=='HEAD':return Response(status_code=status,media_type=data['content_type'],headers=headers)
|
|
234
|
+
def content():
|
|
235
|
+
try:
|
|
236
|
+
with path.open('rb') as stream:
|
|
237
|
+
stream.seek(start);remaining=end-start+1
|
|
238
|
+
while remaining>0 and service.clock()<record['expires']:
|
|
239
|
+
chunk=stream.read(min(65536,remaining))
|
|
240
|
+
if not chunk:break
|
|
241
|
+
remaining-=len(chunk)
|
|
242
|
+
yield chunk
|
|
243
|
+
except FileNotFoundError:
|
|
244
|
+
return
|
|
245
|
+
return StreamingResponse(content(),status_code=status,media_type=data['content_type'],headers=headers)
|