@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.
Files changed (107) hide show
  1. package/.env.example +14 -0
  2. package/README.md +11 -0
  3. package/brand/logos/base.svg +1 -0
  4. package/brand/logos/clawpump.png +0 -0
  5. package/brand/logos/conductors.svg +1 -0
  6. package/brand/logos/notlogin.svg +12 -0
  7. package/brand/logos/pumpfun.png +0 -0
  8. package/brand/logos/solana.png +0 -0
  9. package/brand/logos/spawnerbot.svg +1 -0
  10. package/brand/logos/virtuals.png +0 -0
  11. package/cli/7ots.mjs +61 -1
  12. package/cli/lib/account.mjs +23 -3
  13. package/cli/lib/assistant.mjs +92 -14
  14. package/cli/lib/brain.mjs +84 -11
  15. package/cli/lib/card-shot.mjs +1 -1
  16. package/cli/lib/config.mjs +14 -3
  17. package/cli/lib/desktop-sync.mjs +177 -0
  18. package/cli/lib/i18n.mjs +9 -0
  19. package/cli/lib/inferences.mjs +19 -2
  20. package/cli/lib/integrations.mjs +98 -13
  21. package/cli/lib/mcp.mjs +1 -1
  22. package/cli/lib/open.mjs +3 -1
  23. package/cli/lib/pet-server.mjs +352 -41
  24. package/cli/lib/prompts.mjs +1 -1
  25. package/cli/lib/screen.mjs +1 -1
  26. package/cli/lib/senses/gestures.mjs +121 -0
  27. package/cli/lib/senses/index.mjs +490 -0
  28. package/cli/lib/senses/rules.mjs +159 -0
  29. package/cli/lib/senses/sources/activity.mjs +95 -0
  30. package/cli/lib/senses/sources/calendar.mjs +75 -0
  31. package/cli/lib/senses/sources/index.mjs +17 -0
  32. package/cli/lib/senses/sources/mail.mjs +48 -0
  33. package/cli/lib/senses/sources/system.mjs +39 -0
  34. package/cli/lib/senses/util.mjs +41 -0
  35. package/cli/lib/senses/vendor.mjs +78 -0
  36. package/cli/lib/stt-local.py +16 -8
  37. package/cli/lib/stt.mjs +53 -6
  38. package/cli/lib/tooluse.mjs +56 -0
  39. package/cli/lib/tts-local.mjs +2 -2
  40. package/cli/lib/vm.mjs +2 -2
  41. package/cli/lib/wake-local.py +109 -0
  42. package/cli/lib/wake.mjs +102 -0
  43. package/cli/pet/electron/main.cjs +190 -8
  44. package/cli/pet/pet.html +153 -34
  45. package/cli/pet/senses.html +342 -0
  46. package/cli/pet/settings.html +815 -74
  47. package/dist/7ots.esm.js +373 -146
  48. package/dist/7ots.esm.js.map +4 -4
  49. package/dist/7ots.iife.js +373 -146
  50. package/dist/7ots.iife.js.map +4 -4
  51. package/llms.txt +27 -0
  52. package/package.json +5 -2
  53. package/server/channels/apuchat.mjs +18 -4
  54. package/server/errors.mjs +90 -0
  55. package/server/notify.mjs +78 -0
  56. package/server/server.mjs +84 -14
  57. package/server/settings.mjs +3 -0
  58. package/server/site.mjs +401 -0
  59. package/server/tts.mjs +29 -5
  60. package/src/avatar/AvatarStage.js +2 -2
  61. package/src/avatar/three.js +3 -2
  62. package/src/character/AvatarEditor.js +2 -1
  63. package/src/character/Character.js +38 -5
  64. package/src/character/TradingCard.js +2 -0
  65. package/src/character/beat.js +64 -2
  66. package/src/character/mods/orc.js +8 -1
  67. package/src/character/mods.js +104 -10
  68. package/src/character/motion.js +252 -1
  69. package/src/character/parts.js +40 -38
  70. package/src/character/styles.js +40 -38
  71. package/src/character3d/Character3D.js +26 -5
  72. package/src/character3d/body.js +14 -12
  73. package/src/character3d/export.js +693 -0
  74. package/src/character3d/fx.js +13 -0
  75. package/src/character3d/index.js +2 -0
  76. package/src/character3d/materials.js +106 -10
  77. package/src/character3d/room-themes.js +1184 -0
  78. package/src/character3d/room.js +487 -0
  79. package/src/character3d/stage.js +14 -2
  80. package/src/creator/StepCreator.js +316 -0
  81. package/src/i18n/index.js +3 -3
  82. package/src/i18n/messages/character.js +352 -4
  83. package/src/i18n/messages/creator.js +138 -0
  84. package/src/i18n/messages/identity.js +89 -1
  85. package/src/i18n/messages/platform.js +270 -4
  86. package/src/i18n/messages/server.js +443 -1
  87. package/src/i18n/messages/widget.js +233 -0
  88. package/src/identity/random.js +14 -2
  89. package/src/identity/schema.js +2 -1
  90. package/src/index.js +9 -2
  91. package/src/voice/tags.js +22 -0
  92. package/server/platform/apuchat.mjs +0 -266
  93. package/server/platform/auth.mjs +0 -319
  94. package/server/platform/connect.mjs +0 -387
  95. package/server/platform/crypto.mjs +0 -80
  96. package/server/platform/db.mjs +0 -275
  97. package/server/platform/device.mjs +0 -222
  98. package/server/platform/integrations.mjs +0 -169
  99. package/server/platform/look.mjs +0 -20
  100. package/server/platform/mods.mjs +0 -222
  101. package/server/platform/orquesta.mjs +0 -577
  102. package/server/platform/profile.mjs +0 -161
  103. package/server/platform/routes.mjs +0 -542
  104. package/server/platform/runtime.mjs +0 -242
  105. package/server/platform/sites.mjs +0 -146
  106. package/server/platform/store.mjs +0 -456
  107. package/server/platform/vm.mjs +0 -1057
@@ -1,387 +0,0 @@
1
- /**
2
- * Dashboard routes of the platform's integrations: an apuchat identity per ot and Orquesta tasks.
3
- * Mounted by routes.mjs (same session, same-origin and X-7ots-Admin rules as the rest of /api/platform).
4
- *
5
- * Account:
6
- * DELETE /api/platform/apuchat/link forget the linked apuchat account
7
- * GET /api/platform/orquesta/projects projects of the connected Orquesta account
8
- * POST /api/platform/orquesta/key { key } connect with an oak_ key · DELETE /api/platform/orquesta
9
- * One ot:
10
- * GET …/ots/:id/apuchat its identity, the account's apuchat state, open checkouts
11
- * POST …/ots/:id/apuchat/identity new free identity · DELETE (detach; deletes free ones)
12
- * POST …/ots/:id/apuchat/key { key } use an existing identity key
13
- * GET …/ots/:id/apuchat/quote?callsign= price of a permanent handle
14
- * POST …/ots/:id/apuchat/checkout { callsign } → { url } (card payment on apuchat; back to /app/?apuchat_ots=<id>)
15
- * GET …/ots/:id/apuchat/checkout/:cid result; a newly revealed key is stored in the ot
16
- * POST …/ots/:id/apuchat/claim move the ot's identity into the linked apuchat account
17
- * GET|PUT …/ots/:id/orquesta project, tasks on/off, allowed senders, daily cap; recent tasks
18
- * POST …/ots/:id/orquesta/ask { message, history } the owner talks to the ot (only place with tools + owner)
19
- * GET …/ots/:id/orquesta/tasks/:tid · POST …/cancel
20
- * Browser redirects (state in a signed cookie, bound to the session's account):
21
- * GET /auth/apuchat?ots= → apuchat /link → GET /auth/apuchat/callback?state&code
22
- * GET /auth/orquesta?ots= → Orquesta OAuth (PKCE) → GET /auth/orquesta/callback?code&state
23
- * Both end in /app/?notice=<key>#ots/<id>/<tab>.
24
- */
25
-
26
- import { randomBytes } from 'node:crypto';
27
- import { reqT, requestLocale } from '../i18n.mjs';
28
- import { currentAccount, parseCookies } from './auth.mjs';
29
- import { signValue, unsignValue } from './crypto.mjs';
30
- import { getOwnOts, listTasks, tasksLastDay } from './store.mjs';
31
- import { otsChannels, otsStep } from './runtime.mjs';
32
- import {
33
- CALLSIGN_RE, apuchatAccountView, apuchatHub, callsignOf, checkout, checkoutStatus, claimIdentity, createFreeIdentity, defaultOwner, deleteIdentity,
34
- exchangeLink, linkUrl, pendingCheckouts, quote, unlink,
35
- } from './apuchat.mjs';
36
- import {
37
- askOt, authorizeUrl, cancelTask, disconnect, exchangeCode, listProjects, manageUrl, orquestaAccountView, orquestaUrl, otsOrquesta, parseAllow, projectUrl, saveKey, taskStatus,
38
- registerOts,
39
- } from './orquesta.mjs';
40
- import { assertPublicUrl, integrationsView, normalizeOtIntegrations, otIntegrations, testIntegration } from './integrations.mjs';
41
-
42
- const penv = process.env;
43
- const STATE_TTL = 10 * 60_000;
44
- const COOKIES = { apuchat: 'ots_apuchat_link', orquesta: 'ots_orquesta_oauth' };
45
- const IDENTITY_KEYS = ['APUCHAT_AGENT_CALLSIGN', 'APUCHAT_AGENT_FREE', 'APUCHAT_AGENT_OWNER'];
46
-
47
- /**
48
- * @param {{ send: Function, readJson: Function, originOf: Function, save: (ots, patch) => Promise<object> }} deps
49
- */
50
- export function createConnect({ send, readJson, originOf, save }) {
51
- const base = (req) => (penv.PLATFORM_URL || originOf(req)).replace(/\/+$/, '');
52
-
53
- function cookie(req, name, value, path, maxAge) {
54
- return `${name}=${encodeURIComponent(value)}; Path=${path}; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(maxAge / 1000)}${base(req).startsWith('https:') ? '; Secure' : ''}`;
55
- }
56
- const putState = (req, res, kind, st) => res.setHeader('Set-Cookie', cookie(req, COOKIES[kind], signValue(Buffer.from(JSON.stringify(st)).toString('base64url')), `/auth/${kind}`, STATE_TTL));
57
- function takeState(req, res, kind) {
58
- res.setHeader('Set-Cookie', cookie(req, COOKIES[kind], '', `/auth/${kind}`, 0));
59
- const raw = unsignValue(parseCookies(req.headers.cookie)[COOKIES[kind]]);
60
- try {
61
- const st = raw && JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
62
- return st && st.e > Date.now() ? st : null;
63
- } catch {
64
- return null;
65
- }
66
- }
67
- function redirect(res, to) {
68
- res.writeHead(303, { Location: to, 'Cache-Control': 'no-store' });
69
- res.end();
70
- }
71
- const back = (res, notice, otsId, tab) => redirect(res, `/app/?notice=${encodeURIComponent(notice)}${otsId ? `#ots/${otsId}/${tab}` : ''}`);
72
-
73
- // ───────────────────────────── apuchat identity of an ot ─────────────────────────────
74
-
75
- const hasIdentity = (ots) => !!ots.secrets.APUCHAT_AGENT_IDENTITY_KEY;
76
- const isFree = (ots) => hasIdentity(ots) && ots.settings.APUCHAT_AGENT_FREE === '1';
77
- // A paid handle held by the platform's anonymous account would be lost if the ot let go of its key.
78
- const wouldLose = (ots) => hasIdentity(ots) && !isFree(ots) && ots.settings.APUCHAT_AGENT_OWNER === 'managed';
79
-
80
- function apuchatView(account, ots) {
81
- const st = otsChannels(ots).status().apuchat || null;
82
- const has = hasIdentity(ots);
83
- return {
84
- hub: apuchatHub(),
85
- mintUrl: `${apuchatHub()}/account/mint`,
86
- identity: has ? { callsign: ots.settings.APUCHAT_AGENT_CALLSIGN || st?.callsign || null, free: isFree(ots), owner: ots.settings.APUCHAT_AGENT_OWNER || 'own' } : null,
87
- paused: ots.status !== 'on',
88
- listening: !!st && !st.lastError,
89
- error: st?.lastError || null,
90
- account: apuchatAccountView(account.id),
91
- checkouts: pendingCheckouts(account.id, ots.id),
92
- };
93
- }
94
-
95
- /** Puts an identity in the ot (its key is a channel setting: the apuchat channel restarts with it). */
96
- function setIdentity(ots, { key, callsign, free, owner }) {
97
- const settings = { ...ots.settings };
98
- for (const k of IDENTITY_KEYS) delete settings[k];
99
- const secrets = { ...ots.secrets };
100
- if (key) {
101
- secrets.APUCHAT_AGENT_IDENTITY_KEY = key;
102
- if (callsign) settings.APUCHAT_AGENT_CALLSIGN = callsign;
103
- if (free) settings.APUCHAT_AGENT_FREE = '1';
104
- if (owner) settings.APUCHAT_AGENT_OWNER = owner;
105
- } else delete secrets.APUCHAT_AGENT_IDENTITY_KEY;
106
- return save(ots, { settings, secrets });
107
- }
108
-
109
- /** New free identity for an ot that has none (also used when creating an ot with the box ticked). */
110
- async function freeIdentity(account, ots) {
111
- const id = await createFreeIdentity(account.id);
112
- return setIdentity(ots, { key: id.identityKey, callsign: id.callsign, free: id.free, owner: id.owner });
113
- }
114
-
115
- async function apuchatOts(req, res, account, ots, sub) {
116
- const t = reqT(req);
117
- const url = new URL(req.url, 'http://x');
118
- if (sub === '/apuchat' && req.method === 'GET') return send(res, 200, apuchatView(account, ots));
119
-
120
- if (sub === '/apuchat/identity' && req.method === 'POST') {
121
- // One live free identity per ot; a paid or pasted one has to be detached first.
122
- if (isFree(ots)) return send(res, 409, { error: t('platform.apuchat.alreadyFree') });
123
- if (hasIdentity(ots)) return send(res, 409, { error: t('platform.apuchat.hasIdentity') });
124
- const next = await freeIdentity(account, ots);
125
- return send(res, 201, apuchatView(account, next));
126
- }
127
- if (sub === '/apuchat/identity' && req.method === 'DELETE') {
128
- if (!hasIdentity(ots)) return send(res, 200, apuchatView(account, ots));
129
- if (wouldLose(ots)) return send(res, 409, { error: t('platform.apuchat.claimFirst') });
130
- const { APUCHAT_AGENT_CALLSIGN: cs, APUCHAT_AGENT_OWNER: owner } = ots.settings;
131
- const free = isFree(ots);
132
- const next = await setIdentity(ots, {});
133
- if (free && cs) await deleteIdentity(account.id, owner, cs);
134
- return send(res, 200, apuchatView(account, next));
135
- }
136
- if (sub === '/apuchat/key' && req.method === 'POST') {
137
- const { key } = await readJson(req, 8 * 1024);
138
- const k = String(key || '').trim();
139
- if (!k || k.length > 400 || /\s/.test(k)) return send(res, 400, { error: t('platform.apuchat.badKey') });
140
- if (wouldLose(ots)) return send(res, 409, { error: t('platform.apuchat.claimFirst') });
141
- const callsign = await callsignOf(k);
142
- if (!callsign) return send(res, 400, { error: t('platform.apuchat.keyRefused') });
143
- const next = await setIdentity(ots, { key: k, callsign, owner: 'own' });
144
- return send(res, 200, apuchatView(account, next));
145
- }
146
- if (sub === '/apuchat/quote' && req.method === 'GET') {
147
- const callsign = String(url.searchParams.get('callsign') || '').trim().replace(/^@/, '').toLowerCase();
148
- if (!CALLSIGN_RE.test(callsign)) return send(res, 400, { error: t('platform.apuchat.badCallsign') });
149
- const upgrade = isFree(ots) && ots.settings.APUCHAT_AGENT_CALLSIGN === callsign;
150
- const q = await quote(account.id, upgrade ? ots.settings.APUCHAT_AGENT_OWNER : defaultOwner(account.id, 'identities:mint'), callsign);
151
- return send(res, 200, { ...q, upgrade, available: upgrade || (q.valid && !q.taken) });
152
- }
153
- if (sub === '/apuchat/checkout' && req.method === 'POST') {
154
- const { callsign: raw } = await readJson(req, 4 * 1024);
155
- const callsign = String(raw || '').trim().replace(/^@/, '').toLowerCase();
156
- if (!CALLSIGN_RE.test(callsign)) return send(res, 400, { error: t('platform.apuchat.badCallsign') });
157
- // Same callsign as the ot's free identity → in-place upgrade, made by the account that owns it.
158
- const upgrade = isFree(ots) && ots.settings.APUCHAT_AGENT_CALLSIGN === callsign;
159
- if (!upgrade && wouldLose(ots)) return send(res, 409, { error: t('platform.apuchat.claimFirst') });
160
- const owner = upgrade ? ots.settings.APUCHAT_AGENT_OWNER : defaultOwner(account.id, 'identities:mint');
161
- // No #fragment: apuchat appends ?apuchat_checkout=<id>&status=… to it; the dashboard opens the ot's tab from apuchat_ots.
162
- const out = await checkout(account.id, owner, { otsId: ots.id, callsign, returnUrl: `${base(req)}/app/?apuchat_ots=${ots.id}` });
163
- return send(res, 200, { url: out.url, checkoutId: out.checkoutId, priceUsd: out.priceUsd, tier: out.tier });
164
- }
165
- const ck = sub.match(/^\/apuchat\/checkout\/([A-Za-z0-9_-]{4,100})$/);
166
- if (ck && req.method === 'GET') {
167
- const st = await checkoutStatus(account.id, ots.id, ck[1]);
168
- if (!st) return send(res, 404, { error: t('server.http.notFound') });
169
- let next = ots;
170
- if (st.status === 'fulfilled') {
171
- if (st.identityKey) {
172
- const { APUCHAT_AGENT_CALLSIGN: old, APUCHAT_AGENT_OWNER: oldOwner } = ots.settings;
173
- const wasFree = isFree(ots);
174
- next = await setIdentity(ots, { key: st.identityKey, callsign: st.callsign, owner: st.owner });
175
- // The free handle it replaces goes back to apuchat (best effort).
176
- if (wasFree && old && old !== st.callsign) await deleteIdentity(account.id, oldOwner, old).catch(() => {});
177
- } else if (st.upgraded && ots.settings.APUCHAT_AGENT_CALLSIGN === st.callsign) {
178
- const settings = { ...ots.settings };
179
- delete settings.APUCHAT_AGENT_FREE;
180
- next = await save(ots, { settings });
181
- }
182
- }
183
- return send(res, 200, { status: st.status, callsign: st.callsign, upgraded: st.upgraded, applied: next !== ots, apuchat: apuchatView(account, next) });
184
- }
185
- if (sub === '/apuchat/claim' && req.method === 'POST') {
186
- if (!hasIdentity(ots)) return send(res, 409, { error: t('platform.apuchat.noIdentity') });
187
- await claimIdentity(account.id, ots.secrets.APUCHAT_AGENT_IDENTITY_KEY);
188
- const next = await save(ots, { settings: { ...ots.settings, APUCHAT_AGENT_OWNER: 'linked' } });
189
- return send(res, 200, apuchatView(account, next));
190
- }
191
- return false;
192
- }
193
-
194
- // ───────────────────────────── Orquesta panel of an ot ─────────────────────────────
195
-
196
- function orquestaView(account, ots) {
197
- const cfg = otsOrquesta(ots);
198
- return {
199
- url: orquestaUrl(),
200
- // Where the owner changes which Orquesta projects 7ots may reach (per-project consent).
201
- manageUrl: manageUrl(),
202
- account: orquestaAccountView(account.id),
203
- ...cfg,
204
- projectUrl: cfg.project ? projectUrl(cfg.project) : null,
205
- usedToday: tasksLastDay(ots.id),
206
- recent: listTasks(ots.id, 20).map((x) => ({ id: x.id, who: x.who, channel: x.channel, task: x.task.slice(0, 300), status: x.status, result: x.result.slice(0, 2000), error: x.error, createdAt: x.createdAt, updatedAt: x.updatedAt })),
207
- };
208
- }
209
-
210
- async function orquestaOts(req, res, account, ots, sub) {
211
- const t = reqT(req);
212
- if (sub === '/orquesta' && req.method === 'GET') return send(res, 200, orquestaView(account, ots));
213
- if (sub === '/orquesta' && req.method === 'PUT') {
214
- const body = await readJson(req, 16 * 1024);
215
- const settings = { ...ots.settings };
216
- if (body.project !== undefined) {
217
- const id = String(body.project || '').trim();
218
- if (!id) {
219
- delete settings.ORQUESTA_PROJECT;
220
- delete settings.ORQUESTA_PROJECT_NAME;
221
- } else {
222
- const p = (await listProjects(account.id)).find((x) => x.id === id);
223
- if (!p) return send(res, 400, { error: t('platform.orquesta.noProject') });
224
- settings.ORQUESTA_PROJECT = p.id;
225
- settings.ORQUESTA_PROJECT_NAME = p.name;
226
- }
227
- }
228
- if (body.tasks !== undefined) {
229
- if (body.tasks) settings.ORQUESTA_TASKS = '1';
230
- else delete settings.ORQUESTA_TASKS;
231
- }
232
- if (body.allow !== undefined) {
233
- const { list, bad } = parseAllow(body.allow);
234
- if (bad.length) return send(res, 400, { error: t('platform.orquesta.badAllow', { list: bad.slice(0, 5).join(', ') }) });
235
- if (list.length) settings.ORQUESTA_ALLOW = list.join(', ');
236
- else delete settings.ORQUESTA_ALLOW;
237
- }
238
- if (body.daily !== undefined) settings.ORQUESTA_DAILY = String(Math.min(200, Math.max(1, Math.floor(Number(body.daily)) || 20)));
239
- if (settings.ORQUESTA_TASKS && !settings.ORQUESTA_PROJECT) return send(res, 400, { error: t('platform.orquesta.pickProject') });
240
- const saved = await save(ots, { settings });
241
- registerOts(account.id, { force: true }).catch(() => null); // seeds the link in Orquesta for a first project
242
- return send(res, 200, orquestaView(account, saved));
243
- }
244
- if (sub === '/orquesta/ask' && req.method === 'POST') {
245
- const { message, history } = await readJson(req, 128 * 1024);
246
- const msg = String(message || '').trim();
247
- if (!msg) return send(res, 400, { error: t('server.http.badRequest') });
248
- if (ots.status !== 'on') return send(res, 409, { error: t('platform.api.paused') });
249
- const out = await askOt(ots, { message: msg, history, ownerEmail: account.email || account.id, locale: requestLocale(req) }, (a) => otsStep(ots, a));
250
- return send(res, 200, out);
251
- }
252
- const tm = sub.match(/^\/orquesta\/tasks\/([A-Za-z0-9_-]{4,100})(\/cancel)?$/);
253
- if (tm && !tm[2] && req.method === 'GET') {
254
- const out = await taskStatus(ots, tm[1]);
255
- return out.ok ? send(res, 200, out) : send(res, 404, { error: out.error });
256
- }
257
- if (tm && tm[2] && req.method === 'POST') {
258
- const row = await cancelTask(ots, tm[1]);
259
- return row ? send(res, 200, { id: row.id, status: row.status }) : send(res, 404, { error: t('server.http.notFound') });
260
- }
261
- return false;
262
- }
263
-
264
- // ───────────────────────────── account-level routes ─────────────────────────────
265
-
266
- async function accountApi(req, res, account, path) {
267
- if (path === '/apuchat/link' && req.method === 'DELETE') {
268
- unlink(account.id);
269
- return send(res, 200, { apuchat: apuchatAccountView(account.id) });
270
- }
271
- if (path === '/orquesta/projects' && req.method === 'GET') return send(res, 200, { projects: await listProjects(account.id) });
272
- if (path === '/orquesta/key' && req.method === 'POST') {
273
- const { key } = await readJson(req, 4 * 1024);
274
- await saveKey(account.id, key);
275
- return send(res, 200, { orquesta: orquestaAccountView(account.id) });
276
- }
277
- if (path === '/orquesta' && req.method === 'DELETE') {
278
- disconnect(account.id);
279
- return send(res, 200, { orquesta: orquestaAccountView(account.id) });
280
- }
281
- return false;
282
- }
283
-
284
- // ───────────────────────────── browser redirects ─────────────────────────────
285
-
286
- async function authRoutes(req, res, url) {
287
- const p = url.pathname;
288
- if (!/^\/auth\/(apuchat|orquesta)(\/callback)?$/.test(p) || req.method !== 'GET') return false;
289
- const account = currentAccount(req);
290
- if (!account) {
291
- redirect(res, '/app/');
292
- return true;
293
- }
294
- const kind = p.split('/')[2];
295
- const tab = kind;
296
-
297
- if (!p.endsWith('/callback')) {
298
- const ots = getOwnOts(account.id, url.searchParams.get('ots'));
299
- const st = { s: randomBytes(16).toString('base64url'), acc: account.id, ots: ots?.id || null, e: Date.now() + STATE_TTL };
300
- if (kind === 'apuchat') {
301
- putState(req, res, kind, st);
302
- redirect(res, linkUrl(`${base(req)}/auth/apuchat/callback?state=${st.s}`));
303
- return true;
304
- }
305
- try {
306
- const { url: to, verifier } = await authorizeUrl({ redirectUri: `${base(req)}/auth/orquesta/callback`, state: st.s });
307
- putState(req, res, kind, { ...st, v: verifier });
308
- redirect(res, to);
309
- } catch (e) {
310
- console.warn('[7ots] orquesta connect:', e.message);
311
- back(res, 'orquestaFailed', st.ots, tab);
312
- }
313
- return true;
314
- }
315
-
316
- const st = takeState(req, res, kind);
317
- const code = url.searchParams.get('code');
318
- // The flow must come back to the same browser AND the same 7ots account that started it.
319
- const ok = st && st.acc === account.id && code && url.searchParams.get('state') === st.s;
320
- const otsId = st?.ots && getOwnOts(account.id, st.ots) ? st.ots : null;
321
- if (!ok) {
322
- back(res, url.searchParams.get('error') === 'access_denied' ? `${kind}Denied` : `${kind}Failed`, otsId, tab);
323
- return true;
324
- }
325
- try {
326
- if (kind === 'apuchat') await exchangeLink(account.id, code);
327
- else await exchangeCode(account.id, { code, verifier: st.v, redirectUri: `${base(req)}/auth/orquesta/callback` });
328
- back(res, kind === 'apuchat' ? 'apuchatLinked' : 'orquestaConnected', otsId, tab);
329
- } catch (e) {
330
- console.warn(`[7ots] ${kind} callback:`, e.message);
331
- back(res, `${kind}Failed`, otsId, tab);
332
- }
333
- return true;
334
- }
335
-
336
- /** Dashboard → Assistant → Integrations (MCP servers / APIs the ot can use when its owner asks). */
337
- async function integrationsOts(req, res, account, ots, sub) {
338
- const t = reqT(req);
339
- const fail = (e) => send(res, 400, { error: e.code ? t(`platform.integ.${e.code}`) : String(e.message || e).slice(0, 300) });
340
- if (sub === '/integrations' && req.method === 'GET') return send(res, 200, { items: integrationsView(ots) });
341
- if (sub === '/integrations' && req.method === 'PUT') {
342
- const body = await readJson(req, 64 * 1024);
343
- let out;
344
- try {
345
- out = normalizeOtIntegrations(body.items, ots);
346
- for (const c of out.list) if (c.url && c.on) await assertPublicUrl(c.url);
347
- } catch (e) {
348
- return fail(e);
349
- }
350
- const settings = { ...ots.settings };
351
- if (out.list.length) settings.INTEGRATIONS = JSON.stringify(out.list);
352
- else delete settings.INTEGRATIONS;
353
- const saved = await save(ots, { settings, secrets: out.secrets });
354
- return send(res, 200, { items: integrationsView(saved) });
355
- }
356
- const m = sub.match(/^\/integrations\/([a-z0-9]{6,16})\/test$/);
357
- if (m && req.method === 'POST') {
358
- const c = otIntegrations(ots).find((x) => x.id === m[1]);
359
- if (!c) return send(res, 404, { error: t('platform.integ.notFound') });
360
- try {
361
- return send(res, 200, await testIntegration(ots, c));
362
- } catch (e) {
363
- return send(res, 200, { ok: false, error: e.code ? t(`platform.integ.${e.code}`) : String(e.message || e).replace(/\b(Bearer|Basic)\s+\S+/gi, '$1 ***').slice(0, 300) });
364
- }
365
- }
366
- return false;
367
- }
368
-
369
- return {
370
- /** /api/platform/<path> for the account; false if not one of these routes. */
371
- account: accountApi,
372
- /** /api/platform/ots/:id<sub>; false if not one of these routes. */
373
- async ots(req, res, account, ots, sub) {
374
- if (sub.startsWith('/apuchat')) return (await apuchatOts(req, res, account, ots, sub)) !== false;
375
- if (sub.startsWith('/orquesta')) return (await orquestaOts(req, res, account, ots, sub)) !== false;
376
- if (sub.startsWith('/integrations')) return (await integrationsOts(req, res, account, ots, sub)) !== false;
377
- return false;
378
- },
379
- auth: authRoutes,
380
- freeIdentity,
381
- integrations: (account) => ({ apuchat: apuchatAccountView(account.id), orquesta: { ...orquestaAccountView(account.id), url: orquestaUrl() } }),
382
- /** When an ot is deleted: give its free identity back to apuchat (best effort). */
383
- async release(account, ots) {
384
- if (isFree(ots) && ots.settings.APUCHAT_AGENT_CALLSIGN) await deleteIdentity(account.id, ots.settings.APUCHAT_AGENT_OWNER, ots.settings.APUCHAT_AGENT_CALLSIGN).catch(() => {});
385
- },
386
- };
387
- }
@@ -1,80 +0,0 @@
1
- /**
2
- * Criptografía de la plataforma. Todo sale de PLATFORM_SECRET (≥ 32 caracteres, aleatorio):
3
- * - las claves de cada ots se guardan cifradas (AES-256-GCM),
4
- * - las cookies temporales del login (estado de OIDC) van firmadas (HMAC-SHA256),
5
- * - los tokens (sesión, enlace por email) se guardan como hash, nunca en claro.
6
- * Cambiar PLATFORM_SECRET invalida las claves guardadas: los usuarios tendrían que volver a ponerlas.
7
- */
8
-
9
- import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual } from 'node:crypto';
10
-
11
- let keys = null;
12
-
13
- function derive() {
14
- if (keys) return keys;
15
- const secret = process.env.PLATFORM_SECRET || '';
16
- if (secret.length < 32) throw new Error('PLATFORM_SECRET debe tener al menos 32 caracteres (la plataforma no arranca sin él)');
17
- const k = (info) => Buffer.from(hkdfSync('sha256', secret, '7ots-platform', info, 32));
18
- keys = { box: k('secrets-v1'), mac: k('cookies-v1') };
19
- return keys;
20
- }
21
-
22
- /** Comprueba PLATFORM_SECRET al arrancar (lanza si falta). */
23
- export function assertSecret() {
24
- derive();
25
- }
26
-
27
- /** Cifra un objeto → "v1.<iv>.<tag>.<datos>" (base64url). */
28
- export function seal(obj) {
29
- const iv = randomBytes(12);
30
- const c = createCipheriv('aes-256-gcm', derive().box, iv);
31
- const data = Buffer.concat([c.update(JSON.stringify(obj ?? {}), 'utf8'), c.final()]);
32
- return ['v1', iv.toString('base64url'), c.getAuthTag().toString('base64url'), data.toString('base64url')].join('.');
33
- }
34
-
35
- /** Descifra lo de seal(). Vacío o inválido → {} (y avisa: nunca rompe el ots). */
36
- export function open(text) {
37
- if (!text) return {};
38
- try {
39
- const [v, iv, tag, data] = String(text).split('.');
40
- if (v !== 'v1') return {};
41
- const d = createDecipheriv('aes-256-gcm', derive().box, Buffer.from(iv, 'base64url'));
42
- d.setAuthTag(Buffer.from(tag, 'base64url'));
43
- return JSON.parse(Buffer.concat([d.update(Buffer.from(data, 'base64url')), d.final()]).toString('utf8'));
44
- } catch {
45
- console.warn('[7ots] plataforma: no se pudieron descifrar unas claves (¿cambió PLATFORM_SECRET?)');
46
- return {};
47
- }
48
- }
49
-
50
- /** Firma un valor corto para una cookie: "<valor>.<mac>". */
51
- export function signValue(value) {
52
- return `${value}.${createHmac('sha256', derive().mac).update(value).digest('base64url')}`;
53
- }
54
-
55
- /** Devuelve el valor si la firma es buena; si no, null. */
56
- export function unsignValue(signed) {
57
- const s = String(signed || '');
58
- const i = s.lastIndexOf('.');
59
- if (i < 1) return null;
60
- const value = s.slice(0, i);
61
- return safeEqual(s.slice(i + 1), createHmac('sha256', derive().mac).update(value).digest('base64url')) ? value : null;
62
- }
63
-
64
- export const token = (bytes = 32) => randomBytes(bytes).toString('base64url');
65
- export const sha256 = (s) => createHash('sha256').update(String(s)).digest('base64url');
66
-
67
- /** Id corto y legible para URLs: prefijo + 16 caracteres [a-z0-9]. */
68
- export function newId(prefix) {
69
- const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';
70
- const b = randomBytes(16);
71
- let out = '';
72
- for (const x of b) out += alphabet[x % 36];
73
- return `${prefix}_${out}`;
74
- }
75
-
76
- export function safeEqual(a, b) {
77
- const x = Buffer.from(String(a));
78
- const y = Buffer.from(String(b));
79
- return x.length === y.length && timingSafeEqual(x, y);
80
- }