@7ots/cli 0.1.19 → 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/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 +59 -1
- package/cli/lib/account.mjs +23 -3
- package/cli/lib/assistant.mjs +88 -13
- package/cli/lib/brain.mjs +76 -8
- 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 +61 -6
- package/cli/lib/pet-server.mjs +316 -41
- package/cli/lib/prompts.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/vm.mjs +1 -1
- package/cli/lib/wake-local.py +109 -0
- package/cli/lib/wake.mjs +102 -0
- package/cli/pet/electron/main.cjs +137 -13
- package/cli/pet/pet.html +125 -26
- package/cli/pet/senses.html +342 -0
- package/cli/pet/settings.html +787 -86
- 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 +2 -0
- package/server/errors.mjs +90 -0
- package/server/notify.mjs +78 -0
- package/server/server.mjs +68 -12
- 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 +1 -1
- 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 +162 -0
- 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 +2 -1
- 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 +255 -1
- 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 -337
- package/server/platform/byte.mjs +0 -291
- package/server/platform/connect.mjs +0 -391
- package/server/platform/crypto.mjs +0 -80
- package/server/platform/db.mjs +0 -293
- package/server/platform/device.mjs +0 -247
- 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 -611
- package/server/platform/profile.mjs +0 -182
- package/server/platform/routes.mjs +0 -589
- package/server/platform/runtime.mjs +0 -286
- package/server/platform/sites.mjs +0 -146
- package/server/platform/stage3d.mjs +0 -82
- package/server/platform/store.mjs +0 -469
- package/server/platform/vm.mjs +0 -1057
- package/server/platform/wallet.mjs +0 -255
|
@@ -1,169 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* An ot's own integrations on 7ots.com (dashboard → Assistant → Integrations): MCP servers and APIs it
|
|
3
|
-
* can use when its owner asks it something in the dashboard ("Ask your ot").
|
|
4
|
-
*
|
|
5
|
-
* settings.INTEGRATIONS JSON [{ id, kind: 'mcp'|'api'|'note', name, instructions, url?, on }] (managed, ≤ 10)
|
|
6
|
-
* secrets.INTEG_<id> its token (Bearer), sealed like the other keys and never returned
|
|
7
|
-
*
|
|
8
|
-
* The server reaches these URLs itself, so only public https hosts: every address the name resolves to
|
|
9
|
-
* must be public (no loopback, private, link-local or metadata ranges) and redirects are not followed.
|
|
10
|
-
* Commands are desktop-only (the pet runs them on the user's own computer).
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import { lookup } from 'node:dns/promises';
|
|
14
|
-
import { isIP } from 'node:net';
|
|
15
|
-
import { randomBytes } from 'node:crypto';
|
|
16
|
-
import { mcpCall, mcpTools } from '../../cli/lib/mcp.mjs';
|
|
17
|
-
|
|
18
|
-
export const MAX_INTEGRATIONS = 10;
|
|
19
|
-
const KINDS = ['mcp', 'api', 'note'];
|
|
20
|
-
const MAX_OUT = 6000;
|
|
21
|
-
const str = (v, max) => String(v ?? '').replace(/\r/g, '').trim().slice(0, max);
|
|
22
|
-
|
|
23
|
-
const badUrl = (code) => Object.assign(new Error(code), { code });
|
|
24
|
-
|
|
25
|
-
/** The saved list (never with tokens). */
|
|
26
|
-
export function otIntegrations(ots) {
|
|
27
|
-
try {
|
|
28
|
-
const list = JSON.parse(ots?.settings?.INTEGRATIONS || '[]');
|
|
29
|
-
return Array.isArray(list) ? list : [];
|
|
30
|
-
} catch {
|
|
31
|
-
return [];
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** What the dashboard sees: the list plus whether each one has a token. */
|
|
36
|
-
export function integrationsView(ots) {
|
|
37
|
-
return otIntegrations(ots).map((c) => ({ ...c, hasToken: Boolean(ots.secrets?.[`INTEG_${c.id}`]) }));
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Validates the dashboard's list → { list, secrets } to save. `token` on an item replaces its token,
|
|
42
|
-
* `token: ''` removes it, no `token` keeps the one saved.
|
|
43
|
-
*/
|
|
44
|
-
export function normalizeOtIntegrations(items, ots) {
|
|
45
|
-
if (!Array.isArray(items)) throw badUrl('integList');
|
|
46
|
-
if (items.length > MAX_INTEGRATIONS) throw badUrl('integMax');
|
|
47
|
-
const secrets = { ...(ots.secrets || {}) };
|
|
48
|
-
const list = items.map((c) => {
|
|
49
|
-
const kind = KINDS.includes(c?.kind) ? c.kind : 'note';
|
|
50
|
-
const name = str(c?.name, 60);
|
|
51
|
-
if (!name) throw badUrl('integName');
|
|
52
|
-
const url = kind === 'note' ? '' : str(c.url, 300);
|
|
53
|
-
if (kind !== 'note' && !/^https:\/\/[^\s"'<>]+$/i.test(url)) throw badUrl('integUrl');
|
|
54
|
-
const id = /^[a-z0-9]{6,16}$/.test(c.id || '') ? c.id : randomBytes(5).toString('hex');
|
|
55
|
-
if (typeof c.token === 'string') {
|
|
56
|
-
const tok = c.token.trim().slice(0, 2000);
|
|
57
|
-
if (tok) secrets[`INTEG_${id}`] = tok;
|
|
58
|
-
else delete secrets[`INTEG_${id}`];
|
|
59
|
-
}
|
|
60
|
-
return { id, kind, name, instructions: str(c.instructions, 1500), ...(url ? { url } : {}), on: c.on !== false };
|
|
61
|
-
});
|
|
62
|
-
// tokens of removed integrations go too
|
|
63
|
-
const ids = new Set(list.map((c) => c.id));
|
|
64
|
-
for (const k of Object.keys(secrets)) if (k.startsWith('INTEG_') && !ids.has(k.slice(6))) delete secrets[k];
|
|
65
|
-
return { list, secrets };
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// ── only public hosts ──
|
|
69
|
-
|
|
70
|
-
function privateIp(ip) {
|
|
71
|
-
if (isIP(ip) === 6) {
|
|
72
|
-
const v = ip.toLowerCase();
|
|
73
|
-
if (v.startsWith('::ffff:')) return privateIp(v.slice(7));
|
|
74
|
-
return v === '::' || v === '::1' || /^f[cd]/.test(v) || /^fe[89ab]/.test(v) || v.startsWith('64:ff9b:') || v.startsWith('2001:db8');
|
|
75
|
-
}
|
|
76
|
-
const [a, b] = ip.split('.').map(Number);
|
|
77
|
-
return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 198 && (b === 18 || b === 19)) || a >= 224;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export async function assertPublicUrl(raw) {
|
|
81
|
-
let u;
|
|
82
|
-
try {
|
|
83
|
-
u = new URL(raw);
|
|
84
|
-
} catch {
|
|
85
|
-
throw badUrl('integUrl');
|
|
86
|
-
}
|
|
87
|
-
if (u.protocol !== 'https:' || u.username || u.password) throw badUrl('integUrl');
|
|
88
|
-
const host = u.hostname.replace(/^\[|\]$/g, '');
|
|
89
|
-
if (/^(localhost|.*\.local|.*\.internal|metadata\.google\.internal)$/i.test(host)) throw badUrl('integPrivate');
|
|
90
|
-
const addrs = isIP(host) ? [{ address: host }] : await lookup(host, { all: true }).catch(() => []);
|
|
91
|
-
if (!addrs.length) throw badUrl('integDns');
|
|
92
|
-
if (addrs.some((a) => privateIp(a.address))) throw badUrl('integPrivate');
|
|
93
|
-
return u;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// ── running them ──
|
|
97
|
-
|
|
98
|
-
const tokenOf = (ots, c) => ots.secrets?.[`INTEG_${c.id}`] || '';
|
|
99
|
-
const redact = (s) => String(s ?? '').replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, '$1 ***');
|
|
100
|
-
|
|
101
|
-
/** Dashboard → "Connect and list tools" / "Try it" for one saved integration. */
|
|
102
|
-
export async function testIntegration(ots, c) {
|
|
103
|
-
if (c.kind === 'note') return { ok: true, text: '' };
|
|
104
|
-
await assertPublicUrl(c.url);
|
|
105
|
-
if (c.kind === 'mcp') return { ok: true, tools: (await mcpTools(c, tokenOf(ots, c), { fresh: true })).map((x) => ({ name: x.name, description: x.description })) };
|
|
106
|
-
return { ok: true, text: (await apiGet(ots, c, '')).slice(0, 1500) };
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
async function apiGet(ots, c, path) {
|
|
110
|
-
const target = path && /^[/?][^\s"'<>]*$/.test(path) && !path.startsWith('//') ? c.url.replace(/\/+$/, '') + path : c.url;
|
|
111
|
-
await assertPublicUrl(target);
|
|
112
|
-
const tok = tokenOf(ots, c);
|
|
113
|
-
const res = await fetch(target, { redirect: 'manual', headers: { Accept: 'application/json, text/plain;q=0.9, */*;q=0.5', ...(tok ? { Authorization: `Bearer ${tok}` } : {}) }, signal: AbortSignal.timeout(15000) });
|
|
114
|
-
return redact(`HTTP ${res.status}\n${(await res.text()).slice(0, 20000)}`).slice(0, MAX_OUT);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
const TOOLS = [
|
|
118
|
-
{
|
|
119
|
-
name: 'integration_tools',
|
|
120
|
-
description: 'Lists the tools of one of your MCP integrations (see the list in your instructions).',
|
|
121
|
-
parameters: { type: 'object', properties: { id: { type: 'string', description: 'Integration id' } }, required: ['id'] },
|
|
122
|
-
},
|
|
123
|
-
{
|
|
124
|
-
name: 'integration_call',
|
|
125
|
-
description: 'Calls a tool of one of your MCP integrations. Use the exact tool name from integration_tools.',
|
|
126
|
-
parameters: { type: 'object', properties: { id: { type: 'string' }, tool: { type: 'string' }, args: { type: 'object', description: 'The tool arguments' } }, required: ['id', 'tool'] },
|
|
127
|
-
},
|
|
128
|
-
{
|
|
129
|
-
name: 'integration_get',
|
|
130
|
-
description: 'Reads (HTTP GET) one of your API integrations, optionally with a sub-path or query appended to its URL.',
|
|
131
|
-
parameters: { type: 'object', properties: { id: { type: 'string' }, path: { type: 'string', description: 'Optional, starting with / or ?' } }, required: ['id'] },
|
|
132
|
-
},
|
|
133
|
-
];
|
|
134
|
-
|
|
135
|
-
/**
|
|
136
|
-
* Tools and prompt text for the owner's chat, or null when the ot has no integration turned on.
|
|
137
|
-
* @returns {{ tools: object[], names: string[], run: Function, prompt: string } | null}
|
|
138
|
-
*/
|
|
139
|
-
export function integrationTools(ots) {
|
|
140
|
-
const on = otIntegrations(ots).filter((c) => c.on !== false);
|
|
141
|
-
if (!on.length) return null;
|
|
142
|
-
const usable = on.filter((c) => c.kind !== 'note');
|
|
143
|
-
const prompt = `Integrations your owner set up for you:\n${on.map((c) => `- ${c.name} (id ${c.id}, ${c.kind === 'mcp' ? 'MCP server' : c.kind === 'api' ? `API at ${c.url}` : 'instructions'})${c.instructions ? `: ${c.instructions}` : ''}`).join('\n')}\nOnly call a tool that changes something (creates, sends, deletes, updates) when your owner asked for exactly that.`;
|
|
144
|
-
const find = (id, kind) => {
|
|
145
|
-
const c = usable.find((x) => x.id === String(id || ''));
|
|
146
|
-
if (!c || (kind && c.kind !== kind)) throw new Error(`No ${kind === 'mcp' ? 'MCP' : kind === 'api' ? 'API' : ''} integration with id ${id}`);
|
|
147
|
-
return c;
|
|
148
|
-
};
|
|
149
|
-
const tools = TOOLS.filter((x) => (x.name === 'integration_get' ? usable.some((c) => c.kind === 'api') : usable.some((c) => c.kind === 'mcp')));
|
|
150
|
-
return {
|
|
151
|
-
prompt,
|
|
152
|
-
tools,
|
|
153
|
-
names: tools.map((x) => x.name),
|
|
154
|
-
run: async (name, args = {}) => {
|
|
155
|
-
if (name === 'integration_tools') {
|
|
156
|
-
const c = find(args.id, 'mcp');
|
|
157
|
-
await assertPublicUrl(c.url);
|
|
158
|
-
return { ok: true, tools: await mcpTools(c, tokenOf(ots, c)) };
|
|
159
|
-
}
|
|
160
|
-
if (name === 'integration_call') {
|
|
161
|
-
const c = find(args.id, 'mcp');
|
|
162
|
-
await assertPublicUrl(c.url);
|
|
163
|
-
return { ok: true, result: redact(await mcpCall(c, tokenOf(ots, c), String(args.tool || ''), args.args)).slice(0, MAX_OUT) };
|
|
164
|
-
}
|
|
165
|
-
if (name === 'integration_get') return { ok: true, result: await apiGet(ots, find(args.id, 'api'), String(args.path || '')) };
|
|
166
|
-
throw new Error(`Unknown tool: ${name}`);
|
|
167
|
-
},
|
|
168
|
-
};
|
|
169
|
-
}
|
package/server/platform/look.mjs
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Huella del aspecto de un ot: cada ot de 7ots.com es único, no puede haber dos con la misma cara.
|
|
3
|
-
*
|
|
4
|
-
* La huella sale del personaje ya normalizado (identity.look.character, el mismo que dibujan el 2D y
|
|
5
|
-
* el 3D), con las claves ordenadas para que el orden no cuente. El estilo artístico (filtro) no la
|
|
6
|
-
* cambia: el mismo ot en acuarela sigue siendo el mismo ot. Un ot con foto propia usa la URL.
|
|
7
|
-
*/
|
|
8
|
-
import { createHash } from 'node:crypto';
|
|
9
|
-
|
|
10
|
-
const stable = (v) =>
|
|
11
|
-
Array.isArray(v) ? `[${v.map(stable).join(',')}]` : v && typeof v === 'object' ? `{${Object.keys(v).sort().filter((k) => v[k] !== undefined).map((k) => `${JSON.stringify(k)}:${stable(v[k])}`).join(',')}}` : JSON.stringify(typeof v === 'string' ? v.toLowerCase() : v);
|
|
12
|
-
|
|
13
|
-
/** identity (normalizada por defineIdentity) → huella hex de 32, o null si no tiene aspecto propio. */
|
|
14
|
-
export function lookPrint(identity) {
|
|
15
|
-
const look = identity?.look || {};
|
|
16
|
-
if (look.kind === 'image' && look.image) return createHash('sha256').update(`image:${look.image}`).digest('hex').slice(0, 32);
|
|
17
|
-
const { style, ...character } = look.character || {};
|
|
18
|
-
if (!Object.keys(character).length) return null;
|
|
19
|
-
return createHash('sha256').update(`character:${stable(character)}`).digest('hex').slice(0, 32);
|
|
20
|
-
}
|
package/server/platform/mods.mjs
DELETED
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Community mods: looks that people share for any ot (src/character/mods.js), with installs,
|
|
3
|
-
* 1–5 star ratings (one per account, only after installing) and reports.
|
|
4
|
-
*
|
|
5
|
-
* New mods wait for an admin (PLATFORM_ADMINS: emails, comma separated) unless an admin uploads
|
|
6
|
-
* them. A mod reported by MOD_REPORTS_HIDE accounts (default 3) is hidden until reviewed.
|
|
7
|
-
*
|
|
8
|
-
* Public (any origin):
|
|
9
|
-
* GET /api/mods[?sort=top|new|popular&q=…] → { mods: [view] } approved only
|
|
10
|
-
* GET /api/mods/:id → { mod: view }
|
|
11
|
-
* Signed in, from the dashboard (/api/platform/mods/*, session) or the pet (/api/device/mods/*, bearer):
|
|
12
|
-
* GET /mods/mine → { mods: [view], admin, pending: [view] (admins) }
|
|
13
|
-
* POST /mods { mod } → publish or update one of yours (by its id)
|
|
14
|
-
* POST /mods/files?ext=glb|vrm raw body (≤ 20 MB) → { url: '/mods/<sha16>.<ext>' }
|
|
15
|
-
* POST /mods/:id/install → { mod: view } (counts once per account)
|
|
16
|
-
* POST /mods/:id/rate { stars: 1..5 }
|
|
17
|
-
* POST /mods/:id/report { reason }
|
|
18
|
-
* POST /mods/:id/review { status: approved|rejected|hidden } (admins)
|
|
19
|
-
* DELETE /mods/:id (its author or an admin)
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import { createHash } from 'node:crypto';
|
|
23
|
-
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
24
|
-
import { join } from 'node:path';
|
|
25
|
-
import { normalizeMod } from '../../src/character/mods.js';
|
|
26
|
-
import { dataDir, getDb } from './db.mjs';
|
|
27
|
-
|
|
28
|
-
const MAX_FILE = 20 * 1024 * 1024;
|
|
29
|
-
const MAX_MOD_JSON = 2 * 1024 * 1024;
|
|
30
|
-
const STATUSES = ['pending', 'approved', 'rejected', 'hidden'];
|
|
31
|
-
const MODEL = /^\/mods\/([a-f0-9]{16})\.(glb|vrm)$/;
|
|
32
|
-
|
|
33
|
-
let ready = false;
|
|
34
|
-
function db() {
|
|
35
|
-
const d = getDb();
|
|
36
|
-
if (!ready) {
|
|
37
|
-
d.exec(`
|
|
38
|
-
CREATE TABLE IF NOT EXISTS community_mods (
|
|
39
|
-
id TEXT PRIMARY KEY,
|
|
40
|
-
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
|
41
|
-
author TEXT NOT NULL DEFAULT '',
|
|
42
|
-
mod TEXT NOT NULL,
|
|
43
|
-
status TEXT NOT NULL DEFAULT 'pending',
|
|
44
|
-
installs INTEGER NOT NULL DEFAULT 0,
|
|
45
|
-
stars_sum INTEGER NOT NULL DEFAULT 0,
|
|
46
|
-
stars_n INTEGER NOT NULL DEFAULT 0,
|
|
47
|
-
reports INTEGER NOT NULL DEFAULT 0,
|
|
48
|
-
created_at INTEGER NOT NULL,
|
|
49
|
-
updated_at INTEGER NOT NULL
|
|
50
|
-
);
|
|
51
|
-
CREATE INDEX IF NOT EXISTS community_mods_status ON community_mods(status, created_at DESC);
|
|
52
|
-
CREATE TABLE IF NOT EXISTS mod_installs (mod_id TEXT NOT NULL REFERENCES community_mods(id) ON DELETE CASCADE, account_id TEXT NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (mod_id, account_id));
|
|
53
|
-
CREATE TABLE IF NOT EXISTS mod_ratings (mod_id TEXT NOT NULL REFERENCES community_mods(id) ON DELETE CASCADE, account_id TEXT NOT NULL, stars INTEGER NOT NULL, at INTEGER NOT NULL, PRIMARY KEY (mod_id, account_id));
|
|
54
|
-
CREATE TABLE IF NOT EXISTS mod_reports (mod_id TEXT NOT NULL REFERENCES community_mods(id) ON DELETE CASCADE, account_id TEXT NOT NULL, reason TEXT NOT NULL DEFAULT '', at INTEGER NOT NULL, PRIMARY KEY (mod_id, account_id));
|
|
55
|
-
`);
|
|
56
|
-
ready = true;
|
|
57
|
-
}
|
|
58
|
-
return d;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export const isModAdmin = (account) =>
|
|
62
|
-
!!account?.email && String(process.env.PLATFORM_ADMINS || '').toLowerCase().split(/[\s,]+/).filter(Boolean).includes(account.email.toLowerCase());
|
|
63
|
-
|
|
64
|
-
const authorOf = (a) => String(a.name || (a.email || '').split('@')[0] || 'anon').slice(0, 40);
|
|
65
|
-
|
|
66
|
-
function view(row, me) {
|
|
67
|
-
if (!row) return null;
|
|
68
|
-
const v = {
|
|
69
|
-
id: row.id,
|
|
70
|
-
mod: JSON.parse(row.mod),
|
|
71
|
-
author: row.author,
|
|
72
|
-
status: row.status,
|
|
73
|
-
installs: row.installs,
|
|
74
|
-
rating: row.stars_n ? Math.round((row.stars_sum / row.stars_n) * 10) / 10 : null,
|
|
75
|
-
ratings: row.stars_n,
|
|
76
|
-
createdAt: row.created_at,
|
|
77
|
-
updatedAt: row.updated_at,
|
|
78
|
-
};
|
|
79
|
-
if (me) {
|
|
80
|
-
const d = db();
|
|
81
|
-
v.mine = row.account_id === me.id;
|
|
82
|
-
v.installed = !!d.prepare('SELECT 1 FROM mod_installs WHERE mod_id = ? AND account_id = ?').get(row.id, me.id);
|
|
83
|
-
v.myStars = d.prepare('SELECT stars FROM mod_ratings WHERE mod_id = ? AND account_id = ?').get(row.id, me.id)?.stars || null;
|
|
84
|
-
v.reported = !!d.prepare('SELECT 1 FROM mod_reports WHERE mod_id = ? AND account_id = ?').get(row.id, me.id);
|
|
85
|
-
}
|
|
86
|
-
return v;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
const ORDER = {
|
|
90
|
-
// Bayesian average: a single 5★ does not beat many 4.5★
|
|
91
|
-
top: '(stars_sum + 3.0 * 2) / (stars_n + 2) DESC, installs DESC, created_at DESC',
|
|
92
|
-
new: 'created_at DESC',
|
|
93
|
-
popular: 'installs DESC, stars_n DESC, created_at DESC',
|
|
94
|
-
};
|
|
95
|
-
|
|
96
|
-
export function listMods({ sort = 'top', q = '', limit = 60 } = {}) {
|
|
97
|
-
const like = `%${String(q).toLowerCase().replace(/[%_]/g, '').slice(0, 40)}%`;
|
|
98
|
-
return db()
|
|
99
|
-
.prepare(`SELECT * FROM community_mods WHERE status = 'approved' AND (lower(id) LIKE ? OR lower(mod) LIKE ? OR lower(author) LIKE ?) ORDER BY ${ORDER[sort] || ORDER.top} LIMIT ?`)
|
|
100
|
-
.all(like, like, like, Math.min(100, Math.max(1, Number(limit) || 60)));
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** A model a mod points at must already be on 7ots.com (uploaded first through /mods/files). */
|
|
104
|
-
function modelsMissing(mod) {
|
|
105
|
-
const urls = [mod.model?.url].filter((u) => MODEL.test(u || ''));
|
|
106
|
-
return urls.filter((u) => !existsSync(join(dataDir(), 'mods', u.slice('/mods/'.length))));
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
export function createMods({ send, readJson }) {
|
|
110
|
-
/** Public half. @returns {Promise<boolean>} */
|
|
111
|
-
async function publicApi(req, res, path) {
|
|
112
|
-
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
113
|
-
if (req.method === 'OPTIONS') return send(res, 204), true;
|
|
114
|
-
if (req.method !== 'GET') return false;
|
|
115
|
-
if (path === '' || path === '/') {
|
|
116
|
-
const u = new URL(req.url, 'http://x');
|
|
117
|
-
return send(res, 200, { mods: listMods({ sort: u.searchParams.get('sort'), q: u.searchParams.get('q') || '', limit: u.searchParams.get('limit') }).map((r) => view(r)) }), true;
|
|
118
|
-
}
|
|
119
|
-
const m = /^\/([a-z0-9-]{1,32})$/.exec(path);
|
|
120
|
-
if (m) {
|
|
121
|
-
const row = db().prepare("SELECT * FROM community_mods WHERE id = ? AND status = 'approved'").get(m[1]);
|
|
122
|
-
return row ? send(res, 200, { mod: view(row) }) : send(res, 404, { error: 'not found' }), true;
|
|
123
|
-
}
|
|
124
|
-
return false;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
/** Signed-in half (account from the session or a device). path is after /mods. @returns {Promise<boolean>} */
|
|
128
|
-
async function accountApi(req, res, account, path) {
|
|
129
|
-
const d = db();
|
|
130
|
-
const admin = isModAdmin(account);
|
|
131
|
-
const now = Date.now();
|
|
132
|
-
if (path === '' && req.method === 'GET') {
|
|
133
|
-
const u = new URL(req.url, 'http://x');
|
|
134
|
-
return send(res, 200, { mods: listMods({ sort: u.searchParams.get('sort'), q: u.searchParams.get('q') || '' }).map((r) => view(r, account)) }), true;
|
|
135
|
-
}
|
|
136
|
-
if (path === '/mine' && req.method === 'GET') {
|
|
137
|
-
const mine = d.prepare('SELECT * FROM community_mods WHERE account_id = ? ORDER BY updated_at DESC').all(account.id).map((r) => view(r, account));
|
|
138
|
-
const pending = admin ? d.prepare("SELECT * FROM community_mods WHERE status IN ('pending', 'hidden') ORDER BY reports DESC, created_at").all().map((r) => ({ ...view(r, account), reports: r.reports })) : [];
|
|
139
|
-
return send(res, 200, { mods: mine, admin, pending }), true;
|
|
140
|
-
}
|
|
141
|
-
if (path === '/files' && req.method === 'POST') {
|
|
142
|
-
const ext = new URL(req.url, 'http://x').searchParams.get('ext');
|
|
143
|
-
if (!['glb', 'vrm'].includes(ext)) return send(res, 400, { error: 'ext' }), true;
|
|
144
|
-
const chunks = [];
|
|
145
|
-
let size = 0;
|
|
146
|
-
for await (const c of req) {
|
|
147
|
-
size += c.length;
|
|
148
|
-
if (size > MAX_FILE) return send(res, 413, { error: 'max 20 MB' }), true;
|
|
149
|
-
chunks.push(c);
|
|
150
|
-
}
|
|
151
|
-
const buf = Buffer.concat(chunks);
|
|
152
|
-
if (buf.length < 20 || buf.toString('latin1', 0, 4) !== 'glTF') return send(res, 400, { error: 'not a glTF binary (.glb/.vrm)' }), true;
|
|
153
|
-
const h = createHash('sha256').update(buf).digest('hex').slice(0, 16);
|
|
154
|
-
mkdirSync(join(dataDir(), 'mods'), { recursive: true });
|
|
155
|
-
writeFileSync(join(dataDir(), 'mods', `${h}.${ext}`), buf);
|
|
156
|
-
return send(res, 200, { url: `/mods/${h}.${ext}` }), true;
|
|
157
|
-
}
|
|
158
|
-
if (path === '' && req.method === 'POST') {
|
|
159
|
-
const body = await readJson(req, MAX_MOD_JSON + 4096);
|
|
160
|
-
const mod = normalizeMod(body?.mod);
|
|
161
|
-
if (!mod) return send(res, 400, { error: 'mod' }), true;
|
|
162
|
-
if (!mod.model && !mod.parts.length && !Object.keys(mod.character).length) return send(res, 400, { error: 'empty mod' }), true;
|
|
163
|
-
const missing = modelsMissing(mod);
|
|
164
|
-
if (missing.length) return send(res, 409, { error: 'upload the model first', missing }), true;
|
|
165
|
-
const prev = d.prepare('SELECT account_id FROM community_mods WHERE id = ?').get(mod.id);
|
|
166
|
-
if (prev && prev.account_id !== account.id) return send(res, 409, { error: 'id taken' }), true;
|
|
167
|
-
const json = JSON.stringify({ ...mod, by: mod.by || authorOf(account) });
|
|
168
|
-
if (prev) d.prepare("UPDATE community_mods SET mod = ?, status = ?, updated_at = ? WHERE id = ?").run(json, admin ? 'approved' : 'pending', now, mod.id);
|
|
169
|
-
else d.prepare('INSERT INTO community_mods (id, account_id, author, mod, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)').run(mod.id, account.id, authorOf(account), json, admin ? 'approved' : 'pending', now, now);
|
|
170
|
-
return send(res, prev ? 200 : 201, { mod: view(d.prepare('SELECT * FROM community_mods WHERE id = ?').get(mod.id), account) }), true;
|
|
171
|
-
}
|
|
172
|
-
const m = /^\/([a-z0-9-]{1,32})(\/(install|rate|report|review))?$/.exec(path);
|
|
173
|
-
if (!m) return false;
|
|
174
|
-
const row = d.prepare('SELECT * FROM community_mods WHERE id = ?').get(m[1]);
|
|
175
|
-
// authors and admins see their mod whatever its status; everyone else only approved ones
|
|
176
|
-
if (!row || (row.status !== 'approved' && row.account_id !== account.id && !admin)) return send(res, 404, { error: 'not found' }), true;
|
|
177
|
-
const action = m[3];
|
|
178
|
-
if (!action && req.method === 'GET') return send(res, 200, { mod: view(row, account) }), true;
|
|
179
|
-
if (!action && req.method === 'DELETE') {
|
|
180
|
-
if (row.account_id !== account.id && !admin) return send(res, 403, { error: 'not yours' }), true;
|
|
181
|
-
d.prepare('DELETE FROM community_mods WHERE id = ?').run(row.id);
|
|
182
|
-
return send(res, 200, { ok: true }), true;
|
|
183
|
-
}
|
|
184
|
-
if (req.method !== 'POST') return send(res, 405, { error: 'method' }), true;
|
|
185
|
-
if (action === 'install') {
|
|
186
|
-
const r = d.prepare('INSERT OR IGNORE INTO mod_installs (mod_id, account_id, at) VALUES (?, ?, ?)').run(row.id, account.id, now);
|
|
187
|
-
if (r.changes) d.prepare('UPDATE community_mods SET installs = installs + 1 WHERE id = ?').run(row.id);
|
|
188
|
-
return send(res, 200, { mod: view(d.prepare('SELECT * FROM community_mods WHERE id = ?').get(row.id), account) }), true;
|
|
189
|
-
}
|
|
190
|
-
if (action === 'rate') {
|
|
191
|
-
const stars = Math.round(Number((await readJson(req, 1024))?.stars));
|
|
192
|
-
if (!(stars >= 1 && stars <= 5)) return send(res, 400, { error: 'stars 1-5' }), true;
|
|
193
|
-
if (row.account_id === account.id) return send(res, 403, { error: 'own mod' }), true;
|
|
194
|
-
if (!d.prepare('SELECT 1 FROM mod_installs WHERE mod_id = ? AND account_id = ?').get(row.id, account.id)) return send(res, 403, { error: 'install it first' }), true;
|
|
195
|
-
const old = d.prepare('SELECT stars FROM mod_ratings WHERE mod_id = ? AND account_id = ?').get(row.id, account.id);
|
|
196
|
-
d.prepare('INSERT INTO mod_ratings (mod_id, account_id, stars, at) VALUES (?, ?, ?, ?) ON CONFLICT(mod_id, account_id) DO UPDATE SET stars = excluded.stars, at = excluded.at').run(row.id, account.id, stars, now);
|
|
197
|
-
d.prepare('UPDATE community_mods SET stars_sum = stars_sum + ?, stars_n = stars_n + ? WHERE id = ?').run(stars - (old?.stars || 0), old ? 0 : 1, row.id);
|
|
198
|
-
return send(res, 200, { mod: view(d.prepare('SELECT * FROM community_mods WHERE id = ?').get(row.id), account) }), true;
|
|
199
|
-
}
|
|
200
|
-
if (action === 'report') {
|
|
201
|
-
const reason = String((await readJson(req, 4096))?.reason || '').replace(/[\u0000-\u001f]/g, ' ').trim().slice(0, 300);
|
|
202
|
-
const r = d.prepare('INSERT OR IGNORE INTO mod_reports (mod_id, account_id, reason, at) VALUES (?, ?, ?, ?)').run(row.id, account.id, reason, now);
|
|
203
|
-
if (r.changes) {
|
|
204
|
-
d.prepare('UPDATE community_mods SET reports = reports + 1 WHERE id = ?').run(row.id);
|
|
205
|
-
const hide = Number(process.env.MOD_REPORTS_HIDE || 3);
|
|
206
|
-
d.prepare("UPDATE community_mods SET status = 'hidden' WHERE id = ? AND status = 'approved' AND reports >= ?").run(row.id, hide);
|
|
207
|
-
}
|
|
208
|
-
return send(res, 200, { ok: true }), true;
|
|
209
|
-
}
|
|
210
|
-
if (action === 'review') {
|
|
211
|
-
if (!admin) return send(res, 403, { error: 'admins only' }), true;
|
|
212
|
-
const status = (await readJson(req, 1024))?.status;
|
|
213
|
-
if (!STATUSES.includes(status)) return send(res, 400, { error: 'status' }), true;
|
|
214
|
-
d.prepare('UPDATE community_mods SET status = ?, reports = CASE WHEN ? = \'approved\' THEN 0 ELSE reports END, updated_at = ? WHERE id = ?').run(status, status, now, row.id);
|
|
215
|
-
if (status === 'approved') d.prepare('DELETE FROM mod_reports WHERE mod_id = ?').run(row.id);
|
|
216
|
-
return send(res, 200, { mod: view(d.prepare('SELECT * FROM community_mods WHERE id = ?').get(row.id), account) }), true;
|
|
217
|
-
}
|
|
218
|
-
return false;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
return { publicApi, accountApi };
|
|
222
|
-
}
|