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
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Versioned, browser-owner consent; agent credentials never create receipts.
|
|
2
|
+
|
|
3
|
+
Bump the respective version for a material policy or assistant-transfer change.
|
|
4
|
+
Previously issued provider credentials cannot be recalled by this broker gate.
|
|
5
|
+
"""
|
|
6
|
+
from fastapi import HTTPException
|
|
7
|
+
|
|
8
|
+
PRIVACY_VERSION = '2026-10-15'
|
|
9
|
+
ASSISTANT_VERSION = '2026-10-15'
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def privacy_accepted(metadata, db, user_id):
|
|
13
|
+
record = metadata.vault.get(db, 'saas-consent', user_id)
|
|
14
|
+
return bool(record and record['payload'].get('user_id') == user_id
|
|
15
|
+
and record['payload'].get('privacy_version') == PRIVACY_VERSION)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def require_privacy(metadata, db, user_id):
|
|
19
|
+
if not privacy_accepted(metadata, db, user_id):
|
|
20
|
+
raise HTTPException(403, 'privacy_acceptance_required: The account owner must review the current Privacy Policy in their SocialCli browser account. An assistant cannot accept for the owner.')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def privacy_choice(data, *, required=True):
|
|
24
|
+
accepted = data.get('privacy_accept') == '1'
|
|
25
|
+
if (required or accepted) and (not accepted or data.get('privacy_version') != PRIVACY_VERSION):
|
|
26
|
+
raise HTTPException(400, 'Review the current Privacy Policy and explicitly accept it to enable features.')
|
|
27
|
+
return accepted
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def accept_privacy(metadata, db, user_id, now):
|
|
31
|
+
metadata.vault.put(db, 'saas-consent', user_id,
|
|
32
|
+
{'user_id': user_id, 'privacy_version': PRIVACY_VERSION,
|
|
33
|
+
'accepted_at': now, 'source': 'owner_browser'}, expires=253402300799)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def assistant_choice(data, now):
|
|
37
|
+
if data.get('assistant_accept') != '1' or data.get('assistant_version') != ASSISTANT_VERSION:
|
|
38
|
+
raise HTTPException(400, 'Review and explicitly acknowledge the assistant data access and provider settings before linking.')
|
|
39
|
+
return {'version': ASSISTANT_VERSION, 'accepted_at': now, 'source': 'owner_browser'}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def require_assistant(payload):
|
|
43
|
+
receipt = payload.get('assistant_consent')
|
|
44
|
+
if not isinstance(receipt, dict) or receipt.get('version') != ASSISTANT_VERSION:
|
|
45
|
+
raise HTTPException(403, 'assistant_consent_required: The account owner must revoke and link this assistant again in their browser to review data access and provider settings.')
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def require_legacy(payload):
|
|
49
|
+
receipt=payload.get('privacy_consent')
|
|
50
|
+
if not isinstance(receipt,dict) or receipt.get('version')!=PRIVACY_VERSION:
|
|
51
|
+
raise HTTPException(403,'privacy_acceptance_required: The owner must sign in to the current SocialCli browser flow and review the Privacy Policy before using this connection.')
|
|
52
|
+
require_assistant(payload)
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
"""Immediate local revocation and durable, owner-bound external deletion jobs."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import secrets
|
|
4
|
+
from html import escape
|
|
5
|
+
from urllib.parse import quote
|
|
6
|
+
from fastapi import HTTPException,Request
|
|
7
|
+
from fastapi.responses import HTMLResponse,RedirectResponse
|
|
8
|
+
from socialctl.saas import pages, permissions
|
|
9
|
+
from socialctl.saas.auth import IdentityError,IdentityUnavailable
|
|
10
|
+
from socialctl.saas.routes import read_form
|
|
11
|
+
from socialctl.saas.budget import WorkBudget,using_budget
|
|
12
|
+
from socialctl.saas import revocation
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AccountLifecycle:
|
|
16
|
+
def __init__(self,metadata,clock):
|
|
17
|
+
self.metadata,self.vault,self.clock=metadata,metadata.vault,clock
|
|
18
|
+
|
|
19
|
+
def expandable_installation(self,db,user_id,installation_id):
|
|
20
|
+
record=self.vault.get(db,'saas-installation',installation_id)
|
|
21
|
+
if (record is None or record['expires']<=self.clock()
|
|
22
|
+
or record['payload'].get('user_id')!=user_id):
|
|
23
|
+
raise HTTPException(404,'Assistant unavailable.')
|
|
24
|
+
from socialctl.saas import consent
|
|
25
|
+
consent.require_privacy(self.metadata,db,user_id)
|
|
26
|
+
consent.require_assistant(record['payload'])
|
|
27
|
+
try:permissions.approved(record['payload'])
|
|
28
|
+
except ValueError:
|
|
29
|
+
raise HTTPException(403,'installation_permissions_invalid: Revoke and link this assistant again.') from None
|
|
30
|
+
return record
|
|
31
|
+
|
|
32
|
+
def add_platforms(self,db,user_id,installation_id,additions):
|
|
33
|
+
record=self.expandable_installation(db,user_id,installation_id)
|
|
34
|
+
current=permissions.approved(record['payload'])
|
|
35
|
+
# Additive inside one transaction: a stale form cannot remove a platform
|
|
36
|
+
# or overwrite an addition approved in another tab.
|
|
37
|
+
record['payload']['platform_access']=permissions.policy(set(current)|set(additions))
|
|
38
|
+
self.vault.put(db,'saas-installation',installation_id,record['payload'],
|
|
39
|
+
expires=record['expires'],credential_hash=record['credential_hash'])
|
|
40
|
+
|
|
41
|
+
def owned_records(self,db,user_id,*,kinds=None):
|
|
42
|
+
owned=[]
|
|
43
|
+
query='SELECT kind,id FROM saas_record_owners WHERE user_id=?'
|
|
44
|
+
params=[user_id]
|
|
45
|
+
if kinds:
|
|
46
|
+
query+=' AND kind IN ('+','.join('?' for _ in kinds)+')'
|
|
47
|
+
params.extend(kinds)
|
|
48
|
+
rows=db.execute(query,params).fetchall()
|
|
49
|
+
for row in rows:
|
|
50
|
+
record=self.vault.get(db,row['kind'],row['id'])
|
|
51
|
+
if record is None:continue
|
|
52
|
+
data=record['payload']
|
|
53
|
+
if data.get('user_id')==user_id or data.get('saas',{}).get('user_id')==user_id:
|
|
54
|
+
owned.append((row['kind'],row['id'],record))
|
|
55
|
+
return owned
|
|
56
|
+
|
|
57
|
+
def revoke(self,db,user_id,installation_id):
|
|
58
|
+
record=self.vault.get(db,'saas-installation',installation_id)
|
|
59
|
+
if record is None or record['payload']['user_id']!=user_id:
|
|
60
|
+
raise HTTPException(404,'Assistant unavailable.')
|
|
61
|
+
self.vault.delete(db,'saas-installation',installation_id)
|
|
62
|
+
for kind,record_id,entry in self.owned_records(db,user_id):
|
|
63
|
+
data=entry['payload']
|
|
64
|
+
if data.get('installation_id')==installation_id or data.get('saas',{}).get('installation_id')==installation_id:
|
|
65
|
+
self.vault.delete(db,kind,record_id)
|
|
66
|
+
|
|
67
|
+
def disconnect(self,db,user_id,platform):
|
|
68
|
+
slot=db.execute('SELECT grant_id FROM saas_slots WHERE user_id=? AND platform=?',(user_id,platform)).fetchone()
|
|
69
|
+
if not slot:raise HTTPException(404,'Connection unavailable.')
|
|
70
|
+
return self.disconnect_grant(db,user_id,platform,slot['grant_id'])
|
|
71
|
+
|
|
72
|
+
def disconnect_grant(self,db,user_id,platform,grant_id):
|
|
73
|
+
record=self.vault.get(db,'saas-grant',grant_id)
|
|
74
|
+
job=None
|
|
75
|
+
if record:
|
|
76
|
+
if record['payload'].get('user_id')!=user_id:
|
|
77
|
+
raise HTTPException(404,'Connection unavailable.')
|
|
78
|
+
job=revocation.enqueue(self.metadata,db,grant_id,record['payload'],self.clock())
|
|
79
|
+
if platform=='youtube' and record['payload'].get('refresh_lease'):
|
|
80
|
+
revocation.reserve(db,grant_id+':refresh:'+record['payload']['refresh_lease'],user_id,self.clock())
|
|
81
|
+
else:
|
|
82
|
+
revocation.tombstone(db,'grant',grant_id,self.clock())
|
|
83
|
+
current=db.execute('SELECT grant_id FROM saas_slots WHERE user_id=? AND platform=?',(user_id,platform)).fetchone()
|
|
84
|
+
disconnected_account = (record['payload'].get('account') or {}).get('id') if record else None
|
|
85
|
+
for kind,record_id,entry in self.owned_records(db,user_id):
|
|
86
|
+
data=entry['payload']
|
|
87
|
+
# A pre-disconnect OAuth result cannot reinstall an authorization we
|
|
88
|
+
# just revoked. A stale capability must not cancel a newer connection.
|
|
89
|
+
pending=(current is not None and current['grant_id']==grant_id and
|
|
90
|
+
platform=='youtube' and data.get('platform')=='youtube' and
|
|
91
|
+
kind in {'saas-candidate','authorization'})
|
|
92
|
+
if pending:
|
|
93
|
+
# Fence a provider exchange that has started but has not returned
|
|
94
|
+
# a credential yet. Its late result still needs revocation.
|
|
95
|
+
if kind=='authorization' and data.get('status')=='exchanging':
|
|
96
|
+
revocation.reserve(db,record_id,user_id,self.clock())
|
|
97
|
+
payload={**data,'user_id':user_id}
|
|
98
|
+
if kind=='authorization':payload['grant']=data.get('result',{}).get('grant')
|
|
99
|
+
if payload.get('grant'):
|
|
100
|
+
revocation.enqueue(self.metadata,db,record_id,payload,self.clock())
|
|
101
|
+
operation_history = (current is not None and current['grant_id']==grant_id
|
|
102
|
+
and disconnected_account is not None
|
|
103
|
+
and kind in {'saas-meta-operation','saas-meta-target'}
|
|
104
|
+
and data.get('platform')==platform and data.get('account_id')==disconnected_account)
|
|
105
|
+
if pending or operation_history or data.get('grant_id')==grant_id or kind=='saas-grant' and record_id==grant_id:
|
|
106
|
+
self.vault.delete(db,kind,record_id)
|
|
107
|
+
db.execute('DELETE FROM saas_slots WHERE user_id=? AND platform=? AND grant_id=?',(user_id,platform,grant_id))
|
|
108
|
+
self.release_empty_brand(db,user_id)
|
|
109
|
+
return job
|
|
110
|
+
|
|
111
|
+
def release_empty_brand(self,db,user_id):
|
|
112
|
+
db.execute('DELETE FROM saas_brands WHERE user_id=? AND NOT EXISTS (SELECT 1 FROM saas_slots WHERE user_id=?)',(user_id,user_id))
|
|
113
|
+
|
|
114
|
+
def rename_brand(self,db,user_id,label):
|
|
115
|
+
label=label.strip()
|
|
116
|
+
if not label or len(label)>80 or any(ord(c)<32 or ord(c)==127 for c in label):
|
|
117
|
+
raise HTTPException(400,'Enter a brand name of 1–80 characters without control characters.')
|
|
118
|
+
if not db.execute('UPDATE saas_brands SET label=? WHERE user_id=?',(label,user_id)).rowcount:
|
|
119
|
+
raise HTTPException(404,'Connect a social account before renaming your brand.')
|
|
120
|
+
# Pending authorizations retain their reviewed label and cannot silently
|
|
121
|
+
# activate under the new name. Existing capabilities use stable grant IDs.
|
|
122
|
+
|
|
123
|
+
def request_delete(self,user_id):
|
|
124
|
+
with self.vault.transaction() as db:
|
|
125
|
+
user=self.metadata.user(db,user_id)
|
|
126
|
+
if user is None:raise HTTPException(404,'Account unavailable.')
|
|
127
|
+
if user['deleting']:return
|
|
128
|
+
revocation.tombstone(db,'user',user_id,self.clock())
|
|
129
|
+
for kind,record_id,entry in self.owned_records(db,user_id,kinds=('saas-grant','saas-candidate','authorization')):
|
|
130
|
+
payload=entry['payload']
|
|
131
|
+
if payload.get('platform')=='youtube':
|
|
132
|
+
if kind=='authorization' and payload.get('status')=='exchanging':
|
|
133
|
+
revocation.reserve(db,record_id,user_id,self.clock())
|
|
134
|
+
if kind=='saas-grant' and payload.get('refresh_lease'):
|
|
135
|
+
revocation.reserve(db,record_id+':refresh:'+payload['refresh_lease'],user_id,self.clock())
|
|
136
|
+
if kind=='authorization':
|
|
137
|
+
payload={**payload, 'user_id':user_id, 'grant':payload.get('result',{}).get('grant')}
|
|
138
|
+
if payload.get('grant'):
|
|
139
|
+
revocation.enqueue(self.metadata,db,record_id,payload,self.clock())
|
|
140
|
+
db.execute('UPDATE saas_users SET deleting=1,session_version=session_version+1 WHERE id=?',(user_id,))
|
|
141
|
+
db.execute('INSERT OR IGNORE INTO saas_deletions(user_id,requested) VALUES(?,?)',(user_id,self.clock()))
|
|
142
|
+
# Historical approved pairs may lack user_id. Their installation link
|
|
143
|
+
# proves ownership; unclaimed pairs have no such link and are preserved.
|
|
144
|
+
db.execute("""DELETE FROM records WHERE kind='saas-pair' AND id IN (
|
|
145
|
+
SELECT link.id FROM saas_record_links link JOIN saas_record_owners owner
|
|
146
|
+
ON owner.kind='saas-installation' AND owner.id=link.installation_id
|
|
147
|
+
WHERE link.kind='saas-pair' AND owner.user_id=?)""",(user_id,))
|
|
148
|
+
db.execute("""DELETE FROM records WHERE kind='saas-login' AND id IN (
|
|
149
|
+
SELECT attempt.id FROM saas_record_emails attempt JOIN saas_record_emails identity
|
|
150
|
+
ON identity.email_hash=attempt.email_hash
|
|
151
|
+
WHERE attempt.kind='saas-login' AND identity.kind='saas-user' AND identity.id=?)""",(user_id,))
|
|
152
|
+
db.execute("""DELETE FROM records WHERE (kind,id) IN (
|
|
153
|
+
SELECT kind,id FROM saas_record_owners WHERE user_id=?)""",(user_id,))
|
|
154
|
+
self.vault.delete(db,'saas-user',user_id)
|
|
155
|
+
db.execute('DELETE FROM saas_slots WHERE user_id=?',(user_id,))
|
|
156
|
+
db.execute('DELETE FROM saas_brands WHERE user_id=?',(user_id,))
|
|
157
|
+
# Keep only eligibility markers and minimal billing IDs until cleanup.
|
|
158
|
+
db.execute('DELETE FROM saas_entitlements WHERE user_id=?',(user_id,))
|
|
159
|
+
|
|
160
|
+
def prune_expired(self):
|
|
161
|
+
with self.vault.transaction() as db:
|
|
162
|
+
# Capture expired Google grants before generic expiry discards their
|
|
163
|
+
# only revocation token. Live records are never decrypted by pruning.
|
|
164
|
+
for row in db.execute("SELECT id FROM records WHERE kind='saas-grant' AND expires<=?",(self.clock(),)).fetchall():
|
|
165
|
+
entry=self.vault.get(db,'saas-grant',row['id'])
|
|
166
|
+
revocation.enqueue(self.metadata,db,row['id'],entry['payload'],self.clock())
|
|
167
|
+
self.vault.delete(db,'saas-grant',row['id'])
|
|
168
|
+
self.vault.purge(db,now=self.clock())
|
|
169
|
+
db.execute('DELETE FROM saas_deletion_tombstones WHERE requested<?',(self.clock()-30*86400,))
|
|
170
|
+
db.execute("DELETE FROM saas_google_revocations WHERE state='complete' AND requested<?",(self.clock()-30*86400,))
|
|
171
|
+
db.execute("""DELETE FROM saas_slots WHERE NOT EXISTS (
|
|
172
|
+
SELECT 1 FROM records WHERE kind='saas-grant' AND id=saas_slots.grant_id)""")
|
|
173
|
+
db.execute("""DELETE FROM records WHERE kind='saas-capability' AND id IN (
|
|
174
|
+
SELECT link.id FROM saas_record_links link
|
|
175
|
+
JOIN saas_record_owners owner ON owner.kind=link.kind AND owner.id=link.id
|
|
176
|
+
LEFT JOIN records grant_record ON grant_record.kind='saas-grant' AND grant_record.id=link.grant_id
|
|
177
|
+
LEFT JOIN records installation ON installation.kind='saas-installation' AND installation.id=link.installation_id
|
|
178
|
+
WHERE link.kind='saas-capability' AND (grant_record.id IS NULL OR installation.id IS NULL))""")
|
|
179
|
+
db.execute('DELETE FROM saas_brands WHERE NOT EXISTS (SELECT 1 FROM saas_slots WHERE saas_slots.user_id=saas_brands.user_id)')
|
|
180
|
+
db.execute('DELETE FROM saas_rates WHERE expires<=?',(self.clock(),))
|
|
181
|
+
db.execute('DELETE FROM saas_media_allocations WHERE expires<=?',(self.clock(),))
|
|
182
|
+
db.execute('DELETE FROM saas_trial_markers WHERE retain_until<=?',(self.clock(),))
|
|
183
|
+
|
|
184
|
+
def panel(self,user_id,csrf):
|
|
185
|
+
with self.vault.read_transaction() as db:
|
|
186
|
+
records=self.owned_records(db,user_id,kinds=('saas-grant','saas-installation'))
|
|
187
|
+
brand=db.execute('SELECT label FROM saas_brands WHERE user_id=?',(user_id,)).fetchone()
|
|
188
|
+
pending=db.execute("SELECT count(*) FROM saas_google_revocations WHERE user_id=? AND state='pending'",(user_id,)).fetchone()[0]
|
|
189
|
+
connections=[];installations=[]
|
|
190
|
+
for kind,record_id,record in records:
|
|
191
|
+
data=record['payload']
|
|
192
|
+
if kind=='saas-grant':
|
|
193
|
+
from socialctl.saas.renewal import notice
|
|
194
|
+
label=escape(data['account'].get('name',data['account']['id']))
|
|
195
|
+
platform=escape(data['platform'],quote=True)
|
|
196
|
+
message=('This SocialCli connection expired after inactivity. Ask your assistant to help you connect again.'
|
|
197
|
+
if record['expires']<=self.clock() else notice(data,self.clock()))
|
|
198
|
+
diagnostic=f'<p class="status-notice">{escape(message)}</p>' if message else ''
|
|
199
|
+
connections.append(f'<li><strong>{label}</strong><p>{platform.title()} · {escape(data["account"]["id"])}</p>{diagnostic}<form method="post" action="/account/connections/{platform}/disconnect">{pages.hidden("csrf",csrf)}<button class="secondary-button" type="submit">Disconnect {platform.title()}</button></form></li>')
|
|
200
|
+
elif kind=='saas-installation':
|
|
201
|
+
label=escape(data['label']);rid=escape(record_id,quote=True)
|
|
202
|
+
expired=' · Expired' if record['expires']<=self.clock() else ''
|
|
203
|
+
add_link=(f'<a class="text-link" href="/account/installations/{rid}/platforms">Add social platforms</a>' if not expired else '')
|
|
204
|
+
installations.append(f'<li><strong>{label}{expired}</strong>{permissions.summary_html(data)}{add_link}<form method="post" action="/account/installations/{rid}/revoke">{pages.hidden("csrf",csrf)}<button class="secondary-button" type="submit">Revoke assistant</button></form></li>')
|
|
205
|
+
brand_panel=(f'<section aria-label="Brand"><h2>Brand</h2><form method="post" action="/account/brand" class="form-stack">{pages.hidden("csrf",csrf)}<label for="brand">Brand name</label><input id="brand" name="brand" maxlength="80" required value="{escape(brand["label"],quote=True)}"><button class="secondary-button" type="submit">Rename brand</button></form><p class="expiry-note">Existing connections stay active. Use this name when connecting another network; update your assistant’s local brand name separately.</p></section>' if brand else '')
|
|
206
|
+
pending_notice='<p class="status-notice">Your Google connection is blocked in SocialCli. Google authorization cleanup is pending and retries automatically. An interrupted request whose credential has not arrived may require operator review. Connect again after cleanup completes.</p>' if pending else ''
|
|
207
|
+
return brand_panel+pending_notice+'<section aria-label="Connected accounts"><h2>Connected accounts</h2>'+('<ul class="account-list">'+''.join(connections)+'</ul>' if connections else '<p class="description">No social accounts connected yet. Ask your assistant to connect your account.</p>')+'</section><section aria-label="Assistants"><h2>Assistants</h2>'+('<ul class="account-list">'+''.join(installations)+'</ul>' if installations else '<p class="description">No assistants linked yet.</p>')+'<p class="expiry-note">Selections control access to SocialCli connections. They do not narrow provider permissions, including permissions for linked accounts or individual actions. Previously issued provider tokens may remain usable until they expire or are revoked at the provider. Use Add social platforms to approve additional access without disconnecting existing accounts. To remove platform access, revoke the assistant and link it again.</p></section><a class="text-link" href="/account/delete">Delete my account</a>'
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def run_deletions(metadata,identity,billing,clock,limit=100,*,budget=None):
|
|
211
|
+
with using_budget(budget,identity,billing):
|
|
212
|
+
return _run_deletions(metadata,identity,billing,clock,limit,budget)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _run_deletions(metadata,identity,billing,clock,limit,budget):
|
|
216
|
+
completed=0;pending=0;vault=metadata.vault
|
|
217
|
+
with vault.transaction() as db:
|
|
218
|
+
jobs=[dict(r) for r in db.execute("SELECT * FROM saas_deletions WHERE state='pending' AND next_attempt<=? AND lease_until<=? ORDER BY next_attempt,requested LIMIT ?",(clock(),clock(),limit))]
|
|
219
|
+
for job in jobs:
|
|
220
|
+
if budget and budget.expired():break
|
|
221
|
+
user_id=job['user_id'];token=secrets.token_hex(20)
|
|
222
|
+
with vault.transaction() as db:
|
|
223
|
+
claimed=db.execute("UPDATE saas_deletions SET lease=?,lease_until=? WHERE user_id=? AND state='pending' AND lease_until<=? AND next_attempt<=?",(token,clock()+300,user_id,clock(),clock())).rowcount
|
|
224
|
+
row=db.execute('SELECT * FROM saas_billing WHERE user_id=?',(user_id,)).fetchone()
|
|
225
|
+
billing_row=dict(row) if row else None
|
|
226
|
+
if not claimed:continue
|
|
227
|
+
try:
|
|
228
|
+
if not job['billing_done']:
|
|
229
|
+
if billing_row and (billing_row['customer_id'] or billing_row['customer_started']):
|
|
230
|
+
if billing is None:raise IdentityUnavailable()
|
|
231
|
+
billing.delete_account_billing(user_id,billing_row)
|
|
232
|
+
with vault.transaction() as db:
|
|
233
|
+
db.execute('UPDATE saas_deletions SET billing_done=1 WHERE user_id=? AND lease=?',(user_id,token))
|
|
234
|
+
identity.delete_user(user_id)
|
|
235
|
+
with vault.transaction() as db:
|
|
236
|
+
current=db.execute('SELECT lease FROM saas_deletions WHERE user_id=?',(user_id,)).fetchone()
|
|
237
|
+
if current is None or current['lease']!=token:continue
|
|
238
|
+
current_billing=db.execute('SELECT * FROM saas_billing WHERE user_id=?',(user_id,)).fetchone()
|
|
239
|
+
if current_billing and current_billing['customer_id']:
|
|
240
|
+
billing_row=dict(current_billing)
|
|
241
|
+
events=db.execute('SELECT account_id,mode,event_id FROM saas_billing_events WHERE customer_id=?',(billing_row['customer_id'],)).fetchall()
|
|
242
|
+
for event in events:vault.delete(db,'saas-stripe-event',':'.join(event))
|
|
243
|
+
db.execute('DELETE FROM saas_billing_events WHERE customer_id=?',(billing_row['customer_id'],))
|
|
244
|
+
db.execute('DELETE FROM saas_billing WHERE user_id=?',(user_id,))
|
|
245
|
+
db.execute('DELETE FROM saas_users WHERE id=?',(user_id,))
|
|
246
|
+
db.execute("UPDATE saas_deletions SET state='complete',lease=NULL,lease_until=0 WHERE user_id=?",(user_id,))
|
|
247
|
+
completed+=1
|
|
248
|
+
except (HTTPException,IdentityError,IdentityUnavailable):
|
|
249
|
+
with vault.transaction() as db:
|
|
250
|
+
db.execute("UPDATE saas_deletions SET lease=NULL,lease_until=0,next_attempt=? WHERE user_id=? AND lease=?",(clock()+300,user_id,token))
|
|
251
|
+
pending+=1
|
|
252
|
+
with vault.transaction() as db:
|
|
253
|
+
due=db.execute("SELECT count(*) FROM saas_deletions WHERE state='pending' AND next_attempt<=?",(clock(),)).fetchone()[0]
|
|
254
|
+
return {'completed':completed,'pending':pending,'due':due,
|
|
255
|
+
'budget_exhausted':bool(budget and budget.expired())}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def install_lifecycle_routes(app,settings,metadata,sessions,clock):
|
|
259
|
+
lifecycle=AccountLifecycle(metadata,clock)
|
|
260
|
+
app.state.saas_lifecycle=lifecycle
|
|
261
|
+
async def verified(request,purpose='saas-account'):
|
|
262
|
+
form=await read_form(request,settings.public_url)
|
|
263
|
+
app.state.saas_valid_form(request,form,purpose)
|
|
264
|
+
user=await asyncio.to_thread(sessions.require_user,request,privacy=False)
|
|
265
|
+
return user,form
|
|
266
|
+
|
|
267
|
+
@app.get('/account/installations/{installation_id}/platforms',response_class=HTMLResponse)
|
|
268
|
+
def platform_page(installation_id:str,request:Request):
|
|
269
|
+
url='/account/installations/'+quote(installation_id,safe='')+'/platforms'
|
|
270
|
+
try:user=sessions.require_user(request)
|
|
271
|
+
except HTTPException as exc:
|
|
272
|
+
if exc.status_code!=401:raise
|
|
273
|
+
return RedirectResponse('/account/login?next='+quote(url,safe=''),status_code=303)
|
|
274
|
+
with metadata.vault.read_transaction() as db:
|
|
275
|
+
record=lifecycle.expandable_installation(db,user.id,installation_id)
|
|
276
|
+
payload=record['payload'];current=permissions.approved(payload)
|
|
277
|
+
choices=''.join(f'<label for="allow-{p}"><input id="allow-{p}" type="checkbox" name="allow_{p}" value="1"> {escape(label)}</label>'
|
|
278
|
+
for p,label in permissions.PLATFORMS.items() if p not in current)
|
|
279
|
+
form=(f'<form method="post" action="{escape(url,quote=True)}" class="form-stack">'
|
|
280
|
+
+pages.hidden('csrf',app.state.saas_csrf(request,'platforms:'+installation_id))
|
|
281
|
+
+pages.hidden('platform_access_version','1')
|
|
282
|
+
+'<fieldset class="permission-options"><legend>Additional platforms to allow</legend>'+choices+'</fieldset>'
|
|
283
|
+
+'<button class="primary-button" type="submit">Allow selected platforms</button></form>') if choices else '<p>All social platforms are already allowed for this assistant.</p>'
|
|
284
|
+
content='<p class="eyebrow">ASSISTANT ACCESS</p><h1 id="page-title">Add social platforms</h1><p class="description">Assistant: '+escape(payload['label'])+'</p>'+permissions.summary_html(payload)+(
|
|
285
|
+
'<p class="description">Choose additional SocialCli connections this assistant may access. Existing accounts stay connected. This does not connect a new account, narrow provider permissions or approve any publication. Return to your assistant after saving to connect the new platform.</p>')+form+'<a class="text-link" href="/account/">Back to account</a>'
|
|
286
|
+
return HTMLResponse(pages.page('Add social platforms',content))
|
|
287
|
+
|
|
288
|
+
@app.post('/account/installations/{installation_id}/platforms')
|
|
289
|
+
async def add_platforms(installation_id:str,request:Request):
|
|
290
|
+
user,form=await verified(request,'platforms:'+installation_id)
|
|
291
|
+
additions=permissions.from_form(form)['platforms']
|
|
292
|
+
def commit():
|
|
293
|
+
with metadata.vault.transaction() as db:
|
|
294
|
+
lifecycle.add_platforms(db,user.id,installation_id,additions)
|
|
295
|
+
await asyncio.to_thread(commit)
|
|
296
|
+
return RedirectResponse('/account/',status_code=303)
|
|
297
|
+
|
|
298
|
+
@app.post('/account/installations/{installation_id}/revoke')
|
|
299
|
+
async def revoke(installation_id:str,request:Request):
|
|
300
|
+
user,_=await verified(request)
|
|
301
|
+
def commit():
|
|
302
|
+
with metadata.vault.transaction() as db:lifecycle.revoke(db,user.id,installation_id)
|
|
303
|
+
await asyncio.to_thread(commit)
|
|
304
|
+
return RedirectResponse('/account/',status_code=303)
|
|
305
|
+
|
|
306
|
+
@app.post('/account/connections/{platform}/disconnect')
|
|
307
|
+
async def disconnect(platform:str,request:Request):
|
|
308
|
+
user,_=await verified(request)
|
|
309
|
+
def commit():
|
|
310
|
+
with metadata.vault.transaction() as db:
|
|
311
|
+
job=lifecycle.disconnect(db,user.id,platform)
|
|
312
|
+
if job:
|
|
313
|
+
revocation.run_revocations(metadata,app.state.saas_connections.providers,clock,user_id=user.id,budget=WorkBudget(20))
|
|
314
|
+
await asyncio.to_thread(commit)
|
|
315
|
+
return RedirectResponse('/account/',status_code=303)
|
|
316
|
+
|
|
317
|
+
@app.post('/account/brand')
|
|
318
|
+
async def rename_brand(request:Request):
|
|
319
|
+
user,form=await verified(request)
|
|
320
|
+
def commit():
|
|
321
|
+
with metadata.vault.transaction() as db:lifecycle.rename_brand(db,user.id,form.get('brand',''))
|
|
322
|
+
await asyncio.to_thread(commit)
|
|
323
|
+
return RedirectResponse('/account/',status_code=303)
|
|
324
|
+
|
|
325
|
+
@app.get('/account/delete',response_class=HTMLResponse)
|
|
326
|
+
def delete_page(request:Request):
|
|
327
|
+
sessions.require_user(request,privacy=False)
|
|
328
|
+
return HTMLResponse(pages.page('Delete your account',f'''<p class="eyebrow">ACCOUNT SETTINGS</p><h1 id="page-title">Delete your account?</h1>
|
|
329
|
+
<p class="description">This immediately stops your assistants from using SocialCli and removes your saved social credentials. We will cancel future subscription billing and delete your sign-in account. Cleanup retries automatically if a service is temporarily unavailable.</p>
|
|
330
|
+
<p class="status-notice">Published posts stay on your social networks. Remove local SocialCli credentials from your assistants separately. Google authorization is revoked after local access is removed; temporary failures retry automatically. Other previously delivered provider tokens keep their own expiry. Required payment records stay with Stripe; a minimal free-trial eligibility marker is retained for 365 days.</p>
|
|
331
|
+
<form method="post" action="/account/delete" class="form-stack">{pages.hidden('csrf',app.state.saas_csrf(request,'saas-delete'))}<label for="confirmation">Type DELETE to confirm</label><input id="confirmation" name="confirmation" autocomplete="off" required pattern="DELETE"><button class="secondary-button" type="submit">Delete my account</button></form><a class="text-link" href="/account/">Keep my account</a>'''))
|
|
332
|
+
|
|
333
|
+
@app.post('/account/delete',response_class=HTMLResponse)
|
|
334
|
+
async def delete_account(request:Request):
|
|
335
|
+
user,form=await verified(request,'saas-delete')
|
|
336
|
+
if form.get('confirmation')!='DELETE':raise HTTPException(400,'Type DELETE to confirm account deletion.')
|
|
337
|
+
await asyncio.to_thread(lifecycle.request_delete,user.id)
|
|
338
|
+
await asyncio.to_thread(revocation.run_revocations,metadata,app.state.saas_connections.providers,clock,user_id=user.id,budget=WorkBudget(20))
|
|
339
|
+
response=HTMLResponse(pages.page('Deletion requested','<h1 id="page-title">Deletion requested</h1><p class="description">Your assistants no longer have access through SocialCli. Google authorization, subscription and sign-in cleanup will finish automatically. Remove the local credentials saved by your assistants.</p>'))
|
|
340
|
+
response.delete_cookie(sessions.cookie,path='/',secure=not settings.allow_http_local,httponly=True,samesite='lax')
|
|
341
|
+
return response
|
socialctl/saas/mail.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Verified STARTTLS SMTP, one recipient, with an explicit durable DATA fence."""
|
|
2
|
+
from dataclasses import dataclass,field
|
|
3
|
+
from email.headerregistry import Address
|
|
4
|
+
from email.policy import SMTP
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import smtplib
|
|
8
|
+
import ssl
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def mailbox(value):
|
|
12
|
+
if not isinstance(value,str) or not value.isascii() or any(ord(c)<33 or ord(c)==127 for c in value):
|
|
13
|
+
raise ValueError('Invalid mail recipient.')
|
|
14
|
+
try: address=Address(addr_spec=value)
|
|
15
|
+
except Exception: raise ValueError('Invalid mail recipient.') from None
|
|
16
|
+
if not address.username or not address.domain or address.addr_spec!=value:
|
|
17
|
+
raise ValueError('Invalid mail recipient.')
|
|
18
|
+
return value
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class MailSettings:
|
|
23
|
+
host:str
|
|
24
|
+
port:int
|
|
25
|
+
username:str=field(repr=False)
|
|
26
|
+
password:str=field(repr=False)
|
|
27
|
+
|
|
28
|
+
def __post_init__(self):
|
|
29
|
+
if (not re.fullmatch(r'[A-Za-z0-9.-]{1,253}',self.host) or not 1<=self.port<=65535
|
|
30
|
+
or not self.username or not self.password):
|
|
31
|
+
raise ValueError('Trial reminders require a valid private SMTP configuration.')
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def from_environment(cls):
|
|
35
|
+
if os.environ.get('SOCIALCLI_REMINDERS_ENABLED')!='1':return None
|
|
36
|
+
return cls(os.environ.get('SOCIALCLI_SMTP_HOST',''),int(os.environ.get('SOCIALCLI_SMTP_PORT','587')),
|
|
37
|
+
os.environ.get('SOCIALCLI_SMTP_USER',''),os.environ.get('SOCIALCLI_SMTP_PASSWORD',''))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def rejection(code):
|
|
41
|
+
return 'retry' if 400<=code<500 else 'rejected' if 500<=code<600 else 'uncertain'
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SMTPMailer:
|
|
45
|
+
def __init__(self,settings):
|
|
46
|
+
self.settings=settings
|
|
47
|
+
self.budget=None
|
|
48
|
+
|
|
49
|
+
def constrain(self,server):
|
|
50
|
+
if self.budget:
|
|
51
|
+
server.sock.settimeout(self.budget.timeout(20))
|
|
52
|
+
|
|
53
|
+
def send(self,recipient,message,before_send):
|
|
54
|
+
try:mailbox(recipient)
|
|
55
|
+
except ValueError:return 'rejected'
|
|
56
|
+
server=None;sending=False
|
|
57
|
+
try:
|
|
58
|
+
raw=message.as_bytes(policy=SMTP)
|
|
59
|
+
server=smtplib.SMTP(self.settings.host,self.settings.port,
|
|
60
|
+
timeout=self.budget.timeout(20) if self.budget else 20)
|
|
61
|
+
self.constrain(server)
|
|
62
|
+
code,_=server.ehlo()
|
|
63
|
+
if code!=250:return 'retry'
|
|
64
|
+
self.constrain(server)
|
|
65
|
+
server.starttls(context=ssl.create_default_context())
|
|
66
|
+
self.constrain(server)
|
|
67
|
+
code,_=server.ehlo()
|
|
68
|
+
if code!=250:return 'retry'
|
|
69
|
+
self.constrain(server)
|
|
70
|
+
server.login(self.settings.username,self.settings.password)
|
|
71
|
+
self.constrain(server)
|
|
72
|
+
code,_=server.mail('access@socialcli.app')
|
|
73
|
+
if code!=250:return 'retry' # sender configuration must be fixed by operator
|
|
74
|
+
self.constrain(server)
|
|
75
|
+
code,_=server.rcpt(recipient)
|
|
76
|
+
if code not in {250,251}:return rejection(code)
|
|
77
|
+
self.constrain(server)
|
|
78
|
+
if not before_send():return 'cancelled'
|
|
79
|
+
self.constrain(server)
|
|
80
|
+
sending=True
|
|
81
|
+
try:code,_=server.data(raw)
|
|
82
|
+
except smtplib.SMTPDataError as error:return rejection(error.smtp_code)
|
|
83
|
+
return 'accepted' if code==250 else rejection(code)
|
|
84
|
+
except Exception:
|
|
85
|
+
return 'uncertain' if sending else 'retry'
|
|
86
|
+
finally:
|
|
87
|
+
if server is not None:
|
|
88
|
+
try:server.close()
|
|
89
|
+
except Exception:pass # close cannot undo a received SMTP acceptance
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Isolated, one-shot SaaS billing maintenance; never runs publication jobs."""
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import sys
|
|
5
|
+
import time
|
|
6
|
+
import httpx
|
|
7
|
+
from socialctl.connection_service.settings import Settings
|
|
8
|
+
from socialctl.connection_service.store import Store
|
|
9
|
+
from socialctl.saas.store import SaaSStore
|
|
10
|
+
from socialctl.saas.billing import BillingService
|
|
11
|
+
from socialctl.saas.billing_reconcile import run_pending
|
|
12
|
+
from socialctl.saas.auth import SupabaseAuth
|
|
13
|
+
from socialctl.saas.lifecycle import AccountLifecycle,run_deletions
|
|
14
|
+
from socialctl.saas.revocation import run_revocations
|
|
15
|
+
from socialctl.connection_service.providers import Providers
|
|
16
|
+
from socialctl.saas.reminders import Reminders
|
|
17
|
+
from socialctl.saas.mail import SMTPMailer
|
|
18
|
+
from socialctl.saas.budget import WorkBudget,hard_deadline
|
|
19
|
+
from socialctl.saas.operations import write_heartbeat,inspect_status
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def run(settings):
|
|
23
|
+
metadata=SaaSStore(Store(settings.database,settings.encryption_keys),settings.encryption_keys)
|
|
24
|
+
with httpx.Client(timeout=20,follow_redirects=False) as client:
|
|
25
|
+
billing=BillingService(metadata,settings.saas.billing,client,time.time,settings.public_url) if settings.saas.billing else None
|
|
26
|
+
result=run_pending(billing,budget=WorkBudget(45)) if billing else {'processed':0,'retry_pending':0,'due':0}
|
|
27
|
+
AccountLifecycle(metadata,time.time).prune_expired()
|
|
28
|
+
result['google_revocations']=run_revocations(metadata,Providers(settings,client),time.time,budget=WorkBudget(45))
|
|
29
|
+
result['deletions']=run_deletions(metadata,SupabaseAuth(settings.saas,client),billing,time.time,budget=WorkBudget(45))
|
|
30
|
+
result['reminders']=Reminders(metadata,time.time,settings.public_url).run(
|
|
31
|
+
SMTPMailer(settings.saas.mail) if settings.saas.mail else None,budget=WorkBudget(45))
|
|
32
|
+
return result
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def main():
|
|
36
|
+
if sys.argv[1:]:
|
|
37
|
+
raise SystemExit('Usage: python -m socialctl.saas.maintenance')
|
|
38
|
+
for name in ('httpx','httpcore'):
|
|
39
|
+
logging.getLogger(name).disabled=True
|
|
40
|
+
settings=None
|
|
41
|
+
with hard_deadline():
|
|
42
|
+
try:
|
|
43
|
+
settings=Settings.from_environment()
|
|
44
|
+
if not settings.saas:raise ValueError('Identity is required.')
|
|
45
|
+
# Do not create a fresh database accidentally from a mistyped path.
|
|
46
|
+
if not settings.database.is_file():raise ValueError('Database is required.')
|
|
47
|
+
write_heartbeat(settings.database,'running',time.time())
|
|
48
|
+
result=run(settings)
|
|
49
|
+
attention=(result['retry_pending'] or result['due']
|
|
50
|
+
or result.get('google_revocations',{}).get('pending',0)
|
|
51
|
+
or result['deletions']['pending'] or result['deletions']['due']
|
|
52
|
+
or any(result['reminders'].get(key,0) for key in ('due','uncertain','rejected','retry_pending')))
|
|
53
|
+
write_heartbeat(settings.database,'attention' if attention else 'complete',time.time())
|
|
54
|
+
result['operations']=inspect_status(settings.database,settings.encryption_keys,now=time.time())
|
|
55
|
+
attention=attention or result['operations']['status']!='ok'
|
|
56
|
+
except Exception:
|
|
57
|
+
# Never print exception text: providers and SQL may include private data.
|
|
58
|
+
result={'status':'failed','error':'maintenance_failed'}
|
|
59
|
+
attention=True
|
|
60
|
+
if settings is not None and settings.database.is_file():
|
|
61
|
+
try:write_heartbeat(settings.database,'failed',time.time())
|
|
62
|
+
except Exception:pass
|
|
63
|
+
print(json.dumps(result))
|
|
64
|
+
if attention:raise SystemExit(1)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if __name__=='__main__':
|
|
68
|
+
main()
|