-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
506 lines (427 loc) · 19.7 KB
/
Copy pathapp.py
File metadata and controls
506 lines (427 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
"""
☀ HELIOS — Neural Field Protocol
A private network where human connections inject energy
and the protocol distributes it according to physics, not position.
heliosdigital.xyz
"""
import os
import sys
import time
import logging
from datetime import datetime, timezone
from flask import Flask, render_template, request, g, jsonify, abort, Response
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from config import HeliosConfig
from core.build_manifest import get_build_manifest
from extensions import limiter
from models.member import Base
# Validate config on startup — fails fast if protocol rules are broken
HeliosConfig.validate()
log = logging.getLogger('helios')
def create_app():
"""Application factory."""
app = Flask(__name__)
app.config.from_object(HeliosConfig)
app.config["RATELIMIT_DEFAULT"] = HeliosConfig.RATE_LIMIT_DEFAULT
app.config["RATELIMIT_STORAGE_URI"] = HeliosConfig.RATE_LIMIT_STORAGE_URI
limiter.init_app(app)
if HeliosConfig.SENTRY_DSN:
sentry_sdk.init(
dsn=HeliosConfig.SENTRY_DSN,
integrations=[FlaskIntegration()],
traces_sample_rate=0.1,
environment="development" if HeliosConfig.DEBUG else "production",
)
@app.context_processor
def inject_build_id():
manifest = get_build_manifest()
return {
"helios_build_id": manifest["build_id"],
"helios_build_watermark": manifest["watermark"],
"helios_build_fingerprint": manifest["fingerprint"],
"helios_deployment_route": manifest["route"],
"helios_build_owner": manifest["owner"],
"helios_watermark_mode": manifest["mode"],
"helios_watermark_enabled": manifest["watermark_enabled"],
"helios_show_simple_watermark": manifest["show_simple_watermark"],
"helios_show_visible_watermark": manifest["show_visible_watermark"],
"helios_version": "3.0.0",
"helios_year": datetime.now(timezone.utc).year,
"brand_theme": "helios",
}
# ─── Security Headers ─────────────────────────────────────────
@app.after_request
def security_headers(response):
manifest = get_build_manifest()
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
response.headers['X-XSS-Protection'] = '1; mode=block'
response.headers['X-Build-Fingerprint'] = manifest['fingerprint']
response.headers['X-Deployment-Route'] = manifest['route']
if manifest['build_id']:
response.headers['X-Build-Id'] = manifest['build_id']
if manifest['watermark']:
response.headers['X-Build-Watermark'] = manifest['watermark']
response.headers['Content-Security-Policy'] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://js.stripe.com; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
"font-src 'self' https://fonts.gstatic.com; "
"img-src 'self' data: https:; "
"connect-src 'self' https://api.openai.com https://api.stripe.com https://*.heliosdigital.xyz; "
"frame-src https://js.stripe.com; "
"object-src 'none'; "
"base-uri 'self'"
)
response.headers['Permissions-Policy'] = (
'camera=(), microphone=(), geolocation=(), payment=(self)'
)
if not HeliosConfig.DEBUG:
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
return response
# ─── CORS (allow Netlify preview deploys) ─────────────────────
@app.after_request
def cors_headers(response):
origin = request.headers.get('Origin', '')
allowed = (
origin.endswith('.netlify.app') or
origin.endswith('.heliosdigital.xyz') or
origin == 'https://heliosdigital.xyz' or
origin.endswith('.xxxiii.io') or
origin == 'https://xxxiii.io' or
HeliosConfig.DEBUG
)
if allowed:
response.headers['Access-Control-Allow-Origin'] = origin
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
return response
# ─── Request Logging ──────────────────────────────────────────
@app.before_request
def log_request():
g._request_start = time.time()
@app.after_request
def log_response(response):
duration = time.time() - getattr(g, '_request_start', time.time())
if request.path.startswith('/static/'):
return response # Don't log static assets
log.info('%s %s %s %.0fms',
request.method, request.path, response.status_code,
duration * 1000)
return response
# ─── Error Handlers ───────────────────────────────────────────
@app.errorhandler(404)
def not_found(e):
if request.path.startswith('/api/'):
return jsonify({'success': False, 'error': 'Endpoint not found'}), 404
return render_template('error.html', code=404,
message='This route does not exist in the Helios protocol.'), 404
@app.errorhandler(500)
def server_error(e):
log.exception('Internal server error on %s', request.path)
if request.path.startswith('/api/'):
return jsonify({'success': False, 'error': 'Internal protocol error'}), 500
return render_template('error.html', code=500,
message='An internal protocol error occurred.'), 500
@app.errorhandler(429)
def rate_limited(e):
if request.path.startswith('/api/'):
return jsonify({'success': False, 'error': 'Rate limited — slow down'}), 429
return render_template('error.html', code=429,
message='Too many requests. Please wait before trying again.'), 429
# ─── Database ─────────────────────────────────────────────────
data_dir = os.path.join(os.path.dirname(__file__), "data")
os.makedirs(data_dir, exist_ok=True)
db_url = HeliosConfig.DATABASE_URL
engine_kwargs = dict(echo=False)
# SQLite needs special handling for concurrent access
if db_url.startswith("sqlite"):
engine_kwargs["connect_args"] = {"check_same_thread": False, "timeout": 30}
if db_url in ("sqlite://", "sqlite:///"):
# In-memory DB — must reuse the single connection or tables vanish
from sqlalchemy.pool import StaticPool
engine_kwargs["poolclass"] = StaticPool
else:
from sqlalchemy.pool import NullPool
engine_kwargs["poolclass"] = NullPool
engine = create_engine(db_url, **engine_kwargs)
# Import ALL models so their tables get created
from models.link import Link # noqa: F401 — required for table creation
from models.vault_receipt import VaultReceipt # noqa: F401
from models.certificate import Certificate # noqa: F401
from models.energy_event import EnergyEvent # noqa: F401
from models.credential import Credential # noqa: F401
from models.space import Space, SpaceEvent # noqa: F401
from models.subscription import Subscription # noqa: F401
from models.payment_event import PaymentEvent # noqa: F401
from models.node_event import NodeEvent # noqa: F401 — QR node telemetry
from models.phone_verification import PhoneVerification # noqa: F401
from models.token_pool import TokenPool # noqa: F401 — required for genesis check
Base.metadata.create_all(engine)
SessionFactory = sessionmaker(bind=engine)
Session = scoped_session(SessionFactory)
@app.before_request
def before_request():
g.db_session = Session()
@app.teardown_request
def teardown_request(exception=None):
session = g.pop('db_session', None)
if session:
if exception:
session.rollback()
session.close()
Session.remove() # Release scoped session back to pool
# ─── Register Blueprints ──────────────────────────────────────
from api.routes import (
identity_bp, field_bp, network_bp, energy_bp,
wallet_bp, token_bp, chat_bp,
voice_bp, sms_bp, infra_bp, handoff_bp,
treasury_bp, certificates_bp,
funding_bp,
spaces_bp, metrics_bp, rewards_bp,
nodes_bp
)
from api.evm_routes import evm_bp
app.register_blueprint(identity_bp)
app.register_blueprint(field_bp)
app.register_blueprint(network_bp)
app.register_blueprint(energy_bp)
app.register_blueprint(wallet_bp)
app.register_blueprint(token_bp)
app.register_blueprint(chat_bp)
app.register_blueprint(voice_bp)
app.register_blueprint(sms_bp)
app.register_blueprint(infra_bp)
app.register_blueprint(handoff_bp)
app.register_blueprint(treasury_bp)
app.register_blueprint(certificates_bp)
app.register_blueprint(funding_bp)
app.register_blueprint(spaces_bp)
app.register_blueprint(metrics_bp)
app.register_blueprint(rewards_bp)
app.register_blueprint(nodes_bp)
app.register_blueprint(evm_bp)
# ─── Page Routes ──────────────────────────────────────────────
@app.route("/")
def index():
return render_template("index.html")
@app.route("/enter")
@app.route("/enter/<referrer>")
def enter(referrer=None):
return render_template("join.html", referrer=referrer)
@app.route("/join")
@app.route("/join/<referrer>")
def join(referrer=None):
return render_template("join.html", referrer=referrer)
@app.route("/qr")
@app.route("/qr/<helios_id>")
def qr_page(helios_id=None):
return render_template("qr.html", helios_id=helios_id)
@app.route("/dashboard")
def dashboard():
return render_template("dashboard.html")
@app.route("/field")
def field():
return render_template("network.html")
@app.route("/network")
def network():
return render_template("network.html")
@app.route("/ask")
def ask():
return render_template("ask.html")
@app.route("/guide")
def guide():
return render_template("guide.html")
@app.route("/start")
@app.route("/handoff")
def handoff():
from core.handoff import get_handoff_manifest, list_handoff_docs
return render_template("handoff.html", manifest=get_handoff_manifest(), docs=list_handoff_docs())
@app.route("/handoff/docs/<slug>")
def handoff_doc_page(slug):
from core.handoff import get_handoff_doc
document = get_handoff_doc(slug)
if not document:
abort(404)
return render_template("handoff_doc.html", doc=document)
@app.route("/handoff/docs/<slug>/raw")
def handoff_doc_raw(slug):
from core.handoff import get_handoff_doc
document = get_handoff_doc(slug)
if not document:
abort(404)
return Response(document["content"], mimetype="text/markdown; charset=utf-8")
@app.route("/handoff/docs/<slug>/download")
def handoff_doc_download(slug):
from core.handoff import get_handoff_doc
document = get_handoff_doc(slug)
if not document:
abort(404)
response = Response(document["content"], mimetype="text/markdown; charset=utf-8")
response.headers["Content-Disposition"] = f"attachment; filename={slug}.md"
return response
@app.route("/protocol")
def protocol():
return render_template("status.html")
@app.route("/status")
def status():
return render_template("status.html")
@app.route("/treasury")
def treasury():
return render_template("treasury.html")
@app.route("/vault")
def vault():
return render_template("vault.html")
@app.route("/vault/gold")
def vault_gold():
return render_template("vault_gold.html")
@app.route("/activate")
@app.route("/activate/<referrer>")
def activate(referrer=None):
return render_template("activate.html", referrer=referrer)
@app.route("/earnings")
def earnings():
return render_template("earnings.html")
@app.route("/certificates")
def certificates():
return render_template("certificates.html")
@app.route("/opportunity")
@app.route("/recruit")
def opportunity():
return render_template("recruit.html")
@app.route("/metrics")
def metrics():
return render_template("metrics.html")
@app.route("/ops/nodes")
def ops_nodes():
return render_template("ops_nodes.html")
@app.route("/launch")
@app.route("/token-offering")
def launch():
return render_template("launch.html")
@app.route("/tokenomics")
def tokenomics():
return render_template("tokenomics.html")
@app.route("/web3")
def web3():
return render_template("web3.html")
# ─── Card & Drop Routes (Premium Member Card System) ─────────
@app.route("/card/<display_name>")
def member_card(display_name):
"""Premium member asset card — the showpiece."""
from core.distribution import DistributionEngine
from core.identity import HeliosIdentity
identity = HeliosIdentity(g.db_session)
helios_id = f"{display_name}{HeliosConfig.IDENTITY_SUFFIX}"
member_info = identity.verify_id(helios_id)
is_founder = display_name.lower() in getattr(HeliosConfig, 'FOUNDERS', [])
member_data = {
"helios_id": helios_id,
"display_name": display_name,
"tier": "founder" if is_founder else member_info.get("tier", "founder"),
"is_founder": is_founder,
"member_since": member_info.get("member_since", "") if member_info.get("exists") else "",
}
ctx = DistributionEngine.get_drop_context(member_data)
ctx["member_id"] = member_info.get("member_id", 1) if member_info.get("exists") else 1
return render_template("card.html", **ctx)
@app.route("/drop/<display_name>")
def drop_page(display_name):
"""Lightweight QR-scan landing — fast, clear, one CTA."""
from core.distribution import DistributionEngine
from core.identity import HeliosIdentity
identity = HeliosIdentity(g.db_session)
helios_id = f"{display_name}{HeliosConfig.IDENTITY_SUFFIX}"
member_info = identity.verify_id(helios_id)
is_founder = display_name.lower() in getattr(HeliosConfig, 'FOUNDERS', [])
member_data = {
"helios_id": helios_id,
"display_name": display_name,
"tier": "founder" if is_founder else member_info.get("tier", "founder"),
"is_founder": is_founder,
"member_since": member_info.get("member_since", "") if member_info.get("exists") else "",
}
ctx = DistributionEngine.get_drop_context(member_data)
return render_template("drop.html", **ctx)
@app.route("/api/identity/<display_name>/vcard")
def download_vcard(display_name):
"""Download a premium vCard (.vcf) for a Helios member."""
from core.vcard import HeliosVCard
from core.identity import HeliosIdentity
identity = HeliosIdentity(g.db_session)
helios_id = f"{display_name}{HeliosConfig.IDENTITY_SUFFIX}"
member_info = identity.verify_id(helios_id)
is_founder = display_name.lower() in getattr(HeliosConfig, 'FOUNDERS', [])
member_data = {
"helios_id": helios_id,
"display_name": display_name,
"tier": "founder" if is_founder else member_info.get("tier", "founder"),
"is_founder": is_founder,
"created_at": member_info.get("member_since", "") if member_info.get("exists") else "",
}
vcf_content = HeliosVCard.generate(member_data)
filename = HeliosVCard.generate_filename(display_name, is_founder)
response = Response(vcf_content, mimetype=HeliosVCard.content_type())
response.headers["Content-Disposition"] = HeliosVCard.content_disposition(filename)
return response
# ─── Health Check ─────────────────────────────────────────────
@app.route("/health")
@app.route("/api/health")
def health():
return {
"status": "ok",
"system": "helios",
"version": "3.0.0",
"paradigm": "energy_exchange",
"domain": HeliosConfig.DOMAIN
}
# ─── Initialize Token Pools (first-run) ───────────────────────
with app.app_context():
session = Session()
from models.token_pool import TokenPool
if not session.query(TokenPool).first():
from core.token import TokenEngine
engine_t = TokenEngine(session)
try:
result = engine_t.initialize_pools()
print(f" ☀ Genesis — Token pools initialized: {result['total_supply']:,.0f} HLS")
except ValueError:
pass # Already initialized
finally:
session.close()
return app
# ─── Entry Point ──────────────────────────────────────────────────
if __name__ == "__main__":
import sys
if sys.stdout.encoding and sys.stdout.encoding.lower() not in ('utf-8', 'utf-16'):
try:
sys.stdout.reconfigure(encoding='utf-8')
except Exception:
pass
app = create_app()
print(f"""
╔══════════════════════════════════════════════════╗
║ ║
║ ☀ HELIOS v3.0.0 — Allocation Protocol ║
║ ║
║ Smart contracts. Gold-backed certificates. ║
║ XRPL + Stellar. Deterministic math. ║
║ ║
║ Guide: http://localhost:{HeliosConfig.PORT}/guide ║
║ Treasury: http://localhost:{HeliosConfig.PORT}/treasury ║
║ Gold Vault: http://localhost:{HeliosConfig.PORT}/vault/gold ║
║ Metrics: http://localhost:{HeliosConfig.PORT}/metrics ║
║ Advisory: http://localhost:{HeliosConfig.PORT}/ask ║
║ Domain: {HeliosConfig.DOMAIN} ║
║ ║
╚══════════════════════════════════════════════════╝
""", flush=True)
app.run(
host=HeliosConfig.HOST,
port=HeliosConfig.PORT,
debug=HeliosConfig.DEBUG
)