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,358 @@
|
|
|
1
|
+
"""Opt-in Meta callbacks: encrypted owner-bound hints, never social operations.
|
|
2
|
+
|
|
3
|
+
Enrollment only reads existing provider subscriptions. Account owners consent in
|
|
4
|
+
our browser; callback payloads cannot enroll accounts or perform social writes.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import hashlib
|
|
10
|
+
import hmac
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
from html import escape
|
|
16
|
+
|
|
17
|
+
from fastapi import HTTPException, Request
|
|
18
|
+
from fastapi.responses import HTMLResponse, PlainTextResponse, RedirectResponse
|
|
19
|
+
|
|
20
|
+
from socialctl.management.meta_client import GRAPH
|
|
21
|
+
from socialctl.management.meta_schema import MetaError
|
|
22
|
+
from socialctl.management.meta_webhooks import verify_challenge
|
|
23
|
+
from socialctl.media_registry import parse_json
|
|
24
|
+
from socialctl.saas import consent, pages
|
|
25
|
+
from socialctl.saas.routes import read_form
|
|
26
|
+
|
|
27
|
+
PATH = '/api/saas/v1/meta/webhook'
|
|
28
|
+
BINDING = 'saas-meta-webhook-binding'
|
|
29
|
+
EVENT = 'saas-meta-webhook-event'
|
|
30
|
+
RETENTION = 6 * 86400
|
|
31
|
+
LEASE = 86400
|
|
32
|
+
MAX_BODY = 1024 * 1024
|
|
33
|
+
OWNER_LIMIT = 2000
|
|
34
|
+
GLOBAL_LIMIT = 20000
|
|
35
|
+
BINDING_LIMIT = 10000
|
|
36
|
+
FIELDS = {'facebook': {'feed'}, 'instagram': {'comments', 'mentions'}}
|
|
37
|
+
CONSENT_VERSION = 'meta-hints-2026-10-18'
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _hash(value):
|
|
41
|
+
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _id(value, *, composite=False):
|
|
45
|
+
pattern = r'[0-9]{1,128}(?:_[0-9]{1,128})?' if composite else r'[0-9]{1,128}'
|
|
46
|
+
return value if isinstance(value, str) and re.fullmatch(pattern, value) else None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _unavailable():
|
|
50
|
+
raise HTTPException(409, 'webhook_binding_unverified: Review the current account and existing Meta subscriptions.')
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class MetaWebhooks:
|
|
54
|
+
def __init__(self, connections, public_url, clock):
|
|
55
|
+
self.connections, self.vault, self.clock = connections, connections.vault, clock
|
|
56
|
+
self.callback = public_url + PATH
|
|
57
|
+
self.verify_token = os.environ.get('SOCIALCLI_META_WEBHOOK_VERIFY_TOKEN', '')
|
|
58
|
+
self.previous_secret = os.environ.get('SOCIALCLI_META_WEBHOOK_PREVIOUS_SECRET', '')
|
|
59
|
+
try:
|
|
60
|
+
self.previous_until = float(os.environ.get('SOCIALCLI_META_WEBHOOK_PREVIOUS_UNTIL', '0'))
|
|
61
|
+
if (len(self.verify_token) > 512 or bool(self.previous_secret) != bool(self.previous_until)
|
|
62
|
+
or self.previous_secret and (not math.isfinite(self.previous_until)
|
|
63
|
+
or not clock() < self.previous_until <= clock()+36*3600)):
|
|
64
|
+
raise ValueError()
|
|
65
|
+
except ValueError:
|
|
66
|
+
raise ValueError('Invalid bounded Meta webhook configuration.') from None
|
|
67
|
+
|
|
68
|
+
def credentials(self, platform=None):
|
|
69
|
+
if not self.verify_token:
|
|
70
|
+
raise HTTPException(503, 'webhook_disabled: Hosted Meta delivery is not enabled.')
|
|
71
|
+
available = self.connections.providers.settings.providers
|
|
72
|
+
configured = [available[p] for p in FIELDS if p in available]
|
|
73
|
+
if (not configured or len({(p.client_id, p.client_secret) for p in configured}) != 1
|
|
74
|
+
or platform is not None and platform not in available):
|
|
75
|
+
raise HTTPException(503, 'webhook_configuration_unavailable: Review Meta app configuration.')
|
|
76
|
+
return available[platform] if platform else configured[0]
|
|
77
|
+
|
|
78
|
+
def current(self, db, user_id, platform):
|
|
79
|
+
user = self.connections.metadata.user(db, user_id)
|
|
80
|
+
slot = db.execute('SELECT grant_id FROM saas_slots WHERE user_id=? AND platform=?',
|
|
81
|
+
(user_id, platform)).fetchone()
|
|
82
|
+
grant = self.vault.get(db, 'saas-grant', slot['grant_id']) if slot else None
|
|
83
|
+
if (user is None or user['deleting'] or user['suspended'] or grant is None
|
|
84
|
+
or grant['expires'] <= self.clock() or grant['payload'].get('user_id') != user_id
|
|
85
|
+
or grant['payload'].get('platform') != platform):
|
|
86
|
+
_unavailable()
|
|
87
|
+
consent.require_privacy(self.connections.metadata, db, user_id)
|
|
88
|
+
return slot['grant_id'], grant
|
|
89
|
+
|
|
90
|
+
def purge(self, db):
|
|
91
|
+
db.execute('DELETE FROM records WHERE kind IN (?,?) AND expires<=?',
|
|
92
|
+
(BINDING, EVENT, self.clock()))
|
|
93
|
+
|
|
94
|
+
def register(self, user_id, platform, wanted):
|
|
95
|
+
"""Called only after browser-owned explicit consent and CSRF validation."""
|
|
96
|
+
credentials = self.credentials(platform)
|
|
97
|
+
if not wanted or not wanted <= FIELDS.get(platform, set()):
|
|
98
|
+
raise HTTPException(400, 'Select supported webhook fields.')
|
|
99
|
+
with self.vault.read_transaction() as db:
|
|
100
|
+
grant_id, record = self.current(db, user_id, platform)
|
|
101
|
+
self.connections.allowed(db, user_id)
|
|
102
|
+
payload = record['payload']; account = payload['account']; grant = payload['grant']
|
|
103
|
+
page_id = account.get('page_id') if platform == 'instagram' else account.get('id')
|
|
104
|
+
if not _id(page_id) or not _id(account.get('id')):
|
|
105
|
+
_unavailable()
|
|
106
|
+
token = grant.get('access_token')
|
|
107
|
+
if not isinstance(token, str) or not token or grant.get('expires_at', 0) <= self.clock():
|
|
108
|
+
_unavailable()
|
|
109
|
+
providers = self.connections.providers
|
|
110
|
+
app_headers = {'Authorization': f'Bearer {credentials.client_id}|{credentials.client_secret}'}
|
|
111
|
+
headers = {'Authorization': 'Bearer ' + token}
|
|
112
|
+
try:
|
|
113
|
+
metadata = providers.request('GET', GRAPH+'/debug_token', headers=app_headers,
|
|
114
|
+
params={'input_token': token}).get('data')
|
|
115
|
+
required = {'pages_manage_metadata', 'pages_read_engagement'}
|
|
116
|
+
if platform == 'instagram': required |= {'instagram_basic', 'instagram_manage_comments'}
|
|
117
|
+
if (not isinstance(metadata, dict) or metadata.get('is_valid') is not True
|
|
118
|
+
or metadata.get('app_id') != credentials.client_id or metadata.get('type') not in {None, 'PAGE'}
|
|
119
|
+
or metadata.get('profile_id') != page_id
|
|
120
|
+
or not isinstance(metadata.get('scopes'), list)
|
|
121
|
+
or any(not isinstance(scope, str) for scope in metadata['scopes'])
|
|
122
|
+
or not required <= set(metadata['scopes'])):
|
|
123
|
+
_unavailable()
|
|
124
|
+
actor = providers.request('GET', GRAPH+'/me', headers=headers,
|
|
125
|
+
params={'fields': 'id,instagram_business_account' if platform == 'instagram' else 'id'})
|
|
126
|
+
if (actor.get('id') != page_id or platform == 'instagram'
|
|
127
|
+
and (actor.get('instagram_business_account') or {}).get('id') != account['id']):
|
|
128
|
+
_unavailable()
|
|
129
|
+
subscriptions = providers.request('GET', GRAPH+'/'+credentials.client_id+'/subscriptions',
|
|
130
|
+
headers=app_headers)
|
|
131
|
+
obj = 'page' if platform == 'facebook' else 'instagram'
|
|
132
|
+
rows = subscriptions.get('data')
|
|
133
|
+
matches = [s for s in rows if isinstance(s, dict) and s.get('object') == obj] if isinstance(rows, list) else []
|
|
134
|
+
if (len(matches) != 1 or matches[0].get('active') is not True
|
|
135
|
+
or matches[0].get('callback_url') != self.callback
|
|
136
|
+
or not isinstance(matches[0].get('fields'), list)
|
|
137
|
+
or not wanted <= {f.get('name') for f in matches[0].get('fields', []) if isinstance(f, dict)}):
|
|
138
|
+
_unavailable()
|
|
139
|
+
installed = providers.request('GET', GRAPH+'/'+page_id+'/subscribed_apps', headers=headers,
|
|
140
|
+
params={'fields': 'id,subscribed_fields', 'limit': 100})
|
|
141
|
+
rows = installed.get('data')
|
|
142
|
+
matches = [s for s in rows if isinstance(s, dict) and s.get('id') == credentials.client_id] if isinstance(rows, list) else []
|
|
143
|
+
# Facebook Login IG delivery also requires installation on the linked
|
|
144
|
+
# Page with at least one Page field. This candidate requires feed.
|
|
145
|
+
if (len(matches) != 1 or not isinstance(matches[0].get('subscribed_fields'), list)
|
|
146
|
+
or any(not isinstance(field, str) for field in matches[0]['subscribed_fields'])
|
|
147
|
+
or 'feed' not in matches[0]['subscribed_fields']):
|
|
148
|
+
_unavailable()
|
|
149
|
+
except (ValueError, TypeError, KeyError, MetaError):
|
|
150
|
+
_unavailable()
|
|
151
|
+
key = _hash([obj, account['id']])
|
|
152
|
+
with self.vault.transaction() as db:
|
|
153
|
+
self.purge(db)
|
|
154
|
+
current_id, current = self.current(db, user_id, platform)
|
|
155
|
+
if (current_id != grant_id or current['payload'] != payload):
|
|
156
|
+
_unavailable()
|
|
157
|
+
existing = self.vault.get(db, BINDING, key)
|
|
158
|
+
if existing and (existing['payload']['user_id'], existing['payload']['grant_id']) != (user_id, grant_id):
|
|
159
|
+
_unavailable()
|
|
160
|
+
if not existing and db.execute('SELECT count(*) FROM records WHERE kind=?', (BINDING,)).fetchone()[0] >= BINDING_LIMIT:
|
|
161
|
+
raise HTTPException(503, 'webhook_capacity: Try again after operator review.')
|
|
162
|
+
self.vault.put(db, BINDING, key, {'user_id': user_id, 'grant_id': grant_id,
|
|
163
|
+
'platform': platform, 'account_id': account['id'], 'page_id': page_id,
|
|
164
|
+
'object': obj, 'fields': sorted(wanted), 'verified_at': self.clock(),
|
|
165
|
+
'consent': {'version': CONSENT_VERSION, 'source': 'owner_browser', 'accepted_at': self.clock()}},
|
|
166
|
+
expires=min(record['expires'], grant['expires_at'], self.clock()+LEASE))
|
|
167
|
+
|
|
168
|
+
def binding(self, db, obj, account_id):
|
|
169
|
+
binding = self.vault.get(db, BINDING, _hash([obj, account_id]))
|
|
170
|
+
if binding is None or binding['expires'] <= self.clock(): return None
|
|
171
|
+
data = binding['payload']
|
|
172
|
+
try:
|
|
173
|
+
grant_id, grant = self.current(db, data['user_id'], data['platform'])
|
|
174
|
+
except HTTPException:
|
|
175
|
+
return None
|
|
176
|
+
if (grant_id != data['grant_id'] or grant['payload']['account'].get('id') != account_id
|
|
177
|
+
or (data['platform'] == 'instagram' and grant['payload']['account'].get('page_id') != data['page_id'])
|
|
178
|
+
or data['consent']['version'] != CONSENT_VERSION):
|
|
179
|
+
return None
|
|
180
|
+
return data
|
|
181
|
+
|
|
182
|
+
def ingest(self, raw, signature):
|
|
183
|
+
credentials = self.credentials()
|
|
184
|
+
if not isinstance(raw, bytes) or not 0 < len(raw) <= MAX_BODY:
|
|
185
|
+
raise HTTPException(413, 'Invalid or excessive webhook body.')
|
|
186
|
+
secrets = [credentials.client_secret]
|
|
187
|
+
if self.previous_secret and self.clock() < self.previous_until: secrets.append(self.previous_secret)
|
|
188
|
+
if (not isinstance(signature, str) or not re.fullmatch(r'sha256=[0-9a-f]{64}', signature)
|
|
189
|
+
or not any(hmac.compare_digest(signature, 'sha256='+hmac.new(secret.encode(), raw, hashlib.sha256).hexdigest()) for secret in secrets)):
|
|
190
|
+
raise HTTPException(403, 'Webhook signature rejected.')
|
|
191
|
+
try:
|
|
192
|
+
data = parse_json(raw, limit=MAX_BODY)
|
|
193
|
+
except (ValueError, TypeError, RecursionError):
|
|
194
|
+
raise HTTPException(400, 'Invalid webhook JSON.') from None
|
|
195
|
+
if (not isinstance(data, dict) or data.get('object') not in {'page', 'instagram'}
|
|
196
|
+
or not isinstance(data.get('entry'), list) or not 1 <= len(data['entry']) <= 1000):
|
|
197
|
+
raise HTTPException(400, 'Invalid webhook envelope.')
|
|
198
|
+
size = sum(len(e.get('changes', [])) if isinstance(e, dict) and isinstance(e.get('changes'), list) else 0 for e in data['entry'])
|
|
199
|
+
if size > 1000: raise HTTPException(413, 'Too many webhook updates.')
|
|
200
|
+
counts = {'accepted': 0, 'duplicates': 0, 'out_of_order': 0, 'ignored': 0}
|
|
201
|
+
with self.vault.transaction() as db:
|
|
202
|
+
self.purge(db)
|
|
203
|
+
global_count = db.execute('SELECT count(*) FROM records WHERE kind=?', (EVENT,)).fetchone()[0]
|
|
204
|
+
owners = {}
|
|
205
|
+
for entry in data['entry']:
|
|
206
|
+
if not isinstance(entry, dict): counts['ignored'] += 1; continue
|
|
207
|
+
binding = self.binding(db, data['object'], entry.get('id'))
|
|
208
|
+
timestamp = entry.get('time'); changes = entry.get('changes')
|
|
209
|
+
if (binding is None or type(timestamp) is not int
|
|
210
|
+
or not self.clock()-RETENTION <= timestamp <= self.clock()+300
|
|
211
|
+
or not isinstance(changes, list)):
|
|
212
|
+
counts['ignored'] += 1; continue
|
|
213
|
+
for change in changes:
|
|
214
|
+
hint = self.hint(binding, change)
|
|
215
|
+
if hint is None: counts['ignored'] += 1; continue
|
|
216
|
+
identifier = _hash([binding['user_id'], binding['grant_id'], timestamp, change])
|
|
217
|
+
if self.vault.get(db, EVENT, identifier): counts['duplicates'] += 1; continue
|
|
218
|
+
owner = binding['user_id']
|
|
219
|
+
if owner not in owners:
|
|
220
|
+
rows = db.execute('SELECT id FROM saas_record_owners WHERE user_id=? AND kind=?',
|
|
221
|
+
(owner, EVENT)).fetchall()
|
|
222
|
+
latest_times = {}
|
|
223
|
+
for row in rows:
|
|
224
|
+
saved = self.vault.get(db, EVENT, row['id'])['payload']
|
|
225
|
+
target = (saved['grant_id'], saved['target_id'])
|
|
226
|
+
latest_times[target] = max(latest_times.get(target, -1), saved['source_time'])
|
|
227
|
+
owners[owner] = [len(rows), latest_times]
|
|
228
|
+
count, latest_times = owners[owner]
|
|
229
|
+
if count >= OWNER_LIMIT or global_count >= GLOBAL_LIMIT:
|
|
230
|
+
raise HTTPException(503, 'webhook_capacity: Delivery was not accepted; retry later.')
|
|
231
|
+
target = (binding['grant_id'], hint['target_id'])
|
|
232
|
+
latest = latest_times.get(target, -1)
|
|
233
|
+
late = timestamp < latest
|
|
234
|
+
self.vault.put(db, EVENT, identifier, {**hint, 'user_id': binding['user_id'],
|
|
235
|
+
'grant_id': binding['grant_id'], 'platform': binding['platform'], 'account_id': binding['account_id'],
|
|
236
|
+
'source_time': timestamp, 'received_at': self.clock(), 'out_of_order': late,
|
|
237
|
+
'consent': binding['consent'],
|
|
238
|
+
'state': 'pending_read'}, expires=self.clock()+RETENTION)
|
|
239
|
+
owners[owner][0] += 1; latest_times[target] = max(latest, timestamp)
|
|
240
|
+
counts['accepted'] += 1; counts['out_of_order'] += int(late); global_count += 1
|
|
241
|
+
return counts
|
|
242
|
+
|
|
243
|
+
@staticmethod
|
|
244
|
+
def hint(binding, change):
|
|
245
|
+
if not isinstance(change, dict) or change.get('field') not in binding['fields']: return None
|
|
246
|
+
value = change.get('value')
|
|
247
|
+
if not isinstance(value, dict): return None
|
|
248
|
+
field = change['field']
|
|
249
|
+
media = value.get('media')
|
|
250
|
+
target = value.get('post_id') if field == 'feed' else value.get('media_id', media.get('id') if isinstance(media, dict) else None)
|
|
251
|
+
if not _id(target, composite=field == 'feed'): return None
|
|
252
|
+
comment = value.get('comment_id') if field in {'feed', 'mentions'} else value.get('id')
|
|
253
|
+
if comment is not None and not _id(comment, composite=field == 'feed'): return None
|
|
254
|
+
# Caption/media mentions carry only media_id; comment mentions also
|
|
255
|
+
# carry comment_id. Keep the distinction for the subsequent owned GET.
|
|
256
|
+
if field == 'comments' and comment is None: return None
|
|
257
|
+
return {'field': field, 'target_id': target, 'comment_id': comment}
|
|
258
|
+
|
|
259
|
+
def authorized(self, db, connection_id, request):
|
|
260
|
+
cap = self.connections.capability(db, connection_id, request)['payload']
|
|
261
|
+
if cap['platform'] not in FIELDS: raise HTTPException(403, 'A Meta connection is required.')
|
|
262
|
+
self.connections.allowed(db, cap['user_id'])
|
|
263
|
+
grant_id, _ = self.current(db, cap['user_id'], cap['platform'])
|
|
264
|
+
if grant_id != cap['grant_id']: _unavailable()
|
|
265
|
+
return cap
|
|
266
|
+
|
|
267
|
+
def events(self, connection_id, request, limit):
|
|
268
|
+
if not 1 <= limit <= 100: raise HTTPException(400, 'Event limit must be between 1 and 100.')
|
|
269
|
+
with self.vault.transaction() as db:
|
|
270
|
+
self.purge(db)
|
|
271
|
+
cap = self.authorized(db, connection_id, request)
|
|
272
|
+
result = []
|
|
273
|
+
for row in db.execute('SELECT id FROM saas_record_owners WHERE user_id=? AND kind=? ORDER BY id', (cap['user_id'], EVENT)):
|
|
274
|
+
saved = self.vault.get(db, EVENT, row['id']); hint = saved['payload']
|
|
275
|
+
if (hint['grant_id'] == cap['grant_id'] and hint['account_id'] == cap['account']['id']
|
|
276
|
+
and hint['state'] == 'pending_read'):
|
|
277
|
+
result.append({'id': row['id'], **{k:v for k,v in hint.items() if k not in {'user_id', 'grant_id', 'consent'}}})
|
|
278
|
+
if len(result) >= limit: break
|
|
279
|
+
return {'version': 1, 'events': result, 'remote_writes': 0, 'requires_owned_get': True}
|
|
280
|
+
|
|
281
|
+
def ack(self, connection_id, request, event_id):
|
|
282
|
+
with self.vault.transaction() as db:
|
|
283
|
+
cap = self.authorized(db, connection_id, request)
|
|
284
|
+
saved = self.vault.get(db, EVENT, event_id)
|
|
285
|
+
if (saved is None or saved['expires'] <= self.clock()
|
|
286
|
+
or saved['payload']['user_id'] != cap['user_id'] or saved['payload']['grant_id'] != cap['grant_id']):
|
|
287
|
+
raise HTTPException(404, 'Event unavailable.')
|
|
288
|
+
saved['payload']['state'] = 'consumed_hint'
|
|
289
|
+
self.vault.put(db, EVENT, event_id, saved['payload'], expires=saved['expires'])
|
|
290
|
+
return {'version': 1, 'status': 'acknowledged_hint', 'remote_writes': 0}
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def install_meta_webhook_routes(app, connections, sessions, settings, clock):
|
|
294
|
+
receiver = MetaWebhooks(connections, settings.public_url, clock)
|
|
295
|
+
app.state.saas_meta_webhooks = receiver
|
|
296
|
+
|
|
297
|
+
@app.get(PATH, response_class=PlainTextResponse)
|
|
298
|
+
def challenge(request: Request):
|
|
299
|
+
receiver.credentials()
|
|
300
|
+
keys = ('hub.mode', 'hub.verify_token', 'hub.challenge')
|
|
301
|
+
if any(len(request.query_params.getlist(k)) != 1 for k in keys):
|
|
302
|
+
raise HTTPException(403, 'Webhook verification rejected.')
|
|
303
|
+
try:
|
|
304
|
+
return verify_challenge(*(request.query_params[k] for k in keys), receiver.verify_token)
|
|
305
|
+
except MetaError:
|
|
306
|
+
raise HTTPException(403, 'Webhook verification rejected.') from None
|
|
307
|
+
|
|
308
|
+
@app.post(PATH)
|
|
309
|
+
async def receive(request: Request):
|
|
310
|
+
receiver.credentials()
|
|
311
|
+
if len(request.headers.getlist('x-hub-signature-256')) != 1:
|
|
312
|
+
raise HTTPException(403, 'Webhook signature rejected.')
|
|
313
|
+
raw = bytearray()
|
|
314
|
+
try:
|
|
315
|
+
async with asyncio.timeout(10):
|
|
316
|
+
async for chunk in request.stream():
|
|
317
|
+
if len(raw)+len(chunk) > MAX_BODY: raise HTTPException(413, 'Webhook body is too large.')
|
|
318
|
+
raw.extend(chunk)
|
|
319
|
+
except TimeoutError:
|
|
320
|
+
raise HTTPException(408, 'Webhook body read timed out.') from None
|
|
321
|
+
if not raw: raise HTTPException(400, 'Webhook body is empty.')
|
|
322
|
+
return await asyncio.to_thread(receiver.ingest, bytes(raw), request.headers.get('x-hub-signature-256'))
|
|
323
|
+
|
|
324
|
+
@app.get('/api/saas/v1/connections/{connection_id}/meta/webhook-events')
|
|
325
|
+
def events(connection_id: str, request: Request, limit: int = 100):
|
|
326
|
+
return receiver.events(connection_id, request, limit)
|
|
327
|
+
|
|
328
|
+
@app.post('/api/saas/v1/connections/{connection_id}/meta/webhook-events/{event_id}/ack')
|
|
329
|
+
def ack(connection_id: str, event_id: str, request: Request):
|
|
330
|
+
return receiver.ack(connection_id, request, event_id)
|
|
331
|
+
|
|
332
|
+
@app.get('/account/connections/{platform}/webhooks', response_class=HTMLResponse)
|
|
333
|
+
def enrollment(platform: str, request: Request):
|
|
334
|
+
sessions.require_user(request)
|
|
335
|
+
receiver.credentials(platform)
|
|
336
|
+
if platform not in FIELDS: raise HTTPException(404, 'Meta platform unavailable.')
|
|
337
|
+
checks = ''.join(f'<label><input type="checkbox" name="field_{field}" value="1"> {field}</label>' for field in sorted(FIELDS[platform]))
|
|
338
|
+
content = ('<h1 id="page-title">Enable Meta event hints</h1><p>This stores encrypted account and content IDs '
|
|
339
|
+
'for up to six days. No comment text or author profiles are retained. Your linked assistants can read '
|
|
340
|
+
'these hints and must verify content ownership before acting. Disconnecting removes hints. '
|
|
341
|
+
'This does not subscribe your account at Meta or approve social actions. Existing verified subscriptions are required.</p>'
|
|
342
|
+
f'<form method="post" action="/account/connections/{escape(platform)}/webhooks">'
|
|
343
|
+
+pages.hidden('csrf', app.state.saas_csrf(request, 'meta-webhooks:'+platform))
|
|
344
|
+
+pages.hidden('webhook_consent_version', CONSENT_VERSION)+checks
|
|
345
|
+
+'<label><input type="checkbox" name="webhook_accept" value="1" required> Allow this event storage and assistant access</label>'
|
|
346
|
+
+'<button type="submit">Enable verified hints for one day</button></form>')
|
|
347
|
+
return HTMLResponse(pages.page('Meta event hints', content))
|
|
348
|
+
|
|
349
|
+
@app.post('/account/connections/{platform}/webhooks')
|
|
350
|
+
async def enroll(platform: str, request: Request):
|
|
351
|
+
form = await read_form(request, settings.public_url)
|
|
352
|
+
app.state.saas_valid_form(request, form, 'meta-webhooks:'+platform)
|
|
353
|
+
user = await asyncio.to_thread(sessions.require_user, request)
|
|
354
|
+
if form.get('webhook_accept') != '1' or form.get('webhook_consent_version') != CONSENT_VERSION:
|
|
355
|
+
raise HTTPException(400, 'Review and accept Meta event storage before enabling it.')
|
|
356
|
+
wanted = {field for field in FIELDS.get(platform, set()) if form.get('field_'+field) == '1'}
|
|
357
|
+
await asyncio.to_thread(receiver.register, user.id, platform, wanted)
|
|
358
|
+
return RedirectResponse('/account/', status_code=303)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Explicit human-approved transfer of an existing legacy capability."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import hmac
|
|
4
|
+
import secrets
|
|
5
|
+
from html import escape
|
|
6
|
+
from fastapi import HTTPException,Request
|
|
7
|
+
from fastapi.responses import HTMLResponse,RedirectResponse
|
|
8
|
+
from pydantic import Field
|
|
9
|
+
from socialctl.saas import pages
|
|
10
|
+
from socialctl.saas.auth import digest
|
|
11
|
+
from socialctl.saas.connections import AttachRequest,OAUTH_SECONDS
|
|
12
|
+
from socialctl.saas.pairing import proof
|
|
13
|
+
from socialctl.saas.routes import read_form
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class MigrationRequest(AttachRequest):
|
|
17
|
+
legacy_id:str=Field(pattern='^[A-Za-z0-9_-]{16,256}$')
|
|
18
|
+
poll_challenge:str=Field(pattern='^[0-9a-f]{64}$')
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def legacy_record(connections,db,legacy_id,credential_hash,platform):
|
|
22
|
+
record=connections.vault.get(db,'connection',legacy_id)
|
|
23
|
+
if (record is None or record['expires']<=connections.clock()
|
|
24
|
+
or not hmac.compare_digest(record['credential_hash'],credential_hash)
|
|
25
|
+
or record['payload'].get('saas') or not record['payload'].get('activated')
|
|
26
|
+
or record['payload']['platform']!=platform):
|
|
27
|
+
raise HTTPException(404,'legacy_unavailable: The old connection is unavailable.')
|
|
28
|
+
connections.legacy.require(db,'connection',legacy_id,record)
|
|
29
|
+
return record
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def install_migration_routes(app,settings,metadata,sessions,clock):
|
|
33
|
+
vault=metadata.vault;connections=app.state.saas_connections
|
|
34
|
+
csrf,valid_form=app.state.saas_csrf,app.state.saas_valid_form
|
|
35
|
+
|
|
36
|
+
def require(db,migration_id,request=None,user=None):
|
|
37
|
+
record=vault.get(db,'saas-migration',migration_id)
|
|
38
|
+
if record is None or record['expires']<=clock() or request is not None and not hmac.compare_digest(record['credential_hash'],proof(request)):
|
|
39
|
+
raise HTTPException(404,'migration_expired: Request a new migration link.')
|
|
40
|
+
data=record['payload'];owner=connections.owner(db,data['installation_id'])
|
|
41
|
+
connections.require_platform(db,data['installation_id'],data['platform'])
|
|
42
|
+
if owner!=data['user_id'] or user is not None and owner!=user.id:
|
|
43
|
+
raise HTTPException(403,'This migration belongs to another account.')
|
|
44
|
+
return record
|
|
45
|
+
|
|
46
|
+
@app.post('/api/saas/v1/installations/{installation_id}/migrations',status_code=201)
|
|
47
|
+
def start(installation_id:str,body:MigrationRequest,request:Request):
|
|
48
|
+
secret=request.headers.get('x-socialcli-legacy-secret','')
|
|
49
|
+
if not 16<=len(secret)<=512:raise HTTPException(404,'legacy_unavailable: The old connection is unavailable.')
|
|
50
|
+
with vault.transaction() as db:
|
|
51
|
+
installation=connections.installations.require(db,installation_id,request)
|
|
52
|
+
connections.require_platform(db,installation_id,body.platform)
|
|
53
|
+
user_id=installation['payload']['user_id']
|
|
54
|
+
if not metadata.admit(db,'migration-installation:'+installation_id,clock(),limit=5):
|
|
55
|
+
raise HTTPException(429,'Too many migration attempts. Wait a minute.')
|
|
56
|
+
connections.allowed(db,user_id,new=True);connections.brand(db,user_id,body.brand)
|
|
57
|
+
record=legacy_record(connections,db,body.legacy_id,digest(secret),body.platform)
|
|
58
|
+
current=db.execute('SELECT grant_id FROM saas_slots WHERE user_id=? AND platform=?',(user_id,body.platform)).fetchone()
|
|
59
|
+
migration_id=secrets.token_urlsafe(24)
|
|
60
|
+
data={'user_id':user_id,'installation_id':installation_id,'brand':body.brand,'platform':body.platform,
|
|
61
|
+
'legacy_id':body.legacy_id,'legacy_hash':record['credential_hash'],'account':record['payload']['account'],
|
|
62
|
+
'expected_grant':current['grant_id'] if current else None,'status':'pending'}
|
|
63
|
+
vault.put(db,'saas-migration',migration_id,data,expires=min(record['expires'],clock()+OAUTH_SECONDS),credential_hash=body.poll_challenge)
|
|
64
|
+
return {'version':1,'migration_id':migration_id,'browser_url':settings.public_url+'/account/migrate/'+migration_id,
|
|
65
|
+
'expires_in':OAUTH_SECONDS,'poll_interval':2}
|
|
66
|
+
|
|
67
|
+
@app.get('/account/migrate/{migration_id}',response_class=HTMLResponse)
|
|
68
|
+
def page(migration_id:str,request:Request):
|
|
69
|
+
try:user=sessions.require_user(request)
|
|
70
|
+
except HTTPException as exc:
|
|
71
|
+
if exc.status_code!=401:raise
|
|
72
|
+
return RedirectResponse('/account/login?next=/account/migrate/'+migration_id,status_code=303)
|
|
73
|
+
with vault.transaction() as db:
|
|
74
|
+
data=require(db,migration_id,user=user)['payload']
|
|
75
|
+
if data['status']!='pending':raise HTTPException(409,'This migration has already been confirmed.')
|
|
76
|
+
account=data['account']
|
|
77
|
+
return HTMLResponse(pages.page('Move your connection',f'''<p class="eyebrow">REVIEW EXISTING ACCESS</p><h1 id="page-title">Move your connection</h1>
|
|
78
|
+
<p class="description">Link {escape(account.get('name',account['id']))} ({escape(account['id'])}) on {escape(data['platform'])} to {escape(data['brand'])} in your SocialCli account.</p>
|
|
79
|
+
<div class="status-notice">The old connection stays active until your assistant saves and activates the replacement. This starts your 14-day trial if you are eligible. No content will be published.</div>
|
|
80
|
+
<form method="post" action="/account/migrate/{escape(migration_id,quote=True)}" class="form-stack">{pages.hidden('csrf',csrf(request,'migrate:'+migration_id))}<button class="primary-button" type="submit">Confirm migration</button></form><a class="text-link" href="/account/">Cancel and return to account</a>'''))
|
|
81
|
+
|
|
82
|
+
@app.post('/account/migrate/{migration_id}',response_class=HTMLResponse)
|
|
83
|
+
async def approve(migration_id:str,request:Request):
|
|
84
|
+
form=await read_form(request,settings.public_url);valid_form(request,form,'migrate:'+migration_id)
|
|
85
|
+
user=await asyncio.to_thread(sessions.require_user,request)
|
|
86
|
+
def commit():
|
|
87
|
+
with vault.transaction() as db:
|
|
88
|
+
record=require(db,migration_id,user=user);data=record['payload']
|
|
89
|
+
if data['status']!='pending':raise HTTPException(409,'This migration has already been confirmed.')
|
|
90
|
+
connections.allowed(db,user.id,new=True)
|
|
91
|
+
old=legacy_record(connections,db,data['legacy_id'],data['legacy_hash'],data['platform'])
|
|
92
|
+
result=connections.candidate(db,data['installation_id'],user.id,data['platform'],data['brand'],
|
|
93
|
+
data['account'],grant=old['payload']['grant'],expected=data['expected_grant'])
|
|
94
|
+
candidate=vault.get(db,'saas-candidate',result['connection_id'])
|
|
95
|
+
candidate['payload'].update(legacy_id=data['legacy_id'],legacy_hash=data['legacy_hash'])
|
|
96
|
+
vault.put(db,'saas-candidate',result['connection_id'],candidate['payload'],
|
|
97
|
+
expires=min(candidate['expires'],record['expires']),credential_hash=candidate['credential_hash'])
|
|
98
|
+
data.update(status='selected',selection=result)
|
|
99
|
+
vault.put(db,'saas-migration',migration_id,data,expires=record['expires'],credential_hash=record['credential_hash'])
|
|
100
|
+
await asyncio.to_thread(commit)
|
|
101
|
+
return HTMLResponse(pages.page('Migration confirmed','<p class="eyebrow">CONNECTION CONFIRMED</p><h1 id="page-title">Return to your assistant</h1><p class="description">Keep the command running while it finishes moving your connection. No content was published.</p><a class="secondary-button" href="/account/">Your account</a>'))
|
|
102
|
+
|
|
103
|
+
@app.post('/api/saas/v1/migrations/{migration_id}/poll')
|
|
104
|
+
def poll(migration_id:str,request:Request):
|
|
105
|
+
with vault.transaction() as db:
|
|
106
|
+
data=require(db,migration_id,request)['payload']
|
|
107
|
+
return data['selection'] if data['status']=='selected' else {'version':1,'status':data['status']}
|
socialctl/saas/models.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Private, read-only operations report. Never contacts providers or sends mail."""
|
|
2
|
+
from contextlib import closing
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sqlite3
|
|
8
|
+
import tempfile
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
from cryptography.fernet import Fernet, MultiFernet, InvalidToken
|
|
12
|
+
from socialctl.saas.budget import WorkBudget
|
|
13
|
+
from socialctl.saas.renewal import state as renewal_state
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def heartbeat_path(database):
|
|
17
|
+
return Path(str(database)+'.maintenance.json')
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def write_heartbeat(database,status,now):
|
|
21
|
+
if status not in {'running','complete','attention','failed'} or not math.isfinite(now):
|
|
22
|
+
raise ValueError('Invalid maintenance status.')
|
|
23
|
+
target=heartbeat_path(database)
|
|
24
|
+
fd,name=tempfile.mkstemp(prefix='.maintenance-',dir=target.parent)
|
|
25
|
+
try:
|
|
26
|
+
with os.fdopen(fd,'w') as stream:
|
|
27
|
+
json.dump({'status':status,'at':now},stream)
|
|
28
|
+
stream.flush();os.fsync(stream.fileno())
|
|
29
|
+
os.replace(name,target)
|
|
30
|
+
directory=os.open(target.parent,os.O_RDONLY)
|
|
31
|
+
try:os.fsync(directory)
|
|
32
|
+
finally:os.close(directory)
|
|
33
|
+
finally:
|
|
34
|
+
Path(name).unlink(missing_ok=True)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def inspect_status(database,keys,*,now=None):
|
|
38
|
+
now=time.time() if now is None else now
|
|
39
|
+
issues=[];counts={};budget=WorkBudget(5)
|
|
40
|
+
try:
|
|
41
|
+
with closing(sqlite3.connect(Path(database).resolve().as_uri()+'?mode=ro',uri=True,timeout=1)) as db:
|
|
42
|
+
db.row_factory=sqlite3.Row
|
|
43
|
+
db.set_progress_handler(lambda:int(budget.expired()),1000)
|
|
44
|
+
db.execute('BEGIN')
|
|
45
|
+
if db.execute('SELECT max(version) FROM saas_schema').fetchone()[0]!=10:
|
|
46
|
+
return {'status':'attention','issues':['schema_incompatible'],'counts':{}}
|
|
47
|
+
queries={
|
|
48
|
+
'billing_events_due':("SELECT count(*) FROM saas_billing_events WHERE state='pending' AND next_attempt<=?",(now,)),
|
|
49
|
+
'billing_events_overdue':("SELECT count(*) FROM saas_billing_events WHERE state='pending' AND received<=?",(now-900,)),
|
|
50
|
+
'billing_events_review':("SELECT count(*) FROM saas_billing_events WHERE state='review'",()),
|
|
51
|
+
'billing_review':("SELECT count(*) FROM saas_billing WHERE review!=''",()),
|
|
52
|
+
'billing_overdue':("SELECT count(*) FROM saas_billing b JOIN saas_users u ON u.id=b.user_id WHERE b.customer_id IS NOT NULL AND b.sync_due<=? AND u.deleting=0",(now-900,)),
|
|
53
|
+
'google_revocations_pending':("SELECT count(*) FROM saas_google_revocations WHERE state='pending'",()),
|
|
54
|
+
'google_revocations_overdue':("SELECT count(*) FROM saas_google_revocations WHERE state='pending' AND requested<=?",(now-86400,)),
|
|
55
|
+
'deletions_pending':("SELECT count(*) FROM saas_deletions WHERE state='pending'",()),
|
|
56
|
+
'deletions_overdue':("SELECT count(*) FROM saas_deletions WHERE state='pending' AND requested<=?",(now-900,)),
|
|
57
|
+
'reminders_due':("SELECT count(*) FROM saas_reminders WHERE state='pending' AND next_attempt<=?",(now,)),
|
|
58
|
+
'reminders_overdue':("SELECT count(*) FROM saas_reminders WHERE state='pending' AND next_attempt<=?",(now-900,)),
|
|
59
|
+
'reminders_uncertain':("SELECT count(*) FROM saas_reminders WHERE state='uncertain' OR (state='sending' AND lease_until<=?)",(now,)),
|
|
60
|
+
'reminders_rejected':("SELECT count(*) FROM saas_reminders WHERE state='rejected'",()),
|
|
61
|
+
}
|
|
62
|
+
for name,(sql,params) in queries.items():
|
|
63
|
+
counts[name]=db.execute(sql,params).fetchone()[0]
|
|
64
|
+
cipher=MultiFernet([Fernet(key) for key in keys])
|
|
65
|
+
for row in db.execute("SELECT * FROM records WHERE kind='saas-grant' AND expires>?",(now,)):
|
|
66
|
+
if budget.expired():raise ValueError()
|
|
67
|
+
envelope=json.loads(cipher.decrypt(row['payload']))
|
|
68
|
+
if any(envelope[key]!=row[key] for key in ('kind','id','expires','credential_hash')):
|
|
69
|
+
raise ValueError()
|
|
70
|
+
current=renewal_state(envelope['payload'],now)
|
|
71
|
+
key='renewal_'+current
|
|
72
|
+
counts[key]=counts.get(key,0)+1
|
|
73
|
+
except (OSError,sqlite3.Error,ValueError,TypeError,KeyError,AttributeError,InvalidToken):
|
|
74
|
+
return {'status':'attention','issues':['database_unavailable'],'counts':{}}
|
|
75
|
+
issues.extend(key for key,count in counts.items() if count and
|
|
76
|
+
(key.endswith(('_overdue','_review','_uncertain','_rejected')) or key=='renewal_configuration_error'))
|
|
77
|
+
try:
|
|
78
|
+
with heartbeat_path(database).open('rb') as stream:
|
|
79
|
+
heartbeat=json.loads(stream.read(4096))
|
|
80
|
+
status,at=heartbeat['status'],heartbeat['at']
|
|
81
|
+
if status not in {'running','complete','attention','failed'} or type(at) not in (int,float) or not math.isfinite(at) or at>now+60:
|
|
82
|
+
raise ValueError()
|
|
83
|
+
if now-at>900:issues.append('maintenance_stale')
|
|
84
|
+
elif status=='running' and now-at>240:issues.append('maintenance_stalled')
|
|
85
|
+
elif status in {'attention','failed'}:issues.append('maintenance_'+status)
|
|
86
|
+
except (OSError,ValueError,TypeError,KeyError):
|
|
87
|
+
issues.append('maintenance_unknown')
|
|
88
|
+
return {'status':'attention' if issues else 'ok','issues':issues,'counts':counts}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def main():
|
|
92
|
+
import argparse
|
|
93
|
+
parser=argparse.ArgumentParser(description=__doc__)
|
|
94
|
+
parser.add_argument('database',type=Path)
|
|
95
|
+
args=parser.parse_args()
|
|
96
|
+
keys=[key.strip().encode() for key in os.environ.get('SOCIALCLI_ENCRYPTION_KEYS','').split(',') if key.strip()]
|
|
97
|
+
report=inspect_status(args.database,keys)
|
|
98
|
+
print(json.dumps(report,sort_keys=True))
|
|
99
|
+
raise SystemExit(0 if report['status']=='ok' else 1)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
if __name__=='__main__':main()
|