@7ots/cli 0.1.17 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +14 -0
- package/README.md +11 -0
- package/brand/logos/base.svg +1 -0
- package/brand/logos/clawpump.png +0 -0
- package/brand/logos/conductors.svg +1 -0
- package/brand/logos/notlogin.svg +12 -0
- package/brand/logos/pumpfun.png +0 -0
- package/brand/logos/solana.png +0 -0
- package/brand/logos/spawnerbot.svg +1 -0
- package/brand/logos/virtuals.png +0 -0
- package/cli/7ots.mjs +61 -1
- package/cli/lib/account.mjs +23 -3
- package/cli/lib/assistant.mjs +92 -14
- package/cli/lib/brain.mjs +84 -11
- package/cli/lib/card-shot.mjs +1 -1
- package/cli/lib/config.mjs +14 -3
- package/cli/lib/desktop-sync.mjs +177 -0
- package/cli/lib/i18n.mjs +9 -0
- package/cli/lib/inferences.mjs +19 -2
- package/cli/lib/integrations.mjs +98 -13
- package/cli/lib/mcp.mjs +1 -1
- package/cli/lib/open.mjs +3 -1
- package/cli/lib/pet-server.mjs +352 -41
- package/cli/lib/prompts.mjs +1 -1
- package/cli/lib/screen.mjs +1 -1
- package/cli/lib/senses/gestures.mjs +121 -0
- package/cli/lib/senses/index.mjs +490 -0
- package/cli/lib/senses/rules.mjs +159 -0
- package/cli/lib/senses/sources/activity.mjs +95 -0
- package/cli/lib/senses/sources/calendar.mjs +75 -0
- package/cli/lib/senses/sources/index.mjs +17 -0
- package/cli/lib/senses/sources/mail.mjs +48 -0
- package/cli/lib/senses/sources/system.mjs +39 -0
- package/cli/lib/senses/util.mjs +41 -0
- package/cli/lib/senses/vendor.mjs +78 -0
- package/cli/lib/stt-local.py +16 -8
- package/cli/lib/stt.mjs +53 -6
- package/cli/lib/tooluse.mjs +56 -0
- package/cli/lib/tts-local.mjs +2 -2
- package/cli/lib/vm.mjs +2 -2
- package/cli/lib/wake-local.py +109 -0
- package/cli/lib/wake.mjs +102 -0
- package/cli/pet/electron/main.cjs +190 -8
- package/cli/pet/pet.html +153 -34
- package/cli/pet/senses.html +342 -0
- package/cli/pet/settings.html +815 -74
- package/dist/7ots.esm.js +373 -146
- package/dist/7ots.esm.js.map +4 -4
- package/dist/7ots.iife.js +373 -146
- package/dist/7ots.iife.js.map +4 -4
- package/llms.txt +27 -0
- package/package.json +5 -2
- package/server/channels/apuchat.mjs +18 -4
- package/server/errors.mjs +90 -0
- package/server/notify.mjs +78 -0
- package/server/server.mjs +84 -14
- package/server/settings.mjs +3 -0
- package/server/site.mjs +401 -0
- package/server/tts.mjs +29 -5
- package/src/avatar/AvatarStage.js +2 -2
- package/src/avatar/three.js +3 -2
- package/src/character/AvatarEditor.js +2 -1
- package/src/character/Character.js +38 -5
- package/src/character/TradingCard.js +2 -0
- package/src/character/beat.js +64 -2
- package/src/character/mods/orc.js +8 -1
- package/src/character/mods.js +104 -10
- package/src/character/motion.js +252 -1
- package/src/character/parts.js +40 -38
- package/src/character/styles.js +40 -38
- package/src/character3d/Character3D.js +26 -5
- package/src/character3d/body.js +14 -12
- package/src/character3d/export.js +693 -0
- package/src/character3d/fx.js +13 -0
- package/src/character3d/index.js +2 -0
- package/src/character3d/materials.js +106 -10
- package/src/character3d/room-themes.js +1184 -0
- package/src/character3d/room.js +487 -0
- package/src/character3d/stage.js +14 -2
- package/src/creator/StepCreator.js +316 -0
- package/src/i18n/index.js +3 -3
- package/src/i18n/messages/character.js +352 -4
- package/src/i18n/messages/creator.js +138 -0
- package/src/i18n/messages/identity.js +89 -1
- package/src/i18n/messages/platform.js +270 -4
- package/src/i18n/messages/server.js +443 -1
- package/src/i18n/messages/widget.js +233 -0
- package/src/identity/random.js +14 -2
- package/src/identity/schema.js +2 -1
- package/src/index.js +9 -2
- package/src/voice/tags.js +22 -0
- package/server/platform/apuchat.mjs +0 -266
- package/server/platform/auth.mjs +0 -319
- package/server/platform/connect.mjs +0 -387
- package/server/platform/crypto.mjs +0 -80
- package/server/platform/db.mjs +0 -275
- package/server/platform/device.mjs +0 -222
- package/server/platform/integrations.mjs +0 -169
- package/server/platform/look.mjs +0 -20
- package/server/platform/mods.mjs +0 -222
- package/server/platform/orquesta.mjs +0 -577
- package/server/platform/profile.mjs +0 -161
- package/server/platform/routes.mjs +0 -542
- package/server/platform/runtime.mjs +0 -242
- package/server/platform/sites.mjs +0 -146
- package/server/platform/store.mjs +0 -456
- package/server/platform/vm.mjs +0 -1057
|
@@ -1,242 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Runtime de cada ots en la plataforma: su entorno, su LLM, su voz y sus canales.
|
|
3
|
-
*
|
|
4
|
-
* Cada ots tiene un "entorno" propio (un objeto, nunca process.env) hecho de:
|
|
5
|
-
* 1. lo que fija la plataforma (hub de apuchat, API de apumail, servicio de voz),
|
|
6
|
-
* 2. sus ajustes y claves (solo las de OTS_KEYS),
|
|
7
|
-
* 3. si no trae clave de IA o de voz, la de la plataforma, con cupo gratis por cuenta y mes:
|
|
8
|
-
* PLATFORM_LLM_PROVIDER (anthropic | openai, compatibles como DeepSeek) · PLATFORM_LLM_API_KEY
|
|
9
|
-
* PLATFORM_LLM_BASE_URL (openai compatibles) · PLATFORM_LLM_MODEL
|
|
10
|
-
* (PLATFORM_ANTHROPIC_API_KEY sigue valiendo: equivale a provider anthropic + esa clave)
|
|
11
|
-
* PLATFORM_FREE_MESSAGES respuestas de IA gratis por cuenta y mes (defecto 100)
|
|
12
|
-
* PLATFORM_APUCHAT_VOICE_TOKEN · PLATFORM_FREE_TTS (audios gratis por cuenta y mes, defecto 100)
|
|
13
|
-
* Así un ots nunca ve las claves del proceso ni las de otro ots.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import { createLLM } from '../llm.mjs';
|
|
17
|
-
import { synthesize as synthesizeWith, ttsProvider, openaiTtsKey } from '../tts.mjs';
|
|
18
|
-
import { startAgentChannels } from '../channels/index.mjs';
|
|
19
|
-
import { apumailConfigFromEnv } from '../channels/apumail.mjs';
|
|
20
|
-
import { apuchatConfigFromEnv } from '../channels/apuchat.mjs';
|
|
21
|
-
import { i18nError } from '../i18n.mjs';
|
|
22
|
-
import { OTS_KEYS, accountUsage, addUsage, allLiveOts, getOts, logTurn } from './store.mjs';
|
|
23
|
-
import { orquestaTools } from './orquesta.mjs';
|
|
24
|
-
|
|
25
|
-
const penv = process.env;
|
|
26
|
-
const FIXED = ['APUCHAT_HUB', 'APUMAIL_API', 'APUCHAT_VOICE_URL'];
|
|
27
|
-
// Where tenants' tokens are sent: read once at boot, so nothing that writes process.env later can redirect them.
|
|
28
|
-
const BOOT_FIXED = Object.freeze(Object.fromEntries(FIXED.filter((k) => penv[k]).map((k) => [k, penv[k]])));
|
|
29
|
-
// Platform-paid calls in flight per account (counted with usage, so parallel requests can't overrun the quota).
|
|
30
|
-
const inflight = new Map(); // `${accountId}:${kind}` → n
|
|
31
|
-
const MAX_INFLIGHT = () => Number(penv.PLATFORM_MAX_INFLIGHT || 4);
|
|
32
|
-
const LLM_KEYS = ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY'];
|
|
33
|
-
const TTS_KEYS = ['APUCHAT_VOICE_TOKEN', 'ELEVENLABS_API_KEY', 'XAI_API_KEY', 'FISH_API_KEY', 'OPENAI_API_KEY'];
|
|
34
|
-
|
|
35
|
-
/** IA de la plataforma, o null si no hay. Nunca se mezcla con ajustes del ots (ni base URL ni modelo). */
|
|
36
|
-
export function platformLlmEnv() {
|
|
37
|
-
const key = penv.PLATFORM_LLM_API_KEY || penv.PLATFORM_ANTHROPIC_API_KEY;
|
|
38
|
-
if (!key) return null;
|
|
39
|
-
const provider = (penv.PLATFORM_LLM_PROVIDER || (penv.PLATFORM_LLM_API_KEY ? 'openai' : 'anthropic')).toLowerCase();
|
|
40
|
-
const base = { LLM_EFFORT: 'low', LLM_MAX_TOKENS: '4000' };
|
|
41
|
-
if (provider === 'openai') return { ...base, LLM_PROVIDER: 'openai', OPENAI_API_KEY: key, LLM_BASE_URL: penv.PLATFORM_LLM_BASE_URL || '', LLM_MODEL: penv.PLATFORM_LLM_MODEL || 'gpt-4.1-mini' };
|
|
42
|
-
return { ...base, LLM_PROVIDER: 'anthropic', ANTHROPIC_API_KEY: key, LLM_MODEL: penv.PLATFORM_LLM_MODEL || 'claude-sonnet-5-5' };
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export const freeMessages = () => Number(penv.PLATFORM_FREE_MESSAGES ?? 100);
|
|
46
|
-
export const freeTts = () => Number(penv.PLATFORM_FREE_TTS ?? 100);
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Entorno del ots.
|
|
50
|
-
* @returns {{ env: object, llmEnv: object, platformLlm: boolean, platformTts: boolean }}
|
|
51
|
-
*/
|
|
52
|
-
export function otsEnv(ots) {
|
|
53
|
-
const env = {};
|
|
54
|
-
Object.assign(env, BOOT_FIXED);
|
|
55
|
-
for (const [k, meta] of Object.entries(OTS_KEYS)) {
|
|
56
|
-
const v = meta.secret ? ots.secrets[k] : ots.settings[k];
|
|
57
|
-
if (v == null || v === '') continue;
|
|
58
|
-
env[k] = meta.max ? String(Math.min(meta.max, Math.max(0, Number(v) || 0))) : String(v);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// IA: la suya o la de la plataforma (modelo fijo para controlar el coste).
|
|
62
|
-
let platformLlm = false;
|
|
63
|
-
const provider = (env.LLM_PROVIDER || '').toLowerCase();
|
|
64
|
-
const ownLlm = provider === 'openai' ? !!env.OPENAI_API_KEY : provider === 'anthropic' ? !!env.ANTHROPIC_API_KEY : LLM_KEYS.some((k) => env[k]);
|
|
65
|
-
if (provider === 'mock') {
|
|
66
|
-
// Modo de pruebas: sin IA real.
|
|
67
|
-
} else if (!ownLlm && platformLlmEnv()) {
|
|
68
|
-
platformLlm = true;
|
|
69
|
-
} else if (!ownLlm) {
|
|
70
|
-
env.LLM_PROVIDER = 'mock';
|
|
71
|
-
}
|
|
72
|
-
// The platform key lives only in llmEnv (never in env, which voice and channels see), and none of the
|
|
73
|
-
// ot's own settings (provider, model, base URL) reach it.
|
|
74
|
-
const llmEnv = platformLlm ? platformLlmEnv() : env;
|
|
75
|
-
|
|
76
|
-
// Voz: la suya o la de apuchat de la plataforma.
|
|
77
|
-
let platformTts = false;
|
|
78
|
-
if (!TTS_KEYS.some((k) => (k === 'OPENAI_API_KEY' ? openaiTtsKey(env) : env[k])) && penv.PLATFORM_APUCHAT_VOICE_TOKEN && (!env.TTS_PROVIDER || env.TTS_PROVIDER === 'apuchat')) {
|
|
79
|
-
platformTts = true;
|
|
80
|
-
// On the platform's token the engine and model are the platform's, not the ot's.
|
|
81
|
-
delete env.APUCHAT_VOICE_PROVIDER;
|
|
82
|
-
delete env.APUCHAT_VOICE_MODEL;
|
|
83
|
-
Object.assign(env, { TTS_PROVIDER: 'apuchat', APUCHAT_VOICE_TOKEN: penv.PLATFORM_APUCHAT_VOICE_TOKEN });
|
|
84
|
-
}
|
|
85
|
-
return { env, llmEnv, platformLlm, platformTts };
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// ───────────────────────────── LLM con cupo ─────────────────────────────
|
|
89
|
-
|
|
90
|
-
const llms = new Map(); // ots.id → { stamp, llm }
|
|
91
|
-
|
|
92
|
-
/** LLM del ots (se rehace cuando cambia el ots). */
|
|
93
|
-
function rawLlm(ots) {
|
|
94
|
-
const stamp = ots.updatedAt;
|
|
95
|
-
const hit = llms.get(ots.id);
|
|
96
|
-
if (hit?.stamp === stamp) return hit;
|
|
97
|
-
const { llmEnv, platformLlm } = otsEnv(ots);
|
|
98
|
-
const entry = { stamp, llm: createLLM(llmEnv), platformLlm };
|
|
99
|
-
if (llms.size > 2000) llms.clear();
|
|
100
|
-
llms.set(ots.id, entry);
|
|
101
|
-
return entry;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/** ¿Le queda cupo gratis a la cuenta? */
|
|
105
|
-
export function llmAllowed(ots) {
|
|
106
|
-
const { platformLlm } = rawLlm(ots);
|
|
107
|
-
return !platformLlm || accountUsage(ots.accountId, 'llm_platform') < freeMessages();
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Takes one unit of the account's free quota before a platform-paid call (synchronous, so it is atomic in Node).
|
|
112
|
-
* Returns release(spent): on success the unit becomes usage; on failure it is given back.
|
|
113
|
-
*/
|
|
114
|
-
function reserve(ots, kind, limit, errorKey) {
|
|
115
|
-
const k = `${ots.accountId}:${kind}`;
|
|
116
|
-
const n = inflight.get(k) || 0;
|
|
117
|
-
if (accountUsage(ots.accountId, kind) + n >= limit) throw i18nError(402, errorKey);
|
|
118
|
-
if (n >= MAX_INFLIGHT()) throw i18nError(429, 'server.http.rateLimited');
|
|
119
|
-
inflight.set(k, n + 1);
|
|
120
|
-
return (spent) => {
|
|
121
|
-
const left = (inflight.get(k) || 1) - 1;
|
|
122
|
-
if (left > 0) inflight.set(k, left);
|
|
123
|
-
else inflight.delete(k);
|
|
124
|
-
if (spent) addUsage(ots, kind);
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* Un paso de LLM para este ots, contando el uso.
|
|
130
|
-
* Sin cupo lanza 402 con clave `platform.quota.llm` (la ruta lo convierte en una respuesta amable).
|
|
131
|
-
*/
|
|
132
|
-
export async function otsStep(ots, args) {
|
|
133
|
-
const { llm, platformLlm } = rawLlm(ots);
|
|
134
|
-
const release = platformLlm ? reserve(ots, 'llm_platform', freeMessages(), 'platform.quota.llm') : null;
|
|
135
|
-
let out;
|
|
136
|
-
try {
|
|
137
|
-
out = await llm.step(args);
|
|
138
|
-
} catch (e) {
|
|
139
|
-
release?.(false);
|
|
140
|
-
// The platform's provider errors stay in our logs (they can echo parts of the platform key).
|
|
141
|
-
if (platformLlm) {
|
|
142
|
-
console.error('[7ots] platform llm', e?.status || '', e?.message || e);
|
|
143
|
-
throw i18nError(502, 'server.http.internal');
|
|
144
|
-
}
|
|
145
|
-
throw e;
|
|
146
|
-
}
|
|
147
|
-
release?.(true);
|
|
148
|
-
addUsage(ots, 'llm');
|
|
149
|
-
return out;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
export function otsLlmInfo(ots) {
|
|
153
|
-
const { llm, platformLlm } = rawLlm(ots);
|
|
154
|
-
return { name: llm.name, model: llm.model, platform: platformLlm };
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
// ───────────────────────────── voz ─────────────────────────────
|
|
158
|
-
|
|
159
|
-
export async function otsSynthesize(ots, { text, voice = ots.identity.voice }) {
|
|
160
|
-
const { env, platformTts } = otsEnv(ots);
|
|
161
|
-
const release = platformTts ? reserve(ots, 'tts_platform', freeTts(), 'platform.quota.tts') : null;
|
|
162
|
-
let out;
|
|
163
|
-
try {
|
|
164
|
-
out = await synthesizeWith({ text, voice: platformTts && voice && typeof voice === 'object' ? { ...voice, model: undefined } : voice, env });
|
|
165
|
-
} catch (e) {
|
|
166
|
-
release?.(false);
|
|
167
|
-
throw e;
|
|
168
|
-
}
|
|
169
|
-
release?.(true);
|
|
170
|
-
addUsage(ots, 'tts');
|
|
171
|
-
return out;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
export function otsTtsProvider(ots) {
|
|
175
|
-
return ttsProvider(otsEnv(ots).env);
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// ───────────────────────────── canales ─────────────────────────────
|
|
179
|
-
|
|
180
|
-
const channels = new Map(); // ots.id → { stamp, ch }
|
|
181
|
-
const NO_CHANNELS = {
|
|
182
|
-
handle: async () => false,
|
|
183
|
-
live: () => ({ email: false, apuchat: null, meet: false }),
|
|
184
|
-
openCall: () => {
|
|
185
|
-
throw i18nError(501, 'server.channels.noApuchat');
|
|
186
|
-
},
|
|
187
|
-
status: () => ({ apumail: false, apuchat: false }),
|
|
188
|
-
stop: async () => {},
|
|
189
|
-
};
|
|
190
|
-
|
|
191
|
-
/** Clave que identifica la configuración de canales (si no cambia, no se reinician). */
|
|
192
|
-
function channelStamp(ots) {
|
|
193
|
-
const { env } = otsEnv(ots);
|
|
194
|
-
return JSON.stringify([ots.status, ...Object.keys(OTS_KEYS).filter((k) => OTS_KEYS[k].channels).map((k) => env[k] || '')]);
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/** Canales del ots (apumail/apuchat), arrancándolos o reiniciándolos si hace falta. */
|
|
198
|
-
export function otsChannels(ots) {
|
|
199
|
-
if (!ots || ots.status !== 'on') return NO_CHANNELS;
|
|
200
|
-
const stamp = channelStamp(ots);
|
|
201
|
-
const hit = channels.get(ots.id);
|
|
202
|
-
if (hit?.stamp === stamp) return hit.ch;
|
|
203
|
-
hit?.ch.stop().catch(() => {});
|
|
204
|
-
const { env } = otsEnv(ots);
|
|
205
|
-
const id = ots.id;
|
|
206
|
-
// Siempre la versión vigente del ots: identidad e instrucciones cambian sin reiniciar.
|
|
207
|
-
const current = () => getOts(id) || ots;
|
|
208
|
-
const ch = startAgentChannels({
|
|
209
|
-
llm: { get name() { return otsLlmInfo(current()).name; }, get model() { return otsLlmInfo(current()).model; }, step: (a) => otsStep(current(), a) },
|
|
210
|
-
identity: () => current().identity,
|
|
211
|
-
instructions: () => current().settings.SERVER_INSTRUCTIONS || '',
|
|
212
|
-
config: { apumail: { ...apumailConfigFromEnv(env), webhookSecret: '' }, apuchat: apuchatConfigFromEnv(env) },
|
|
213
|
-
log: (...a) => console.log(`[7ots:${id}]`, ...a),
|
|
214
|
-
// Orquesta tasks: only for senders on the ot's own list (see orquesta.mjs), read on every message.
|
|
215
|
-
tools: (ctx) => orquestaTools(current(), ctx),
|
|
216
|
-
// mails and DMs go to its conversations (dashboard, and the desktop ot through /api/device/…/inbox)
|
|
217
|
-
onTurn: ({ key, channel, user, reply }) => logTurn(current(), { key, channel: channel === 'dm' ? 'apuchat' : 'apumail', visitor: key.replace(/^\w+:/, ''), user, reply }),
|
|
218
|
-
});
|
|
219
|
-
channels.set(id, { stamp, ch });
|
|
220
|
-
return ch;
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/** Para los canales de un ots (al pausarlo o borrarlo). */
|
|
224
|
-
export async function stopOtsChannels(id) {
|
|
225
|
-
const hit = channels.get(id);
|
|
226
|
-
channels.delete(id);
|
|
227
|
-
llms.delete(id);
|
|
228
|
-
await hit?.ch.stop().catch(() => {});
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/** Arranca los canales de todos los ots encendidos que los tengan configurados. */
|
|
232
|
-
export function startAllChannels() {
|
|
233
|
-
for (const ots of allLiveOts()) {
|
|
234
|
-
const s = ots.settings;
|
|
235
|
-
const sec = ots.secrets;
|
|
236
|
-
if ((s.APUMAIL_AGENT_INBOX && sec.APUMAIL_AGENT_TOKEN) || sec.APUCHAT_AGENT_IDENTITY_KEY) otsChannels(ots);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
export async function stopAllChannels() {
|
|
241
|
-
await Promise.all([...channels.keys()].map(stopOtsChannels));
|
|
242
|
-
}
|
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sites, APIs and MCP servers an account enrolls so ots know how to use them.
|
|
3
|
-
*
|
|
4
|
-
* The directory is Prowl.world: 7ots registers the entry there (source '7ots') as one Prowl
|
|
5
|
-
* vendor, starts the domain claim and hands the owner Prowl's three proofs (DNS TXT,
|
|
6
|
-
* /.well-known/prowl-verify.txt or a <meta>). Once verified, Prowl serves the owner's usage
|
|
7
|
-
* guide at GET /v1/context/{domain}, which is what desktop ots read.
|
|
8
|
-
*
|
|
9
|
-
* From the dashboard (session cookie, X-7ots-Admin: 1, same origin; see routes.mjs):
|
|
10
|
-
* GET /api/platform/sites → { sites, enabled }
|
|
11
|
-
* POST /api/platform/sites { kind, url, name, guide } → { site }
|
|
12
|
-
* POST /api/platform/sites/:id/verify → { site } (422 while the proof isn't there)
|
|
13
|
-
* DELETE /api/platform/sites/:id
|
|
14
|
-
*
|
|
15
|
-
* Env: PROWL_API (default https://prowl.world), PROWL_EMAIL + PROWL_PASSWORD (the 7ots vendor).
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
import { getDb } from './db.mjs';
|
|
19
|
-
import { newId } from './crypto.mjs';
|
|
20
|
-
|
|
21
|
-
const KINDS = ['site', 'api', 'mcp'];
|
|
22
|
-
const base = () => (process.env.PROWL_API || 'https://prowl.world').replace(/\/+$/, '');
|
|
23
|
-
export const sitesEnabled = () => !!(process.env.PROWL_EMAIL && process.env.PROWL_PASSWORD);
|
|
24
|
-
|
|
25
|
-
let access = null;
|
|
26
|
-
async function prowl(path, { method = 'GET', body, retry = true } = {}) {
|
|
27
|
-
if (!access) {
|
|
28
|
-
const r = await fetch(`${base()}/v1/auth/login`, {
|
|
29
|
-
method: 'POST',
|
|
30
|
-
headers: { 'content-type': 'application/json' },
|
|
31
|
-
body: JSON.stringify({ email: process.env.PROWL_EMAIL, password: process.env.PROWL_PASSWORD }),
|
|
32
|
-
signal: AbortSignal.timeout(15_000),
|
|
33
|
-
});
|
|
34
|
-
if (!r.ok) throw Object.assign(new Error(`prowl login ${r.status}`), { status: 502 });
|
|
35
|
-
access = (await r.json()).access_token;
|
|
36
|
-
}
|
|
37
|
-
const r = await fetch(`${base()}${path}`, {
|
|
38
|
-
method,
|
|
39
|
-
headers: { authorization: `Bearer ${access}`, ...(body ? { 'content-type': 'application/json' } : {}) },
|
|
40
|
-
body: body ? JSON.stringify(body) : undefined,
|
|
41
|
-
signal: AbortSignal.timeout(30_000),
|
|
42
|
-
});
|
|
43
|
-
if (r.status === 401 && retry) {
|
|
44
|
-
access = null;
|
|
45
|
-
return prowl(path, { method, body, retry: false });
|
|
46
|
-
}
|
|
47
|
-
const data = await r.json().catch(() => ({}));
|
|
48
|
-
return { status: r.status, data };
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const row = (r) =>
|
|
52
|
-
r && {
|
|
53
|
-
id: r.id,
|
|
54
|
-
kind: r.kind,
|
|
55
|
-
url: r.url,
|
|
56
|
-
domain: r.domain,
|
|
57
|
-
name: r.name,
|
|
58
|
-
guide: r.guide,
|
|
59
|
-
status: r.status,
|
|
60
|
-
proof: JSON.parse(r.proof || 'null'),
|
|
61
|
-
createdAt: r.created_at,
|
|
62
|
-
verifiedAt: r.verified_at,
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
export function listSites(accountId) {
|
|
66
|
-
return getDb().prepare('SELECT * FROM sites WHERE account_id = ? ORDER BY created_at DESC').all(accountId).map(row);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function cleanUrl(raw) {
|
|
70
|
-
let u;
|
|
71
|
-
try {
|
|
72
|
-
u = new URL(/^https?:\/\//i.test(raw) ? raw : `https://${raw}`);
|
|
73
|
-
} catch {
|
|
74
|
-
return null;
|
|
75
|
-
}
|
|
76
|
-
if (!/^https?:$/.test(u.protocol) || !u.hostname.includes('.')) return null;
|
|
77
|
-
return u;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export function createSites({ send, readJson }) {
|
|
81
|
-
const fail = (res, e) => send(res, e.status || 502, { error: e.message || 'Prowl error' });
|
|
82
|
-
|
|
83
|
-
return async function sites(req, res, account, path) {
|
|
84
|
-
if (!path.startsWith('/sites')) return false;
|
|
85
|
-
const d = getDb();
|
|
86
|
-
if (path === '/sites' && req.method === 'GET') return send(res, 200, { sites: listSites(account.id), enabled: sitesEnabled() }), true;
|
|
87
|
-
if (!sitesEnabled()) return send(res, 503, { error: 'Site enrollment is not configured on this server (PROWL_EMAIL/PROWL_PASSWORD).' }), true;
|
|
88
|
-
|
|
89
|
-
if (path === '/sites' && req.method === 'POST') {
|
|
90
|
-
const { kind, url, name, guide } = await readJson(req, 32 * 1024);
|
|
91
|
-
const u = cleanUrl(String(url || '').trim());
|
|
92
|
-
if (!u) return send(res, 400, { error: 'Invalid URL' }), true;
|
|
93
|
-
const k = KINDS.includes(kind) ? kind : 'site';
|
|
94
|
-
const domain = u.hostname.replace(/^www\./, '').toLowerCase();
|
|
95
|
-
if (d.prepare('SELECT 1 FROM sites WHERE account_id = ? AND domain = ?').get(account.id, domain)) return send(res, 409, { error: `${domain} is already registered` }), true;
|
|
96
|
-
const title = String(name || '').trim().slice(0, 120) || domain;
|
|
97
|
-
const text = String(guide || '').trim().slice(0, 8000);
|
|
98
|
-
try {
|
|
99
|
-
const reg = await prowl('/v1/register', {
|
|
100
|
-
method: 'POST',
|
|
101
|
-
body: {
|
|
102
|
-
name: title,
|
|
103
|
-
website_url: `https://${domain}`,
|
|
104
|
-
category: [k === 'mcp' ? 'mcp' : k === 'api' ? 'api' : 'website'],
|
|
105
|
-
kind: k,
|
|
106
|
-
usage_guide: text || undefined,
|
|
107
|
-
source: '7ots',
|
|
108
|
-
...(k === 'mcp' ? { mcp_manifest_url: u.href } : k === 'api' && u.pathname !== '/' ? { api_docs_url: u.href } : {}),
|
|
109
|
-
},
|
|
110
|
-
});
|
|
111
|
-
const serviceId = reg.status === 201 ? reg.data.id : reg.status === 409 ? reg.data.detail?.service_id : null;
|
|
112
|
-
if (!serviceId) throw Object.assign(new Error(reg.data.detail?.message || reg.data.detail || `Prowl register ${reg.status}`), { status: 502 });
|
|
113
|
-
const claim = await prowl('/v1/claim', { method: 'POST', body: { service_id: serviceId } });
|
|
114
|
-
if (claim.status !== 200) throw Object.assign(new Error(claim.data.detail || `Prowl claim ${claim.status}`), { status: claim.status === 409 ? 409 : 502 });
|
|
115
|
-
const c = claim.data;
|
|
116
|
-
const proof = { dnsRecord: c.dns_record, dnsValue: c.dns_value, wellKnownUrl: c.well_known_url, wellKnownContent: c.well_known_content, metaTag: c.meta_tag };
|
|
117
|
-
const id = newId('site');
|
|
118
|
-
d.prepare('INSERT INTO sites (id, account_id, kind, url, domain, name, guide, service_id, status, proof, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?)')
|
|
119
|
-
.run(id, account.id, k, u.href, domain, title, text, serviceId, 'pending', JSON.stringify(proof), Date.now());
|
|
120
|
-
return send(res, 201, { site: row(d.prepare('SELECT * FROM sites WHERE id = ?').get(id)) }), true;
|
|
121
|
-
} catch (e) {
|
|
122
|
-
return fail(res, e), true;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
const m = path.match(/^\/sites\/(site_[A-Za-z0-9_-]{6,60})(\/verify)?$/);
|
|
127
|
-
const s = m && d.prepare('SELECT * FROM sites WHERE id = ? AND account_id = ?').get(m[1], account.id);
|
|
128
|
-
if (!s) return send(res, 404, { error: 'Not found' }), true;
|
|
129
|
-
if (m[2] && req.method === 'POST') {
|
|
130
|
-
try {
|
|
131
|
-
const v = await prowl('/v1/claim/verify', { method: 'POST', body: { service_id: s.service_id } });
|
|
132
|
-
if (v.status === 422) return send(res, 422, { error: 'proof_missing', site: row(s) }), true;
|
|
133
|
-
if (v.status !== 200) throw Object.assign(new Error(v.data.detail || `Prowl verify ${v.status}`), { status: 502 });
|
|
134
|
-
d.prepare("UPDATE sites SET status = 'verified', verified_at = ? WHERE id = ?").run(Date.now(), s.id);
|
|
135
|
-
return send(res, 200, { site: row(d.prepare('SELECT * FROM sites WHERE id = ?').get(s.id)) }), true;
|
|
136
|
-
} catch (e) {
|
|
137
|
-
return fail(res, e), true;
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
if (!m[2] && req.method === 'DELETE') {
|
|
141
|
-
d.prepare('DELETE FROM sites WHERE id = ?').run(s.id);
|
|
142
|
-
return send(res, 200, { ok: true }), true;
|
|
143
|
-
}
|
|
144
|
-
return send(res, 405, { error: 'Method not allowed' }), true;
|
|
145
|
-
};
|
|
146
|
-
}
|