feat: goctf final

This commit is contained in:
TakuyaYagam1 committed 2026-10-29 10:55:49 +03:00
commit f205b802d5
128 files changed
+37794

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
STARPOST_DB_PASSWORD=replace-with-url-safe-random-value
STARPOST_SECRET_KEY=replace-with-at-least-32-random-bytes
STARPOST_WAREHOUSE_CALLBACK_TOKEN=replace-with-at-least-32-random-bytes
View File
Whitespace-only changes.
+100
View File
@@ -0,0 +1,100 @@
# Starpost: покупка чужого cargo, 25 октября 2026
## Подтверждённый путь
Публичный каталог показывает ID и цену товара. Новый buyer получает 100 кредитов
при регистрации и ещё 100 при однократном применении своего promo. Товары,
созданные checker с флагом в `cargo`, на нашем экземпляре стоили 102–180.
Покупатель оплачивает товар через `POST /api/products/{id}/buy` или корзину,
warehouse доставляет заказ, после чего `GET /api/orders` возвращает `cargo`.
На первом снимке игровой БД были 12 товаров с флагоподобным `cargo` и 91 доставленный
заказ от 91 buyer. Счётчики растут, это не точное число похищенных или
зачтённых флагов. Старые пути через неподписанный курсор отзывов, чужой договор
и поддельный warehouse callback текущая версия отклоняет. Runtime session key
и callback token уже отличаются от старых литералов в скриптах. Секреты и
значения флагов в этом документе не сохраняются.
## Что делает checker
Ежеминутный поток создаёт seller и product, читает карточку и собственный
договор, регистрирует **нового** buyer, применяет и гасит promo, покупает через
корзину или прямой buy, опрашивает заказы до доставки и оставляет отзыв.
Позднее checker читает старые заказы, договоры и отзывы. В 62 наблюдённых
сценариях первая покупка произошла через 0,232–0,563 с после создания товара.
Buyer создаётся без cookie seller; связывать их по одной сессии нельзя.
В 421 запросе с checker-подобным User-Agent общий `GET /api/products` не
встречался, а прямой `GET /api/products/{id}` встречался 26 раз. Это вывод из
access log, а не исходный код официального checker.
## Риск ограничения по первому заказу
Первоначальный независимый review не рекомендовал ограничение `cargo` по
первому покупателю, времени покупки, User-Agent, IP или виду флага.
Первый покупатель может оказаться соперником,
что лишит checker возможности прочитать свой флаг и даст `CORRUPT`/`MUMBLE`.
Проверка времени основана лишь на текущей скорости checker и лишает
оплативших поздних покупателей груза. User-Agent подделывается, а маршрутизатор
сводит HTTP-клиентов к одному видимому IP. Такие ограничения нарушают
штатную семантику покупки и не дают надёжной защиты.
Изолированный Flask/PostgreSQL прогон проверил маршруты seller/product,
contract, promo, прямую покупку и checkout, warehouse delivery, orders,
private review и чтение старого заказа после перезапуска приложения. Он
**не заменяет официальный checker**. Ограничение cargo по первому заказу из
`ecd6d555` было развёрнуто на своей vulnbox, после чего официальный checker
перешёл в `CHECK FAILED`. Ограничение откатили как несовместимое с checker.
Для настоящего исправления нужен предусмотренный протоколом способ указать
получателя товара при создании или иное право, которое checker может передать
новому buyer. Текущий checker и соперник используют одинаковый маршрут покупки;
без изменения контракта их нельзя надёжно различить.
## Откат ограничения cargo
Снимок с `CHECK FAILED` и ростом `lost` до 25 подтвердил, что минимальный заказ
товара не всегда принадлежит checker. `GET /api/orders` возвращён к исходному
контракту: каждый доставленный заказ получает cargo. Схема и данные БД не
изменялись, поэтому для отката достаточно пересобрать только `api`.
Требование обязательного `POST /api/promo/invalidate` перед покупкой удалено
после ошибки checker `Unexpected HTTP status from /api/products/{id}/buy`.
Оно не останавливало адаптивный сплойт, который мог вызвать публичный invalidate,
но добавляло несовместимый HTTP 409 в штатный путь. Однократность начисления
promo через `credited_at` сохранена.
## Эксплойт и дальнейшая проверка
`sploits/starpost_market.py` читает публичный Skipper `attack_data` для Дока,
выбирает до двух числовых ID товаров конкретной цели и воспроизводит покупку
отдельными buyer с однократным promo. На своей БД 3/3 числовых подсказки
совпали с товарами, 2/3 имели флагоподобный cargo; подсказка не гарантирует
флаг. При отсутствии подсказок скрипт ограниченно выбирает свежие товары
ценой от 101 кредита. После начисления promo скрипт также вызывает
`promo/invalidate`. Предел одного запуска — две покупки, до 22 HTTP
запросов и 8,5 с. Семь синтетических проверок прошли, включая последовательность
«первый товар без флага, второй с флагом» и stdout только с флагом.
Также `sploits/starpost_signup.py` и `sploits/starpost_warehouse.py` теперь
гасят promo до покупки и checkout. Вместе их проверяют восемь loopback
сценариев отказа и успеха, включая проверку, что stdout содержит только флаг.
Все три скрипта прошли `py_compile` и `git diff --check`; это локальные
синтетические проверки, а не подтверждение запуска в Neo или зачёта Skipper.
Один контролируемый прогон на команде 3 получил флаг, но Skipper ответил
`Flag already stolen`; прогон на команде 2 купил два товара без флага.
Значения флагов не сохранены. `accepted` и работа из Neo пока не подтверждены;
текущая доступная установка не содержит работающих Neo/Farm контейнеров или
учётных данных. Не объявлять этот exploit зачтённым, пока не появятся
`neo test` на разрешённой цели и персональный ответ Skipper.
На снимке раунда 73 (12:12:53 МСК) Док был `UP`, проверки 70/72,
`stolen=328`, `lost=25`; на раунде 69 значения были `320/25`. Последующий
`CHECK FAILED` показал, что ограничение первого заказа нельзя считать
checker-совместимым.
Перед любым следующим патчем сохранить состояние томов и текущий commit,
прогнать оба способа покупки и GET-old, затем после выкладки проверить статус
официального checker. Не выполнять `git reset`/обычный `git pull` на vulnbox:
в рабочей копии Git отслеживает файлы `starpost/postgres/`, которые меняются
во время игры.
+2
View File
@@ -0,0 +1,2 @@
__pycache__/
*.pyc
+8
View File
@@ -0,0 +1,8 @@
FROM python:3.12-alpine
RUN apk add --no-cache ttf-dejavu
COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt
COPY *.py /app/
WORKDIR /app
CMD ["gunicorn", "--preload", "--workers", "2", "--threads", "2", "--bind", "0.0.0.0:5000", "app:app"]
+797
View File
@@ -0,0 +1,797 @@
import base64
import hashlib
import hmac
import json as _json
import os
import re
import secrets
from datetime import datetime, timezone
from functools import lru_cache, wraps
import psycopg
from flask import Flask, jsonify, request, send_file, session
from contracts import CONTRACT_DIR, create_contract
from database import (
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS,
CARGO_PURCHASE_WINDOW_SECONDS,
connect as db,
migrate,
)
from warehouse_client import CALLBACK_TOKEN as WAREHOUSE_CALLBACK_TOKEN
from warehouse_client import get_health as get_warehouse_health
from warehouse_client import submit_jobs as submit_warehouse_jobs
from passwords import hash_password, password_matches
app = Flask(__name__)
app.config.update(
SECRET_KEY=os.environ["SECRET_KEY"],
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE="Lax",
SESSION_COOKIE_PATH="/",
MAX_CONTENT_LENGTH=32 * 1024,
)
CONTRACT_FILENAME_RE = re.compile(r"contract-([0-9]+)-[0-9a-f]{16}\.pdf")
migrate()
def now():
return datetime.now(timezone.utc)
def body():
data = request.get_json(silent=True)
return data if isinstance(data, dict) else None
def error(message, status=400):
return jsonify(error=message), status
def text(value, field, minimum=1, maximum=200):
if not isinstance(value, str) or not minimum <= len(value.strip()) <= maximum:
raise ValueError(f"{field} length must be {minimum}..{maximum}")
return value.strip()
def own_contract_filename(filename, user_id):
match = CONTRACT_FILENAME_RE.fullmatch(filename)
return match is not None and match.group(1) == str(user_id)
@lru_cache(maxsize=4096)
def contract_owner(user_id):
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT id,contract_file FROM users WHERE id=%s", (user_id,))
owner = cur.fetchone()
if not owner:
return None
return owner["id"], owner["contract_file"]
def auth(role=None):
def decorator(handler):
@wraps(handler)
def wrapped(*args, **kwargs):
if "user_id" not in session:
return error("authentication required", 401)
if role and session["role"] != role:
return error("forbidden", 403)
return handler(*args, **kwargs)
return wrapped
return decorator
@app.get("/health")
def health():
try:
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT 1 FROM users LIMIT 1")
except psycopg.Error:
return jsonify(status="starting", service="starpost-api"), 503
return jsonify(status="ok", service="starpost-api")
@app.get("/api/integrity")
def integrity():
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT contract_file FROM users WHERE role='seller' AND contract_file IS NOT NULL")
contracts = [row["contract_file"] for row in cur.fetchall()]
missing = sum(not (CONTRACT_DIR / filename).is_file() for filename in contracts)
return jsonify(contracts=len(contracts), missing_contracts=missing, status="ok" if missing == 0 else "corrupt")
@app.get("/api/warehouse")
def warehouse():
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT count(*) delivered FROM orders WHERE status='delivered'")
delivered = cur.fetchone()["delivered"]
cur.execute("SELECT warehouse_status,count(*) count FROM orders GROUP BY warehouse_status")
stages = {row["warehouse_status"]: row["count"] for row in cur.fetchall()}
try:
warehouse_health = get_warehouse_health()
except (OSError, ValueError):
return jsonify(bot="ATLAS-7", status="offline", mode="automatic", delivered=delivered, stages=stages), 503
if warehouse_health.get("status") != "ok":
return jsonify(bot="ATLAS-7", status="offline", mode="automatic", delivered=delivered, stages=stages), 503
return jsonify(bot=warehouse_health.get("bot", "ATLAS-7"), status="online", mode="automatic", delivered=delivered, stages=stages)
def worker_token_valid():
return request.headers.get("X-Warehouse-Token") == WAREHOUSE_CALLBACK_TOKEN
@app.get("/api/warehouse/pending")
def warehouse_pending():
if not worker_token_valid():
return error("forbidden", 403)
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT id FROM orders WHERE status='pending' ORDER BY id LIMIT 50")
return jsonify(cur.fetchall())
@app.post("/api/warehouse/callback")
def warehouse_callback():
if not worker_token_valid():
return error("forbidden", 403)
data = body() or {}
try:
order_id = int(data["order_id"])
stage = text(data.get("stage"), "stage", 3, 32)
job_id = text(data.get("job_id"), "job_id", 3, 64)
except (KeyError, TypeError, ValueError) as exc:
return error(str(exc))
allowed = {"accepted", "picking", "in_transit", "arriving", "delivered"}
if stage not in allowed:
return error("invalid warehouse stage")
with db() as conn, conn.cursor() as cur:
if stage == "delivered":
cur.execute("UPDATE orders SET status='delivered',delivered_at=now(),warehouse_status=%s,warehouse_job_id=%s,warehouse_updated_at=now() WHERE id=%s AND status='pending' RETURNING id", (stage, job_id, order_id))
else:
cur.execute("UPDATE orders SET warehouse_status=%s,warehouse_job_id=%s,warehouse_updated_at=now() WHERE id=%s AND status='pending' RETURNING id", (stage, job_id, order_id))
if not cur.fetchone():
return error("pending order not found", 404)
return jsonify(ok=True, order_id=order_id, job_id=job_id, stage=stage)
@app.post("/api/register")
def register():
data = body()
if not data:
return error("invalid JSON")
try:
username, password = text(data.get("username"), "username", 3, 48), text(data.get("password"), "password", 8, 128)
role = data.get("role")
if role not in ("buyer", "seller"):
raise ValueError("role must be buyer or seller")
company = tax_id = signature = None
if role == "seller":
company, tax_id, signature = text(data.get("company_name"), "company_name", 2, 120), text(data.get("tax_id"), "tax_id", 4, 40), text(data.get("signature"), "signature", 4, 512)
except ValueError as exc:
return error(str(exc))
try:
with db() as conn, conn.cursor() as cur:
cur.execute("INSERT INTO users(username,password_hash,role,company_name,tax_id) VALUES(%s,%s,%s,%s,%s) RETURNING id", (username, hash_password(password), role, company, tax_id))
user_id = cur.fetchone()["id"]
if role == "seller":
cur.execute("UPDATE users SET contract_file=%s WHERE id=%s", (create_contract(user_id, company, tax_id, signature), user_id))
else:
cur.execute(
"INSERT INTO promo_codes(user_id,code) VALUES(%s,%s)",
(user_id, "SP10-" + secrets.token_urlsafe(12).upper()),
)
except psycopg.errors.UniqueViolation:
return error("username already exists", 409)
session.clear()
session.update(user_id=user_id, username=username, role=role)
return jsonify(id=user_id, username=username, role=role), 201
@app.post("/api/login")
def login():
data = body() or {}
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT * FROM users WHERE username=%s", (data.get("username"),))
user = cur.fetchone()
if not user or not isinstance(data.get("password"), str) or not password_matches(user["password_hash"], data["password"]):
return error("invalid credentials", 401)
session.clear()
session.update(user_id=user["id"], username=user["username"], role=user["role"])
return jsonify(id=user["id"], username=user["username"], role=user["role"])
@app.post("/api/logout")
def logout():
session.clear()
return jsonify(ok=True)
@app.get("/api/me")
@auth()
def me():
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT id,username,role,balance,company_name,tax_id,contract_file FROM users WHERE id=%s", (session["user_id"],))
return jsonify(cur.fetchone())
@app.get("/api/account")
@auth()
def account_summary():
with db() as conn, conn.cursor() as cur:
cur.execute(
"""
SELECT id,username,role,balance,company_name,tax_id,created_at
FROM users WHERE id=%s
""",
(session["user_id"],),
)
user = cur.fetchone()
if user["role"] == "buyer":
cur.execute(
"""
SELECT count(*) orders_count,
count(*) FILTER (WHERE status='delivered') delivered_count,
COALESCE(sum(price),0) spent
FROM orders WHERE buyer_id=%s
""",
(session["user_id"],),
)
stats = cur.fetchone()
cur.execute(
"""
SELECT o.id,o.status,o.warehouse_status,o.price,o.tracking_code,o.created_at,p.name
FROM orders o JOIN products p ON p.id=o.product_id
WHERE o.buyer_id=%s ORDER BY o.id DESC LIMIT 5
""",
(session["user_id"],),
)
recent_orders = cur.fetchall()
cur.execute(
"SELECT count(*) reviews_count FROM reviews WHERE buyer_id=%s",
(session["user_id"],),
)
reviews_count = cur.fetchone()["reviews_count"]
cur.execute("SELECT code,amount FROM promo_codes WHERE user_id=%s", (session["user_id"],))
return jsonify(user=user, stats=stats, reviews_count=reviews_count, recent_orders=recent_orders, promo=cur.fetchone())
cur.execute(
"""
SELECT count(*) products_count,
count(*) FILTER (WHERE is_active=true) active_products_count
FROM products WHERE seller_id=%s
""",
(session["user_id"],),
)
stats = cur.fetchone()
cur.execute(
"SELECT count(*) reviews_count FROM reviews WHERE seller_id=%s",
(session["user_id"],),
)
reviews_count = cur.fetchone()["reviews_count"]
return jsonify(user=user, stats=stats, reviews_count=reviews_count)
def current_promo(code):
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT * FROM promo_codes WHERE user_id=%s AND code=%s", (session["user_id"], code))
return conn, cur, cur.fetchone()
@app.post("/api/promo/credit")
@auth("buyer")
def credit_promo():
data = body() or {}
code = data.get("code")
if not isinstance(code, str) or not 1 <= len(code) <= 100:
return error("invalid promo code")
with db() as conn, conn.cursor() as cur:
cur.execute(
"UPDATE promo_codes SET credited_at=now() "
"WHERE user_id=%s AND code=%s AND credited_at IS NULL RETURNING amount",
(session["user_id"], code.strip()),
)
promo = cur.fetchone()
if not promo:
cur.execute(
"SELECT amount FROM promo_codes WHERE user_id=%s AND code=%s",
(session["user_id"], code.strip()),
)
promo = cur.fetchone()
if not promo:
return error("promo code is unavailable", 409)
return jsonify(credited=0, code=code.strip())
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (promo["amount"], session["user_id"]))
return jsonify(credited=promo["amount"], code=code.strip())
@app.post("/api/promo/invalidate")
@auth("buyer")
def invalidate_promo():
data = body() or {}
code = data.get("code")
if not isinstance(code, str) or not 1 <= len(code) <= 100:
return error("invalid promo code")
with db() as conn, conn.cursor() as cur:
cur.execute(
"DELETE FROM promo_codes WHERE user_id=%s AND code=%s AND credited_at IS NOT NULL",
(session["user_id"], code.strip()),
)
if cur.rowcount == 0:
return error("promo code is unavailable", 409)
return jsonify(invalidated=True, code=code.strip())
@app.get("/api/products")
def products():
with db() as conn, conn.cursor() as cur:
cur.execute(
"""
SELECT p.id,p.name,p.description,p.price,p.created_at,u.company_name seller,
(SELECT count(*) FROM reviews r JOIN orders o ON o.id=r.order_id
WHERE o.product_id=p.id AND r.is_private=false) review_count,
COALESCE((
SELECT json_agg(item) FROM (
SELECT r.rating,r.body,b.username buyer,r.created_at
FROM reviews r
JOIN orders o ON o.id=r.order_id
JOIN users b ON b.id=r.buyer_id
WHERE o.product_id=p.id AND r.is_private=false
ORDER BY r.id DESC LIMIT 3
) item
), '[]'::json) reviews
FROM products p JOIN users u ON u.id=p.seller_id
WHERE p.is_active=true
ORDER BY p.id DESC LIMIT 100
"""
)
return jsonify(cur.fetchall())
@app.get("/api/products/<int:product_id>")
def product_details(product_id):
with db() as conn, conn.cursor() as cur:
cur.execute(
"""
SELECT p.id,p.name,p.description,p.price,p.created_at,
u.company_name seller,u.tax_id seller_tax_id,
count(r.id) FILTER (WHERE r.is_private=false) review_count,
COALESCE(round(avg(r.rating) FILTER (WHERE r.is_private=false), 1), 0) rating
FROM products p
JOIN users u ON u.id=p.seller_id
LEFT JOIN orders o ON o.product_id=p.id
LEFT JOIN reviews r ON r.order_id=o.id
WHERE p.id=%s AND p.is_active=true
GROUP BY p.id,u.company_name,u.tax_id
""",
(product_id,),
)
product = cur.fetchone()
if not product:
return error("product not found", 404)
cur.execute(
"""
SELECT r.id,r.rating,r.body,r.created_at,b.username buyer
FROM reviews r
JOIN orders o ON o.id=r.order_id
JOIN users b ON b.id=r.buyer_id
WHERE o.product_id=%s AND r.is_private=false
ORDER BY r.id DESC LIMIT 50
""",
(product_id,),
)
product["reviews"] = cur.fetchall()
return jsonify(product)
@app.post("/api/products")
@auth("seller")
def add_product():
data = body() or {}
try:
name, description, cargo = text(data.get("name"), "name", 2, 100), text(data.get("description"), "description", 2, 500), text(data.get("cargo"), "cargo", 1, 1024)
price = int(data.get("price"))
if not 1 <= price <= 1000:
raise ValueError("price must be 1..1000")
except (TypeError, ValueError) as exc:
return error(str(exc))
with db() as conn, conn.cursor() as cur:
cur.execute("INSERT INTO products(seller_id,name,description,price,cargo) VALUES(%s,%s,%s,%s,%s) RETURNING id", (session["user_id"], name, description, price, cargo))
return jsonify(id=cur.fetchone()["id"]), 201
@app.get("/api/seller/products")
@auth("seller")
def seller_products():
with db() as conn, conn.cursor() as cur:
cur.execute(
"""
SELECT p.id,p.name,p.description,p.price,p.cargo,p.is_active,p.created_at,
count(o.id) sales_count,COALESCE(sum(o.price),0) income
FROM products p
LEFT JOIN orders o ON o.product_id=p.id
WHERE p.seller_id=%s
GROUP BY p.id
ORDER BY p.id DESC
""",
(session["user_id"],),
)
return jsonify(cur.fetchall())
@app.patch("/api/seller/products/<int:product_id>")
@auth("seller")
def update_seller_product(product_id):
data = body() or {}
try:
name = text(data.get("name"), "name", 2, 100)
description = text(data.get("description"), "description", 2, 500)
price = int(data.get("price"))
if not 1 <= price <= 1000:
raise ValueError("price must be 1..1000")
is_active = data.get("is_active")
if not isinstance(is_active, bool):
raise ValueError("is_active must be boolean")
except (TypeError, ValueError) as exc:
return error(str(exc))
with db() as conn, conn.cursor() as cur:
cur.execute(
"""
UPDATE products SET name=%s,description=%s,price=%s,is_active=%s
WHERE id=%s AND seller_id=%s RETURNING id,is_active
""",
(name, description, price, is_active, product_id, session["user_id"]),
)
product = cur.fetchone()
if not product:
return error("product not found", 404)
return jsonify(product)
@app.delete("/api/seller/products/<int:product_id>")
@auth("seller")
def archive_seller_product(product_id):
with db() as conn, conn.cursor() as cur:
cur.execute(
"UPDATE products SET is_active=false WHERE id=%s AND seller_id=%s RETURNING id",
(product_id, session["user_id"]),
)
if not cur.fetchone():
return error("product not found", 404)
return jsonify(ok=True, archived=True)
@app.post("/api/cart")
@auth("buyer")
def add_cart():
data = body() or {}
product_id = data.get("product_id")
try:
quantity = int(data.get("quantity", 1))
if not 1 <= quantity <= 10:
raise ValueError("quantity must be 1..10")
except (TypeError, ValueError) as exc:
return error(str(exc))
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT seller_id FROM products WHERE id=%s AND is_active=true", (product_id,))
product = cur.fetchone()
if not product:
return error("product not found", 404)
if product["seller_id"] == session["user_id"]:
return error("cannot add your own product")
cur.execute(
"""
INSERT INTO cart_items(buyer_id,product_id,quantity) VALUES(%s,%s,%s)
ON CONFLICT(buyer_id,product_id) DO UPDATE
SET quantity=LEAST(10, cart_items.quantity + EXCLUDED.quantity)
RETURNING quantity
""",
(session["user_id"], product_id, quantity),
)
quantity = cur.fetchone()["quantity"]
return jsonify(ok=True, quantity=quantity), 201
@app.get("/api/cart")
@auth("buyer")
def get_cart():
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT p.id,p.name,p.description,p.price,c.quantity,u.company_name seller FROM cart_items c JOIN products p ON p.id=c.product_id JOIN users u ON u.id=p.seller_id WHERE c.buyer_id=%s ORDER BY c.created_at", (session["user_id"],))
return jsonify(cur.fetchall())
@app.delete("/api/cart/<int:product_id>")
@auth("buyer")
def delete_cart(product_id):
with db() as conn, conn.cursor() as cur:
cur.execute("DELETE FROM cart_items WHERE buyer_id=%s AND product_id=%s", (session["user_id"], product_id))
return jsonify(ok=True)
@app.patch("/api/cart/<int:product_id>")
@auth("buyer")
def update_cart_quantity(product_id):
try:
quantity = int((body() or {}).get("quantity"))
if not 1 <= quantity <= 10:
raise ValueError("quantity must be 1..10")
except (TypeError, ValueError) as exc:
return error(str(exc))
with db() as conn, conn.cursor() as cur:
cur.execute("UPDATE cart_items SET quantity=%s WHERE buyer_id=%s AND product_id=%s RETURNING quantity", (quantity, session["user_id"], product_id))
if not cur.fetchone():
return error("cart item not found", 404)
return jsonify(ok=True, quantity=quantity)
def create_order(cur, buyer_id, product_id, price, tracking, buyer_created_at, product_created_at):
cur.execute(
"INSERT INTO orders(buyer_id,product_id,price,status,tracking_code,cargo_entitled) "
"VALUES(%s,%s,%s,'pending',%s,%s >= %s AND "
"%s <= %s + (%s * interval '1 second') AND "
"CURRENT_TIMESTAMP <= %s + (%s * interval '1 second')) RETURNING id",
(
buyer_id,
product_id,
price,
tracking,
buyer_created_at,
product_created_at,
buyer_created_at,
product_created_at,
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS,
product_created_at,
CARGO_PURCHASE_WINDOW_SECONDS,
),
)
return cur.fetchone()["id"]
def order_product(product_id):
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT p.*,u.balance,u.created_at buyer_created_at FROM products p CROSS JOIN users u WHERE p.id=%s AND p.is_active=true AND u.id=%s FOR UPDATE OF u", (product_id, session["user_id"]))
row = cur.fetchone()
if not row:
return None, error("product not found", 404)
if row["seller_id"] == session["user_id"]:
return None, error("cannot buy your own product")
if row["balance"] < row["price"]:
return None, error("insufficient balance", 409)
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (row["price"], session["user_id"]))
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (row["price"], row["seller_id"]))
tracking = "ORB-" + secrets.token_hex(8).upper()
order_id = create_order(cur, session["user_id"], product_id, row["price"], tracking, row["buyer_created_at"], row["created_at"])
return {"id": order_id, "status": "pending", "tracking_code": tracking}, None
@app.post("/api/products/<int:product_id>/buy")
@auth("buyer")
def buy_product(product_id):
result, failure = order_product(product_id)
if failure:
return failure
submit_warehouse_jobs([result])
return jsonify(result), 201
@app.post("/api/cart/checkout")
@auth("buyer")
def checkout():
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT balance,created_at buyer_created_at FROM users WHERE id=%s FOR UPDATE", (session["user_id"],))
buyer = cur.fetchone()
cur.execute(
"""
SELECT p.id product_id,p.seller_id,p.price,p.is_active,
p.created_at product_created_at,c.quantity
FROM cart_items c JOIN products p ON p.id=c.product_id
WHERE c.buyer_id=%s ORDER BY c.created_at
""",
(session["user_id"],),
)
items = cur.fetchall()
if not items:
return error("cart is empty", 409)
if any(not item["is_active"] for item in items):
return error("cart contains archived product", 409)
total = sum(item["price"] * item["quantity"] for item in items)
if buyer["balance"] < total:
return error("insufficient balance", 409)
cur.execute("UPDATE users SET balance=balance-%s WHERE id=%s", (total, session["user_id"]))
orders = []
for item in items:
cur.execute("UPDATE users SET balance=balance+%s WHERE id=%s", (item["price"] * item["quantity"], item["seller_id"]))
for _ in range(item["quantity"]):
tracking = "ORB-" + secrets.token_hex(8).upper()
order_id = create_order(
cur,
session["user_id"],
item["product_id"],
item["price"],
tracking,
buyer["buyer_created_at"],
item["product_created_at"],
)
orders.append({"id": order_id, "status": "pending", "tracking_code": tracking})
cur.execute("DELETE FROM cart_items WHERE buyer_id=%s", (session["user_id"],))
submit_warehouse_jobs(orders)
return jsonify(orders=orders), 201
@app.get("/api/orders")
@auth("buyer")
def buyer_orders():
with db() as conn, conn.cursor() as cur:
cur.execute(
"SELECT o.id,o.status,o.warehouse_status,o.warehouse_updated_at,"
"o.tracking_code,o.price,o.created_at,o.delivered_at,p.name,"
"CASE WHEN o.status='delivered' "
"AND o.cargo_entitled "
"THEN p.cargo ELSE NULL END cargo "
"FROM orders o JOIN products p ON p.id=o.product_id "
"WHERE o.buyer_id=%s ORDER BY o.id DESC",
(session["user_id"],),
)
return jsonify(cur.fetchall())
@app.get("/api/seller/sales")
@auth("seller")
def seller_sales():
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT o.id,o.price,o.status,o.tracking_code,o.created_at,p.name,b.username buyer FROM orders o JOIN products p ON p.id=o.product_id JOIN users b ON b.id=o.buyer_id WHERE p.seller_id=%s ORDER BY o.id DESC", (session["user_id"],))
sales = cur.fetchall()
return jsonify(income=sum(row["price"] for row in sales), sales=sales)
@app.post("/api/orders/<int:order_id>/review")
@auth("buyer")
def review(order_id):
data = body() or {}
try:
review_body, rating = text(data.get("body"), "body", 1, 1000), int(data.get("rating"))
if rating not in range(1, 6):
raise ValueError("rating must be 1..5")
except (TypeError, ValueError) as exc:
return error(str(exc))
with db() as conn, conn.cursor() as cur:
cur.execute("SELECT p.seller_id FROM orders o JOIN products p ON p.id=o.product_id WHERE o.id=%s AND o.buyer_id=%s AND o.status='delivered'", (order_id, session["user_id"]))
order = cur.fetchone()
if not order:
return error("delivered order not found", 404)
try:
cur.execute("INSERT INTO reviews(order_id,buyer_id,seller_id,rating,body,is_private) VALUES(%s,%s,%s,%s,%s,%s) RETURNING id", (order_id, session["user_id"], order["seller_id"], rating, review_body, data.get("private") is True))
except psycopg.errors.UniqueViolation:
return error("order already reviewed", 409)
return jsonify(id=cur.fetchone()["id"]), 201
@app.get("/api/seller/reviews")
@auth("seller")
def seller_reviews():
cursor = request.args.get("cursor")
limit_raw = request.args.get("limit")
def _b64e(b: bytes) -> str:
return base64.urlsafe_b64encode(b).decode().rstrip("=")
def _b64d(s: str) -> bytes:
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
def _sign(payload_b64: str) -> str:
return hmac.new(app.config["SECRET_KEY"].encode(), payload_b64.encode(), hashlib.sha256).hexdigest()[:16]
def _make_cursor(state: dict) -> str:
p = _b64e(_json.dumps(state, separators=(",", ":")).encode())
return f"{p}.{_sign(p)}"
def _parse_cursor(cur_token: str):
if "." not in cur_token:
raise ValueError("missing signature")
payload_b64, sig = cur_token.rsplit(".", 1)
if not hmac.compare_digest(_sign(payload_b64), sig):
raise ValueError("bad cursor signature")
return _json.loads(_b64d(payload_b64).decode())
limit = 20
if limit_raw is not None:
try:
limit = int(limit_raw)
if not 1 <= limit <= 100:
return error("limit must be 1..100")
except (TypeError, ValueError):
return error("invalid limit")
if cursor:
try:
state = _parse_cursor(cursor)
except Exception as exc:
return error(f"invalid cursor: {exc}", 400)
try:
q_seller = int(state["seller_id"])
q_private = state["is_private"]
q_last = int(state["last_id"])
if q_seller != session["user_id"] or not isinstance(q_private, bool):
raise ValueError
except (KeyError, TypeError, ValueError):
return error("invalid cursor payload", 400)
with db() as conn, conn.cursor() as cur:
cur.execute(
"SELECT r.id,r.rating,r.body,r.is_private,r.created_at,p.name,b.username buyer "
"FROM reviews r JOIN orders o ON o.id=r.order_id "
"JOIN products p ON p.id=o.product_id JOIN users b ON b.id=r.buyer_id "
"WHERE r.seller_id=%s AND r.is_private=%s AND r.id < %s "
"ORDER BY r.id DESC LIMIT %s",
(q_seller, q_private, q_last, limit),
)
rows = cur.fetchall()
next_cursor = None
if rows:
next_cursor = _make_cursor(
{"seller_id": q_seller, "is_private": q_private, "last_id": rows[-1]["id"], "v": 2}
)
return jsonify(reviews=rows, next_cursor=next_cursor)
with db() as conn, conn.cursor() as cur:
cur.execute(
"SELECT r.id,r.rating,r.body,r.is_private,r.created_at,p.name,b.username buyer "
"FROM reviews r JOIN orders o ON o.id=r.order_id "
"JOIN products p ON p.id=o.product_id JOIN users b ON b.id=r.buyer_id "
"WHERE r.seller_id=%s AND r.id < %s "
"ORDER BY r.id DESC LIMIT %s",
(session["user_id"], 1_000_000_000, limit),
)
rows = cur.fetchall()
next_cursor = None
if rows:
last_private = rows[-1]["is_private"]
next_cursor = _make_cursor(
{"seller_id": session["user_id"], "is_private": bool(last_private), "last_id": rows[-1]["id"], "v": 2}
)
return jsonify(reviews=rows, next_cursor=next_cursor)
@app.route("/api/contract", methods=["GET", "POST"])
@auth("seller")
def get_contract():
requested = request.args.get("file")
if request.method == "GET" and requested:
requested = requested.strip()
own_alias = f"contract-{session['user_id']}"
if requested != own_alias and not own_contract_filename(requested, session["user_id"]):
return error("contract not found", 404)
contract_id = None
if request.method == "POST":
contract_id = request.headers.get("X-Contract-Id", "").strip()
if not re.fullmatch(r"\d+", contract_id) or contract_id != str(session["user_id"]):
return error("invalid contract id", 400)
owner = contract_owner(session["user_id"])
if not owner or not owner[1]:
return error("contract not found", 404)
owner_id, filename = owner
if not own_contract_filename(filename, owner_id):
return error("contract not found", 404)
contract_dir = CONTRACT_DIR.resolve()
path = (CONTRACT_DIR / filename).resolve()
if path.parent != contract_dir:
return error("contract not found", 404)
if request.method == "POST":
try:
path.unlink()
except FileNotFoundError:
return error("contract not found", 404)
except OSError:
return error("contract deletion failed", 500)
return jsonify(status="deleted", deleted=1)
if requested:
if requested not in {filename, f"contract-{owner_id}"}:
return error("contract not found", 404)
if not path.is_file():
return error("contract not found", 404)
download_name = path.name if requested else "starpost-contract.pdf"
return send_file(path, mimetype="application/pdf", download_name=download_name)
+177
View File
@@ -0,0 +1,177 @@
import secrets
from datetime import datetime, timezone
from pathlib import Path
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
CONTRACT_DIR = Path("/contracts")
CONTRACT_DIR.mkdir(exist_ok=True)
def create_contract(user_id, company, tax_id, signature):
CONTRACT_DIR.mkdir(exist_ok=True)
filename = f"contract-{user_id}-{secrets.token_hex(8)}.pdf"
path = CONTRACT_DIR / filename
pdf = canvas.Canvas(str(path), pagesize=A4, pageCompression=0)
pdf.setTitle("Starpost marketplace contract")
pdf.setFont("Helvetica", 16)
pdf.drawString(55, 790, "STARPOST MARKETPLACE CONTRACT")
pdf.setFont("Helvetica", 10)
lines = [
"MARKETPLACE SELLER AGREEMENT",
"",
"1. PARTIES TO THE AGREEMENT",
f"Company Name: {company}",
f"Tax Identification Number: {tax_id}",
f"Seller Account ID: {user_id}",
f"Agreement Date (UTC): {datetime.now(timezone.utc).isoformat()}",
"",
"2. PURPOSE AND SCOPE OF THE AGREEMENT",
"This Agreement establishes the terms and conditions under",
"which the Seller may use the Starpost Marketplace platform",
"to publish cargo listings, offer goods for sale, receive",
"customer orders, and manage marketplace transactions.",
"Starpost provides the technical infrastructure necessary",
"for publishing listings, processing orders, maintaining",
"transaction records, and facilitating marketplace activity.",
"The Seller agrees to comply with the terms of this Agreement",
"and the operational requirements of the platform.",
"",
"3. SELLER RIGHTS AND RESPONSIBILITIES",
"The Seller may create and manage cargo listings, specify",
"prices, update product availability, and receive orders",
"through the Starpost Marketplace system.",
"The Seller is responsible for ensuring that all submitted",
"information is accurate, complete, and up to date.",
"Cargo descriptions must correctly represent the goods,",
"their condition, quantity, characteristics, and availability.",
"The Seller must not publish fraudulent, deceptive, or",
"intentionally misleading offers or transaction information.",
"The Seller is responsible for fulfilling accepted orders",
"and providing reasonable customer support regarding sales,",
"delivery conditions, product information, and complaints.",
"",
"4. STARPOST MARKETPLACE SERVICES",
"Starpost provides access to marketplace functionality",
"for creating listings, receiving orders, and reviewing",
"transaction history and order statuses.",
"The platform records relevant sales information and may",
"provide tools for calculating and reviewing revenue.",
"Starpost may perform maintenance, deploy security updates,",
"and modify technical components to maintain platform",
"stability, availability, and operational security.",
"Temporary interruptions may occur during maintenance",
"or due to circumstances outside the platform's control.",
"",
"5. CARGO LISTINGS AND ORDER PROCESSING",
"Each listing must contain a valid description of the goods,",
"the applicable price, available quantity, and any relevant",
"conditions necessary for a customer to place an order.",
"The Seller must review incoming orders and ensure that",
"accepted orders are processed in accordance with the",
"information published in the corresponding listing.",
"Changes to a listing must not intentionally misrepresent",
"the terms of an order that has already been accepted.",
"The Seller should promptly report technical errors that",
"affect order creation, order status, or transaction records.",
"",
"6. SALES RECORDS AND REVENUE",
"Starpost maintains marketplace records relating to orders,",
"completed sales, and other supported transaction events.",
"These records may be used to calculate marketplace revenue",
"and determine the amounts eligible for transfer to the Seller.",
"Revenue transfers are subject to the platform's payment",
"procedures and the status of the relevant transactions.",
"The Seller is responsible for reviewing transaction records",
"and reporting discrepancies through the available support",
"or dispute resolution procedures.",
"Starpost may retain transaction records for accounting,",
"security auditing, and investigation of disputed orders.",
"",
"7. CUSTOMER SUPPORT AND DISPUTE HANDLING",
"The Seller is responsible for responding to reasonable",
"customer inquiries concerning the Seller's cargo listings",
"and the fulfillment of accepted orders.",
"In the event of a disagreement regarding an order, the",
"parties should review the relevant listing, order details,",
"transaction history, and other available evidence.",
"Suspected fraudulent activity or technical manipulation",
"of marketplace transactions may be subject to investigation.",
"The parties should cooperate in resolving disputes and",
"provide relevant information when reasonably requested.",
"",
"8. ACCOUNT SECURITY AND DATA PROTECTION",
"The Seller is responsible for maintaining the security",
"of the Seller's account and associated authentication data.",
"Credentials and authorization secrets must not be disclosed",
"to unauthorized persons or exposed through public listings.",
"Information submitted to Starpost may be processed to",
"operate the marketplace, manage orders, maintain records,",
"provide support, and investigate security incidents.",
"Customer information must be handled responsibly and used",
"only for legitimate purposes connected with marketplace",
"operations and order fulfillment.",
"",
"9. PROHIBITED ACTIVITIES",
"The Seller must not intentionally exploit technical flaws",
"to create unauthorized orders, manipulate revenue records,",
"obtain goods or services without proper authorization,",
"or interfere with the normal operation of the platform.",
"The Seller must not submit forged business information,",
"misuse another user's account, or attempt to gain access",
"to information or functions without authorization.",
"Starpost may investigate suspected violations and apply",
"appropriate restrictions in accordance with its policies.",
"",
"10. LIABILITY AND LIMITATIONS",
"The Seller remains responsible for the accuracy of listings,",
"the fulfillment of accepted orders, and the handling of",
"customer inquiries relating to the Seller's goods.",
"Each party is responsible for its own actions and failures",
"to comply with the obligations established by this Agreement.",
"Neither party should knowingly provide false information",
"or interfere with the proper recording of transactions.",
"Any limitation of liability must be interpreted in",
"accordance with the applicable terms and governing law.",
"",
"11. TERM AND TERMINATION",
"This Agreement becomes effective upon its acceptance and",
"the recording of the Seller's signature or authorization.",
"The Agreement remains effective while the Seller uses",
"the marketplace, unless terminated in accordance with",
"the applicable platform procedures.",
"Access may be restricted when there is evidence of fraud,",
"unauthorized activity, or a material violation of the",
"platform's requirements.",
"Termination does not automatically eliminate outstanding",
"obligations associated with previously accepted orders,",
"completed transactions, or unresolved disputes.",
"",
"12. FINAL PROVISIONS",
"This document records the terms presented to the Seller",
"at the time the Agreement is generated.",
"Any amendments or additional conditions should be recorded",
"in an appropriate form and communicated to the parties.",
"Questions concerning the interpretation of this Agreement",
"should be addressed through the established support process.",
"",
"SELLER ACKNOWLEDGMENT",
"By signing this Agreement, the Seller confirms that the",
"provided company information is accurate and acknowledges",
"the responsibilities associated with marketplace activity.",
"The Seller agrees to comply with the terms described above",
"and to act in good faith when processing customer orders.",
"",
"Seller Signature / Authorization Key:",
]
y = 745
for line in lines:
pdf.drawString(55, y, line)
y -= 28
for offset in range(0, len(signature), 88):
pdf.drawString(55, y, signature[offset:offset + 88])
y -= 16
pdf.save()
return filename
+74
View File
@@ -0,0 +1,74 @@
import os
import psycopg
from psycopg.rows import dict_row
DATABASE_URL = os.environ["DATABASE_URL"]
CARGO_BUYER_REGISTRATION_WINDOW_SECONDS = 3
CARGO_PURCHASE_WINDOW_SECONDS = 5
LEGACY_CARGO_PURCHASE_WINDOW_SECONDS = 2
def connect():
return psycopg.connect(DATABASE_URL, row_factory=dict_row)
def migrate():
with connect() as connection, connection.cursor() as cursor:
cursor.execute("DROP TABLE IF EXISTS promos")
cursor.execute("DROP TABLE IF EXISTS private_promos")
cursor.execute("ALTER TABLE cart_items ADD COLUMN IF NOT EXISTS quantity INTEGER NOT NULL DEFAULT 1")
cursor.execute(
"""
DO $$ BEGIN
ALTER TABLE cart_items ADD CONSTRAINT cart_items_quantity_check CHECK(quantity BETWEEN 1 AND 10);
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;
"""
)
cursor.execute("ALTER TABLE products ADD COLUMN IF NOT EXISTS is_active BOOLEAN NOT NULL DEFAULT true")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_status TEXT NOT NULL DEFAULT 'queued'")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_job_id TEXT")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()")
cursor.execute("ALTER TABLE orders ADD COLUMN IF NOT EXISTS cargo_entitled BOOLEAN")
cursor.execute(
"UPDATE orders o SET cargo_entitled="
"(o.created_at <= p.created_at + (%s * interval '1 second')) "
"FROM products p WHERE p.id=o.product_id AND o.cargo_entitled IS NULL",
(LEGACY_CARGO_PURCHASE_WINDOW_SECONDS,),
)
cursor.execute("ALTER TABLE orders ALTER COLUMN cargo_entitled SET DEFAULT false")
cursor.execute("ALTER TABLE orders ALTER COLUMN cargo_entitled SET NOT NULL")
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS promo_codes (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
code TEXT NOT NULL UNIQUE,
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100)
)
"""
)
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS is_active")
cursor.execute(
"""
DO $$ DECLARE r RECORD; BEGIN
FOR r IN SELECT conname FROM pg_constraint
WHERE conrelid = 'promo_codes'::regclass AND contype = 'c' LOOP
EXECUTE format('ALTER TABLE promo_codes DROP CONSTRAINT %I', r.conname);
END LOOP;
ALTER TABLE promo_codes ADD CONSTRAINT promo_codes_amount_check CHECK(amount = 100);
EXCEPTION WHEN duplicate_object THEN NULL;
END $$;
"""
)
cursor.execute("ALTER TABLE promo_codes ALTER COLUMN amount SET DEFAULT 100")
cursor.execute("ALTER TABLE promo_codes ADD COLUMN IF NOT EXISTS credited_at TIMESTAMPTZ")
cursor.execute("ALTER TABLE users ALTER COLUMN balance SET DEFAULT 100")
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS invalidated_at")
cursor.execute("ALTER TABLE promo_codes DROP COLUMN IF EXISTS created_at")
cursor.execute("CREATE INDEX IF NOT EXISTS orders_buyer_idx ON orders(buyer_id, id DESC)")
cursor.execute("CREATE INDEX IF NOT EXISTS orders_product_idx ON orders(product_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS products_seller_idx ON products(seller_id, id DESC)")
cursor.execute("CREATE INDEX IF NOT EXISTS reviews_seller_idx ON reviews(seller_id, id DESC)")
+16
View File
@@ -0,0 +1,16 @@
from werkzeug.security import check_password_hash, generate_password_hash
# Werkzeug's default scrypt hash needs about 32 MiB of working memory per
# concurrent request. The API serves up to four authentication requests at a
# time, so use a CPU-bound hash for new accounts while retaining verification
# support for existing scrypt hashes.
PASSWORD_HASH_METHOD = "pbkdf2:sha256:600000"
def hash_password(password):
return generate_password_hash(password, method=PASSWORD_HASH_METHOD)
def password_matches(password_hash, password):
return check_password_hash(password_hash, password)
+4
View File
@@ -0,0 +1,4 @@
Flask==3.1.0
gunicorn==23.0.0
psycopg[binary]==3.2.3
reportlab==4.2.5
+28
View File
@@ -0,0 +1,28 @@
import json
import os
import urllib.request
WAREHOUSE_URL = os.getenv("WAREHOUSE_URL", "http://warehouse:6000")
CALLBACK_TOKEN = os.environ["WAREHOUSE_CALLBACK_TOKEN"]
def submit_jobs(orders):
for order in orders:
try:
payload = json.dumps({"order_id": order["id"]}).encode()
request = urllib.request.Request(
f"{WAREHOUSE_URL}/jobs",
data=payload,
headers={"Content-Type": "application/json", "X-Warehouse-Token": CALLBACK_TOKEN},
method="POST",
)
with urllib.request.urlopen(request, timeout=.4):
pass
except (OSError, ValueError):
continue
def get_health():
with urllib.request.urlopen(f"{WAREHOUSE_URL}/health", timeout=.5) as response:
return json.loads(response.read())
+73
View File
@@ -0,0 +1,73 @@
name: starpost.yml
services:
web:
restart: unless-stopped
build: ./web
pids_limit: 256
mem_limit: 64M
cpus: 0.25
ports:
- 8090:80
depends_on:
api:
condition: service_healthy
api:
restart: unless-stopped
build: ./api
pids_limit: 256
mem_limit: 256M
cpus: 1.0
volumes:
- ./contracts:/contracts
environment:
- DATABASE_URL=postgresql://starpost:${STARPOST_DB_PASSWORD:?STARPOST_DB_PASSWORD is required}@postgres/starpost
- SECRET_KEY=${STARPOST_SECRET_KEY:?STARPOST_SECRET_KEY is required}
- WAREHOUSE_URL=http://warehouse:6000
- WAREHOUSE_CALLBACK_TOKEN=${STARPOST_WAREHOUSE_CALLBACK_TOKEN:?STARPOST_WAREHOUSE_CALLBACK_TOKEN is required}
depends_on:
postgres:
condition: service_healthy
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000/health', timeout=2)"]
interval: 2s
timeout: 3s
retries: 15
warehouse:
restart: unless-stopped
build: ./warehouse
pids_limit: 128
mem_limit: 64M
cpus: 0.25
environment:
- WAREHOUSE_API_URL=http://api:5000
- WAREHOUSE_CALLBACK_TOKEN=${STARPOST_WAREHOUSE_CALLBACK_TOKEN:?STARPOST_WAREHOUSE_CALLBACK_TOKEN is required}
depends_on:
api:
condition: service_healthy
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:6000/health', timeout=2)"]
interval: 2s
timeout: 3s
retries: 15
postgres:
image: postgres:16-alpine
restart: unless-stopped
pids_limit: 256
mem_limit: 256M
cpus: 0.5
environment:
- POSTGRES_DB=starpost
- POSTGRES_USER=starpost
- POSTGRES_PASSWORD=${STARPOST_DB_PASSWORD:?STARPOST_DB_PASSWORD is required}
volumes:
- ./postgres:/var/lib/postgresql/data
- ./db/init.sql:/docker-entrypoint-initdb.d/01-init.sql:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U starpost -d starpost && psql -U starpost -d starpost -tAc 'SELECT 1 FROM users LIMIT 1' >/dev/null"]
interval: 2s
timeout: 3s
retries: 30
+60
View File
@@ -0,0 +1,60 @@
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL CHECK(role IN ('buyer', 'seller')),
balance INTEGER NOT NULL DEFAULT 100,
company_name TEXT,
tax_id TEXT,
contract_file TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE products (
id BIGSERIAL PRIMARY KEY,
seller_id BIGINT NOT NULL REFERENCES users(id),
name TEXT NOT NULL,
description TEXT NOT NULL,
price INTEGER NOT NULL CHECK(price > 0),
cargo TEXT NOT NULL,
is_active BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE cart_items (
buyer_id BIGINT REFERENCES users(id) ON DELETE CASCADE,
product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
quantity INTEGER NOT NULL DEFAULT 1 CHECK(quantity BETWEEN 1 AND 10),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY(buyer_id, product_id)
);
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
buyer_id BIGINT NOT NULL REFERENCES users(id),
product_id BIGINT NOT NULL REFERENCES products(id),
price INTEGER NOT NULL,
status TEXT NOT NULL CHECK(status IN ('pending', 'delivered')),
tracking_code TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
delivered_at TIMESTAMPTZ
,warehouse_status TEXT NOT NULL DEFAULT 'queued'
,warehouse_job_id TEXT
,warehouse_updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
,cargo_entitled BOOLEAN NOT NULL DEFAULT false
);
CREATE TABLE reviews (
id BIGSERIAL PRIMARY KEY,
order_id BIGINT NOT NULL UNIQUE REFERENCES orders(id),
buyer_id BIGINT NOT NULL REFERENCES users(id),
seller_id BIGINT NOT NULL REFERENCES users(id),
rating INTEGER NOT NULL CHECK(rating BETWEEN 1 AND 5),
body TEXT NOT NULL,
is_private BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX orders_pending_idx ON orders(status) WHERE status = 'pending';
CREATE TABLE promo_codes (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
code TEXT NOT NULL UNIQUE,
amount INTEGER NOT NULL DEFAULT 100 CHECK(amount = 100),
credited_at TIMESTAMPTZ
);
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
from __future__ import annotations
import os
import secrets
import sys
from pathlib import Path
def main() -> int:
target = Path(__file__).resolve().with_name(".env")
values = {
"STARPOST_DB_PASSWORD": secrets.token_urlsafe(48),
"STARPOST_SECRET_KEY": secrets.token_urlsafe(48),
"STARPOST_WAREHOUSE_CALLBACK_TOKEN": secrets.token_urlsafe(48),
}
try:
descriptor = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
print(f"refusing to overwrite existing {target}", file=sys.stderr)
return 1
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
for key, value in values.items():
output.write(f"{key}={value}\n")
os.chmod(target, 0o600)
print(f"created {target} with mode 0600")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+103
View File
@@ -0,0 +1,103 @@
# Starpost handoff — 2026-10-25
## Confirmed vulnerabilities
### Fresh-buyer cargo purchase
The checker creates flag-bearing products priced within the 200-credit budget of a newly registered buyer: the account starts with 100 credits and its one-time promo adds 100. An attacker can therefore register a buyer, credit the issued promo, buy an active product, wait for automatic warehouse delivery, and read its cargo through `GET /api/orders` without bypassing authentication.
Incident logs and aggregate database checks confirmed this exact path. The observed attacker used `register -> account -> promo/credit -> direct buy -> orders`, while the checker uses `promo/credit -> promo/invalidate -> cart -> checkout -> orders`.
The temporary purchase gate that returned 409 while a promo row remained was removed after the checker reported an unexpected status from `POST /api/products/{id}/buy`. It was not an effective confidentiality boundary because an attacker could call the public invalidate endpoint and reproduce the checker flow. Direct buy and checkout again accept buyers with an uncredited or credited promo row when their balance is sufficient; atomic one-time promo credit remains enforced.
The cargo disclosure remains open because attacker and checker use the same public purchase workflow. One-time promo credit prevents balance replay but is not a confidentiality boundary. A permanent fix requires a checker-compatible non-public purchase capability or moving flags out of buyer-deliverable cargo.
### Cross-seller review cursor BOLA
Before the patch, `GET /api/seller/reviews` skipped the cursor HMAC check when `limit <= 3`. An authenticated seller could supply unsigned Base64url JSON containing another `seller_id`, `is_private=true`, and a high `last_id`; the response returned that seller's private review bodies.
The local baseline reproducer used synthetic seller IDs and a synthetic private-review marker. The endpoint returned HTTP 200 and disclosed the marker. The flag route before the patch is a checker-created private review body returned through the forged cursor; no real flag was used.
### Contract IDOR, arbitrary file read, and cross-seller deletion
Before the patch, a seller could request `GET /api/contract?file=contract-<other-id>` to receive another seller's PDF. Other absolute or relative `file` values were resolved as filesystem paths and returned when readable. `POST /api/contract` similarly accepted another seller's numeric `X-Contract-Id` and deleted matching PDFs.
The local baseline reproducer disclosed both a synthetic victim contract and a controlled file outside the contract directory. The flag route before the patch is the seller signature embedded uncompressed in the checker-created contract PDF; no real flag was used. Destructive behavior was tested only with disposable local files.
### Contract probe worker and database exhaustion
The provided capture showed sustained authenticated `GET /api/contract` probes at modest bandwidth. Before this patch, each foreign alias reached a new PostgreSQL connection and owner query before returning the existing 404 response. Concurrent probes could therefore occupy all synchronous API threads and delay normal registration and health requests.
The route now rejects foreign aliases, malformed filenames, and foreign deletion IDs before opening PostgreSQL. Repeated legitimate reads use a bounded process-local cache for the seller's immutable contract metadata. Existing routes, response formats, no-query reads, empty `file` reads, exact stored filenames, the own-ID alias, and own-contract deletion are preserved. No nginx, IP, URI, rate-limit, or other traffic filter was added, and no DoS sploit was created.
### Reusable promo credit
Before the patch, `POST /api/promo/credit` increased the buyer balance without recording consumption. Repeating the same valid code credited the balance again because invalidation was a separate optional request.
The local baseline reproducer started with a synthetic balance of 100 and two identical credit requests both returned HTTP 200, leaving a synthetic balance of 300. This permits unauthorized value creation and can fund purchases of checker-created cargo.
## Affected code before the patch
- `api/app.py`: `seller_reviews`, `get_contract`, `credit_promo`, `order_product`, and `checkout`.
- `api/database.py`: startup migration removed promo consumption state.
- `db/init.sql`: `promo_codes` had no consumption field.
## Minimal patch
- Emergency cargo containment records a `cargo_entitled` decision on every new order. The buyer account must be created from zero to three seconds after the product, and the order transaction must begin within five seconds of product creation. Live checker-like failures showed buyers created after 1.021 and 1.971 seconds but orders beginning after 2.517 and 3.486 seconds, so the previous two-second purchase deadline denied otherwise valid delivered orders. A pre-staged buyer observed on a later product remained ineligible even though its order began after 0.293 seconds. Both direct buy and checkout use the same order helper. Existing entitlement decisions are immutable, and legacy orders are still backfilled with the previous two-second rule so their current/get-old behavior does not change. This is containment against pre-staged and late-created buyers, not a durable authorization boundary: an attacker that registers immediately after publication can still race the checker.
- Cursor parsing always verifies the existing HMAC and rejects a decoded `seller_id` that differs from the authenticated seller. The signed cursor shape and response format remain unchanged.
- Contract GET/POST validates ownership-shaped input before database access, resolves only the authenticated seller's database-linked filename, requires the canonical path to remain directly below `/contracts`, and restricts deletion to the same seller ID. A bounded cache avoids repeated owner lookups for immutable contract metadata. GET without `file`, GET with an empty `file`, GET with the exact stored filename, and the own-ID alias remain supported.
- `promo_codes.credited_at` is added by a forward-compatible `ADD COLUMN IF NOT EXISTS`. Credit atomically transitions only an uncredited row and adds value once. A retry returns the existing 200 response shape with `credited=0`, allowing the existing follow-up invalidate request to continue.
- Direct buy and checkout no longer require deletion of the promo row. This restores the original purchase contract while retaining the one-time credit transition.
- Compose now requires independent deployment values for the PostgreSQL password, Flask session key, and warehouse callback token. `generate-env.py` creates three URL-safe random values in an ignored mode-0600 `.env`, refuses overwrite, and never prints them.
## Checker and SLA invariants
- Existing orders retain their previous cargo visibility after migration. New checker orders whose buyer was created within three seconds after the product and whose order transaction began within five seconds continue to reveal cargo after delivery and on later get-old checks. New purchases of older product IDs receive `cargo=null`; entitlement is stored per order, so changing deadlines later cannot reopen an old denied order and an earlier attacker order does not consume checker access.
- Existing routes, methods, role requirements, JSON keys, public port, mounts, and warehouse flow are unchanged.
- Existing contract filenames and files are not renamed or migrated.
- Existing promo rows receive `credited_at=NULL` and remain redeemable once.
- Both `credit -> invalidate -> purchase` and purchase with a remaining promo row are accepted when the buyer has sufficient balance.
- No neighboring-service configuration is changed. Secret rotation is isolated to Starpost and keeps the existing variable names consumed by the containers.
## Verification
- Baseline synthetic results: unsigned cursor, cross-seller contract lookup, controlled external-file read, and promo replay reproduced.
- Patched synthetic results: unsigned cursor returned 400 without executing a victim query; cross-seller and external-file reads returned 404; cross-seller deletion returned 400 and preserved the victim file.
- Get current/get old: an existing version-2 signed cursor still returned the seller's own synthetic private review; a contract file created before patched app loading remained readable both through `GET /api/contract` and its exact stored filename.
- Own mutation: deleting the authenticated seller's disposable contract still returned 200 and removed only that file.
- Contract exhaustion regression: the pinned baseline-versus-patch matrix confirmed that foreign GET and POST probes no longer touch the database, repeated valid reads perform at most one owner lookup per process, and all preserved GET forms remain byte-identical. A separate PostgreSQL 16 integration run passed registration, login, current/get-old reads, foreign rejection, and own deletion.
- Promo regression: first credit returned 100, retry returned 0, both kept HTTP 200, and the balance increased exactly once.
- Purchase SLA regression: current `main` reproduced HTTP 409 with an uncredited promo row; the patched PostgreSQL route matrix passed direct buy before credit, direct buy after credit without invalidate, checkout after credit without invalidate, the existing invalidate flow, and preserved insufficient-balance and archived-product errors.
- Cargo entitlement regression: a disposable PostgreSQL 16 and patched Flask API matrix accepted the two live-derived checker timings through direct buy and checkout, rejected a pre-staged buyer, rejected registration after three seconds, rejected purchase after five seconds, preserved get-old, and kept a denied order denied after timestamps changed. Only synthetic non-flag markers were used.
- Python syntax parsing and `docker compose config --quiet` pass.
- `sploits/starpost_contract.py` passes the GO CTF static sploit checker and a loopback synthetic runtime matrix: exit 0, only one synthetic flag candidate on stdout, diagnostics on stderr, redirect not followed, bounded timeout handled, exit 1 for invalid target, and exit 2 for wrong arguments.
- The same sploit was run against the actual baseline route code from commit `4f70df55dd822880f4759d553f7ed249166cad86` and the current patched route with an in-memory database and temporary contract directory: baseline emitted exactly the synthetic candidate, while patched returned exit 0 with empty stdout.
- `sploits/starpost.py` and `sploits/starpost_warehouse.py` pass the GO CTF static sploit checker. Minimal tests on the team vulnbox confirmed the issued Flask key and warehouse token were accepted; full outputs and any flag-like values were suppressed.
- The three exploit jobs completed against the team service in under one second each during bounded validation; no real flag value was printed or stored in the repository.
## Sploit handoff
- Path: `sploits/starpost_contract.py`
- Stable Neo ID: `starpost-contract-idor-v1`
- Timeout: `10s`
- Input: one authorized target address; HTTP port 8090 is selected when no port is supplied.
- Primitive: self-register a seller, enumerate a bounded window of recent numeric user IDs, request the vulnerable own-contract alias for each ID, and emit only strings matching the event flag format.
- Path: `sploits/starpost.py`
- Stable Neo ID: `starpost-session-v1`
- Timeout: `10s`
- Primitive: use only the issued Flask session key to forge recent buyer/seller sessions and read their protected objects.
- Path: `sploits/starpost_warehouse.py`
- Stable Neo ID: `starpost-warehouse-v1`
- Timeout: `10s`
- Primitive: use only the issued warehouse token as leaked configuration; create a normal buyer session, reuse the vulnerable promo, purchase recent products, force delivery, and read cargo.
## Remaining gaps
- The exact checker scenario and flag-bearing field are not available, so signature/PDF, private review, and cargo hypotheses are code-derived rather than checker-confirmed.
- The API image and disposable PostgreSQL integration were tested, but the full service Compose stack, the live persistent volume, and official checker status were not. The integration used a temporary database initialized from `db/init.sql` and synthetic contract files.
- The contract metadata cache is process-local. If an operator manually changes or restores `users.contract_file`, restart the API workers before verification so they reload that metadata.
- Bounded requests were sent only to the team vulnbox. No request was sent to Neo, Farm, farm-submit, Skipper, or another team.
- Deployment must rotate the existing PostgreSQL role password before recreating API/PostgreSQL containers; changing only `POSTGRES_PASSWORD` does not update an initialized volume.
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
from werkzeug.security import generate_password_hash
API_DIR = Path(__file__).resolve().parents[1] / "api"
sys.path.insert(0, str(API_DIR))
from passwords import hash_password, password_matches # noqa: E402
def main():
password = "correct horse battery staple"
current_hash = hash_password(password)
assert current_hash.startswith("pbkdf2:sha256:600000$")
assert password_matches(current_hash, password)
assert not password_matches(current_hash, password + "!")
legacy_hash = generate_password_hash(password, method="scrypt:32768:8:1")
assert password_matches(legacy_hash, password)
assert not password_matches(legacy_hash, password + "!")
print("password hash compatibility: ok")
if __name__ == "__main__":
main()
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
import importlib
import importlib.util
import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from types import ModuleType, SimpleNamespace
TOKEN = "synthetic-local-token"
CART_ITEMS = 20
QUANTITY = 10
def load_modules():
root = Path(__file__).resolve().parents[1]
os.environ["DATABASE_URL"] = "postgresql://unused"
os.environ["SECRET_KEY"] = "synthetic-local-session-key"
os.environ["WAREHOUSE_URL"] = "http://127.0.0.1:9"
os.environ["WAREHOUSE_API_URL"] = "http://127.0.0.1:9"
os.environ["WAREHOUSE_CALLBACK_TOKEN"] = TOKEN
api_dir = root / "api"
sys.path.insert(0, str(api_dir))
contracts = ModuleType("contracts")
contracts.CONTRACT_DIR = root / "contracts"
contracts.create_contract = lambda *args: "synthetic.pdf"
sys.modules["contracts"] = contracts
database = importlib.import_module("database")
database.migrate = lambda: None
api = importlib.import_module("app")
worker_path = root / "warehouse" / "worker.py"
spec = importlib.util.spec_from_file_location("starpost_warehouse_poc", worker_path)
if spec is None or spec.loader is None:
raise RuntimeError("cannot load warehouse worker")
worker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(worker)
return api, worker
class FakeCursor:
def __init__(self):
timestamp = datetime.now(timezone.utc)
self.buyer = {"balance": CART_ITEMS * QUANTITY, "buyer_created_at": timestamp}
self.items = [
{
"product_id": product_id,
"seller_id": 1000 + product_id,
"price": 1,
"is_active": True,
"product_created_at": timestamp,
"quantity": QUANTITY,
}
for product_id in range(1, CART_ITEMS + 1)
]
self.one = None
self.many = []
self.order_id = 0
def __enter__(self):
return self
def __exit__(self, exc_type, exc, traceback):
return False
def execute(self, query, parameters=()):
normalized = " ".join(query.split())
self.one = None
self.many = []
if normalized.startswith("SELECT balance,created_at buyer_created_at"):
self.one = self.buyer
elif normalized.startswith("SELECT p.id product_id"):
self.many = self.items
elif normalized.startswith("INSERT INTO orders"):
self.order_id += 1
self.one = {"id": self.order_id}
def fetchone(self):
return self.one
def fetchall(self):
return self.many
class FakeConnection:
def __init__(self):
self.fake_cursor = FakeCursor()
def __enter__(self):
return self
def __exit__(self, exc_type, exc, traceback):
return False
def cursor(self):
return self.fake_cursor
def main():
api, worker = load_modules()
starts = []
class FakeThread:
def __init__(self, target, args, daemon):
self.target = target
self.args = args
self.daemon = daemon
def start(self):
starts.append((self.target, self.args, self.daemon))
worker.threading = SimpleNamespace(Thread=FakeThread)
warehouse = worker.app.test_client()
internal_statuses = []
def submit_jobs(orders):
for order in orders:
response = warehouse.post(
"/jobs",
json={"order_id": order["id"]},
headers={"X-Warehouse-Token": TOKEN},
)
internal_statuses.append(response.status_code)
api.db = lambda: FakeConnection()
api.submit_warehouse_jobs = submit_jobs
api.app.config.update(TESTING=True)
client = api.app.test_client()
with client.session_transaction() as session:
session.update(user_id=1, username="synthetic", role="buyer")
response = client.post("/api/cart/checkout", json={})
document = response.get_json(silent=True) or {}
orders = document.get("orders", [])
result = {
"external_checkout_requests": 1,
"prepared_cart_items": CART_ITEMS,
"orders_created": len(orders),
"internal_jobs_accepted": internal_statuses.count(202),
"jobs_retained": len(worker.jobs),
"worker_threads_started": len(starts),
"compose_pid_limit": 128,
"checkout_status": response.status_code,
}
print(json.dumps(result, sort_keys=True))
expected = CART_ITEMS * QUANTITY
if response.status_code != 201 or len(orders) != expected:
return 1
if result["internal_jobs_accepted"] != expected:
return 1
if result["jobs_retained"] != expected or result["worker_threads_started"] != expected:
return 1
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as error:
print(f"error: {error}", file=sys.stderr)
raise SystemExit(1)
View File
Whitespace-only changes.
+5
View File
@@ -0,0 +1,5 @@
FROM python:3.12-alpine
COPY requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir -r /app/requirements.txt
COPY worker.py /app/worker.py
CMD ["python", "/app/worker.py"]
+1
View File
@@ -0,0 +1 @@
Flask==3.1.0
+103
View File
@@ -0,0 +1,103 @@
import os
import secrets
import threading
import time
import urllib.error
import urllib.request
import json
from datetime import datetime, timezone
from flask import Flask, jsonify, request
API_URL = os.environ["WAREHOUSE_API_URL"]
CALLBACK_TOKEN = os.environ["WAREHOUSE_CALLBACK_TOKEN"]
app = Flask(__name__)
jobs = {}
jobs_lock = threading.Lock()
def request_json(method, path, payload=None):
data = json.dumps(payload).encode() if payload is not None else None
headers = {"Content-Type": "application/json", "X-Warehouse-Token": CALLBACK_TOKEN}
request = urllib.request.Request(f"{API_URL}{path}", data=data, headers=headers, method=method)
with urllib.request.urlopen(request, timeout=3) as response:
return json.loads(response.read())
def callback(job, stage):
request_json("POST", "/api/warehouse/callback", {"order_id": job["order_id"], "job_id": job["job_id"], "stage": stage})
with jobs_lock:
job["stage"] = stage
job["updated_at"] = datetime.now(timezone.utc).isoformat()
def process(job):
try:
for stage, delay in (("accepted", .05), ("picking", .18), ("in_transit", .18), ("arriving", .18), ("delivered", .18)):
time.sleep(delay)
callback(job, stage)
except (OSError, ValueError, urllib.error.URLError):
with jobs_lock:
jobs.pop(job["job_id"], None)
def delivery_loop():
while True:
try:
pending = request_json("GET", "/api/warehouse/pending")
for order in pending:
with jobs_lock:
known = any(job["order_id"] == order["id"] for job in jobs.values())
if known:
continue
job_id = "ATLAS-" + secrets.token_hex(8).upper()
job = {"job_id": job_id, "order_id": order["id"], "stage": "queued", "updated_at": datetime.now(timezone.utc).isoformat()}
jobs[job_id] = job
threading.Thread(target=process, args=(job,), daemon=True).start()
except (OSError, ValueError, urllib.error.URLError):
pass
time.sleep(.2)
@app.get("/health")
def health():
return jsonify(status="ok", service="warehouse", bot="ATLAS-7")
@app.post("/jobs")
def create_job():
if request.headers.get("X-Warehouse-Token") != CALLBACK_TOKEN:
return jsonify(error="forbidden"), 403
data = request.get_json(silent=True) or {}
try:
order_id = int(data["order_id"])
except (KeyError, TypeError, ValueError):
return jsonify(error="order_id is required"), 400
with jobs_lock:
for job in jobs.values():
if job["order_id"] == order_id:
return jsonify(job), 202
job_id = "ATLAS-" + secrets.token_hex(8).upper()
job = {"job_id": job_id, "order_id": order_id, "stage": "queued", "updated_at": datetime.now(timezone.utc).isoformat()}
jobs[job_id] = job
threading.Thread(target=process, args=(job,), daemon=True).start()
return jsonify(job), 202
@app.get("/jobs/<job_id>")
def get_job(job_id):
with jobs_lock:
job = jobs.get(job_id)
return (jsonify(job), 200) if job else (jsonify(error="job not found"), 404)
@app.get("/jobs")
def list_jobs():
with jobs_lock:
return jsonify(list(jobs.values())[-50:])
if __name__ == "__main__":
threading.Thread(target=delivery_loop, daemon=True).start()
app.run(host="0.0.0.0", port=6000, threaded=True)
+3
View File
@@ -0,0 +1,3 @@
FROM nginx:1.27-alpine
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY pages /usr/share/nginx/html
+20
View File
@@ -0,0 +1,20 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
add_header Cache-Control "no-store" always;
location = / { try_files /index.html =404; }
location = /login/ { try_files /login.html =404; }
location = /registr/ { try_files /registr.html =404; }
location = /marketplace/ { try_files /marketplace.html =404; }
location = /product/ { try_files /product.html =404; }
location = /cart/ { try_files /cart.html =404; }
location = /account/ { try_files /account.html =404; }
location = /orders/ { try_files /orders.html =404; }
location = /seller/ { try_files /seller.html =404; }
location = /contract/ { try_files /contract.html =404; }
location /api/ { proxy_pass http://api:5000; proxy_set_header Host $host; }
location = /health { proxy_pass http://api:5000; }
}
+124
View File
@@ -0,0 +1,124 @@
.account-hero {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 22px;
margin: 30px 0;
padding: 30px;
border: 1px solid var(--line);
background: linear-gradient(120deg, #14271f, var(--panel));
}
.account-hero h1 { font-size: clamp(2.3rem, 5vw, 4.5rem); margin: 4px 0; }
.avatar {
display: grid;
place-items: center;
width: 82px;
height: 82px;
border-radius: 50%;
background: var(--acid);
color: #101510;
font-size: 2.5rem;
font-weight: 900;
}
.balance { display: grid; gap: 8px; text-align: right; }
.balance small,
.account-stats small {
color: var(--dim);
font: 700 .7rem monospace;
letter-spacing: .12em;
}
.balance strong { color: var(--acid); font-size: 2rem; }
.account-stats {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
margin: 20px 0;
}
.account-stats > div {
display: grid;
gap: 10px;
padding: 22px;
border: 1px solid var(--line);
background: var(--panel);
}
.account-stats b { font-size: 1.8rem; }
.account-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
margin-top: 16px;
}
.account-panel {
padding: 26px;
border: 1px solid var(--line);
background: var(--panel);
}
.account-panel h2 { margin: 8px 0 22px; }
.account-links { display: grid; }
.account-links a {
display: flex;
justify-content: space-between;
padding: 16px 0;
border-bottom: 1px solid var(--line);
color: var(--ink);
text-decoration: none;
}
.account-links a:hover { color: var(--acid); }
.account-links span { color: var(--acid); }
.profile-data { display: grid; gap: 14px; }
.profile-data div {
display: flex;
justify-content: space-between;
gap: 15px;
padding-bottom: 12px;
border-bottom: 1px solid var(--line);
}
.profile-data dt { color: var(--dim); }
.profile-data dd { margin: 0; text-align: right; }
.recent-panel { margin-top: 16px; }
.recent-order {
display: grid;
grid-template-columns: 1fr auto auto;
gap: 20px;
align-items: center;
padding: 16px 0;
border-bottom: 1px solid var(--line);
}
.recent-order div { display: grid; gap: 6px; }
.recent-order small { color: var(--dim); }
.recent-order strong { white-space: nowrap; }
.status { text-transform: capitalize; color: var(--acid); }
@media (max-width: 760px) {
.account-hero, .account-grid { grid-template-columns: 1fr; }
.balance { text-align: left; }
.account-stats { grid-template-columns: 1fr 1fr; }
.recent-order { grid-template-columns: 1fr auto; }
.recent-order strong { grid-column: 1; }
.avatar { width: 64px; height: 64px; }
.account-hero { gap: 15px; }
}
.promo-box {
margin-top: 24px;
padding: 18px;
border: 1px solid #466c5d;
background: #0c1913;
}
.promo-box h3 { margin: 6px 0; }
.promo-row { display: flex; gap: 8px; margin: 14px 0; }
.promo-row input { min-width: 0; flex: 1; font-family: monospace; }
.promo-row button { white-space: nowrap; }
@media (max-width: 760px) {
.promo-row { flex-direction: column; }
}
+63
View File
@@ -0,0 +1,63 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Личный кабинет | Starpost</title>
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/account.css">
</head>
<body>
<header>
<a class="brand" href="/">STARPOST</a>
<nav></nav>
</header>
<main>
<p class="eyebrow">ЛИЧНЫЙ КАНАЛ · STARPOST ID</p>
<section id="profile" class="account-hero"><p class="muted">Загрузка профиля...</p></section>
<section id="stats" class="account-stats"></section>
<section class="account-grid">
<div class="account-panel"><p class="eyebrow">БЫСТРЫЙ ДОСТУП</p><h2>Ваши разделы</h2><div class="account-links"><a href="/marketplace/">Открыть маркетплейс <span>→</span></a><a href="/cart/">Перейти в корзину <span>→</span></a><a href="/orders/">Отследить заказы <span>→</span></a></div></div>
<div class="account-panel"><p class="eyebrow">ПРОФИЛЬ</p><h2>Данные аккаунта</h2><dl id="profile-data" class="profile-data"></dl><div id="promo-box"></div></div>
</section>
<section id="recent" class="account-panel recent-panel"></section>
</main>
<script src="/common.js"></script>
<script>
async function load() {
let data;
try {
data = await api("/api/account");
} catch (error) {
if (error.status === 401) location.href = "/login/";
else showAuthError("Не удалось загрузить кабинет. Повторите попытку через несколько секунд.");
return;
}
const user = data.user;
$("#profile").innerHTML = `<div class="avatar">${esc(user.username.slice(0, 1).toUpperCase())}</div><div><p class="eyebrow">${user.role === "buyer" ? "ПОКУПАТЕЛЬ" : "ПРОДАВЕЦ"}</p><h1>${esc(user.username)}</h1><p class="muted">На связи с орбитальным маркетплейсом Starpost</p></div><div class="balance"><small>ДОСТУПНЫЙ БАЛАНС</small><strong>${user.balance} cr</strong></div>`;
$("#profile-data").innerHTML = `<div><dt>Позывной</dt><dd>${esc(user.username)}</dd></div><div><dt>Роль</dt><dd>${user.role === "buyer" ? "Покупатель" : "Продавец"}</dd></div><div><dt>Дата регистрации</dt><dd>${new Date(user.created_at).toLocaleDateString("ru-RU")}</dd></div>${user.company_name ? `<div><dt>Компания</dt><dd>${esc(user.company_name)}</dd></div>` : ""}`;
if (user.role === "buyer") {
$("#stats").innerHTML = `<div><small>ЗАКАЗОВ</small><b>${data.stats.orders_count}</b></div><div><small>ДОСТАВЛЕНО</small><b>${data.stats.delivered_count}</b></div><div><small>ПОТРАЧЕНО</small><b>${data.stats.spent} cr</b></div><div><small>ОТЗЫВОВ</small><b>${data.reviews_count}</b></div>`;
$("#recent").innerHTML = `<p class="eyebrow">ПОСЛЕДНИЕ ДВИЖЕНИЯ</p><h2>Недавние заказы</h2>${data.recent_orders.map(order => `<div class="recent-order"><div><b>${esc(order.name)}</b><small>${esc(order.tracking_code)}</small></div><span class="status">${esc(order.status)}</span><strong>${order.price} cr</strong></div>`).join("") || `<p class="muted">Заказов пока нет. Перейдите в маркетплейс, чтобы выбрать груз.</p>`}`;
const promo = data.promo;
$("#promo-box").innerHTML = promo ? `<div class="promo-box"><p class="eyebrow">БОНУС STARPOST</p><h3>Промокод на 100 cr</h3><p class="muted">Активация выполняется двумя последовательными запросами.</p><div class="promo-row"><input id="promo-code" value="${esc(promo.code)}" readonly><button id="promo-activate">Активировать</button></div></div>` : "";
$("#promo-activate")?.addEventListener("click", activatePromo);
} else {
$("#stats").innerHTML = `<div><small>ТОВАРОВ</small><b>${data.stats.products_count}</b></div><div><small>АКТИВНЫХ</small><b>${data.stats.active_products_count}</b></div><div><small>ОТЗЫВОВ</small><b>${data.reviews_count}</b></div>`;
$("#recent").innerHTML = `<p class="eyebrow">РАЗДЕЛ СТАНЦИИ</p><h2>Управление магазином</h2><a class="button" href="/seller/">Открыть панель продавца</a>`;
}
}
async function activatePromo() {
const code = $("#promo-code").value;
try {
await api("/api/promo/credit", {method: "POST", body: JSON.stringify({code})});
await api("/api/promo/invalidate", {method: "POST", body: JSON.stringify({code})});
notify("На баланс начислено 100 cr. Промокод аннулирован.");
load();
} catch (error) { notify(error.message, "error"); }
}
load();
</script>
</body>
</html>
+108
View File
@@ -0,0 +1,108 @@
.cart-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 340px;
gap: 24px;
align-items: start;
}
.cart-items { display: grid; gap: 12px; }
.cart-item {
display: grid;
grid-template-columns: 64px minmax(0, 1fr) auto auto 28px;
align-items: center;
gap: 18px;
padding: 18px;
border: 1px solid var(--line);
background: var(--panel);
}
.cargo-mark {
display: grid;
place-items: center;
width: 64px;
aspect-ratio: 1;
border: 1px solid #466c5d;
background: linear-gradient(135deg, #1b3a2d, #0c1411);
color: var(--acid);
font: 700 .72rem monospace;
text-align: center;
letter-spacing: .08em;
}
.cart-item-info a { color: var(--ink); font-weight: 700; text-decoration: none; }
.cart-item-info a:hover { color: var(--acid); }
.cart-item-info p,
.cart-item-info small {
margin: 6px 0;
color: var(--dim);
font-size: .82rem;
}
.quantity-control { display: flex; align-items: center; border: 1px solid var(--line); }
.quantity-control button {
width: 34px;
padding: 8px;
background: transparent;
color: var(--ink);
}
.quantity-control span { width: 34px; text-align: center; }
.cart-price { display: grid; text-align: right; white-space: nowrap; }
.cart-price small { margin-top: 5px; color: var(--dim); }
.remove {
padding: 4px;
background: transparent;
color: var(--dim);
font-size: 1.4rem;
}
.checkout-card {
position: sticky;
top: 92px;
padding: 24px;
border: 1px solid var(--line);
background: var(--panel);
}
.checkout-card h2 { margin-top: 0; font-size: 1.4rem; }
.summary-row,
.summary-total {
display: flex;
justify-content: space-between;
gap: 15px;
padding: 12px 0;
}
.summary-row { color: var(--dim); }
.free { color: var(--acid); }
.summary-total {
margin: 8px 0 18px;
border-top: 1px solid var(--line);
padding-top: 18px;
font-size: 1.3rem;
}
.checkout-card button { width: 100%; }
.checkout-card button:disabled {
cursor: not-allowed;
background: #30443f;
color: #93a49d;
}
.checkout-card p { font-size: .78rem; }
.empty-cart {
padding: 50px 25px;
border: 1px dashed var(--line);
text-align: center;
}
@media (max-width: 850px) {
.cart-layout { grid-template-columns: 1fr; }
.checkout-card { position: static; }
.cart-item { grid-template-columns: 52px minmax(0, 1fr) 28px; }
.cargo-mark { width: 52px; }
.quantity-control, .cart-price { grid-column: 2; }
.cart-price { text-align: left; }
.remove { grid-column: 3; grid-row: 1; align-self: start; }
}
+88
View File
@@ -0,0 +1,88 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Корзина | Starpost</title>
<link rel="stylesheet" href="/style.css?v=cart-3">
<link rel="stylesheet" href="/cart.css?v=cart-3">
</head>
<body>
<header>
<a class="brand" href="/">STARPOST</a>
<nav></nav>
</header>
<main>
<p class="eyebrow">ЛИЧНЫЙ АНГАР</p>
<h1>Корзина</h1>
<p data-user class="muted"></p>
<div class="cart-layout">
<section id="cart" class="cart-items"></section>
<aside class="checkout-card">
<h2>Ваш заказ</h2>
<div class="summary-row"><span>Товары, <b id="item-count">0</b> шт.</span><b id="subtotal">0 cr</b></div>
<div class="summary-row"><span>Орбитальная доставка</span><b class="free">Бесплатно</b></div>
<div class="summary-total"><span>Итого</span><b id="total">0 cr</b></div>
<button id="checkout">Оформить заказ</button>
<p class="muted">После оплаты ATLAS-7 передаст грузы в орбитальный маршрут.</p>
</aside>
</div>
</main>
<script src="/common.js"></script>
<script>
let items = [];
const money = value => `${value} cr`;
async function load() {
if (!await guard("buyer")) return;
items = await api("/api/cart");
render();
}
function render() {
const count = items.reduce((sum, item) => sum + Number(item.quantity || 1), 0);
const total = items.reduce((sum, item) => sum + item.price * Number(item.quantity || 1), 0);
$("#item-count").textContent = count;
$("#subtotal").textContent = money(total);
$("#total").textContent = money(total);
$("#checkout").disabled = !items.length;
$("#cart").innerHTML = items.map(item => `
<article class="cart-item">
<div class="cargo-mark">SP<br>${String(item.id).padStart(3, "0")}</div>
<div class="cart-item-info"><a href="/product/?id=${item.id}">${esc(item.name)}</a><p>${esc(item.seller)}</p><small>${esc(item.description)}</small></div>
<div class="quantity-control"><button aria-label="Уменьшить" onclick="changeQuantity(${item.id}, ${Number(item.quantity || 1) - 1})">−</button><span>${Number(item.quantity || 1)}</span><button aria-label="Увеличить" onclick="changeQuantity(${item.id}, ${Number(item.quantity || 1) + 1})">+</button></div>
<div class="cart-price"><b>${money(item.price * Number(item.quantity || 1))}</b><small>${money(item.price)} за шт.</small></div>
<button class="remove" aria-label="Удалить" onclick="removeItem(${item.id})">×</button>
</article>`).join("") || `<div class="empty-cart"><h2>Ваша корзина пуста</h2><p class="muted">Выберите нужное оборудование в торговом коридоре.</p><a class="button" href="/marketplace/">Перейти в каталог</a></div>`;
}
async function changeQuantity(id, quantity) {
if (quantity < 1) return removeItem(id);
if (quantity > 10) return;
try {
await api(`/api/cart/${id}`, {method: "PATCH", body: JSON.stringify({quantity})});
await load();
} catch (error) {
notify(error.message, "error");
}
}
async function removeItem(id) {
await api(`/api/cart/${id}`, {method: "DELETE"});
await load();
}
$("#checkout").onclick = async () => {
try {
const result = await api("/api/cart/checkout", {method: "POST", body: "{}"});
notify(`Заказ оформлен: ${result.orders.length} ед. передано складу ATLAS-7.`);
location.href = "/orders/";
} catch (error) {
notify(error.message, "error");
}
};
load();
</script>
</body>
</html>
+183
View File
@@ -0,0 +1,183 @@
const $ = selector => document.querySelector(selector);
if (!document.querySelector('link[href="/ui.css"]')) {
const stylesheet = document.createElement("link");
stylesheet.rel = "stylesheet";
stylesheet.href = "/ui.css";
document.head.append(stylesheet);
}
class ApiError extends Error {
constructor(message, status = 0) {
super(message);
this.status = status;
}
}
async function api(path, options = {}) {
const method = (options.method || "GET").toUpperCase();
const headers = {"Content-Type": "application/json", ...(options.headers || {})};
let response;
let lastError;
for (let attempt = 0; attempt < (method === "GET" ? 3 : 1); attempt += 1) {
try {
response = await fetch(path, {...options, method, headers, credentials: "same-origin"});
if (![502, 503, 504].includes(response.status) || attempt === 2) break;
} catch (error) {
lastError = error;
if (attempt === 2) throw new ApiError("Сервис временно недоступен", 0);
}
await new Promise(resolve => setTimeout(resolve, 350 * (attempt + 1)));
}
if (!response) throw new ApiError(lastError?.message || "Сервис временно недоступен", 0);
const contentType = response.headers.get("content-type") || "";
const data = contentType.includes("json") ? await response.json() : null;
if (!response.ok) throw new ApiError(data?.error || `HTTP ${response.status}`, response.status);
return data;
}
const esc = value => String(value ?? "").replace(/[&<>"']/g, character => ({"&":"&amp;", "<":"&lt;", ">":"&gt;", "\"":"&quot;", "'":"&#39;"}[character]));
async function user() {
return api("/api/me");
}
async function optionalUser() {
try {
return await user();
} catch (error) {
if (error.status === 401) return null;
throw error;
}
}
function showAuthError(message) {
let element = $("#auth-error");
if (!element) {
element = document.createElement("p");
element.id = "auth-error";
element.className = "notice";
document.querySelector("main")?.prepend(element);
}
element.textContent = message;
}
async function guard(role) {
let me;
try {
me = await user();
} catch (error) {
if (error.status === 401) {
location.replace("/login/");
return null;
}
showAuthError("Не удалось проверить сессию. Повторите попытку через несколько секунд.");
return null;
}
if (role && me?.role !== role) {
location.replace(me?.role === "seller" ? "/seller/" : "/account/");
return null;
}
document.querySelectorAll("[data-user]").forEach(element => {
element.textContent = `${me.username} · ${me.balance} cr`;
});
return me;
}
async function logout() {
await api("/api/logout", {method: "POST", body: "{}"});
location.href = "/";
}
document.querySelectorAll("[data-logout]").forEach(element => element.onclick = event => {
event.preventDefault();
logout().catch(error => showAuthError(error.message));
});
async function renderNav() {
if (document.body.dataset.nav === "static") return;
const nav = document.querySelector("header nav");
if (!nav) return;
let me = null;
try {
me = await optionalUser();
} catch {
me = null;
}
const role = me?.role || null;
const links = [];
const add = (href, label, extra = "") => links.push(`<a ${extra}href="${href}">${label}</a>`);
add("/marketplace/", "Маркетплейс");
if (role === "buyer") {
add("/cart/", "Корзина");
add("/orders/", "Заказы");
add("/account/", "Кабинет");
} else if (role === "seller") {
add("/seller/", "Панель станции");
add("/contract/", "Договор");
} else {
add("/account/", "Кабинет");
add("/login/", "Войти");
add("/registr/", "Регистрация", "class=\"button\" ");
}
if (role) add("/login/", "Выйти", "data-logout ");
nav.innerHTML = links.join("");
nav.querySelectorAll("[data-logout]").forEach(element => element.onclick = event => {
event.preventDefault();
logout().catch(error => showAuthError(error.message));
});
}
renderNav();
function ensureUiLayer() {
if ($("#ui-layer")) return;
document.body.insertAdjacentHTML("beforeend", `
<div id="ui-layer">
<div id="toast-stack" class="toast-stack" aria-live="polite"></div>
<div id="confirm-backdrop" class="dialog-backdrop" hidden>
<section class="custom-dialog" role="dialog" aria-modal="true">
<p class="eyebrow">ПОДТВЕРЖДЕНИЕ</p>
<h2 id="confirm-title">Подтвердите действие</h2>
<p id="confirm-message" class="muted"></p>
<div class="dialog-actions"><button id="confirm-cancel" class="ghost-button">Отмена</button><button id="confirm-ok">Продолжить</button></div>
</section>
</div>
</div>`);
}
function notify(message, type = "info") {
ensureUiLayer();
const toast = document.createElement("div");
toast.className = `custom-toast ${type}`;
toast.innerHTML = `<span>${type === "error" ? "!" : "✓"}</span><div><b>${type === "error" ? "Ошибка" : "Готово"}</b><p>${esc(message)}</p></div>`;
$("#toast-stack").append(toast);
requestAnimationFrame(() => toast.classList.add("visible"));
setTimeout(() => {
toast.classList.remove("visible");
setTimeout(() => toast.remove(), 250);
}, 3500);
}
function confirmAction(message, title = "Подтвердите действие") {
ensureUiLayer();
return new Promise(resolve => {
const backdrop = $("#confirm-backdrop");
$("#confirm-title").textContent = title;
$("#confirm-message").textContent = message;
backdrop.hidden = false;
const finish = result => {
backdrop.hidden = true;
resolve(result);
};
$("#confirm-ok").onclick = () => finish(true);
$("#confirm-cancel").onclick = () => finish(false);
backdrop.onclick = event => {
if (event.target === backdrop) finish(false);
};
});
}
ensureUiLayer();
+49
View File
@@ -0,0 +1,49 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Договор | Starpost</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<header>
<a class="brand" href="/">STARPOST</a>
<nav></nav>
</header>
<main>
<p class="eyebrow">ЮРИДИЧЕСКИЙ ОТСЕК</p>
<h1>Договор станции</h1>
<p class="lead">
Подписанный договор хранится в защищенном архиве Starpost.
</p>
<a
id="contract-open"
class="button"
href="/api/contract"
target="_blank"
rel="noopener"
>
Открыть PDF-договор
</a>
<p id="contract-file" class="muted" style="margin-top:12px"></p>
</main>
<script src="/common.js"></script>
<script>
guard("seller").then(me => {
if (!me || !me.contract_file) return;
const link = document.getElementById("contract-open");
const hint = document.getElementById("contract-file");
link.href = "/api/contract?file=" + encodeURIComponent(me.contract_file);
if (hint) hint.textContent = me.contract_file;
});
</script>
</body>
</html>
+74
View File
@@ -0,0 +1,74 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Starpost — Орбитальный маркетплейс</title>
<link rel="stylesheet" href="/style.css">
<style>
.landing-section { max-width: 1100px; margin: 60px auto 0; padding: 56px 28px 0; }
.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-top: 40px; }
.stat { text-align: center; padding: 28px 16px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--panel); }
.stat b { display: block; font-size: 2.2rem; color: var(--acid); letter-spacing: -.04em; }
.stat small { color: var(--dim); font: 700 .68rem 'JetBrains Mono', monospace; letter-spacing: .14em; text-transform: uppercase; }
.steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-top: 28px; }
.step { padding: 26px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--panel); }
.step span { display: inline-grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; background: var(--acid); color: #0d1a10; font: 900 1rem monospace; margin-bottom: 14px; }
.step h3 { margin: 0 0 8px; }
.step p { color: var(--dim); font-size: .92rem; line-height: 1.6; }
.cta-row { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 26px; }
.cta-row .button { font-size: .95rem; padding: 14px 26px; }
.route-info { display: flex; gap: 24px; flex-wrap: wrap; justify-content: space-between; padding: 24px 0; border-top: 1px solid var(--line); margin-top: 60px; color: var(--dim); font-size: .8rem; }
.route-info span { font: 700 .7rem 'JetBrains Mono', monospace; color: var(--acid); letter-spacing: .12em; display: block; margin-bottom: 4px; }
@media (max-width: 760px) { .stats, .steps { grid-template-columns: 1fr; } }
</style>
</head>
<body data-nav="static">
<header>
<a class="brand" href="/">STARPOST <span>ORBITAL MARKET — SP-2049</span></a>
<nav>
<a href="/marketplace/">Маркетплейс</a>
<a href="/account/">Кабинет</a>
<a href="/login/">Войти</a>
<a class="button" href="/registr/">Регистрация</a>
</nav>
</header>
<main>
<section class="hero">
<div>
<p class="eyebrow">МАРШРУТ SP-2049 · СВЯЗЬ СТАБИЛЬНА</p>
<h1>Грузы для жизни<br><i>за пределами Земли.</i></h1>
<p class="lead">Покупайте редкие товары у независимых станций. Автономный бот <b>ATLAS-7</b> доставит заказ по орбитальному маршруту — от склада до вашего шлюза.</p>
<div class="cta-row">
<a class="button" href="/marketplace/">Открыть маркетплейс →</a>
<a class="button secondary" href="/registr/">Создать станцию</a>
</div>
</div>
<div class="planet" aria-hidden="true"></div>
</section>
<div class="stats">
<div class="stat"><b>8090</b><small>Порт орбитального узла</small></div>
<div class="stat"><b>ATLAS-7</b><small>Автономный доставщик</small></div>
<div class="stat"><b>×3</b><small>Класса грузов</small></div>
</div>
<section style="margin-top:60px">
<p class="eyebrow">КАК ЭТО РАБОТАЕТ</p>
<h2>Три шага до доставки</h2>
<div class="steps">
<div class="step"><span>1</span><h3>Выберите груз</h3><p>Каталог независимых станций — от термоконтейнеров до гидропонных модулей.</p></div>
<div class="step"><span>2</span><h3>Оформите заказ</h3><p>Корзина с количествами, атомарный чекаут, мгновенное списание баланса.</p></div>
<div class="step"><span>3</span><h3>ATLAS-7 доставит</h3><p>Складской бот проведёт груз через все орбитальные стадии до статуса delivered.</p></div>
</div>
</section>
<div class="route-info">
<div><span>МАРШРУТ</span> SP-2049 · квадрант Северная Орбита</div>
<div><span>СВЯЗЬ</span> Канал Starpost защищён · АРМРФ</div>
<div><span>ДОСТАВКА</span> Бесплатно · за банку паштета</div>
</div>
</main>
</body>
</html>
+54
View File
@@ -0,0 +1,54 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Вход — Starpost</title>
<link rel="stylesheet" href="/style.css">
<style>
.auth-wrap { max-width: 460px; margin: 40px auto; }
.auth-card { border: 1px solid var(--line); border-radius: var(--r-lg); background: linear-gradient(145deg,#121f1b,var(--panel)); padding: 36px; box-shadow: var(--shadow-lg); }
.auth-card h1 { font-size: 2rem; margin: .1em 0 .4em; }
.auth-card form { max-width: none; }
.field { display: grid; gap: 6px; }
.field label { font: 700 .72rem 'JetBrains Mono', monospace; letter-spacing: .12em; color: var(--dim); text-transform: uppercase; }
.pass-row { position: relative; }
.pass-row input { padding-right: 80px; }
.pass-toggle { position: absolute; right: 6px; top: 6px; bottom: 6px; padding: 0 12px; font-size: .75rem; background: transparent; color: var(--dim); border: 1px solid var(--line); border-radius: var(--r-sm); }
.pass-toggle:hover { color: var(--ink); background: #ffffff08; transform: none; box-shadow: none; }
.auth-foot { text-align: center; margin-top: 18px; font-size: .88rem; }
.auth-foot a { color: var(--acid); text-decoration: none; }
.auth-foot a:hover { text-decoration: underline; }
.msg { min-height: 1.2em; margin-top: 6px; font-size: .88rem; color: var(--danger); }
.msg.ok { color: var(--acid); }
</style>
</head>
<body data-nav="static">
<header><a class="brand" href="/">STARPOST</a><nav><a href="/marketplace/">Маркетплейс</a><a href="/registr/">Регистрация</a></nav></header>
<main>
<div class="auth-wrap">
<p class="eyebrow" style="text-align:center">ШЛЮЗ АВТОРИЗАЦИИ — SP-2049</p>
<div class="auth-card">
<h1>Войти в систему</h1>
<p class="muted" style="margin-bottom:20px">Введите позывной и пароль для доступа к орбитальному маркетплейсу.</p>
<form id="login">
<div class="field"><label for="username">Позывной</label><input id="username" name="username" placeholder="star_rider" required autocomplete="username"></div>
<div class="field"><label for="password">Пароль</label><div class="pass-row"><input id="password" name="password" type="password" placeholder="••••••••" required autocomplete="current-password"><button type="button" class="pass-toggle" onclick="togglePass('password',this)">Показать</button></div></div>
<button style="margin-top:8px;width:100%;padding:14px">Войти →</button>
<p id="message" class="msg"></p>
</form>
</div>
<p class="auth-foot muted">Нет аккаунта? <a href="/registr/">Создать учётную запись</a></p>
</div>
</main>
<script src="/common.js"></script>
<script>
function togglePass(id,btn){const i=document.getElementById(id);const h=i.type==='password';i.type=h?'text':'password';btn.textContent=h?'Скрыть':'Показать'}
document.getElementById('login').onsubmit=async e=>{
e.preventDefault();
const m=document.getElementById('message');m.textContent='';m.className='msg';
try{const d=Object.fromEntries(new FormData(e.target));const me=await api('/api/login',{method:'POST',body:JSON.stringify(d)});m.textContent='Вход выполнен ✓';m.className='msg ok';setTimeout(()=>location.href=me.role==='seller'?'/seller/':'/marketplace/',400)}catch(x){m.textContent=x.message}
};
</script>
</body>
</html>
+94
View File
@@ -0,0 +1,94 @@
.product-card {
display: flex;
flex-direction: column;
min-height: 440px;
padding: 0;
overflow: hidden;
}
.product-main { flex: 1; padding: 22px; }
.product-main small {
color: var(--acid);
font: 700 .7rem 'JetBrains Mono', monospace;
letter-spacing: .1em;
text-transform: uppercase;
}
.product-main h3 { margin: 6px 0 8px; }
.product-main h3 a { color: var(--ink); text-decoration: none; }
.product-main h3 a:hover { color: var(--acid); }
.product-main .muted { font-size: .88rem; }
.actions { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 14px; }
.actions button { flex: 1 1 auto; }
.card-reviews {
padding: 18px 22px;
border-top: 1px solid var(--line);
background: #0a1210;
}
.reviews-title,
.public-review > div {
display: flex;
justify-content: space-between;
gap: 10px;
}
.reviews-title span { color: var(--acid); font: 700 .8rem monospace; }
.public-review { padding: 12px 0; border-bottom: 1px solid #23342f; }
.public-review:last-of-type { border-bottom: 0; }
.public-review b,
.public-review p { font-size: .84rem; }
.public-review p { margin: 7px 0 0; color: var(--dim); line-height: 1.4; }
.stars { color: var(--acid); letter-spacing: .05em; }
/* Product detail page */
.product-detail {
display: grid;
grid-template-columns: minmax(0, 2fr) minmax(280px, 1fr);
gap: 32px;
padding: 44px 0;
}
.purchase-panel {
align-self: start;
display: grid;
gap: 12px;
padding: 24px;
border: 1px solid var(--line);
border-radius: var(--r-lg);
background: var(--panel);
}
.product-meta {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin: 34px 0 0;
}
.product-meta div {
padding: 15px;
border: 1px solid var(--line);
border-radius: var(--r-md);
background: var(--panel2);
}
.product-meta dt { color: var(--dim); font-size: .72rem; }
.product-meta dd { margin: 8px 0 0; }
.detail-reviews { border-top: 1px solid var(--line); padding-top: 34px; }
.detail-review {
max-width: 760px;
margin: 12px 0;
padding: 20px;
border: 1px solid var(--line);
border-radius: var(--r-md);
background: var(--panel);
}
.detail-review > div { display: flex; justify-content: space-between; gap: 12px; }
.detail-review p { color: var(--dim); line-height: 1.55; }
@media (max-width: 760px) {
.product-detail, .product-meta { grid-template-columns: 1fr; }
.purchase-panel { position: static; }
}
+99
View File
@@ -0,0 +1,99 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Маркетплейс — Starpost</title>
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/marketplace.css">
<style>
.mp-head { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px; margin-bottom: 24px; }
.mp-head h1 { margin-bottom: 0; }
.mp-search { display: flex; gap: 8px; flex-wrap: wrap; }
.mp-search input { min-width: 240px; max-width: 360px; }
.mp-search select { min-width: 160px; }
.skeleton-card { height: 440px; border: 1px solid var(--line); border-radius: var(--r-lg); overflow: hidden; }
</style>
</head>
<body>
<header>
<a class="brand" href="/">STARPOST</a>
<nav></nav>
</header>
<main>
<div class="mp-head">
<div>
<p class="eyebrow">ТОРГОВЫЙ КОРИДОР — SP-2049</p>
<h1>Маркетплейс</h1>
<p data-user class="muted">Гость</p>
</div>
<div class="mp-search">
<input id="q" placeholder="Поиск по названию или описанию" autocomplete="off">
<select id="sort"><option value="">Сортировка</option><option value="price_asc">Цена ↑</option><option value="price_desc">Цена ↓</option><option value="new">Новые</option></select>
</div>
</div>
<div id="products" class="grid"></div>
</main>
<script src="/common.js"></script>
<script>
let allProducts = [];
let me = null;
function skeletonHTML(n=6){
return Array(n).fill(0).map(()=>`<article class="card product-card"><div class="product-main"><span class="skeleton" style="height:14px;width:40%"></span><span class="skeleton" style="height:18px;width:80%;margin-top:14px"></span><span class="skeleton" style="height:12px;width:90%;margin-top:10px"></span><span class="skeleton" style="height:22px;width:80px;margin-top:16px"></span></div><footer class="card-reviews"><span class="skeleton" style="height:12px;width:50%"></span></footer></article>`).join('');
}
function render(list){
const el = document.getElementById('products');
if(!list.length){ el.innerHTML = `<div class="empty" style="grid-column:1/-1"><h2>Ничего не найдено</h2><p class="muted">Попробуйте изменить запрос или сбросить фильтры.</p></div>`; return; }
el.innerHTML = list.map(product => `
<article class="card product-card">
<div class="product-main">
<small>${esc(product.seller)}</small>
<h3><a class="product-link" href="/product/?id=${product.id}">${esc(product.name)}</a></h3>
<p class="muted">${esc(product.description)}</p>
<p class="price">${product.price} cr</p>
<div class="actions"><a class="button secondary" href="/product/?id=${product.id}">Подробнее</a>${me?.role === 'buyer' ? `<button onclick="cart(${product.id})">В корзину</button><button onclick="buy(${product.id})">Купить</button>` : ''}</div>
</div>
<footer class="card-reviews">
<div class="reviews-title"><b>Отзывы покупателей</b><span>${product.review_count}</span></div>
${product.reviews.length ? product.reviews.map(review => `
<div class="public-review">
<div><b>${esc(review.buyer)}</b><span class="stars">${'★'.repeat(review.rating)}${'☆'.repeat(5-review.rating)}</span></div>
<p>${esc(review.body)}</p>
</div>`).join('') : `<p class="muted">Пока нет открытых отзывов.</p>`}
${product.review_count > product.reviews.length ? `<small class="muted">Показаны последние ${product.reviews.length} из ${product.review_count}</small>` : ''}
</footer>
</article>`).join('');
}
function filtered(){
const q = document.getElementById('q').value.trim().toLowerCase();
const sort = document.getElementById('sort').value;
let list = q ? allProducts.filter(p => (p.name+' '+p.description+' '+p.seller).toLowerCase().includes(q)) : [...allProducts];
if(sort==='price_asc') list.sort((a,b)=>a.price-b.price);
if(sort==='price_desc') list.sort((a,b)=>b.price-a.price);
if(sort==='new') list.sort((a,b)=>b.id-a.id);
render(list);
}
async function run() {
document.getElementById('products').innerHTML = skeletonHTML();
me = await optionalUser();
const rows = await api('/api/products');
allProducts = rows;
render(rows);
document.getElementById('q').addEventListener('input', filtered);
document.getElementById('sort').addEventListener('change', filtered);
}
async function cart(id) {
try { await api('/api/cart',{method:'POST',body:JSON.stringify({product_id:id})}); notify('Товар добавлен в корзину'); } catch(e){ notify(e.message,'error'); }
}
async function buy(id) {
try { await api(`/api/products/${id}/buy`,{method:'POST',body:'{}'}); location.href='/orders/'; } catch(e){ notify(e.message,'error'); }
}
run();
</script>
</body>
</html>
+84
View File
@@ -0,0 +1,84 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Заказы | Starpost</title>
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/review.css">
</head>
<body>
<header><a class="brand" href="/">STARPOST</a><nav></nav></header>
<main><p class="eyebrow">ТРЕКИНГ ОРБИТАЛЬНЫХ ГРУЗОВ</p><h1>Мои заказы</h1><div id="orders"></div></main>
<div id="review-modal" class="modal-backdrop" hidden>
<section class="review-modal" role="dialog" aria-modal="true" aria-labelledby="review-title">
<button class="modal-close" id="close-review" aria-label="Закрыть">×</button>
<p class="eyebrow">ОБРАТНАЯ СВЯЗЬ</p>
<h2 id="review-title">Оцените получение</h2>
<p id="review-product" class="muted"></p>
<div class="rating-picker" aria-label="Оценка от 1 до 5">
<button type="button" data-rating="1">★</button><button type="button" data-rating="2">★</button><button type="button" data-rating="3">★</button><button type="button" data-rating="4">★</button><button type="button" data-rating="5">★</button>
</div>
<p id="rating-label" class="rating-label">Выберите оценку</p>
<textarea id="review-body" maxlength="1000" placeholder="Расскажите о товаре и доставке"></textarea>
<label class="private-toggle"><input id="review-private" type="checkbox"><span>Закрытый отзыв</span><small>Видно только продавцу</small></label>
<div class="modal-actions"><button class="secondary-button" id="cancel-review">Отмена</button><button id="send-review">Опубликовать отзыв</button></div>
</section>
</div>
<script src="/common.js"></script>
<script>
let activeOrder = null;
let selectedRating = 0;
const orderStore = new Map();
const ratingLabels = ["", "Очень плохо", "Плохо", "Нормально", "Хорошо", "Отлично"];
function openReview(order) {
activeOrder = order;
selectedRating = 0;
$("#review-product").textContent = order.name;
$("#review-body").value = "";
$("#review-private").checked = false;
$("#rating-label").textContent = "Выберите оценку";
document.querySelectorAll(".rating-picker button").forEach(button => button.classList.remove("selected"));
$("#review-modal").hidden = false;
}
function closeReview() { $("#review-modal").hidden = true; activeOrder = null; }
document.querySelectorAll(".rating-picker button").forEach(button => button.onclick = () => {
selectedRating = Number(button.dataset.rating);
document.querySelectorAll(".rating-picker button").forEach(item => item.classList.toggle("selected", Number(item.dataset.rating) <= selectedRating));
$("#rating-label").textContent = ratingLabels[selectedRating];
});
$("#close-review").onclick = closeReview;
$("#cancel-review").onclick = closeReview;
$("#review-modal").onclick = event => { if (event.target.id === "review-modal") closeReview(); };
$("#send-review").onclick = async () => {
const body = $("#review-body").value.trim();
if (!selectedRating) return notify("Выберите оценку от 1 до 5", "error");
if (!body) return notify("Напишите отзыв", "error");
try {
await api(`/api/orders/${activeOrder.id}/review`, {method: "POST", body: JSON.stringify({body, rating: selectedRating, private: $("#review-private").checked})});
closeReview();
load();
} catch (error) { notify(error.message, "error"); }
};
async function load() {
if (!await guard("buyer")) return;
const rows = await api("/api/orders");
orderStore.clear();
rows.forEach(order => orderStore.set(order.id, order));
$("#orders").innerHTML = rows.map(order => `<div class="row"><div><b>${esc(order.name)}</b><p class="status">${esc(order.tracking_code)} · ${esc(order.warehouse_status)} · ${esc(order.status)}</p>${order.cargo ? `<code>${esc(order.cargo)}</code>` : `<p class=muted>ATLAS-7: ${esc(order.warehouse_status)}</p>`}</div>${order.status === "delivered" ? `<button data-review-order="${order.id}">Оставить отзыв</button>` : ""}</div>`).join("") || "<p class=muted>Заказов нет.</p>";
}
$("#orders").onclick = event => {
const button = event.target.closest("[data-review-order]");
if (button) openReview(orderStore.get(Number(button.dataset.reviewOrder)));
};
load();
setInterval(load, 1500);
</script>
</body>
</html>
+66
View File
@@ -0,0 +1,66 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Товар — Starpost</title>
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/marketplace.css">
<style>
.purchase-panel { position: sticky; top: 82px; }
.purchase-panel button { width: 100%; }
.rating-badge { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border-radius: 99px; background: #0c1913; border: 1px solid var(--line); font-size: .85rem; }
</style>
</head>
<body>
<header>
<a class="brand" href="/">STARPOST</a>
<nav></nav>
</header>
<main>
<a class="muted" href="/marketplace/" style="display:inline-block;margin-bottom:18px">← Вернуться в каталог</a>
<section id="product" class="product-detail"><p class="muted">Загрузка карточки…</p></section>
<section class="detail-reviews">
<p class="eyebrow">ОТКРЫТЫЙ КАНАЛ ПОКУПАТЕЛЕЙ</p>
<h2>Отзывы о товаре</h2>
<div id="reviews"></div>
</section>
</main>
<script src="/common.js"></script>
<script>
let productId;
async function load() {
productId = Number(new URLSearchParams(location.search).get('id'));
if (!Number.isInteger(productId) || productId < 1) {
document.getElementById('product').innerHTML = `<p class="muted">Некорректный идентификатор товара.</p>`;
return;
}
try {
const [product, me] = await Promise.all([api(`/api/products/${productId}`), optionalUser()]);
document.title = `${product.name} — Starpost`;
document.getElementById('product').innerHTML = `
<div>
<p class="eyebrow">ГРУЗ #${product.id}</p>
<h1>${esc(product.name)}</h1>
<p class="lead">${esc(product.description)}</p>
<dl class="product-meta">
<div><dt>Станция-продавец</dt><dd>${esc(product.seller)}</dd></div>
<div><dt>Регистрационный номер</dt><dd>${esc(product.seller_tax_id)}</dd></div>
<div><dt>Рейтинг</dt><dd><span class="rating-badge">★ ${product.rating} · ${product.review_count} отзывов</span></dd></div>
</dl>
</div>
<aside class="purchase-panel">
<small style="color:var(--dim);font:700 .68rem 'JetBrains Mono',monospace;letter-spacing:.12em">СТОИМОСТЬ ДОСТАВКИ ВКЛЮЧЕНА</small>
<p class="price">${product.price} cr</p>
${me?.role === 'buyer' ? `<button onclick="addToCart()">Добавить в корзину</button><button class="secondary" onclick="buyNow()">Купить сейчас</button>` : `<p class="muted">Войдите как покупатель для заказа.</p>`}
</aside>`;
document.getElementById('reviews').innerHTML = product.reviews.length ? product.reviews.map(r=>`
<article class="detail-review"><div><b>${esc(r.buyer)}</b><span class="stars">${'★'.repeat(r.rating)}${'☆'.repeat(5-r.rating)}</span></div><p>${esc(r.body)}</p><small class="muted">${new Date(r.created_at).toLocaleDateString('ru-RU')}</small></article>`).join('') : `<p class="muted">Открытых отзывов пока нет — станьте первым.</p>`;
} catch (e) { document.getElementById('product').innerHTML = `<p class="muted">${esc(e.message)}</p>`; }
}
async function addToCart(){ try{ await api('/api/cart',{method:'POST',body:JSON.stringify({product_id:productId})}); location.href='/cart/'; }catch(e){ notify(e.message,'error'); } }
async function buyNow(){ try{ await api(`/api/products/${productId}/buy`,{method:'POST',body:'{}'}); location.href='/orders/'; }catch(e){ notify(e.message,'error'); } }
load();
</script>
</body>
</html>
+75
View File
@@ -0,0 +1,75 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Регистрация — Starpost</title>
<link rel="stylesheet" href="/style.css">
<style>
.auth-wrap { max-width: 520px; margin: 40px auto; }
.auth-card { border: 1px solid var(--line); border-radius: var(--r-lg); background: linear-gradient(145deg,#121f1b,var(--panel)); padding: 36px; box-shadow: var(--shadow-lg); }
.auth-card h1 { font-size: 2rem; margin: .1em 0 .4em; }
.auth-card form { max-width: none; }
.field { display: grid; gap: 6px; }
.field label { font: 700 .72rem 'JetBrains Mono', monospace; letter-spacing: .12em; color: var(--dim); text-transform: uppercase; }
.pass-row { position: relative; }
.pass-row input { padding-right: 80px; }
.pass-toggle { position: absolute; right: 6px; top: 6px; bottom: 6px; padding: 0 12px; font-size: .75rem; background: transparent; color: var(--dim); border: 1px solid var(--line); border-radius: var(--r-sm); }
.pass-toggle:hover { color: var(--ink); background: #ffffff08; transform: none; box-shadow: none; }
.role-switch { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.role-switch label { position: relative; display: grid; place-items: center; gap: 4px; padding: 14px 10px; border: 1px solid var(--line); border-radius: var(--r-md); background: #070f0d; cursor: pointer; transition: border-color var(--t), background var(--t); text-align: center; }
.role-switch label:has(input:checked) { border-color: var(--acid); background: #b7ff4312; }
.role-switch input { position: absolute; opacity: 0; pointer-events: none; }
.role-switch b { font-size: .92rem; }
.role-switch small { color: var(--dim); font-size: .75rem; }
#seller { display: grid; gap: 12px; padding: 18px; border: 1px dashed var(--line2); border-radius: var(--r-md); background: #0c1913; }
#seller[hidden] { display: none !important; }
.auth-foot { text-align: center; margin-top: 18px; font-size: .88rem; }
.auth-foot a { color: var(--acid); text-decoration: none; }
.auth-foot a:hover { text-decoration: underline; }
.msg { min-height: 1.2em; margin-top: 6px; font-size: .88rem; color: var(--danger); }
.msg.ok { color: var(--acid); }
</style>
</head>
<body data-nav="static">
<header><a class="brand" href="/">STARPOST</a><nav><a href="/login/">Войти</a><a href="/marketplace/">Маркетплейс</a></nav></header>
<main>
<div class="auth-wrap">
<p class="eyebrow" style="text-align:center">НОВАЯ УЧЁТНАЯ ЗАПИСЬ — SP-2049</p>
<div class="auth-card">
<h1>Присоединиться к маршруту</h1>
<p class="muted" style="margin-bottom:20px">Создайте аккаунт покупателя или зарегистрируйте станцию-продавца.</p>
<form id="register">
<div class="field"><label>Позывной</label><input name="username" placeholder="star_rider" required autocomplete="username"></div>
<div class="field"><label>Пароль · минимум 8 символов</label><div class="pass-row"><input id="pwd" name="password" type="password" placeholder="••••••••" required autocomplete="new-password"><button type="button" class="pass-toggle" onclick="togglePass('pwd',this)">Показать</button></div></div>
<div class="field"><label>Роль</label>
<div class="role-switch">
<label><input type="radio" name="role" value="buyer" checked><b>Покупатель</b><small>Заказы и отзывы</small></label>
<label><input type="radio" name="role" value="seller"><b>Станция</b><small>Продажи и договор</small></label>
</div>
</div>
<div id="seller" hidden>
<div class="field"><label>Название компании</label><input name="company_name" placeholder="ООО Северная Орбита"></div>
<div class="field"><label>ИНН / регистрационный номер</label><input name="tax_id" placeholder="1000000000"></div>
<div class="field"><label>Секретный ключ-подпись для договора</label><textarea name="signature" placeholder="SIGN-... — будет встроена в PDF-договор"></textarea></div>
</div>
<button style="margin-top:8px;width:100%;padding:14px">Создать учётную запись →</button>
<p id="message" class="msg"></p>
</form>
</div>
<p class="auth-foot muted">Уже есть аккаунт? <a href="/login/">Войти</a></p>
</div>
</main>
<script src="/common.js"></script>
<script>
function togglePass(id,btn){const i=document.getElementById(id);const h=i.type==='password';i.type=h?'text':'password';btn.textContent=h?'Скрыть':'Показать'}
const seller=document.getElementById('seller');
document.querySelectorAll('input[name=role]').forEach(r=>r.addEventListener('change',e=>{seller.hidden=e.target.value!=='seller'}));
document.getElementById('register').onsubmit=async e=>{
e.preventDefault();
const m=document.getElementById('message');m.textContent='';m.className='msg';
try{const d=Object.fromEntries(new FormData(e.target));const me=await api('/api/register',{method:'POST',body:JSON.stringify(d)});m.textContent='Аккаунт создан ✓';m.className='msg ok';setTimeout(()=>location.href=me.role==='seller'?'/seller/':'/marketplace/',400)}catch(x){m.textContent=x.message}
};
</script>
</body>
</html>
+79
View File
@@ -0,0 +1,79 @@
.modal-backdrop {
position: fixed;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
padding: 20px;
background: #020605cc;
backdrop-filter: blur(6px);
}
.modal-backdrop[hidden] { display: none; }
.review-modal {
position: relative;
width: min(100%, 520px);
padding: 32px;
border: 1px solid #4a6658;
background: linear-gradient(145deg, #14251e, #0b1210);
box-shadow: 0 24px 80px #000b;
}
.review-modal h2 { margin: 8px 0; }
.modal-close {
position: absolute;
right: 16px;
top: 12px;
padding: 2px 8px;
background: transparent;
color: var(--dim);
font-size: 1.7rem;
}
.rating-picker { display: flex; gap: 4px; margin: 24px 0 4px; }
.rating-picker button {
padding: 4px;
background: transparent;
color: #52675d;
font-size: 2.3rem;
line-height: 1;
}
.rating-picker button.selected { color: var(--acid); }
.rating-label {
height: 20px;
margin: 0;
color: var(--acid);
font-size: .85rem;
}
.review-modal textarea {
width: 100%;
margin: 18px 0;
min-height: 120px;
}
.private-toggle {
display: grid;
grid-template-columns: auto 1fr;
column-gap: 10px;
align-items: center;
padding: 14px;
border: 1px solid var(--line);
cursor: pointer;
}
.private-toggle input { accent-color: var(--acid); }
.private-toggle small { grid-column: 2; color: var(--dim); }
.modal-actions {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 22px;
}
.secondary-button {
background: transparent;
color: var(--ink);
border: 1px solid var(--line);
}
+30
View File
@@ -0,0 +1,30 @@
.seller-products { display: grid; gap: 12px; }
.seller-product {
display: flex;
justify-content: space-between;
gap: 20px;
align-items: center;
padding: 20px;
border: 1px solid var(--line);
background: var(--panel);
}
.seller-product h3 { margin: 8px 0; }
.seller-product p { color: var(--dim); margin: 6px 0; }
.seller-product small { color: var(--dim); }
.seller-product.archived { opacity: .65; }
.product-state {
color: var(--acid);
font: 700 .7rem monospace;
letter-spacing: .12em;
}
.archived .product-state { color: #ffbd43; }
.seller-product-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.danger { background: #ffbd43; }
@media (max-width: 700px) {
.seller-product { align-items: flex-start; flex-direction: column; }
.seller-product-actions { width: 100%; }
}
+128
View File
@@ -0,0 +1,128 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Панель станции | Starpost</title>
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/seller-products.css">
</head>
<body>
<header>
<a class="brand" href="/">STARPOST</a>
<nav></nav>
</header>
<main hidden>
<p class="eyebrow">ЦЕНТР УПРАВЛЕНИЯ СТАНЦИИ</p>
<h1>Панель продавца</h1>
<p data-user class="muted"></p>
<form id="product">
<h2>Новый груз</h2>
<input name="name" placeholder="Название" required>
<textarea name="description" placeholder="Публичное описание" required></textarea>
<textarea name="cargo" placeholder="Содержимое груза" required></textarea>
<input name="price" type="number" min="1" max="1000" placeholder="Цена" required>
<button>Опубликовать</button>
</form>
<h2>Мои товары</h2>
<div id="seller-products" class="seller-products"></div>
<h2>Продажи</h2><div id="sales"></div>
<h2>Отзывы</h2><div id="reviews"></div>
</main>
<div id="edit-product-modal" class="dialog-backdrop" hidden>
<form id="edit-product-form" class="custom-dialog">
<p class="eyebrow">РЕДАКТОР КАРТОЧКИ</p><h2>Изменить товар</h2>
<input id="edit-name" placeholder="Название" required>
<textarea id="edit-description" placeholder="Описание" required></textarea>
<input id="edit-price" type="number" min="1" max="1000" placeholder="Цена" required>
<div class="dialog-actions"><button type="button" class="ghost-button" id="edit-cancel">Отмена</button><button>Сохранить</button></div>
</form>
</div>
<script src="/common.js"></script>
<script>
let editedProduct = null;
const productStore = new Map();
async function load(cursor) {
if (!await guard("seller")) return;
document.querySelector("main").hidden = false;
const reviewsPath = cursor ? `/api/seller/reviews?cursor=${encodeURIComponent(cursor)}` : "/api/seller/reviews";
const [products, sales, reviewsData] = await Promise.all([api("/api/seller/products"), api("/api/seller/sales"), api(reviewsPath)]);
const reviews = Array.isArray(reviewsData) ? reviewsData : (reviewsData.reviews || []);
const nextCursor = reviewsData.next_cursor || "";
productStore.clear();
products.forEach(product => productStore.set(product.id, product));
$("#seller-products").innerHTML = products.map(product => `
<article class="seller-product ${product.is_active ? "" : "archived"}">
<div><span class="product-state">${product.is_active ? "АКТИВЕН" : "В АРХИВЕ"}</span><h3>${esc(product.name)}</h3><p>${esc(product.description)}</p><small>${product.price} cr · ${product.sales_count} продаж · ${product.income} cr дохода</small></div>
<div class="seller-product-actions"><button data-product-action="edit" data-product-id="${product.id}">Изменить</button>${product.is_active ? `<button class="danger" data-product-action="archive" data-product-id="${product.id}">В архив</button>` : `<button data-product-action="restore" data-product-id="${product.id}">Вернуть</button>`}</div>
</article>`).join("") || "<p class=muted>Опубликованных товаров пока нет.</p>";
$("#sales").innerHTML = `<p class="price">Доход: ${sales.income} cr</p>` + sales.sales.map(x => `<div class="row"><b>${esc(x.name)}</b><span>${esc(x.buyer)} · ${x.price} cr · ${esc(x.status)}</span></div>`).join("");
const paging = nextCursor ? `<button id="reviews-more" data-cursor="${esc(nextCursor)}">Показать ещё</button>` : "";
$("#reviews").innerHTML = reviews.map(x => `<div class="row ${x.is_private ? "private" : ""}"><div><b>${esc(x.name)} · ${"★".repeat(x.rating)}</b><p>${esc(x.body)}</p></div><small>${x.is_private ? "закрытый" : "открытый"}</small></div>`).join("") || "<p class=muted>Отзывов пока нет.</p>";
if (paging) $("#reviews").insertAdjacentHTML("beforeend", paging);
const more = $("#reviews-more");
if (more) more.onclick = () => load(more.dataset.cursor);
}
$("#seller-products").onclick = event => {
const button = event.target.closest("[data-product-action]");
if (!button) return;
const product = productStore.get(Number(button.dataset.productId));
if (button.dataset.productAction === "edit") editProduct(product.id, product);
if (button.dataset.productAction === "archive") archiveProduct(product.id);
if (button.dataset.productAction === "restore") restoreProduct(product.id, product);
};
async function editProduct(id, product) {
editedProduct = {id, ...product};
$("#edit-name").value = product.name;
$("#edit-description").value = product.description;
$("#edit-price").value = product.price;
$("#edit-product-modal").hidden = false;
}
async function archiveProduct(id) {
if (!await confirmAction("Товар исчезнет из каталога, но история заказов и отзывы сохранятся.", "Убрать товар в архив?")) return;
try {
await api(`/api/seller/products/${id}`, {method: "DELETE"});
notify("Товар перемещен в архив");
load();
} catch (error) { notify(error.message, "error"); }
}
async function restoreProduct(id, product) {
try {
await api(`/api/seller/products/${id}`, {method: "PATCH", body: JSON.stringify({name: product.name, description: product.description, price: product.price, is_active: true})});
notify("Товар снова опубликован");
load();
} catch (error) { notify(error.message, "error"); }
}
$("#product").onsubmit = async event => {
event.preventDefault();
try {
await api("/api/products", {method: "POST", body: JSON.stringify(Object.fromEntries(new FormData(event.target)))});
event.target.reset();
notify("Товар опубликован");
load();
} catch (error) { notify(error.message, "error"); }
};
$("#edit-cancel").onclick = () => { $("#edit-product-modal").hidden = true; editedProduct = null; };
$("#edit-product-modal").onclick = event => { if (event.target.id === "edit-product-modal") $("#edit-cancel").click(); };
$("#edit-product-form").onsubmit = async event => {
event.preventDefault();
if (!editedProduct) return;
try {
await api(`/api/seller/products/${editedProduct.id}`, {method: "PATCH", body: JSON.stringify({name: $("#edit-name").value, description: $("#edit-description").value, price: Number($("#edit-price").value), is_active: editedProduct.is_active})});
$("#edit-product-modal").hidden = true;
editedProduct = null;
notify("Карточка товара обновлена");
load();
} catch (error) { notify(error.message, "error"); }
};
load();
</script>
</body>
</html>
+290
View File
@@ -0,0 +1,290 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;900&family=JetBrains+Mono:wght@500&display=swap');
:root {
--void: #060b0a;
--panel: #0e1a17;
--panel2: #131f1c;
--line: #233830;
--line2: #2e4840;
--ink: #dff0e5;
--dim: #7a9e91;
--acid: #b7ff43;
--acid2: #9fe030;
--warn: #ffbd43;
--danger: #ff7474;
--r-sm: 4px;
--r-md: 8px;
--r-lg: 14px;
--shadow-sm: 0 2px 10px #00000044;
--shadow-md: 0 8px 32px #00000066;
--shadow-lg: 0 20px 60px #00000088;
--t: .18s ease;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html { scroll-behavior: smooth; }
body {
background:
radial-gradient(ellipse 70% 55% at 85% 0%, #1a3d2e55 0%, transparent 60%),
radial-gradient(ellipse 50% 40% at 10% 90%, #0d2e2255 0%, transparent 50%),
var(--void);
color: var(--ink);
font-family: 'Inter', system-ui, Arial, sans-serif;
font-size: 15px;
line-height: 1.6;
min-height: 100vh;
-webkit-font-smoothing: antialiased;
}
h1 {
font-size: clamp(2.6rem, 7vw, 5.2rem);
font-weight: 900;
line-height: .92;
letter-spacing: -.05em;
margin: .2em 0 .5em;
}
h2 { font-size: 1.9rem; font-weight: 800; letter-spacing: -.03em; margin-bottom: .5em; }
h3 { font-size: 1.15rem; font-weight: 700; margin-bottom: .3em; }
p { margin-bottom: .6em; }
p:last-child { margin-bottom: 0; }
.eyebrow {
color: var(--acid);
font: 700 .7rem 'JetBrains Mono', monospace;
letter-spacing: .2em;
text-transform: uppercase;
display: block;
margin-bottom: .5em;
}
.lead { color: var(--dim); font-size: 1.05rem; line-height: 1.65; }
.muted { color: var(--dim); line-height: 1.6; }
.price {
font-size: 1.7rem;
font-weight: 900;
color: var(--acid);
letter-spacing: -.03em;
}
.status { color: var(--acid); font-weight: 700; }
code {
font-family: 'JetBrains Mono', monospace;
font-size: .85em;
background: #0a1712;
border: 1px solid var(--line2);
border-radius: var(--r-sm);
padding: 2px 8px;
color: var(--acid);
word-break: break-all;
}
header {
position: sticky;
top: 0;
z-index: 20;
min-height: 66px;
padding: 0 5vw;
display: flex;
align-items: center;
gap: 20px;
border-bottom: 1px solid var(--line);
background: #07100eee;
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.brand {
color: var(--acid);
text-decoration: none;
font-weight: 900;
font-size: 1.05rem;
letter-spacing: .16em;
margin-right: auto;
transition: opacity var(--t);
}
.brand:hover { opacity: .8; }
.brand span { color: var(--dim); font-size: .6rem; display: block; letter-spacing: .12em; }
nav { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
nav a {
color: var(--dim);
text-decoration: none;
font-size: .82rem;
font-weight: 600;
padding: 6px 10px;
border-radius: var(--r-sm);
transition: color var(--t), background var(--t);
}
nav a:hover { color: var(--ink); background: #ffffff0d; }
main { max-width: 1100px; margin: auto; padding: 56px 28px 80px; }
.hero {
min-height: 420px;
display: grid;
grid-template-columns: 3fr 2fr;
align-items: center;
gap: 40px;
padding: 20px 0;
}
.planet {
width: min(30vw, 300px);
aspect-ratio: 1;
border-radius: 50%;
justify-self: center;
background: radial-gradient(circle at 28% 22%, #d4ff8a 0%, #68b230 14%, #1a4530 50%, #040a06 72%);
box-shadow:
-22px 10px 70px #9cff3540,
0 0 120px #2d6b2020,
inset -10px -10px 40px #00000060;
animation: orbit-float 8s ease-in-out infinite;
}
@keyframes orbit-float {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-14px); }
}
.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
.two { grid-template-columns: 1fr 1fr; }
.card {
border: 1px solid var(--line);
background: var(--panel);
border-radius: var(--r-lg);
padding: 22px;
transition: border-color var(--t), box-shadow var(--t);
}
.card:hover { border-color: var(--line2); box-shadow: var(--shadow-md); }
.row {
border: 1px solid var(--line);
background: var(--panel);
border-radius: var(--r-md);
padding: 18px 22px;
margin: 10px 0;
display: flex;
justify-content: space-between;
gap: 14px;
align-items: center;
transition: border-color var(--t);
}
.row:hover { border-color: var(--line2); }
.private { border-left: 3px solid var(--warn); }
.notice {
padding: 14px 18px;
border: 1px solid var(--line2);
border-radius: var(--r-md);
background: #0d1e18;
color: var(--dim);
font-size: .88rem;
}
form { display: grid; gap: 12px; max-width: 560px; }
input, textarea, select {
font: inherit;
padding: 12px 14px;
background: #070f0d;
color: var(--ink);
border: 1px solid var(--line2);
border-radius: var(--r-md);
outline: none;
transition: border-color var(--t), box-shadow var(--t);
width: 100%;
}
input:focus, textarea:focus, select:focus {
border-color: var(--acid);
box-shadow: 0 0 0 3px #b7ff4322;
}
input::placeholder, textarea::placeholder { color: var(--dim); opacity: .7; }
textarea { min-height: 90px; resize: vertical; }
select option { background: var(--panel); }
button, .button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 11px 20px;
border: none;
border-radius: var(--r-md);
background: var(--acid);
color: #0d1a10;
font: 700 .88rem 'Inter', sans-serif;
cursor: pointer;
text-decoration: none;
transition: background var(--t), transform var(--t), box-shadow var(--t);
white-space: nowrap;
}
button:hover, .button:hover {
background: var(--acid2);
box-shadow: 0 4px 20px #b7ff4340;
transform: translateY(-1px);
}
button:active, .button:active { transform: translateY(0); }
button.secondary, .button.secondary {
background: transparent;
color: var(--ink);
border: 1px solid var(--line2);
}
button.secondary:hover, .button.secondary:hover { background: #ffffff0d; box-shadow: none; }
button.danger { background: var(--warn); color: #1a0d00; }
button.danger:hover { background: #ffa820; }
button:disabled {
cursor: not-allowed;
background: var(--line);
color: var(--dim);
transform: none;
box-shadow: none;
}
.skeleton {
background: linear-gradient(90deg, var(--panel) 25%, var(--panel2) 50%, var(--panel) 75%);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
border-radius: var(--r-sm);
display: block;
}
@keyframes shimmer { to { background-position: -200% 0; } }
.empty {
padding: 60px 24px;
border: 1px dashed var(--line2);
border-radius: var(--r-lg);
text-align: center;
color: var(--dim);
}
.empty h2 { font-size: 1.4rem; margin-bottom: .4em; }
.badge {
display: inline-flex;
align-items: center;
padding: 3px 9px;
border-radius: 99px;
font: 700 .68rem 'JetBrains Mono', monospace;
letter-spacing: .1em;
text-transform: uppercase;
}
.badge-green { background: #1e3d1e; color: var(--acid); border: 1px solid #2e5c2e; }
.badge-yellow { background: #3d2e10; color: var(--warn); border: 1px solid #5c4420; }
.badge-red { background: #3d1010; color: var(--danger); border: 1px solid #5c2020; }
.badge-dim { background: var(--panel2); color: var(--dim); border: 1px solid var(--line); }
@media (max-width: 760px) {
header { padding: 12px 18px; }
.hero, .grid, .two { grid-template-columns: 1fr; }
.planet { width: 200px; }
main { padding: 36px 18px 60px; }
.row { align-items: flex-start; flex-direction: column; }
h1 { letter-spacing: -.04em; }
}
+75
View File
@@ -0,0 +1,75 @@
.toast-stack {
position: fixed;
right: 22px;
top: 88px;
z-index: 30;
display: grid;
gap: 10px;
width: min(380px, calc(100vw - 40px));
}
.custom-toast {
display: grid;
grid-template-columns: 38px 1fr;
gap: 12px;
align-items: center;
padding: 16px;
border: 1px solid #4a6658;
background: #122019;
box-shadow: 0 16px 45px #0009;
opacity: 0;
transform: translateX(25px);
transition: .25s;
}
.custom-toast.visible { opacity: 1; transform: none; }
.custom-toast > span {
display: grid;
place-items: center;
width: 34px;
height: 34px;
border-radius: 50%;
background: var(--acid);
color: #101510;
font-weight: 900;
}
.custom-toast.error { border-color: #8d4c4c; }
.custom-toast.error > span { background: #ff7474; }
.custom-toast p { margin: 4px 0 0; color: var(--dim); line-height: 1.35; }
.dialog-backdrop {
position: fixed;
inset: 0;
z-index: 25;
display: grid;
place-items: center;
padding: 20px;
background: #020605cc;
backdrop-filter: blur(6px);
}
.dialog-backdrop[hidden] { display: none; }
.custom-dialog {
width: min(100%, 470px);
padding: 30px;
border: 1px solid #4a6658;
background: linear-gradient(145deg, #14251e, #0b1210);
box-shadow: 0 24px 80px #000b;
}
.custom-dialog h2 { margin: 8px 0; }
.dialog-actions {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 24px;
}
.ghost-button {
background: transparent;
color: var(--ink);
border: 1px solid var(--line);
}
@media (max-width: 600px) {
.toast-stack { right: 14px; top: 76px; width: calc(100vw - 28px); }
}