Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Configure these only in the production host (for example, Vercel).
# Never commit a real .env file, token, secret, seed phrase or private key.
TELEGRAM_BOT_TOKEN=
TELEGRAM_WEBHOOK_SECRET=
TELEGRAM_MINI_APP_URL=https://aitor.alienflow.space
MANUS_API_KEY=
MANUS_WEBHOOK_SECRET=

# Public client configuration is already supplied by the deployed project.
# Use these only when overriding the existing Supabase/Reown configuration.
VITE_SUPABASE_URL=
VITE_SUPABASE_PUBLISHABLE_KEY=
VITE_REOWN_PROJECT_ID=
94 changes: 94 additions & 0 deletions IMPLEMENTATION_LOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Implementation Log

## Globe stabilization — 15 August 2026

### Completed

- Connected the tactical legend to the Cesium renderer.
- Standardized tactical categories used by the dashboard and globe layers.
- Made market arcs visible only when both related hotspots are enabled.
- Preserved valid flight and marine markers at latitude or longitude `0`.
- Stabilized the local production build by removing MCP code generation that wrote a machine-specific Windows path into the Supabase function.
- Pinned the MCP package version and synchronized the dependency lockfile.

### Validation

- Production build completed successfully with Vite.

### Next priorities

1. Resolve the existing TypeScript and lint backlog in Globe and agent modules.
2. Add layer-combination regression tests for the Globe.
3. Implement Reown wallet connection and the crypto/NFT paywall after chain and billing rules are defined.

## Module 1 delivery plan — 15 August 2026

### Completed

- Published a delivery plan that records the current baseline, completion scope, ownership, acceptance criteria, and required Web3 decisions.
- Stored the plan in `docs/AiTor_Modulo_1_Plano_de_Entrega.docx` and published it to the private project repository.
- Re-ran the Vite production build successfully after documenting the plan.

### Remaining external decisions

- Supported chain(s), Reown project ID, accepted asset, price and receiving wallet.
- NFT contract, token ID rules and the access tier granted by ownership.
- Production deployment ownership and the final Telegram-to-web payment journey.

## Paywall foundation — 15 August 2026

### Completed

- Added a service-role-only data model for verified wallets, payment orders and access entitlements.
- Added an authenticated access-status endpoint so the web and Telegram flows can consume the same access source.
- Added the owner handoff document with configuration values and the server-side verification sequence.

### Deliberate boundary

- No payment, NFT possession or wallet is accepted as valid until owner-supplied network and billing rules are configured and verified server-side.

## Wallet connection and public DAO references — 19 August 2026

### Completed

- Recovered the public Reown configuration, supported EVM networks, DAO references and OpenSea profiles from the official AlienFlowSpace source repository.
- Added the Reown AppKit wallet connection to the AiTor top navigation. It supports Polygon as the default network, plus Ethereum, Arbitrum, Base and BSC.
- Shows the connected wallet's abbreviated public address and opens the account screen on a subsequent click.
- Documented the official public references and the remaining verification requirement for NFT access.

### Validation

- Vite production build completed successfully.

### Still intentionally pending

- A specific NFT contract address, token eligibility rule, payment recipient, asset and price. OpenSea profile URLs alone cannot be used to verify ownership or grant access.

## Secure wallet linking — 19 August 2026

### Completed

- Added one-time, expiring wallet-verification challenges in Supabase.
- Added the authenticated `wallet-link` Edge Function. It verifies an EVM signature on the server before associating a public wallet address with the logged-in user.
- Updated the wallet button to guide the user through connect → sign → verified status.
- Updated tier resolution to consume confirmed backend entitlements in addition to the existing credit tier.

### Deployment boundary

- The migration and Edge Functions require deployment by the owner of the Supabase project. No service key, seed phrase or private key is required from Aitor or from a wallet holder.

## Module 1 production readiness — 19 August 2026

### Verified public routes

- AiTor domain, Telegram bot, Telegram Mini App and the deployed POST-only webhook route are reachable.

### Completed in code

- Added the production environment template and M1 go-live checklist.
- Changed Telegram webhook validation to fail closed when its secret is missing or invalid.
- Replaced the broken Telegram short-name Mini App link with a configurable direct Web App button.

### Owner-only activation

- Configure encrypted production variables, register Telegram's webhook secret, deploy, and run the real-account acceptance test described in `docs/M1_TELEGRAM_GO_LIVE.md`.
30 changes: 21 additions & 9 deletions api/telegram-webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { VercelRequest, VercelResponse } from '@vercel/node';
// Variables de entorno (se configuran en Vercel)
const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN!;
const MANUS_API_KEY = process.env.MANUS_API_KEY!;
const TELEGRAM_MINI_APP_URL = process.env.TELEGRAM_MINI_APP_URL || 'https://aitor.alienflow.space';

// Supabase de AiTor (función de chat existente)
const SUPABASE_URL = 'https://wkdtvrxavkhbifjtvvdw.supabase.co';
Expand All @@ -12,7 +13,11 @@ const CHAT_URL = `${SUPABASE_URL}/functions/v1/chat`;
const TELEGRAM_API = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}`;

// Enviar mensaje a Telegram
async function sendTelegramMessage(chatId: number, text: string) {
type TelegramReplyMarkup = {
inline_keyboard: Array<Array<{ text: string; web_app?: { url: string }; url?: string }>>;
};

async function sendTelegramMessage(chatId: number, text: string, replyMarkup?: TelegramReplyMarkup) {
// Telegram tiene límite de 4096 caracteres por mensaje
const maxLen = 4000;
if (text.length > maxLen) {
Expand All @@ -26,6 +31,7 @@ async function sendTelegramMessage(chatId: number, text: string) {
chat_id: chatId,
text: part,
parse_mode: 'Markdown',
...(replyMarkup ? { reply_markup: replyMarkup } : {}),
}),
});
}
Expand All @@ -37,6 +43,7 @@ async function sendTelegramMessage(chatId: number, text: string) {
chat_id: chatId,
text: text,
parse_mode: 'Markdown',
...(replyMarkup ? { reply_markup: replyMarkup } : {}),
}),
});
}
Expand Down Expand Up @@ -138,17 +145,14 @@ export default async function handler(req: VercelRequest, res: VercelResponse) {
return res.status(405).send('Method Not Allowed');
}

// Verify the request really comes from Telegram (setWebhook secret_token).
// Only enforced when a secret is configured AND the webhook was registered
// with it; otherwise the bot would go silent (Telegram sends no header).
// Production webhooks must use Telegram's setWebhook secret_token.
// Fail closed: accepting a request without this header lets anyone trigger
// bot replies or consume AI-provider credits.
const expectedSecret = process.env.TELEGRAM_WEBHOOK_SECRET;
const providedSecret = req.headers['x-telegram-bot-api-secret-token'];
if (expectedSecret && providedSecret && providedSecret !== expectedSecret) {
if (!expectedSecret || providedSecret !== expectedSecret) {
return res.status(401).send('Unauthorized');
}
if (expectedSecret && !providedSecret) {
console.warn('Telegram webhook received without secret_token header — re-register the webhook with secret_token.');
}

const { message } = req.body || {};

Expand All @@ -169,7 +173,15 @@ export default async function handler(req: VercelRequest, res: VercelResponse) {
}
else if (command === '/app') {
await sendTelegramMessage(chatId,
'🎮 Accede a la Mini App:\nhttps://t.me/Alien69Bot/app'
'🎮 *Accede a la Mini App de AI Tor*',
{
inline_keyboard: [[
{
text: '🚀 Abrir Mini App',
web_app: { url: TELEGRAM_MINI_APP_URL },
},
]],
},
);
}
else if (command === '/dao') {
Expand Down
Binary file added docs/AiTor_Modulo_1_Plano_de_Entrega.docx
Binary file not shown.
118 changes: 118 additions & 0 deletions docs/M1_PRODUCTION_HANDOFF_ES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# M1 — Entrega y activación en producción

Fecha de verificación: 22 de agosto de 2026.

Este documento separa el código incluido en la PR de las acciones que requieren acceso del propietario a Vercel, Supabase, Telegram y Reown. Ninguna semilla, clave privada, contraseña o token secreto debe añadirse al repositorio.

## Alcance incluido en la PR

- Integración del bot de Telegram con AiTor y la función de IA existente.
- Endpoint serverless `POST /api/telegram-webhook` para Vercel.
- Comandos básicos `/start`, `/app`, `/dao`, `/help` y `/manus`.
- Respuestas automáticas y envío de consultas a AiTor.
- Botón directo `web_app` para abrir la Mini App sin depender del short name inexistente `t.me/Alien69Bot/app`.
- Validación obligatoria del header `X-Telegram-Bot-Api-Secret-Token`.
- Integración inicial de Reown AppKit para Polygon, Ethereum, Base, Arbitrum y BNB Chain.
- Vinculación segura de wallet mediante challenge y firma, sin solicitar seed phrase ni clave privada.
- Estructura de entitlements para liberar el tier confirmado.
- Migraciones y Edge Functions de Supabase para `wallet-link` y `access-status`.
- Estabilización de las capas combinadas del globe incluida en la rama de trabajo.

## Estado público verificado

- `https://aitor.alienflow.space/` responde correctamente.
- `https://aitor.alienflow.space/api/telegram-webhook` está publicado y acepta únicamente `POST`.
- Proyecto Supabase identificado: `wkdtvrxavkhbifjtvvdw`.
- La Edge Function `chat` está publicada.
- Las funciones `wallet-link` y `access-status` todavía no están publicadas y devuelven `404` antes de aplicar esta entrega.
- Los deployments de GitHub son realizados por `vercel[bot]` en los entornos `Preview` y `Production`.
- El webhook público actual no rechaza un secret token inválido; después del deploy de esta PR debe responder `401`.

## Acciones del propietario después del merge

### 1. Vercel

Configurar en el proyecto de producción, usando el panel cifrado de Environment Variables:

```text
TELEGRAM_BOT_TOKEN=<token de BotFather>
TELEGRAM_WEBHOOK_SECRET=<secreto aleatorio fuerte>
TELEGRAM_MINI_APP_URL=https://aitor.alienflow.space
MANUS_API_KEY=<clave de Manus>
MANUS_WEBHOOK_SECRET=<secreto del callback de Manus>
```

Las variables públicas de Supabase ya tienen una configuración de respaldo en el proyecto. Se pueden sobrescribir por despliegue con `VITE_SUPABASE_URL` y `VITE_SUPABASE_PUBLISHABLE_KEY`.

Después de configurar las variables, realizar un nuevo deployment de producción.

### 2. Supabase

Vincular Supabase CLI al proyecto `wkdtvrxavkhbifjtvvdw` con una cuenta autorizada. Aplicar las migraciones nuevas:

```text
supabase/migrations/20260815143000_prepare_wallet_entitlements.sql
supabase/migrations/20260819170000_add_wallet_verification_challenges.sql
```

Publicar las funciones:

```text
supabase/functions/wallet-link
supabase/functions/access-status
```

Confirmar que las políticas RLS siguen activas y que un usuario solamente puede consultar o modificar sus propios datos.

### 3. Telegram

Después del deployment, volver a registrar el webhook utilizando el mismo valor definido como `TELEGRAM_WEBHOOK_SECRET` en Vercel:

```bash
curl "https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/setWebhook" \
-d "url=https://aitor.alienflow.space/api/telegram-webhook" \
-d "secret_token=<TELEGRAM_WEBHOOK_SECRET>"
```

No guardar el token ni el secreto en commits, issues, PRs o mensajes públicos.

### 4. Reown

- Autorizar `https://aitor.alienflow.space` en el proyecto Reown utilizado por AlienFlowSpace, o configurar un proyecto separado mediante `VITE_REOWN_PROJECT_ID`.
- Mantener Polygon como red principal inicial.
- Ethereum y las demás redes EVM quedan disponibles como expansión.
- Lightning Network requiere una integración separada y no forma parte del cierre técnico de M1.

### 5. Reglas de acceso NFT/paywall

Antes de activar accesos comerciales reales, confirmar y configurar públicamente:

- dirección exacta de cada contrato NFT;
- red y estándar del contrato;
- colección o token que concede cada tier;
- si el NFT solamente concede acceso o también se consume/canjea;
- duración del acceso;
- wallet de recepción, activo aceptado y precio cuando exista pago directo.

Hasta que estas reglas sean confirmadas, el sistema mantiene los entitlements en modo seguro y no inventa accesos ni cobros.

## Pruebas de aceptación

- `/start`, `/help`, `/dao` y `/app` responden en Telegram.
- `/app` abre `https://aitor.alienflow.space` dentro de Telegram.
- Una pregunta normal recibe respuesta de AiTor.
- Un POST sin secret token o con secret token inválido devuelve `401`.
- El login web funciona.
- La conexión Reown abre el selector de wallets.
- La firma vincula la wallet a la cuenta autenticada.
- `wallet-link` y `access-status` dejan de devolver `404`.
- Un entitlement activo libera únicamente el tier correspondiente.
- El build de producción y los endpoints serverless terminan sin errores.

## Fuera del alcance de cierre de M1

- Migración o pagos nativos mediante Lightning Network.
- Emisión de nuevos criptoactivos.
- Conversión fiat y liquidación multimoneda.
- Publicación automática en redes sociales y fases avanzadas de Agents, Loops y RAG.

37 changes: 37 additions & 0 deletions docs/M1_TELEGRAM_GO_LIVE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# M1 — Telegram + AI production checklist

## Publicly verified on 19 August 2026

- `https://aitor.alienflow.space/` responds successfully.
- `GET https://aitor.alienflow.space/api/telegram-webhook` returns `405 Method Not Allowed`, which confirms that a POST-only webhook endpoint is deployed.
- `https://t.me/Alien69Bot` and `https://t.me/Alien69Bot/app` are publicly reachable.
- The code routes ordinary Telegram messages to the AiTor chat function and routes `/manus` tasks to the Manus callback flow.

These checks prove that the public routes exist. They do not prove that private production credentials, webhook registration, model provider credits or payment rules are currently valid.

## Owner activation steps

1. In the production host, set `TELEGRAM_BOT_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`, `MANUS_API_KEY` and `MANUS_WEBHOOK_SECRET` using the host's encrypted environment-variable panel.
2. Deploy the branch containing this checklist and the strict webhook-secret check.
3. Register the Telegram webhook using the same `TELEGRAM_WEBHOOK_SECRET`:

```bash
curl "https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/setWebhook" \
-d "url=https://aitor.alienflow.space/api/telegram-webhook" \
-d "secret_token=<TELEGRAM_WEBHOOK_SECRET>" \
-d 'allowed_updates=["message"]'
```

4. Set `TELEGRAM_MINI_APP_URL` to the public HTTPS URL of the AiTor Mini App (default: `https://aitor.alienflow.space`). The `/app` command sends a direct Telegram Web App button, so it does not depend on an unregistered BotFather short name such as `/app`.
5. In BotFather, configure group privacy according to the intended community behaviour.
6. Test from a real Telegram account:
- `/start` returns the welcome message;
- a normal message receives an AI response;
- `/app` opens the Mini App;
- `/manus <question>` receives its asynchronous callback;
- an invalid webhook request is rejected with `401`.
7. Check the hosting logs and Telegram's `getWebhookInfo` after the test. Pending updates and last webhook errors must be zero.

## Monetization boundary

M1 can link Telegram to the same verified-access backend, but payment activation remains disabled until the NFT contracts, payment recipient, accepted asset and pricing rules are confirmed by the owner.
Loading