-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
314 lines (264 loc) · 11.5 KB
/
app.py
File metadata and controls
314 lines (264 loc) · 11.5 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
"""
☀ HELIOS — Neural Field Protocol
A private network where human connections inject energy
and the protocol distributes it according to physics, not position.
xxxiii.io
"""
import os
import sys
import time
import logging
from datetime import datetime, timezone
from flask import Flask, render_template, request, g, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
from config import HeliosConfig
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.context_processor
def inject_build_id():
return {
"helios_build_id": os.environ.get("HELIOS_BUILD_ID", ""),
"helios_version": "3.0.0",
"helios_year": datetime.now(timezone.utc).year,
}
# ─── Security Headers ─────────────────────────────────────────
@app.after_request
def security_headers(response):
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'
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('.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)
engine = create_engine(
HeliosConfig.DATABASE_URL,
echo=False,
pool_pre_ping=True
)
# Import ALL models so their tables get created
from models.bond import Bond # 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
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()
# ─── 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,
treasury_bp, certificates_bp,
spaces_bp, metrics_bp, rewards_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(treasury_bp)
app.register_blueprint(certificates_bp)
app.register_blueprint(spaces_bp)
app.register_blueprint(metrics_bp)
app.register_blueprint(rewards_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("/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("/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")
# ─── 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__":
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} ║
║ ║
╚══════════════════════════════════════════════════╝
""")
app.run(
host=HeliosConfig.HOST,
port=HeliosConfig.PORT,
debug=HeliosConfig.DEBUG
)