socialcli 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of socialcli might be problematic. Click here for more details.
- socialcli-0.3.0.dist-info/METADATA +168 -0
- socialcli-0.3.0.dist-info/RECORD +224 -0
- socialcli-0.3.0.dist-info/WHEEL +4 -0
- socialcli-0.3.0.dist-info/entry_points.txt +3 -0
- socialcli-0.3.0.dist-info/licenses/LICENSE +21 -0
- socialctl/__init__.py +0 -0
- socialctl/__main__.py +6 -0
- socialctl/adapters/__init__.py +6 -0
- socialctl/adapters/base.py +68 -0
- socialctl/adapters/errores.py +56 -0
- socialctl/adapters/facebook.py +180 -0
- socialctl/adapters/instagram.py +442 -0
- socialctl/adapters/tiktok.py +535 -0
- socialctl/adapters/youtube.py +331 -0
- socialctl/agent_errors.py +176 -0
- socialctl/agent_guide.py +23 -0
- socialctl/approval_cli.py +27 -0
- socialctl/auth.py +139 -0
- socialctl/authflow.py +344 -0
- socialctl/brands.py +194 -0
- socialctl/capabilities.py +57 -0
- socialctl/capabilities.yml +5945 -0
- socialctl/cli.py +1766 -0
- socialctl/connection_service/__init__.py +0 -0
- socialctl/connection_service/__main__.py +33 -0
- socialctl/connection_service/app.py +496 -0
- socialctl/connection_service/assets/PLATFORM-LOGOS-LICENSE.txt +50 -0
- socialctl/connection_service/assets/connection.css +75 -0
- socialctl/connection_service/assets/facebook.webp +0 -0
- socialctl/connection_service/assets/instagram.svg +194 -0
- socialctl/connection_service/assets/socialcli-logo.png +0 -0
- socialctl/connection_service/assets/tiktok.png +0 -0
- socialctl/connection_service/assets/youtube.svg +1 -0
- socialctl/connection_service/landing.py +146 -0
- socialctl/connection_service/legacy.py +48 -0
- socialctl/connection_service/peer.py +13 -0
- socialctl/connection_service/providers.py +324 -0
- socialctl/connection_service/settings.py +76 -0
- socialctl/connection_service/store.py +124 -0
- socialctl/connections/__init__.py +0 -0
- socialctl/connections/account_cli.py +438 -0
- socialctl/connections/cli.py +379 -0
- socialctl/connections/client.py +126 -0
- socialctl/connections/credential_cli.py +224 -0
- socialctl/connections/credential_store.py +49 -0
- socialctl/connections/file_store.py +193 -0
- socialctl/connections/keychain.py +78 -0
- socialctl/connections/meta_user.py +81 -0
- socialctl/connections/rotation_cli.py +116 -0
- socialctl/connections/saas_client.py +91 -0
- socialctl/connections/temporary_media.py +62 -0
- socialctl/delivery_options.py +70 -0
- socialctl/engagement.py +200 -0
- socialctl/engagement_cli.py +50 -0
- socialctl/executor.py +135 -0
- socialctl/formatter.py +291 -0
- socialctl/hosted_media.py +152 -0
- socialctl/identity.py +200 -0
- socialctl/inbox.py +298 -0
- socialctl/inbox_cli.py +46 -0
- socialctl/inventory.py +155 -0
- socialctl/inventory_cli.py +171 -0
- socialctl/inventory_sources.py +101 -0
- socialctl/management/__init__.py +1 -0
- socialctl/management/batch_cli.py +115 -0
- socialctl/management/batches.py +325 -0
- socialctl/management/changes.py +485 -0
- socialctl/management/cli.py +227 -0
- socialctl/management/comments_cli.py +352 -0
- socialctl/management/community_batch_cli.py +63 -0
- socialctl/management/community_batches.py +294 -0
- socialctl/management/community_changes.py +370 -0
- socialctl/management/community_cli.py +142 -0
- socialctl/management/community_schema.py +119 -0
- socialctl/management/facebook_groups.py +1118 -0
- socialctl/management/groups_cli.py +274 -0
- socialctl/management/inbox_readers.py +87 -0
- socialctl/management/meta_changes.py +197 -0
- socialctl/management/meta_cli.py +342 -0
- socialctl/management/meta_client.py +631 -0
- socialctl/management/meta_comment_inbox.py +565 -0
- socialctl/management/meta_comments.py +587 -0
- socialctl/management/meta_errors.py +59 -0
- socialctl/management/meta_pagination.py +52 -0
- socialctl/management/meta_schema.py +128 -0
- socialctl/management/meta_webhooks.py +147 -0
- socialctl/management/metadata_parts.py +144 -0
- socialctl/management/owned_assets.py +85 -0
- socialctl/management/owned_changes.py +470 -0
- socialctl/management/owned_cli.py +128 -0
- socialctl/management/owned_reorder.py +62 -0
- socialctl/management/owned_schema.py +368 -0
- socialctl/management/reply_context.py +24 -0
- socialctl/management/reply_evidence.py +80 -0
- socialctl/management/resource_changes.py +407 -0
- socialctl/management/resource_cli.py +136 -0
- socialctl/management/snippet_readback.py +26 -0
- socialctl/management/stories.py +713 -0
- socialctl/management/stories_cli.py +172 -0
- socialctl/management/youtube.py +323 -0
- socialctl/management/youtube_community.py +326 -0
- socialctl/management/youtube_metadata.py +122 -0
- socialctl/management/youtube_owned.py +259 -0
- socialctl/management/youtube_resources.py +305 -0
- socialctl/media.py +269 -0
- socialctl/media_cli.py +183 -0
- socialctl/media_ingress.py +211 -0
- socialctl/media_preflight.py +114 -0
- socialctl/media_registry.py +301 -0
- socialctl/media_requirements.py +52 -0
- socialctl/metricas/__init__.py +6 -0
- socialctl/metricas/almacen.py +133 -0
- socialctl/metricas/analytics_changes.py +295 -0
- socialctl/metricas/analytics_cli.py +191 -0
- socialctl/metricas/analytics_client.py +304 -0
- socialctl/metricas/analytics_ingest.py +260 -0
- socialctl/metricas/analytics_schema.py +174 -0
- socialctl/metricas/base.py +147 -0
- socialctl/metricas/facebook.py +418 -0
- socialctl/metricas/insights.py +227 -0
- socialctl/metricas/instagram.py +133 -0
- socialctl/metricas/modelos.py +87 -0
- socialctl/metricas/piezas.py +134 -0
- socialctl/metricas/reach.py +94 -0
- socialctl/metricas/reporting_client.py +112 -0
- socialctl/metricas/resumen.py +251 -0
- socialctl/metricas/slugs.py +89 -0
- socialctl/metricas/tiktok.py +185 -0
- socialctl/metricas/youtube.py +403 -0
- socialctl/migration_cli.py +60 -0
- socialctl/migration_files.py +68 -0
- socialctl/models.py +150 -0
- socialctl/native_schedule/__init__.py +13 -0
- socialctl/native_schedule/api_delivery.py +15 -0
- socialctl/native_schedule/api_reconcile.py +40 -0
- socialctl/native_schedule/approval.py +160 -0
- socialctl/native_schedule/cadence.py +73 -0
- socialctl/native_schedule/cli.py +510 -0
- socialctl/native_schedule/dispatcher.py +120 -0
- socialctl/native_schedule/facebook.py +112 -0
- socialctl/native_schedule/facebook_reels.py +140 -0
- socialctl/native_schedule/first_comment.py +181 -0
- socialctl/native_schedule/handoff.py +193 -0
- socialctl/native_schedule/instagram_delivery.py +224 -0
- socialctl/native_schedule/instagram_runtime.py +66 -0
- socialctl/native_schedule/inventory.py +70 -0
- socialctl/native_schedule/migration.py +310 -0
- socialctl/native_schedule/models.py +103 -0
- socialctl/native_schedule/reconcile.py +83 -0
- socialctl/native_schedule/remote_data.py +177 -0
- socialctl/native_schedule/report.py +151 -0
- socialctl/native_schedule/store.py +560 -0
- socialctl/native_schedule/verification.py +32 -0
- socialctl/native_schedule/youtube.py +339 -0
- socialctl/operation_output.py +87 -0
- socialctl/plantillas/accounts.yml +33 -0
- socialctl/plantillas/brand.md +95 -0
- socialctl/plantillas/estrategia.md +64 -0
- socialctl/postfile.py +240 -0
- socialctl/preflight.py +73 -0
- socialctl/publication_policy.py +34 -0
- socialctl/publication_status.py +75 -0
- socialctl/publication_steps.py +398 -0
- socialctl/publish_output.py +96 -0
- socialctl/publisher.py +445 -0
- socialctl/queue_migration.py +302 -0
- socialctl/read_budget.py +224 -0
- socialctl/read_reports.py +91 -0
- socialctl/rutas.py +103 -0
- socialctl/saas/__init__.py +1 -0
- socialctl/saas/access.py +75 -0
- socialctl/saas/auth.py +213 -0
- socialctl/saas/backup.py +124 -0
- socialctl/saas/billing.py +327 -0
- socialctl/saas/billing_enrollment.py +1237 -0
- socialctl/saas/billing_enrollment_schema.py +519 -0
- socialctl/saas/billing_inventory.py +775 -0
- socialctl/saas/billing_reconcile.py +127 -0
- socialctl/saas/billing_routes.py +27 -0
- socialctl/saas/budget.py +66 -0
- socialctl/saas/connections.py +374 -0
- socialctl/saas/consent.py +52 -0
- socialctl/saas/lifecycle.py +341 -0
- socialctl/saas/mail.py +89 -0
- socialctl/saas/maintenance.py +68 -0
- socialctl/saas/meta_user.py +298 -0
- socialctl/saas/meta_webhooks.py +358 -0
- socialctl/saas/migration.py +107 -0
- socialctl/saas/models.py +8 -0
- socialctl/saas/operations.py +102 -0
- socialctl/saas/pages.py +126 -0
- socialctl/saas/pairing.py +158 -0
- socialctl/saas/permissions.py +57 -0
- socialctl/saas/reminders.py +128 -0
- socialctl/saas/renewal.py +74 -0
- socialctl/saas/restore_guard.py +229 -0
- socialctl/saas/revocation.py +97 -0
- socialctl/saas/rotation.py +114 -0
- socialctl/saas/routes.py +221 -0
- socialctl/saas/settings.py +34 -0
- socialctl/saas/store.py +106 -0
- socialctl/saas/temporary_media.py +245 -0
- socialctl/saas/webhooks.py +76 -0
- socialctl/schedule_remote.py +262 -0
- socialctl/schedule_sqlite.py +44 -0
- socialctl/scheduler.py +581 -0
- socialctl/scheduler_launchd.py +319 -0
- socialctl/scheduler_systemd.py +167 -0
- socialctl/source_links.py +119 -0
- socialctl/ui/__init__.py +1 -0
- socialctl/ui/assets/agent-manual.md +850 -0
- socialctl/ui/assets/agents.md +27 -0
- socialctl/ui/assets/components.css +20 -0
- socialctl/ui/assets/connection-layout.css +53 -0
- socialctl/ui/assets/otp.template.html +10 -0
- socialctl/ui/assets/tokens.css +1 -0
- socialctl/ui/assets/trial.template.html +11 -0
- socialctl/ui/assets/web-layout.css +38 -0
- socialctl/ui/email/otp.html +10 -0
- socialctl/ui/email/trial.html +11 -0
- socialctl/upload_consent.py +13 -0
- socialctl/workspace.py +8 -0
- socialctl/youtube_data.py +471 -0
- socialctl/youtube_data_service.py +225 -0
socialctl/rutas.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Shared validation for externally supplied path components and relative paths."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def validar_componente_de_ruta(
|
|
10
|
+
raiz: Path,
|
|
11
|
+
valor: object,
|
|
12
|
+
excepcion: type[Exception],
|
|
13
|
+
sustantivo: str,
|
|
14
|
+
) -> Path:
|
|
15
|
+
"""Validate a single safe path component within the root, including symbolic-link containment."""
|
|
16
|
+
if not isinstance(valor, str):
|
|
17
|
+
raise excepcion(
|
|
18
|
+
f"{sustantivo} invalid: {valor!r} (must be a string)"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
if not valor or not valor.strip():
|
|
22
|
+
raise excepcion(
|
|
23
|
+
f"{sustantivo} invalid: {valor!r} (is empty or contains only whitespace)"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
candidato = Path(valor)
|
|
27
|
+
if candidato.is_absolute():
|
|
28
|
+
raise excepcion(
|
|
29
|
+
f"{sustantivo} invalid: {valor!r} (is an absolute path; must be "
|
|
30
|
+
"a name without path separators)"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
if (
|
|
34
|
+
"/" in valor
|
|
35
|
+
or os.sep in valor
|
|
36
|
+
or len(candidato.parts) != 1
|
|
37
|
+
or valor in (".", "..")
|
|
38
|
+
):
|
|
39
|
+
raise excepcion(
|
|
40
|
+
f"{sustantivo} invalid: {valor!r} (cannot contain path separators "
|
|
41
|
+
"or be '.' or '..')"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
raiz_resuelta = raiz.resolve()
|
|
45
|
+
resultado_resuelto = (raiz / valor).resolve()
|
|
46
|
+
if resultado_resuelto.parent != raiz_resuelta:
|
|
47
|
+
raise excepcion(
|
|
48
|
+
f'{sustantivo} invalid: {valor!r} (resolves outside {raiz}, probably through a symbolic link)'
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
return raiz / valor
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def validar_ruta_relativa(
|
|
55
|
+
raiz: Path,
|
|
56
|
+
valor: object,
|
|
57
|
+
excepcion: type[Exception],
|
|
58
|
+
sustantivo: str,
|
|
59
|
+
) -> Path:
|
|
60
|
+
"""Validate a relative path within the root, allowing safe subdirectories and rejecting symbolic-link escapes."""
|
|
61
|
+
if not isinstance(valor, str):
|
|
62
|
+
raise excepcion(
|
|
63
|
+
f"{sustantivo} invalid: {valor!r} (must be a string)"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
if "\x00" in valor:
|
|
67
|
+
raise excepcion(
|
|
68
|
+
f"{sustantivo} invalid: {valor!r} (cannot contain a null byte)"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
if not valor or not valor.strip():
|
|
72
|
+
raise excepcion(
|
|
73
|
+
f"{sustantivo} invalid: {valor!r} (is empty or contains only whitespace)"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
if "\\" in valor:
|
|
77
|
+
raise excepcion(
|
|
78
|
+
f"{sustantivo} invalid: {valor!r} (use '/' as the subdirectory separator; '\\' is not supported)"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
if valor.startswith("/"):
|
|
82
|
+
raise excepcion(
|
|
83
|
+
f"{sustantivo} invalid: {valor!r} (is an absolute path; must be "
|
|
84
|
+
"relative within the corresponding directory)"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
segmentos = valor.split("/")
|
|
88
|
+
if any(not segmento.strip() or segmento in (".", "..") for segmento in segmentos):
|
|
89
|
+
raise excepcion(
|
|
90
|
+
f"{sustantivo} invalid: {valor!r} (no segment may be "
|
|
91
|
+
"empty, contain only whitespace, or be '.' or '..')"
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
resultado = raiz.joinpath(*segmentos)
|
|
95
|
+
|
|
96
|
+
raiz_resuelta = raiz.resolve()
|
|
97
|
+
resultado_resuelto = resultado.resolve()
|
|
98
|
+
if raiz_resuelta not in resultado_resuelto.parents:
|
|
99
|
+
raise excepcion(
|
|
100
|
+
f'{sustantivo} invalid: {valor!r} (resolves outside {raiz}, probably through a symbolic link)'
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
return resultado
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Owner-bound hosted account service. Optional server-only imports stay here."""
|
socialctl/saas/access.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Local entitlement decisions; no clock or payment status comes from the CLI."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
TRIAL_SECONDS=14*86400
|
|
7
|
+
MARKER_RETENTION_SECONDS=365*86400
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class AccessDecision:
|
|
12
|
+
allowed:bool
|
|
13
|
+
reason:str
|
|
14
|
+
access_until:float|None=None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AccessControl:
|
|
18
|
+
def __init__(self,metadata):
|
|
19
|
+
self.metadata,self.vault=metadata,metadata.vault
|
|
20
|
+
|
|
21
|
+
def previous_trial(self,db,email,now):
|
|
22
|
+
markers=[hmac.new(key,b'socialcli-trial-v1\0'+email.casefold().encode(),hashlib.sha256).hexdigest() for key in self.metadata.eligibility_keys]
|
|
23
|
+
original=None
|
|
24
|
+
for marker in markers:
|
|
25
|
+
row=db.execute('SELECT * FROM saas_trial_markers WHERE marker=? AND retain_until>?',(marker,now)).fetchone()
|
|
26
|
+
if row and (original is None or row['trial_start']<original['trial_start']):
|
|
27
|
+
original=row
|
|
28
|
+
return markers,original
|
|
29
|
+
|
|
30
|
+
def restore_trial(self,db,user_id,email,now):
|
|
31
|
+
"""Restore eligibility on verified login without starting a new trial."""
|
|
32
|
+
_,original=self.previous_trial(db,email,now)
|
|
33
|
+
if original is None:
|
|
34
|
+
return
|
|
35
|
+
db.execute('INSERT OR IGNORE INTO saas_entitlements(user_id) VALUES(?)',(user_id,))
|
|
36
|
+
db.execute('UPDATE saas_entitlements SET trial_start=?,trial_end=? WHERE user_id=? AND trial_start IS NULL',
|
|
37
|
+
(original['trial_start'],original['trial_end'],user_id))
|
|
38
|
+
|
|
39
|
+
def activate_trial(self,db,user_id,now):
|
|
40
|
+
user=self.metadata.user(db,user_id)
|
|
41
|
+
if user is None or user['deleting'] or user['suspended']:
|
|
42
|
+
raise ValueError('Account is unavailable for activation.')
|
|
43
|
+
current=db.execute('SELECT * FROM saas_entitlements WHERE user_id=?',(user_id,)).fetchone()
|
|
44
|
+
if current and current['trial_start'] is not None:
|
|
45
|
+
return current['trial_start'],current['trial_end']
|
|
46
|
+
identity=self.vault.get(db,'saas-user',user_id)
|
|
47
|
+
if identity is None:
|
|
48
|
+
raise ValueError('Verified identity is required for activation.')
|
|
49
|
+
markers,original=self.previous_trial(db,identity['payload']['email'],now)
|
|
50
|
+
start,end=(original['trial_start'],original['trial_end']) if original else (now,now+TRIAL_SECONDS)
|
|
51
|
+
retain=max(now+MARKER_RETENTION_SECONDS,original['retain_until'] if original else 0)
|
|
52
|
+
for marker in markers:
|
|
53
|
+
db.execute('INSERT OR REPLACE INTO saas_trial_markers VALUES(?,?,?,?)',(marker,start,end,retain))
|
|
54
|
+
db.execute('INSERT OR IGNORE INTO saas_entitlements(user_id) VALUES(?)',(user_id,))
|
|
55
|
+
db.execute('UPDATE saas_entitlements SET trial_start=?,trial_end=? WHERE user_id=?',(start,end,user_id))
|
|
56
|
+
return start,end
|
|
57
|
+
|
|
58
|
+
def decision(self,db,user_id,now):
|
|
59
|
+
user=self.metadata.user(db,user_id)
|
|
60
|
+
if user is None or user['deleting']:
|
|
61
|
+
return AccessDecision(False,'account_unavailable')
|
|
62
|
+
if user['suspended']:
|
|
63
|
+
return AccessDecision(False,'suspended')
|
|
64
|
+
row=db.execute('SELECT * FROM saas_entitlements WHERE user_id=?',(user_id,)).fetchone()
|
|
65
|
+
if row is None or row['trial_start'] is None:
|
|
66
|
+
return AccessDecision(False,'trial_not_started')
|
|
67
|
+
if row['subscription_status'] in {'active','canceled'} and row['paid_until']>now:
|
|
68
|
+
return AccessDecision(True,'paid',row['paid_until'])
|
|
69
|
+
if row['trial_end']>now:
|
|
70
|
+
return AccessDecision(True,'trial',row['trial_end'])
|
|
71
|
+
return AccessDecision(False,'trial_expired',row['trial_end'])
|
|
72
|
+
|
|
73
|
+
def access_for(self,user_id,now):
|
|
74
|
+
with self.vault.transaction() as db:
|
|
75
|
+
return self.decision(db,user_id,now)
|
socialctl/saas/auth.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Supabase Auth REST adapter; browser sessions never reach agent installations."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import secrets
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
import httpx
|
|
6
|
+
from fastapi import HTTPException
|
|
7
|
+
from socialctl.saas.models import AuthenticatedUser
|
|
8
|
+
from socialctl.saas.budget import BudgetExpired
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def digest(value):
|
|
12
|
+
return hashlib.sha256(value.encode()).hexdigest()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class IdentityError(Exception):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class IdentityUnavailable(Exception):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class SupabaseAuth:
|
|
24
|
+
def __init__(self, settings, client):
|
|
25
|
+
self.settings, self.client = settings, client
|
|
26
|
+
self.budget = None
|
|
27
|
+
|
|
28
|
+
def request(self, method, path, *, token=None, data=None, identity_errors=(400,401,403,422)):
|
|
29
|
+
headers = {'apikey':self.settings.auth_key} if self.settings.auth_key else {}
|
|
30
|
+
if token:
|
|
31
|
+
headers['Authorization']='Bearer '+token
|
|
32
|
+
try:
|
|
33
|
+
result = self.client.request(method,self.settings.auth_url+path,json=data,headers=headers,
|
|
34
|
+
timeout=self.budget.timeout(15) if self.budget else 15,follow_redirects=False)
|
|
35
|
+
if result.status_code in identity_errors:
|
|
36
|
+
raise IdentityError()
|
|
37
|
+
result.raise_for_status()
|
|
38
|
+
return result.json() if result.content else {}
|
|
39
|
+
except (httpx.HTTPError,ValueError,BudgetExpired):
|
|
40
|
+
raise IdentityUnavailable() from None
|
|
41
|
+
|
|
42
|
+
def send_code(self,email):
|
|
43
|
+
# OTP has no user bearer token: 401/403 concern service authorization.
|
|
44
|
+
self.request('POST','/otp',data={'email':email,'create_user':True},identity_errors=(400,422))
|
|
45
|
+
|
|
46
|
+
def verify(self,email,code):
|
|
47
|
+
data=self.request('POST','/verify',data={'email':email,'token':code,'type':'email'})
|
|
48
|
+
user=self.parse_user(data.get('user',{}))
|
|
49
|
+
if user.email.casefold()!=email.casefold():
|
|
50
|
+
raise IdentityError()
|
|
51
|
+
token,expiry,refresh=self.tokens(data)
|
|
52
|
+
return user,token,expiry,refresh
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def tokens(data):
|
|
56
|
+
token=data.get('access_token');expiry=data.get('expires_in');refresh=data.get('refresh_token')
|
|
57
|
+
if (not isinstance(token,str) or not 16<=len(token)<=16384
|
|
58
|
+
or type(expiry) not in (int,float) or not 0<expiry<=86400
|
|
59
|
+
or not isinstance(refresh,str) or not 1<=len(refresh)<=16384 or any(ord(c)<33 or ord(c)==127 for c in refresh)):
|
|
60
|
+
raise IdentityError()
|
|
61
|
+
return token,expiry,refresh
|
|
62
|
+
|
|
63
|
+
def refresh(self,refresh_token):
|
|
64
|
+
data=self.request('POST','/token?grant_type=refresh_token',data={'refresh_token':refresh_token})
|
|
65
|
+
user=self.parse_user(data.get('user',{}))
|
|
66
|
+
return user,*self.tokens(data)
|
|
67
|
+
|
|
68
|
+
def get_user(self,token):
|
|
69
|
+
return self.parse_user(self.request('GET','/user',token=token))
|
|
70
|
+
|
|
71
|
+
def logout(self,token):
|
|
72
|
+
self.request('POST','/logout?scope=local',token=token)
|
|
73
|
+
|
|
74
|
+
def delete_user(self,user_id):
|
|
75
|
+
user_id=str(UUID(user_id))
|
|
76
|
+
if not self.settings.auth_admin_key:raise IdentityUnavailable()
|
|
77
|
+
try:
|
|
78
|
+
result=self.client.request('DELETE',self.settings.auth_url+'/admin/users/'+user_id,
|
|
79
|
+
headers={'Authorization':'Bearer '+self.settings.auth_admin_key,'apikey':self.settings.auth_admin_key},
|
|
80
|
+
timeout=self.budget.timeout(15) if self.budget else 15,follow_redirects=False)
|
|
81
|
+
if result.status_code in {200,204}:return
|
|
82
|
+
if result.status_code==404 and result.json().get('error_code')=='user_not_found':return
|
|
83
|
+
raise IdentityUnavailable()
|
|
84
|
+
except (httpx.HTTPError,ValueError,AttributeError,BudgetExpired):
|
|
85
|
+
raise IdentityUnavailable() from None
|
|
86
|
+
|
|
87
|
+
@staticmethod
|
|
88
|
+
def parse_user(data):
|
|
89
|
+
try:
|
|
90
|
+
user_id=str(UUID(data['id']))
|
|
91
|
+
email=data['email']
|
|
92
|
+
if not data.get('email_confirmed_at') or not isinstance(email,str) or not 3<=len(email)<=254 or '@' not in email:
|
|
93
|
+
raise ValueError()
|
|
94
|
+
return AuthenticatedUser(user_id,email)
|
|
95
|
+
except (KeyError,TypeError,ValueError,AttributeError):
|
|
96
|
+
raise IdentityError() from None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class WebSessions:
|
|
100
|
+
cookie='socialcli-session'
|
|
101
|
+
max_lifetime=12*3600
|
|
102
|
+
verification_seconds=45
|
|
103
|
+
|
|
104
|
+
def __init__(self,metadata,identity,clock):
|
|
105
|
+
self.metadata,self.vault,self.identity,self.clock=metadata,metadata.vault,identity,clock
|
|
106
|
+
|
|
107
|
+
def create(self,db,user,token,lifetime,refresh_token=None):
|
|
108
|
+
secret=secrets.token_urlsafe(32)
|
|
109
|
+
row=self.metadata.user(db,user.id)
|
|
110
|
+
if row['deleting']:
|
|
111
|
+
raise IdentityError()
|
|
112
|
+
self.vault.put(db,'saas-session',digest(secret),{'user_id':user.id,'email':user.email,
|
|
113
|
+
'access_token':token,'version':row['session_version'],'refresh_token':refresh_token,
|
|
114
|
+
'access_expires':self.clock()+lifetime,'verified_until':0},
|
|
115
|
+
expires=self.clock()+(self.max_lifetime if refresh_token else lifetime))
|
|
116
|
+
return secret
|
|
117
|
+
|
|
118
|
+
def checked(self,db,key):
|
|
119
|
+
record=self.vault.get(db,'saas-session',key)
|
|
120
|
+
if record is None or record['expires']<=self.clock():
|
|
121
|
+
raise HTTPException(401,'Your session expired. Sign in again.')
|
|
122
|
+
data=record['payload'];row=self.metadata.user(db,data['user_id'])
|
|
123
|
+
if row is None or row['deleting'] or row['session_version']!=data['version']:
|
|
124
|
+
raise HTTPException(401,'Sign in to SocialCli to continue.')
|
|
125
|
+
return record
|
|
126
|
+
|
|
127
|
+
def require_user(self,request,*,privacy=True):
|
|
128
|
+
user=self.authenticated_user(request)
|
|
129
|
+
if privacy:
|
|
130
|
+
from socialctl.saas import consent
|
|
131
|
+
with self.vault.read_transaction() as db:
|
|
132
|
+
accepted=consent.privacy_accepted(self.metadata,db,user.id)
|
|
133
|
+
if not accepted:
|
|
134
|
+
if request.method in {'GET','HEAD'}:
|
|
135
|
+
from urllib.parse import urlencode
|
|
136
|
+
from socialctl.saas.routes import safe_next
|
|
137
|
+
raise HTTPException(303,'Review the Privacy Policy.',headers={
|
|
138
|
+
'Location':'/account/privacy?'+urlencode({'next':safe_next(request.url.path)})})
|
|
139
|
+
raise HTTPException(403,'privacy_acceptance_required: The account owner must review the current Privacy Policy in their browser.')
|
|
140
|
+
return user
|
|
141
|
+
|
|
142
|
+
def authenticated_user(self,request):
|
|
143
|
+
secret=request.cookies.get(self.cookie,'')
|
|
144
|
+
if not 16<=len(secret)<=512:
|
|
145
|
+
raise HTTPException(401,'Sign in to SocialCli to continue.')
|
|
146
|
+
key=digest(secret);lease=None
|
|
147
|
+
with self.vault.read_transaction() as db:
|
|
148
|
+
record=self.checked(db,key)
|
|
149
|
+
data=record['payload']
|
|
150
|
+
refresh=bool(data.get('refresh_token') and data.get('access_expires',record['expires'])<=self.clock()+60)
|
|
151
|
+
if not refresh and data.get('verified_until',0)>self.clock():
|
|
152
|
+
request.state.saas_session=data
|
|
153
|
+
return AuthenticatedUser(data['user_id'],data['email'])
|
|
154
|
+
if refresh:
|
|
155
|
+
with self.vault.transaction() as db:
|
|
156
|
+
record=self.checked(db,key);data=record['payload']
|
|
157
|
+
if data.get('access_expires',0)>self.clock()+60:
|
|
158
|
+
request.state.saas_session=data
|
|
159
|
+
return AuthenticatedUser(data['user_id'],data['email'])
|
|
160
|
+
if data.get('refresh_lease'):
|
|
161
|
+
# An ambiguous rotation must never replay an old refresh token.
|
|
162
|
+
if data['refresh_until']<=self.clock():
|
|
163
|
+
raise HTTPException(401,'Your session needs a fresh sign-in.')
|
|
164
|
+
if request.method not in {'GET','HEAD'} or data.get('access_expires',0)<=self.clock():
|
|
165
|
+
raise HTTPException(503,'Your session is refreshing. Please try again shortly.')
|
|
166
|
+
# Verify the still-live access token without replaying refresh.
|
|
167
|
+
# The final checked transaction preserves logout/account fences.
|
|
168
|
+
else:
|
|
169
|
+
lease=secrets.token_urlsafe(24)
|
|
170
|
+
data.update(refresh_lease=lease,refresh_until=self.clock()+30)
|
|
171
|
+
self.vault.put(db,'saas-session',key,data,expires=record['expires'])
|
|
172
|
+
try:
|
|
173
|
+
if lease:
|
|
174
|
+
user,access,expiry,refresh_token=self.identity.refresh(data['refresh_token'])
|
|
175
|
+
else:
|
|
176
|
+
user=self.identity.get_user(data['access_token'])
|
|
177
|
+
if user.id!=data['user_id'] or user.email!=data['email']:
|
|
178
|
+
raise IdentityError()
|
|
179
|
+
except IdentityError:
|
|
180
|
+
with self.vault.transaction() as db:
|
|
181
|
+
current=self.vault.get(db,'saas-session',key)
|
|
182
|
+
if current and current['payload'].get('access_token')==data['access_token']:
|
|
183
|
+
self.vault.delete(db,'saas-session',key)
|
|
184
|
+
raise HTTPException(401,'Sign in to SocialCli to continue.') from None
|
|
185
|
+
except IdentityUnavailable:
|
|
186
|
+
raise HTTPException(503,'Sign-in is temporarily unavailable. Please try again.') from None
|
|
187
|
+
# A concurrent logout, deletion or credential rotation must win.
|
|
188
|
+
with self.vault.transaction() as db:
|
|
189
|
+
current=self.checked(db,key);latest=current['payload']
|
|
190
|
+
if lease:
|
|
191
|
+
if latest.get('refresh_lease')!=lease:
|
|
192
|
+
raise HTTPException(401,'Sign in to SocialCli to continue.')
|
|
193
|
+
latest.update(access_token=access,refresh_token=refresh_token,access_expires=self.clock()+expiry)
|
|
194
|
+
latest.pop('refresh_lease',None);latest.pop('refresh_until',None)
|
|
195
|
+
else:
|
|
196
|
+
if latest.get('refresh_lease') and latest['refresh_until']<=self.clock():
|
|
197
|
+
raise HTTPException(401,'Your session needs a fresh sign-in.')
|
|
198
|
+
if latest.get('access_expires',current['expires'])<=self.clock():
|
|
199
|
+
raise HTTPException(503,'Your session is refreshing. Please try again shortly.')
|
|
200
|
+
if latest['access_token']!=data['access_token'] and latest.get('verified_until',0)<=self.clock():
|
|
201
|
+
raise HTTPException(503,'Your session changed. Please try again.')
|
|
202
|
+
latest['verified_until']=min(self.clock()+self.verification_seconds,latest.get('access_expires',current['expires']))
|
|
203
|
+
self.vault.put(db,'saas-session',key,latest,expires=current['expires'])
|
|
204
|
+
request.state.saas_session=latest
|
|
205
|
+
return user
|
|
206
|
+
|
|
207
|
+
def revoke(self,request):
|
|
208
|
+
with self.vault.transaction() as db:
|
|
209
|
+
self.vault.delete(db,'saas-session',digest(request.cookies.get(self.cookie,'')))
|
|
210
|
+
try:
|
|
211
|
+
self.identity.logout(request.state.saas_session['access_token'])
|
|
212
|
+
except (IdentityError,IdentityUnavailable):
|
|
213
|
+
pass # Local revocation is already durable, even if upstream is down.
|
socialctl/saas/backup.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Private online SQLite snapshots; never restore over a running service."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import sqlite3
|
|
11
|
+
import tempfile
|
|
12
|
+
import time
|
|
13
|
+
from contextlib import closing
|
|
14
|
+
|
|
15
|
+
from cryptography.fernet import Fernet, MultiFernet, InvalidToken
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class BackupError(Exception):
|
|
19
|
+
"""Sanitized operator error: no SQL, identities or credentials in diagnostics."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _read(path, timeout=5):
|
|
23
|
+
return sqlite3.connect(Path(path).resolve().as_uri()+'?mode=ro',uri=True,timeout=timeout)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def verify_snapshot(path: Path, keys: list[bytes]) -> dict:
|
|
27
|
+
"""Check an isolated snapshot read-only; no migrations, expiry or network I/O."""
|
|
28
|
+
try:
|
|
29
|
+
cipher=MultiFernet([Fernet(key) for key in keys])
|
|
30
|
+
with closing(_read(path)) as db:
|
|
31
|
+
db.row_factory=sqlite3.Row
|
|
32
|
+
db.execute('BEGIN')
|
|
33
|
+
if db.execute('PRAGMA integrity_check').fetchall()[0][0]!='ok':
|
|
34
|
+
raise ValueError()
|
|
35
|
+
if db.execute('PRAGMA foreign_key_check').fetchone() is not None:
|
|
36
|
+
raise ValueError()
|
|
37
|
+
records=0
|
|
38
|
+
for row in db.execute('SELECT * FROM records'):
|
|
39
|
+
envelope=json.loads(cipher.decrypt(row['payload']))
|
|
40
|
+
if (envelope['kind']!=row['kind'] or envelope['id']!=row['id']
|
|
41
|
+
or envelope['expires']!=row['expires']
|
|
42
|
+
or envelope['credential_hash']!=row['credential_hash']
|
|
43
|
+
or not isinstance(envelope['payload'],dict)):
|
|
44
|
+
raise ValueError()
|
|
45
|
+
records+=1
|
|
46
|
+
names={row[0] for row in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
|
|
47
|
+
version=db.execute('SELECT coalesce(max(version),0) FROM saas_schema').fetchone()[0] if 'saas_schema' in names else 0
|
|
48
|
+
cutoff=bool(db.execute('SELECT 1 FROM legacy_cutoff WHERE singleton=1').fetchone()) if 'legacy_cutoff' in names else False
|
|
49
|
+
tables=len(names)
|
|
50
|
+
with Path(path).open('rb') as stream:
|
|
51
|
+
digest=hashlib.file_digest(stream,'sha256').hexdigest()
|
|
52
|
+
return {'integrity':'ok','records':records,'tables':tables,'schema_version':version,
|
|
53
|
+
'legacy_cutoff':cutoff,'sha256':digest}
|
|
54
|
+
except (OSError,sqlite3.Error,ValueError,TypeError,KeyError,InvalidToken):
|
|
55
|
+
raise BackupError('Snapshot validation failed; check the database and its separate key set.') from None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def snapshot(source: Path, destination: Path, keys: list[bytes], *, timeout=60) -> dict:
|
|
59
|
+
"""Publish a verified 0600 snapshot atomically, refusing any existing target."""
|
|
60
|
+
source,destination=Path(source),Path(destination)
|
|
61
|
+
if not math.isfinite(timeout) or timeout<=0:
|
|
62
|
+
raise BackupError('Backup timeout must be positive and finite.')
|
|
63
|
+
temporary=None
|
|
64
|
+
try:
|
|
65
|
+
if destination.exists() or destination.is_symlink() or not source.is_file():
|
|
66
|
+
raise BackupError('Source must exist and destination must be new.')
|
|
67
|
+
destination.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
|
|
68
|
+
# Do not change permissions of a pre-existing operator directory.
|
|
69
|
+
if destination.parent.stat().st_mode & 0o077:
|
|
70
|
+
raise BackupError('Use a private destination directory with mode 0700.')
|
|
71
|
+
fd,name=tempfile.mkstemp(prefix='.socialcli-snapshot-',dir=destination.parent)
|
|
72
|
+
temporary=Path(name);os.close(fd)
|
|
73
|
+
deadline=time.monotonic()+timeout
|
|
74
|
+
def progress(status,remaining,total):
|
|
75
|
+
if time.monotonic()>=deadline:
|
|
76
|
+
raise BackupError('Snapshot timed out; no completed artifact was published.')
|
|
77
|
+
with closing(_read(source,min(timeout,1))) as live, closing(sqlite3.connect(temporary)) as target:
|
|
78
|
+
live.backup(target,pages=128,progress=progress,sleep=min(timeout,.05))
|
|
79
|
+
# A backup must never become a live SaaS database just by mounting it.
|
|
80
|
+
# Only restore_guard may apply current deletion authority and release
|
|
81
|
+
# a separately staged copy after isolated identity cleanup.
|
|
82
|
+
if target.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='saas_schema'").fetchone():
|
|
83
|
+
target.execute('CREATE TABLE IF NOT EXISTS saas_restore_guard (singleton INTEGER PRIMARY KEY CHECK(singleton=1),state TEXT NOT NULL,prepared REAL NOT NULL,snapshot_created REAL NOT NULL)')
|
|
84
|
+
target.execute("INSERT OR REPLACE INTO saas_restore_guard VALUES(1,'unprepared',0,?)",(time.time(),))
|
|
85
|
+
target.commit()
|
|
86
|
+
# Produce a self-contained single file even when the source uses WAL.
|
|
87
|
+
target.execute('PRAGMA journal_mode=DELETE')
|
|
88
|
+
report=verify_snapshot(temporary,keys)
|
|
89
|
+
with temporary.open('rb') as stream:os.fsync(stream.fileno())
|
|
90
|
+
# Same-directory hard link is atomic and cannot replace an existing path.
|
|
91
|
+
os.link(temporary,destination)
|
|
92
|
+
directory_fd=os.open(destination.parent,os.O_RDONLY)
|
|
93
|
+
try:os.fsync(directory_fd)
|
|
94
|
+
finally:os.close(directory_fd)
|
|
95
|
+
return report
|
|
96
|
+
except (OSError,sqlite3.Error):
|
|
97
|
+
raise BackupError('Snapshot failed; source preserved. Inspect storage permissions and locks.') from None
|
|
98
|
+
finally:
|
|
99
|
+
if temporary is not None:
|
|
100
|
+
temporary.unlink(missing_ok=True)
|
|
101
|
+
for suffix in ('-journal','-wal','-shm'):
|
|
102
|
+
Path(str(temporary)+suffix).unlink(missing_ok=True)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def main():
|
|
106
|
+
parser=argparse.ArgumentParser(description=__doc__)
|
|
107
|
+
parser.add_argument('operation',choices=['snapshot','verify'])
|
|
108
|
+
parser.add_argument('database',type=Path)
|
|
109
|
+
parser.add_argument('destination',type=Path,nargs='?')
|
|
110
|
+
parser.add_argument('--timeout',type=float,default=60)
|
|
111
|
+
args=parser.parse_args()
|
|
112
|
+
if (args.operation=='snapshot') != (args.destination is not None):
|
|
113
|
+
parser.error('snapshot requires a destination; verify accepts only a database')
|
|
114
|
+
keys=[value.strip().encode() for value in os.environ.get('SOCIALCLI_ENCRYPTION_KEYS','').split(',') if value.strip()]
|
|
115
|
+
try:
|
|
116
|
+
report=(snapshot(args.database,args.destination,keys,timeout=args.timeout)
|
|
117
|
+
if args.operation=='snapshot' else verify_snapshot(args.database,keys))
|
|
118
|
+
except BackupError as error:
|
|
119
|
+
parser.exit(1,str(error)+'\n')
|
|
120
|
+
print(json.dumps(report,sort_keys=True))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
if __name__=='__main__':
|
|
124
|
+
main()
|