dscord 0.2.0-alpha.1 → 0.4.0-alpha.2
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/LICENSE +201 -0
- package/NOTICE +22 -0
- package/README.md +70 -49
- package/bin/dscord.mjs +5 -4
- package/cordis.patch.yml +3 -0
- package/deploy/synapse/dscord_guard.py +212 -0
- package/dist/admin/assets/index-DXyc54Ce.css +1 -0
- package/dist/admin/assets/index-vZ7hJNEU.js +10 -0
- package/dist/admin/assets/mark-128-C4ed4p0U.png +0 -0
- package/dist/admin/index.html +13 -0
- package/dist/admin/licenses/bundled-dependencies.txt +421 -0
- package/dist/admin/licenses/lucide.txt +43 -0
- package/dist/admin/licenses/ui-foundation.txt +336 -0
- package/dist/admin/theme.js +66 -0
- package/dist/web/assets/apple-touch-icon-C_qAgjR1.png +0 -0
- package/dist/web/assets/common-DGlCXKV6.js +5 -0
- package/dist/web/assets/favicon-32-CEKpvmlx.png +0 -0
- package/dist/web/assets/favicon-6aWeKmcy.ico +0 -0
- package/dist/web/assets/index-62nMLjE0.css +1 -0
- package/dist/web/assets/index-OaWUoxQD.js +55 -0
- package/dist/web/assets/{manifest-eq_1S_IC.webmanifest → manifest-Ca-bIZpP.webmanifest} +2 -8
- package/dist/web/assets/mark-128-C4ed4p0U.png +0 -0
- package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/dist/web/client-config.json +3 -0
- package/dist/web/icons/apple-touch-icon.png +0 -0
- package/dist/web/icons/favicon-32.png +0 -0
- package/dist/web/icons/favicon.ico +0 -0
- package/dist/web/icons/icon-192.png +0 -0
- package/dist/web/icons/icon-512.png +0 -0
- package/dist/web/icons/mark-128.png +0 -0
- package/dist/web/index.html +9 -7
- package/dist/web/licenses/bundled-dependencies.txt +2452 -0
- package/dist/web/licenses/ui-foundation.txt +336 -0
- package/dist/web/manifest.webmanifest +2 -8
- package/dist/web/sw.js +233 -79
- package/dist/web/theme.js +27 -5
- package/dsh-connect/KERNEL.md +70 -0
- package/dsh-connect/client.js +28821 -0
- package/dsh-connect/controller.mjs +450 -0
- package/dsh-connect/decision-settings.mjs +66 -0
- package/dsh-connect/index.mjs +40 -0
- package/dsh-connect/kernel-runtime.mjs +120 -0
- package/dsh-connect/models.mjs +64 -0
- package/dsh-connect/native-bots.mjs +97 -0
- package/dsh-connect/native-bridge.mjs +482 -0
- package/dsh-connect/native-connections.mjs +160 -0
- package/dsh-connect/native-team.mjs +63 -0
- package/dsh-connect/processes.mjs +119 -0
- package/dsh-connect/work-core.mjs +573 -0
- package/dsh-plugin/README.md +32 -31
- package/dsh-plugin/index.mjs +18 -11
- package/dsh-plugin/model-profile.mjs +73 -0
- package/dsh-plugin/runtime-dependencies-lock.json +696 -6
- package/dsh-plugin/runtime-dependencies-pnpm-lock.yaml +489 -0
- package/dsh-plugin/runtime-dependencies.json +7 -2
- package/dsh-plugin/runtime-rules.mjs +9 -0
- package/dsh-plugin/runtime.mjs +330 -45
- package/dsh-plugin/scoped-work.mjs +73 -0
- package/dsh-plugin/work-files.mjs +24 -5
- package/memory/contacts.mjs +36 -0
- package/memory/ingress.mjs +57 -0
- package/memory/model-options.mjs +9 -0
- package/memory/native.mjs +374 -0
- package/memory/observation-policy.mjs +67 -0
- package/memory/ombre.mjs +165 -0
- package/memory/panel.mjs +88 -0
- package/memory/review.mjs +90 -0
- package/memory/service.mjs +429 -0
- package/memory/snapshot-context.mjs +95 -0
- package/memory/source-query.mjs +87 -0
- package/memory/store.mjs +339 -0
- package/memory/views.mjs +304 -0
- package/memory//345/244/215/347/224/250/344/270/216/350/277/220/350/241/214.md +47 -0
- package/memory//345/275/223/345/211/215/344/270/212/344/270/213/346/226/207/344/270/216/345/233/236/351/241/276.md +73 -0
- package/package.json +46 -6
- package/scripts/admin.mjs +41 -0
- package/scripts/central-init.mjs +39 -0
- package/scripts/dsh-node.mjs +92 -54
- package/scripts/memory-setup.mjs +21 -0
- package/scripts/runtime-config.mjs +55 -23
- package/scripts/runtime-dependencies.mjs +79 -0
- package/scripts/server-admin.mjs +25 -3
- package/scripts/server-bootstrap.mjs +55 -9
- package/scripts/server-init.mjs +88 -10
- package/scripts/service.mjs +39 -14
- package/service/ombre/LICENSE +21 -0
- package/service/ombre/SOURCE.json +15 -0
- package/service/ombre/controlled_store.py +295 -0
- package/service/ombre/harrier_profile.py +320 -0
- package/service/ombre/protocol.py +67 -0
- package/service/ombre/requirements.lock.txt +1100 -0
- package/service/ombre/semantic.py +449 -0
- package/service/ombre/service.py +204 -0
- package/src/accounts.mjs +373 -0
- package/src/admin-auth.mjs +246 -0
- package/src/admin.mjs +285 -0
- package/src/attachment-access.mjs +57 -0
- package/src/attention.mjs +140 -0
- package/src/bot-node.mjs +839 -48
- package/src/bot-work-policy.mjs +77 -0
- package/src/bot-work.mjs +276 -0
- package/src/budget.mjs +22 -7
- package/src/collaboration.mjs +178 -0
- package/src/contact-book.mjs +206 -0
- package/src/core/attachment-routes.mjs +43 -0
- package/src/core/bot-routes.mjs +37 -0
- package/src/core/node-routes.mjs +51 -0
- package/src/core/room-routes.mjs +285 -0
- package/src/core/router.mjs +31 -0
- package/src/core/session-routes.mjs +58 -0
- package/src/core.mjs +139 -356
- package/src/decision-provider.mjs +128 -0
- package/src/file-formats.mjs +1 -1
- package/src/governance.mjs +350 -0
- package/src/http-json.mjs +19 -0
- package/src/identity.mjs +100 -0
- package/src/kernel-control.mjs +374 -0
- package/src/kernel-node-client.mjs +162 -0
- package/src/matrix-client.mjs +70 -13
- package/src/media.mjs +50 -28
- package/src/mentions.mjs +28 -8
- package/src/message-context.mjs +105 -0
- package/src/model-config.mjs +51 -0
- package/src/model-failure.mjs +5 -0
- package/src/native-bot-catalog.mjs +75 -0
- package/src/native-request.mjs +42 -0
- package/src/node-auth.mjs +60 -0
- package/src/node-delivery.mjs +2 -2
- package/src/node-files.mjs +29 -7
- package/src/node-store.mjs +581 -13
- package/src/node-work.mjs +43 -0
- package/src/participant-labels.mjs +9 -0
- package/src/push.mjs +23 -3
- package/src/room-media.mjs +122 -0
- package/src/synapse-control.mjs +409 -0
- package/src/tasks.mjs +19 -5
- package/src/verified-media.mjs +283 -0
- package/src/web-mode.mjs +9 -0
- package/vendor/ds-bot/NOTICE +86 -0
- package/vendor/ds-bot/UPSTREAM.json +83 -5
- package/vendor/ds-bot/client.js +15079 -9868
- package/vendor/ds-bot/index.js +6 -2
- package/vendor/ds-bot/package.json +9 -4
- package/vendor/ds-bot/src/host/approvals.js +54 -7
- package/vendor/ds-bot/src/host/browser/script-child.js +136 -0
- package/vendor/ds-bot/src/host/browser/script-runner.js +77 -0
- package/vendor/ds-bot/src/host/browser/script.js +1 -0
- package/vendor/ds-bot/src/host/browser/session.js +19 -29
- package/vendor/ds-bot/src/host/capabilities.js +6 -3
- package/vendor/ds-bot/src/host/channel.js +214 -54
- package/vendor/ds-bot/src/host/computer/catalog.js +91 -0
- package/vendor/ds-bot/src/host/computer/index.js +1213 -0
- package/vendor/ds-bot/src/host/computer/leases.js +71 -0
- package/vendor/ds-bot/src/host/connectors/catalog.js +96 -0
- package/vendor/ds-bot/src/host/connectors/gateway.js +264 -0
- package/vendor/ds-bot/src/host/connectors/index.js +863 -0
- package/vendor/ds-bot/src/host/connectors/mail/index.js +613 -0
- package/vendor/ds-bot/src/host/connectors/mail/presets.js +23 -0
- package/vendor/ds-bot/src/host/connectors/mail/transport.js +306 -0
- package/vendor/ds-bot/src/host/connectors/oauth.js +191 -0
- package/vendor/ds-bot/src/host/constants.js +1 -1
- package/vendor/ds-bot/src/host/context-failure.js +11 -0
- package/vendor/ds-bot/src/host/delivery.js +6 -3
- package/vendor/ds-bot/src/host/feed.js +10 -3
- package/vendor/ds-bot/src/host/groups.js +58 -16
- package/vendor/ds-bot/src/host/home-lock.js +103 -35
- package/vendor/ds-bot/src/host/im/format.js +190 -0
- package/vendor/ds-bot/src/host/im/index.js +943 -0
- package/vendor/ds-bot/src/host/im/platforms/dingtalk.js +207 -0
- package/vendor/ds-bot/src/host/im/platforms/discord.js +234 -0
- package/vendor/ds-bot/src/host/im/platforms/feishu.js +352 -0
- package/vendor/ds-bot/src/host/im/platforms/index.js +12 -0
- package/vendor/ds-bot/src/host/im/platforms/qq.js +216 -0
- package/vendor/ds-bot/src/host/im/platforms/slack.js +210 -0
- package/vendor/ds-bot/src/host/im/platforms/telegram.js +249 -0
- package/vendor/ds-bot/src/host/im/platforms/wecom.js +217 -0
- package/vendor/ds-bot/src/host/im/platforms/weixin.js +256 -0
- package/vendor/ds-bot/src/host/images.js +22 -7
- package/vendor/ds-bot/src/host/learning.js +27 -7
- package/vendor/ds-bot/src/host/legacy.mjs +4 -0
- package/vendor/ds-bot/src/host/local-agents/acp.js +232 -0
- package/vendor/ds-bot/src/host/local-agents/adapter.js +540 -0
- package/vendor/ds-bot/src/host/local-agents/claude.js +179 -0
- package/vendor/ds-bot/src/host/local-agents/codex.js +175 -0
- package/vendor/ds-bot/src/host/local-agents/discover.js +99 -0
- package/vendor/ds-bot/src/host/local-agents/engines.js +65 -0
- package/vendor/ds-bot/src/host/local-agents/index.js +235 -0
- package/vendor/ds-bot/src/host/local-agents/jsonrpc.js +111 -0
- package/vendor/ds-bot/src/host/local-agents/mcp.js +141 -0
- package/vendor/ds-bot/src/host/memory.js +14 -1
- package/vendor/ds-bot/src/host/message-source.js +56 -0
- package/vendor/ds-bot/src/host/parts.js +259 -48
- package/vendor/ds-bot/src/host/providers.js +142 -17
- package/vendor/ds-bot/src/host/resume.js +54 -4
- package/vendor/ds-bot/src/host/roster.js +25 -3
- package/vendor/ds-bot/src/host/schedules.js +101 -7
- package/vendor/ds-bot/src/host/steward.js +2 -1
- package/vendor/ds-bot/src/host/store.js +52 -5
- package/vendor/ds-bot/src/host/tools.js +102 -15
- package/vendor/ds-bot/src/host/turns.js +28 -5
- package/vendor/ds-bot/src/host/update.js +3 -0
- package/vendor/ds-bot/src/shared/im-platforms.js +86 -0
- package//346/250/241/345/236/213/351/205/215/347/275/256/344/270/216/350/277/201/347/247/273.md +66 -0
- package/dist/web/assets/apple-touch-icon-BVvy03qx.png +0 -0
- package/dist/web/assets/icon-C8lhqe5n.svg +0 -6
- package/dist/web/assets/index-D2MsIF_C.js +0 -20
- package/dist/web/assets/index-DpwihgYi.css +0 -1
- package/dist/web/icons/icon.svg +0 -6
- package/vendor/ds-bot/README.md +0 -258
package/src/accounts.mjs
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { chmod, mkdir, readFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import { MatrixClient } from './matrix-client.mjs';
|
|
6
|
+
|
|
7
|
+
const failure = (status, message) => Object.assign(new Error(message), { status });
|
|
8
|
+
const publicPerson = ({ id, localpart, name, kind, ownerId }) => ({ id, localpart, name, kind,
|
|
9
|
+
...(kind === 'bot' ? { ownerId } : {}) });
|
|
10
|
+
function accountInput(value) {
|
|
11
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw failure(400, 'Account details must be an object');
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const SESSION_CACHE_MS = 15000;
|
|
16
|
+
|
|
17
|
+
/** Persistent local identities. Matrix owns passwords and browser sessions. */
|
|
18
|
+
|
|
19
|
+
export class AccountService {
|
|
20
|
+
constructor({ setup, config = {}, dataRoot, onParticipant, registrationSecret, clientFactory } = {}) {
|
|
21
|
+
this.setup = setup;
|
|
22
|
+
this.config = config;
|
|
23
|
+
this.dataRoot = dataRoot;
|
|
24
|
+
this.onParticipant = onParticipant;
|
|
25
|
+
this.registrationSecret = registrationSecret;
|
|
26
|
+
this.clientFactory = clientFactory || (accessToken => new MatrixClient({ baseUrl: setup.homeserverUrl, accessToken }));
|
|
27
|
+
this.serverName = setup.serverName || setup.participants[0]?.id.split(':').slice(1).join(':');
|
|
28
|
+
this.mode = config.registrationMode ?? 'open';
|
|
29
|
+
if (!['open', 'closed'].includes(this.mode)) throw new Error('registrationMode must be open or closed');
|
|
30
|
+
this.operations = new Map();
|
|
31
|
+
this.sessions = new Map();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async initialize() {
|
|
35
|
+
await mkdir(this.dataRoot, { recursive: true, mode: 0o700 });
|
|
36
|
+
try {
|
|
37
|
+
const metadata = JSON.parse(await readFile(path.join(this.dataRoot, 'server.json'), 'utf8'));
|
|
38
|
+
if (this.serverName && metadata.serverName && metadata.serverName !== this.serverName) throw new Error('Account registration belongs to another Matrix server');
|
|
39
|
+
this.serverName ||= metadata.serverName;
|
|
40
|
+
this.registrationSecret ??= metadata.registrationSecret;
|
|
41
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
42
|
+
const filename = path.join(this.dataRoot, 'accounts.sqlite');
|
|
43
|
+
this.db = new DatabaseSync(filename);
|
|
44
|
+
try { return await this.#initializeDatabase(filename); }
|
|
45
|
+
catch (error) { this.close(); throw error; }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async #initializeDatabase(filename) {
|
|
49
|
+
await chmod(filename, 0o600);
|
|
50
|
+
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
|
|
51
|
+
CREATE TABLE IF NOT EXISTS account_metadata (key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
|
52
|
+
CREATE TABLE IF NOT EXISTS accounts (
|
|
53
|
+
user_id TEXT PRIMARY KEY, localpart TEXT UNIQUE NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL,
|
|
54
|
+
owner_id TEXT, status TEXT NOT NULL, service_token TEXT, service_device_id TEXT,
|
|
55
|
+
recovery_password TEXT, registration_hash TEXT, last_error TEXT,
|
|
56
|
+
created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
|
|
57
|
+
);
|
|
58
|
+
CREATE TABLE IF NOT EXISTS bot_creation_requests (
|
|
59
|
+
request_key TEXT PRIMARY KEY, input_hash TEXT NOT NULL, user_id TEXT NOT NULL
|
|
60
|
+
);
|
|
61
|
+
CREATE TABLE IF NOT EXISTS account_subjects (
|
|
62
|
+
user_id TEXT PRIMARY KEY, subject_id TEXT UNIQUE NOT NULL, created_at INTEGER NOT NULL
|
|
63
|
+
);`);
|
|
64
|
+
const identityVersion = this.db.prepare("SELECT value FROM account_metadata WHERE key='identitySchemaVersion'").get()?.value;
|
|
65
|
+
if (identityVersion !== undefined && identityVersion !== '1') throw new Error('Unsupported account identity schema version');
|
|
66
|
+
const storedServer = this.db.prepare("SELECT value FROM account_metadata WHERE key='serverName'").get()?.value;
|
|
67
|
+
if (storedServer && this.serverName && storedServer !== this.serverName) throw new Error('Account database belongs to another Matrix server');
|
|
68
|
+
this.serverName ||= storedServer;
|
|
69
|
+
if (this.serverName) {
|
|
70
|
+
this.setup.serverName = this.serverName;
|
|
71
|
+
this.db.prepare("INSERT OR IGNORE INTO account_metadata VALUES ('serverName',?)").run(this.serverName);
|
|
72
|
+
}
|
|
73
|
+
this.db.prepare("INSERT OR IGNORE INTO account_metadata VALUES ('authorityId',?)").run(`urn:uuid:${randomUUID()}`);
|
|
74
|
+
this.authorityId = this.db.prepare("SELECT value FROM account_metadata WHERE key='authorityId'").get().value;
|
|
75
|
+
const seedOwner = this.setup.participants.find(person => person.kind === 'human')?.id;
|
|
76
|
+
if (seedOwner) this.db.prepare("INSERT OR IGNORE INTO account_metadata VALUES ('ownerId',?)").run(seedOwner);
|
|
77
|
+
this.ownerId = this.db.prepare("SELECT value FROM account_metadata WHERE key='ownerId'").get()?.value;
|
|
78
|
+
for (const person of this.setup.participants) {
|
|
79
|
+
if (!['human', 'bot'].includes(person.kind) || person.id !== `@${person.localpart}:${this.serverName}`) {
|
|
80
|
+
throw new Error('Account registry must contain complete identities on its own Matrix server');
|
|
81
|
+
}
|
|
82
|
+
const existing = this.row(person.id);
|
|
83
|
+
if (existing && existing.kind !== person.kind) throw new Error('An existing account cannot change identity kind');
|
|
84
|
+
this.db.prepare(`INSERT OR IGNORE INTO accounts
|
|
85
|
+
(user_id,localpart,name,kind,owner_id,status,service_token,created_at,updated_at) VALUES (?,?,?,?,?,'active',?,?,?)`)
|
|
86
|
+
.run(person.id, person.localpart, person.name, person.kind, person.kind === 'bot' ? person.ownerId || this.ownerId : null,
|
|
87
|
+
person.accessToken || null, Date.now(), Date.now());
|
|
88
|
+
}
|
|
89
|
+
// Additive migration: neither Matrix accounts nor owner/node bindings are replaced.
|
|
90
|
+
for (const row of this.db.prepare("SELECT user_id FROM accounts WHERE status='active'").all()) this.ensureSubject(row.user_id);
|
|
91
|
+
this.db.prepare("INSERT OR REPLACE INTO account_metadata VALUES ('identitySchemaVersion','1')").run();
|
|
92
|
+
this.refreshSetup();
|
|
93
|
+
return this;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
registration() { return { enabled: this.mode === 'open' && Boolean(this.serverName && this.registrationSecret), mode: this.mode }; }
|
|
97
|
+
|
|
98
|
+
row(userId) { return this.db.prepare('SELECT * FROM accounts WHERE user_id=?').get(userId); }
|
|
99
|
+
|
|
100
|
+
ensureSubject(userId) {
|
|
101
|
+
this.db.prepare('INSERT OR IGNORE INTO account_subjects VALUES (?,?,?)').run(userId, randomUUID(), Date.now());
|
|
102
|
+
return this.db.prepare('SELECT subject_id FROM account_subjects WHERE user_id=?').get(userId).subject_id;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
identity(userId) {
|
|
106
|
+
const row = this.row(userId);
|
|
107
|
+
if (!row) throw failure(403, 'A registered account is required');
|
|
108
|
+
const owner = row.owner_id && this.row(row.owner_id);
|
|
109
|
+
return { authorityId: this.authorityId, subjectId: this.ensureSubject(userId), matrixUserId: userId, kind: row.kind,
|
|
110
|
+
...(row.owner_id ? { ownerMatrixUserId: row.owner_id, ...(owner?.kind === 'human' ? { ownerSubjectId: this.ensureSubject(row.owner_id) } : {}) } : {}) };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
assertActive(userId) {
|
|
114
|
+
if (this.row(userId)?.status !== 'active') throw Object.assign(failure(403, 'This account is not active on its home server'), { code: 'ACCOUNT_INACTIVE' });
|
|
115
|
+
return userId;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// Matrix owns token validity; a short cache avoids one whoami round trip per API call.
|
|
119
|
+
async authenticate(token) {
|
|
120
|
+
const now = Date.now();
|
|
121
|
+
let cached = this.sessions.get(token);
|
|
122
|
+
if (!cached || cached.expires <= now) {
|
|
123
|
+
if (this.sessions.size > 1000) for (const [key, value] of this.sessions) if (value.expires <= now) this.sessions.delete(key);
|
|
124
|
+
cached = { result: await this.clientFactory(token).whoami(), expires: now + SESSION_CACHE_MS };
|
|
125
|
+
this.sessions.set(token, cached);
|
|
126
|
+
}
|
|
127
|
+
this.assertActive(cached.result.user_id);
|
|
128
|
+
return cached.result;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
session(session) {
|
|
132
|
+
this.assertActive(session.user_id);
|
|
133
|
+
return { ...session, identity: this.identity(session.user_id), ...(this.home ? { home: this.home } : {}) };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
participant(row) {
|
|
137
|
+
return { id: row.user_id, localpart: row.localpart, name: row.name, kind: row.kind,
|
|
138
|
+
...(row.owner_id ? { ownerId: row.owner_id } : {}), ...(row.service_token ? { accessToken: row.service_token } : {}) };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
refreshSetup() {
|
|
142
|
+
const existing = new Map(this.setup.participants.map(person => [person.id, person]));
|
|
143
|
+
const people = this.db.prepare("SELECT * FROM accounts WHERE status='active' ORDER BY created_at,rowid").all()
|
|
144
|
+
.map(row => ({ ...existing.get(row.user_id), ...this.participant(row) }));
|
|
145
|
+
this.setup.participants.splice(0, this.setup.participants.length, ...people);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
person(userId) { return this.setup.participants.find(person => person.id === userId); }
|
|
149
|
+
publicParticipants() { return this.setup.participants.map(publicPerson); }
|
|
150
|
+
ownedBots(userId) { return this.setup.participants.filter(person => person.kind === 'bot' && person.ownerId === userId).map(publicPerson); }
|
|
151
|
+
|
|
152
|
+
human(userId) {
|
|
153
|
+
this.assertActive(userId);
|
|
154
|
+
const person = this.person(userId);
|
|
155
|
+
if (person?.kind !== 'human') throw failure(403, 'A registered human account is required');
|
|
156
|
+
return person;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async publish(userId) {
|
|
160
|
+
this.refreshSetup();
|
|
161
|
+
const person = this.person(userId);
|
|
162
|
+
await this.onParticipant?.(person);
|
|
163
|
+
return person;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
normalizeUsername(value) {
|
|
167
|
+
if (!this.serverName) throw failure(503, 'This server has no Matrix account identity configured');
|
|
168
|
+
if (typeof value !== 'string') throw failure(400, 'Choose an account name');
|
|
169
|
+
let localpart = value.trim();
|
|
170
|
+
if (localpart.startsWith('@')) {
|
|
171
|
+
const suffix = `:${this.serverName}`;
|
|
172
|
+
if (!localpart.endsWith(suffix)) throw failure(400, 'Use an account on this server');
|
|
173
|
+
localpart = localpart.slice(1, -suffix.length);
|
|
174
|
+
}
|
|
175
|
+
if (!/^[a-z0-9][a-z0-9._=-]{0,63}$/.test(localpart)) throw failure(400, 'Account names use 1–64 lowercase letters, digits, dots, underscores, equals or hyphens');
|
|
176
|
+
return localpart;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
password(value) {
|
|
180
|
+
if (typeof value !== 'string' || !value || value.length > 1024 || value.includes('\0')) throw failure(400, 'Enter a password of 1–1024 characters');
|
|
181
|
+
return value;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
displayName(value) {
|
|
185
|
+
if (typeof value !== 'string' || !value.trim() || value.trim().length > 80 || /[\u0000-\u001f]/.test(value)) throw failure(400, 'Choose a display name of 1–80 characters');
|
|
186
|
+
return value.trim();
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async serialize(key, work) {
|
|
190
|
+
const previous = this.operations.get(key);
|
|
191
|
+
if (previous) return previous;
|
|
192
|
+
const promise = Promise.resolve().then(work);
|
|
193
|
+
this.operations.set(key, promise);
|
|
194
|
+
try { return await promise; }
|
|
195
|
+
finally { this.operations.delete(key); }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async passwordLogin(userId, password, service = false, clientIp) {
|
|
199
|
+
const deviceId = service ? `DSCORD_CORE_${createHash('sha256').update(userId).digest('hex').slice(0, 24)}` : `DSCORD_${randomUUID()}`;
|
|
200
|
+
const session = await this.clientFactory().request('POST', '/_matrix/client/v3/login', {
|
|
201
|
+
type: 'm.login.password', identifier: { type: 'm.id.user', user: userId }, password,
|
|
202
|
+
device_id: deviceId, initial_device_display_name: service ? 'DSCord server' : 'DSCord client',
|
|
203
|
+
}, { clientIp });
|
|
204
|
+
if (session.user_id !== userId || !session.access_token) throw failure(502, 'Matrix returned another account identity');
|
|
205
|
+
return session;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async saveServiceSession(userId, session) {
|
|
209
|
+
this.db.prepare('UPDATE accounts SET service_token=?,service_device_id=?,updated_at=? WHERE user_id=?')
|
|
210
|
+
.run(session.access_token, session.device_id || null, Date.now(), userId);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async ensureServiceSession(userId, password, clientIp) {
|
|
214
|
+
const row = this.row(userId);
|
|
215
|
+
if (row?.service_token) {
|
|
216
|
+
try {
|
|
217
|
+
if ((await this.clientFactory(row.service_token).whoami()).user_id === userId) return;
|
|
218
|
+
} catch (error) { if (![401, 403].includes(error.status)) throw error; }
|
|
219
|
+
}
|
|
220
|
+
await this.saveServiceSession(userId, await this.passwordLogin(userId, password, true, clientIp));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async joinInitialRoom(userId) {
|
|
224
|
+
if (!this.setup.roomId || userId === this.ownerId || this.row(userId).kind === 'bot') return;
|
|
225
|
+
const person = this.row(userId);
|
|
226
|
+
const client = this.clientFactory(person.service_token);
|
|
227
|
+
const { joined_rooms: joined = [] } = await client.request('GET', '/_matrix/client/v3/joined_rooms');
|
|
228
|
+
if (joined.includes(this.setup.roomId)) return;
|
|
229
|
+
const owner = this.row(this.ownerId);
|
|
230
|
+
if (!owner?.service_token) throw failure(503, 'The server owner must sign in before new members can join');
|
|
231
|
+
await this.clientFactory(owner.service_token).request('POST', `/_matrix/client/v3/rooms/${encodeURIComponent(this.setup.roomId)}/invite`, { user_id: userId });
|
|
232
|
+
await client.join(this.setup.roomId);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async activate(userId) {
|
|
236
|
+
if (['disabled', 'deactivated'].includes(this.row(userId)?.status)) throw failure(403, 'This account is disabled');
|
|
237
|
+
this.ensureSubject(userId);
|
|
238
|
+
this.db.prepare("UPDATE accounts SET status='active',last_error=NULL,updated_at=? WHERE user_id=?").run(Date.now(), userId);
|
|
239
|
+
if (!this.ownerId && this.row(userId).kind === 'human') {
|
|
240
|
+
this.db.prepare("INSERT OR IGNORE INTO account_metadata VALUES ('ownerId',?)").run(userId);
|
|
241
|
+
this.ownerId = this.db.prepare("SELECT value FROM account_metadata WHERE key='ownerId'").get().value;
|
|
242
|
+
}
|
|
243
|
+
return this.publish(userId);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async provision(userId, password, clientIp) {
|
|
247
|
+
const row = this.row(userId);
|
|
248
|
+
if (['disabled', 'deactivated'].includes(row?.status)) throw failure(403, 'This account is disabled');
|
|
249
|
+
try {
|
|
250
|
+
if (!row.service_token) {
|
|
251
|
+
const recovering = Boolean(row.last_error);
|
|
252
|
+
this.db.prepare("UPDATE accounts SET last_error='REGISTRATION_STARTED' WHERE user_id=?").run(userId);
|
|
253
|
+
const anonymous = this.clientFactory();
|
|
254
|
+
const { nonce } = await anonymous.request('GET', '/_synapse/admin/v1/register', undefined, { clientIp });
|
|
255
|
+
const mac = createHmac('sha1', this.registrationSecret).update([nonce, row.localpart, password, 'notadmin'].join('\0')).digest('hex');
|
|
256
|
+
let session;
|
|
257
|
+
try {
|
|
258
|
+
session = await anonymous.request('POST', '/_synapse/admin/v1/register', {
|
|
259
|
+
nonce, username: row.localpart, password, displayname: row.name, admin: false, mac,
|
|
260
|
+
}, { clientIp });
|
|
261
|
+
} catch (error) {
|
|
262
|
+
if (error.errcode !== 'M_USER_IN_USE') throw error;
|
|
263
|
+
if (!recovering) throw Object.assign(failure(409, 'This Matrix account already exists. Sign in to continue'), { code: 'ACCOUNT_EXISTS' });
|
|
264
|
+
// A previous attempt may have reached Matrix before its response was lost.
|
|
265
|
+
session = await this.passwordLogin(userId, password, true, clientIp);
|
|
266
|
+
}
|
|
267
|
+
if (session.user_id !== userId || !session.access_token) throw failure(502, 'Matrix returned another account identity');
|
|
268
|
+
await this.saveServiceSession(userId, session);
|
|
269
|
+
} else await this.ensureServiceSession(userId, password, clientIp);
|
|
270
|
+
const client = this.clientFactory(this.row(userId).service_token);
|
|
271
|
+
await client.request('PUT', `/_matrix/client/v3/profile/${encodeURIComponent(userId)}/displayname`, { displayname: row.name });
|
|
272
|
+
await this.joinInitialRoom(userId);
|
|
273
|
+
return await this.activate(userId);
|
|
274
|
+
} catch (error) {
|
|
275
|
+
this.db.prepare('UPDATE accounts SET last_error=?,updated_at=? WHERE user_id=?').run(error.code || error.errcode || 'PROVISIONING_PENDING', Date.now(), userId);
|
|
276
|
+
throw error;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async register(input = {}, { clientIp } = {}) {
|
|
281
|
+
accountInput(input);
|
|
282
|
+
if (!this.registration().enabled) throw failure(403, this.mode === 'closed' ? 'Registration is closed on this server' : 'This server has no account registration configuration');
|
|
283
|
+
const localpart = this.normalizeUsername(input.username);
|
|
284
|
+
const password = this.password(input.password);
|
|
285
|
+
const name = this.displayName(input.displayName ?? localpart);
|
|
286
|
+
const userId = `@${localpart}:${this.serverName}`;
|
|
287
|
+
const hash = createHmac('sha256', this.registrationSecret).update(JSON.stringify([localpart, name, password])).digest('hex');
|
|
288
|
+
const previous = this.row(userId);
|
|
289
|
+
if (['disabled', 'deactivated'].includes(previous?.status)) throw failure(403, 'This account is disabled');
|
|
290
|
+
if (previous && (previous.kind !== 'human' || previous.registration_hash !== hash || previous.status === 'active' || previous.last_error === 'ACCOUNT_EXISTS')) throw failure(409, 'This account name is already in use. Sign in to continue');
|
|
291
|
+
if (!previous) this.db.prepare(`INSERT INTO accounts
|
|
292
|
+
(user_id,localpart,name,kind,status,registration_hash,created_at,updated_at) VALUES (?,?,?,'human','provisioning',?,?,?)`)
|
|
293
|
+
.run(userId, localpart, name, hash, Date.now(), Date.now());
|
|
294
|
+
await this.serialize(userId, () => this.provision(userId, password, clientIp));
|
|
295
|
+
return this.session(await this.passwordLogin(userId, password, false, clientIp));
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async login(input = {}, { clientIp } = {}) {
|
|
299
|
+
accountInput(input);
|
|
300
|
+
const localpart = this.normalizeUsername(input.user);
|
|
301
|
+
const password = this.password(input.password);
|
|
302
|
+
const userId = `@${localpart}:${this.serverName}`;
|
|
303
|
+
const previous = this.row(userId);
|
|
304
|
+
if (previous?.kind === 'bot') throw failure(403, 'Sign in with a human account');
|
|
305
|
+
if (['disabled', 'deactivated'].includes(previous?.status)) throw failure(403, 'This account is disabled');
|
|
306
|
+
const session = await this.passwordLogin(userId, password, false, clientIp);
|
|
307
|
+
try {
|
|
308
|
+
await this.serialize(userId, async () => {
|
|
309
|
+
const current = this.row(userId);
|
|
310
|
+
if (!current || current.last_error === 'ACCOUNT_EXISTS') {
|
|
311
|
+
const profile = await this.clientFactory(session.access_token).request('GET', `/_matrix/client/v3/profile/${encodeURIComponent(userId)}/displayname`);
|
|
312
|
+
this.db.prepare(`INSERT INTO accounts (user_id,localpart,name,kind,status,created_at,updated_at)
|
|
313
|
+
VALUES (?,?,?,'human','provisioning',?,?) ON CONFLICT(user_id) DO UPDATE SET name=excluded.name`)
|
|
314
|
+
.run(userId, localpart, profile.displayname || localpart, Date.now(), Date.now());
|
|
315
|
+
}
|
|
316
|
+
await this.ensureServiceSession(userId, password, clientIp);
|
|
317
|
+
await this.joinInitialRoom(userId);
|
|
318
|
+
await this.activate(userId);
|
|
319
|
+
});
|
|
320
|
+
return this.session(session);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
await this.clientFactory(session.access_token).request('POST', '/_matrix/client/v3/logout', {}).catch(() => {});
|
|
323
|
+
throw error;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async me(token) {
|
|
328
|
+
const { user_id: userId } = await this.authenticate(token);
|
|
329
|
+
return { user: publicPerson(this.human(userId)), ownedBots: this.ownedBots(userId), identity: this.identity(userId),
|
|
330
|
+
...(this.home ? { home: this.home } : {}) };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async logout(token) {
|
|
334
|
+
this.sessions.delete(token);
|
|
335
|
+
// Synthetic demo credentials are also the Core service credential. They are never revoked here.
|
|
336
|
+
if (this.setup.participants.some(person => person.accessToken === token)) return { loggedOut: true, localOnly: true };
|
|
337
|
+
try { await this.clientFactory(token).request('POST', '/_matrix/client/v3/logout', {}); }
|
|
338
|
+
catch (error) { if (error.status !== 401) throw error; }
|
|
339
|
+
return { loggedOut: true };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async createBot(userId, input = {}) {
|
|
343
|
+
accountInput(input);
|
|
344
|
+
this.human(userId);
|
|
345
|
+
if (!this.registrationSecret) throw failure(503, 'This server has no Bot account registration configuration');
|
|
346
|
+
const name = this.displayName(input.name);
|
|
347
|
+
const requestId = input.requestId ?? randomUUID();
|
|
348
|
+
if (typeof requestId !== 'string' || !/^[a-zA-Z0-9_.:-]{1,200}$/.test(requestId)) throw failure(400, 'Invalid Bot creation request ID');
|
|
349
|
+
const key = JSON.stringify([userId, requestId]);
|
|
350
|
+
const hash = createHash('sha256').update(name).digest('hex');
|
|
351
|
+
let request = this.db.prepare('SELECT * FROM bot_creation_requests WHERE request_key=?').get(key);
|
|
352
|
+
if (request && request.input_hash !== hash) throw failure(409, 'This Bot creation request belongs to another name');
|
|
353
|
+
if (!request) {
|
|
354
|
+
const localpart = `bot-${randomUUID()}`;
|
|
355
|
+
const botId = `@${localpart}:${this.serverName}`;
|
|
356
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
357
|
+
try {
|
|
358
|
+
this.db.prepare(`INSERT INTO accounts
|
|
359
|
+
(user_id,localpart,name,kind,owner_id,status,recovery_password,created_at,updated_at) VALUES (?,?,?,'bot',?,'provisioning',?,?,?)`)
|
|
360
|
+
.run(botId, localpart, name, userId, randomBytes(32).toString('base64url'), Date.now(), Date.now());
|
|
361
|
+
this.db.prepare('INSERT INTO bot_creation_requests VALUES (?,?,?)').run(key, hash, botId);
|
|
362
|
+
this.db.exec('COMMIT');
|
|
363
|
+
} catch (error) { this.db.exec('ROLLBACK'); throw error; }
|
|
364
|
+
request = { user_id: botId };
|
|
365
|
+
}
|
|
366
|
+
const row = this.row(request.user_id);
|
|
367
|
+
if (row.status === 'active') return publicPerson(this.person(row.user_id));
|
|
368
|
+
const person = await this.serialize(row.user_id, () => this.provision(row.user_id, row.recovery_password));
|
|
369
|
+
return publicPerson(person);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
close() { this.db?.close(); this.db = null; }
|
|
373
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import {
|
|
3
|
+
randomBytes,
|
|
4
|
+
scrypt as scryptCallback,
|
|
5
|
+
timingSafeEqual,
|
|
6
|
+
createHash,
|
|
7
|
+
} from "node:crypto";
|
|
8
|
+
import { promisify } from "node:util";
|
|
9
|
+
import { mkdir, chmod } from "node:fs/promises";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { policyError } from "./governance.mjs";
|
|
12
|
+
|
|
13
|
+
const scrypt = promisify(scryptCallback);
|
|
14
|
+
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
15
|
+
const roles = new Set(["owner", "operator", "auditor"]);
|
|
16
|
+
const username = (value) => {
|
|
17
|
+
if (typeof value !== "string" || !/^[a-z][a-z0-9_.-]{2,63}$/.test(value))
|
|
18
|
+
throw policyError(
|
|
19
|
+
400,
|
|
20
|
+
"Administrator name must use 3–64 lowercase letters, digits, dots or hyphens",
|
|
21
|
+
);
|
|
22
|
+
return value;
|
|
23
|
+
};
|
|
24
|
+
async function passwordHash(password, salt) {
|
|
25
|
+
if (
|
|
26
|
+
typeof password !== "string" ||
|
|
27
|
+
password.length < 12 ||
|
|
28
|
+
password.length > 512
|
|
29
|
+
)
|
|
30
|
+
throw policyError(
|
|
31
|
+
400,
|
|
32
|
+
"Use an administrator password of 12–512 characters",
|
|
33
|
+
);
|
|
34
|
+
return Buffer.from(
|
|
35
|
+
await scrypt(password, salt, 64, { N: 16384, r: 8, p: 1 }),
|
|
36
|
+
).toString("hex");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Purpose-specific, instance-local credentials. Matrix tokens are never accepted here. */
|
|
40
|
+
export class AdminAuth {
|
|
41
|
+
constructor(dataRoot) {
|
|
42
|
+
this.filename = path.join(dataRoot, "administrators.sqlite");
|
|
43
|
+
this.mutations = Promise.resolve();
|
|
44
|
+
}
|
|
45
|
+
async initialize() {
|
|
46
|
+
await mkdir(path.dirname(this.filename), { recursive: true, mode: 0o700 });
|
|
47
|
+
this.db = new DatabaseSync(this.filename);
|
|
48
|
+
await chmod(this.filename, 0o600);
|
|
49
|
+
this.db
|
|
50
|
+
.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
|
|
51
|
+
CREATE TABLE IF NOT EXISTS administrators (username TEXT PRIMARY KEY,role TEXT NOT NULL,salt TEXT NOT NULL,password_hash TEXT NOT NULL,enabled INTEGER NOT NULL,created_at INTEGER NOT NULL);
|
|
52
|
+
CREATE TABLE IF NOT EXISTS admin_sessions (token_hash TEXT PRIMARY KEY,username TEXT NOT NULL,expires_at INTEGER NOT NULL,last_seen INTEGER NOT NULL);
|
|
53
|
+
CREATE TABLE IF NOT EXISTS admin_login_limits (scope TEXT PRIMARY KEY,failures INTEGER NOT NULL,reset_at INTEGER NOT NULL);
|
|
54
|
+
CREATE TABLE IF NOT EXISTS admin_audit (sequence INTEGER PRIMARY KEY AUTOINCREMENT,at INTEGER NOT NULL,actor TEXT NOT NULL,action TEXT NOT NULL,detail TEXT NOT NULL);`);
|
|
55
|
+
return this;
|
|
56
|
+
}
|
|
57
|
+
audit(actor, action, detail = {}) {
|
|
58
|
+
this.db
|
|
59
|
+
.prepare(
|
|
60
|
+
"INSERT INTO admin_audit(at,actor,action,detail) VALUES(?,?,?,?)",
|
|
61
|
+
)
|
|
62
|
+
.run(Date.now(), actor, action, JSON.stringify(detail));
|
|
63
|
+
}
|
|
64
|
+
list() {
|
|
65
|
+
return this.db
|
|
66
|
+
.prepare(
|
|
67
|
+
"SELECT username,role,enabled,created_at AS createdAt FROM administrators ORDER BY username",
|
|
68
|
+
)
|
|
69
|
+
.all()
|
|
70
|
+
.map((row) => ({ ...row, enabled: Boolean(row.enabled) }));
|
|
71
|
+
}
|
|
72
|
+
change(actor, input, { bootstrap = false } = {}) {
|
|
73
|
+
const operation = this.mutations
|
|
74
|
+
.catch(() => {})
|
|
75
|
+
.then(async () => {
|
|
76
|
+
const name = username(input.username);
|
|
77
|
+
if (!roles.has(input.role) || typeof input.enabled !== "boolean")
|
|
78
|
+
throw policyError(400, "Invalid administrator role or state");
|
|
79
|
+
if (bootstrap && this.list().length)
|
|
80
|
+
throw policyError(409, "This instance already has an administrator");
|
|
81
|
+
const previous = this.db
|
|
82
|
+
.prepare("SELECT * FROM administrators WHERE username=?")
|
|
83
|
+
.get(name);
|
|
84
|
+
if (
|
|
85
|
+
previous?.role === "owner" &&
|
|
86
|
+
previous.enabled &&
|
|
87
|
+
(input.role !== "owner" || !input.enabled) &&
|
|
88
|
+
this.list().filter((row) => row.enabled && row.role === "owner")
|
|
89
|
+
.length < 2
|
|
90
|
+
)
|
|
91
|
+
throw policyError(409, "Keep at least one active owner");
|
|
92
|
+
const salt =
|
|
93
|
+
input.password !== undefined
|
|
94
|
+
? randomBytes(32).toString("hex")
|
|
95
|
+
: previous?.salt;
|
|
96
|
+
const encoded =
|
|
97
|
+
input.password !== undefined
|
|
98
|
+
? await passwordHash(input.password, salt)
|
|
99
|
+
: previous?.password_hash;
|
|
100
|
+
if (!encoded)
|
|
101
|
+
throw policyError(
|
|
102
|
+
400,
|
|
103
|
+
"A password is required for a new administrator",
|
|
104
|
+
);
|
|
105
|
+
this.db
|
|
106
|
+
.prepare(
|
|
107
|
+
`INSERT INTO administrators VALUES(?,?,?,?,?,?) ON CONFLICT(username) DO UPDATE SET
|
|
108
|
+
role=excluded.role,salt=excluded.salt,password_hash=excluded.password_hash,enabled=excluded.enabled`,
|
|
109
|
+
)
|
|
110
|
+
.run(
|
|
111
|
+
name,
|
|
112
|
+
input.role,
|
|
113
|
+
salt,
|
|
114
|
+
encoded,
|
|
115
|
+
Number(input.enabled),
|
|
116
|
+
Date.now(),
|
|
117
|
+
);
|
|
118
|
+
this.db
|
|
119
|
+
.prepare("DELETE FROM admin_sessions WHERE username=?")
|
|
120
|
+
.run(name);
|
|
121
|
+
this.audit(actor, bootstrap ? "admin.bootstrap" : "admin.change", {
|
|
122
|
+
username: name,
|
|
123
|
+
role: input.role,
|
|
124
|
+
enabled: input.enabled,
|
|
125
|
+
passwordChanged: input.password !== undefined,
|
|
126
|
+
});
|
|
127
|
+
return this.list();
|
|
128
|
+
});
|
|
129
|
+
this.mutations = operation;
|
|
130
|
+
return operation;
|
|
131
|
+
}
|
|
132
|
+
async login(input, address) {
|
|
133
|
+
const name = typeof input.username === "string" ? input.username : "";
|
|
134
|
+
const now = Date.now();
|
|
135
|
+
const scopes = [
|
|
136
|
+
`address:${hash(address || "unknown")}`,
|
|
137
|
+
`account:${hash(name)}`,
|
|
138
|
+
];
|
|
139
|
+
for (const scope of scopes) {
|
|
140
|
+
const limit = this.db
|
|
141
|
+
.prepare("SELECT * FROM admin_login_limits WHERE scope=?")
|
|
142
|
+
.get(scope);
|
|
143
|
+
if (limit?.reset_at > now && limit.failures >= 10)
|
|
144
|
+
throw policyError(
|
|
145
|
+
429,
|
|
146
|
+
"Too many administrator login attempts; try again in 15 minutes",
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
const row = this.db
|
|
150
|
+
.prepare("SELECT * FROM administrators WHERE username=?")
|
|
151
|
+
.get(name);
|
|
152
|
+
const candidate =
|
|
153
|
+
typeof input.password === "string" &&
|
|
154
|
+
input.password.length >= 12 &&
|
|
155
|
+
input.password.length <= 512
|
|
156
|
+
? await passwordHash(
|
|
157
|
+
input.password,
|
|
158
|
+
row?.salt || "dscord-admin-unknown-account",
|
|
159
|
+
)
|
|
160
|
+
: await passwordHash(
|
|
161
|
+
"dummy-password-for-authentication",
|
|
162
|
+
"dscord-admin-unknown-account",
|
|
163
|
+
);
|
|
164
|
+
if (
|
|
165
|
+
!row?.enabled ||
|
|
166
|
+
!timingSafeEqual(
|
|
167
|
+
Buffer.from(candidate, "hex"),
|
|
168
|
+
Buffer.from(row.password_hash, "hex"),
|
|
169
|
+
)
|
|
170
|
+
) {
|
|
171
|
+
for (const scope of scopes)
|
|
172
|
+
this.db
|
|
173
|
+
.prepare(
|
|
174
|
+
`INSERT INTO admin_login_limits VALUES(?,1,?) ON CONFLICT(scope) DO UPDATE SET
|
|
175
|
+
failures=CASE WHEN reset_at<=? THEN 1 ELSE failures+1 END, reset_at=CASE WHEN reset_at<=? THEN excluded.reset_at ELSE reset_at END`,
|
|
176
|
+
)
|
|
177
|
+
.run(scope, now + 900000, now, now);
|
|
178
|
+
this.audit("unauthenticated", "admin.login_rejected", {
|
|
179
|
+
accountHash: hash(name),
|
|
180
|
+
});
|
|
181
|
+
throw policyError(401, "Administrator sign-in failed");
|
|
182
|
+
}
|
|
183
|
+
for (const scope of scopes)
|
|
184
|
+
this.db
|
|
185
|
+
.prepare("DELETE FROM admin_login_limits WHERE scope=?")
|
|
186
|
+
.run(scope);
|
|
187
|
+
const token = `dscord_admin_${randomBytes(48).toString("base64url")}`;
|
|
188
|
+
const expiresAt = now + 8 * 3600000;
|
|
189
|
+
this.db
|
|
190
|
+
.prepare("DELETE FROM admin_sessions WHERE expires_at<=? OR last_seen<=?")
|
|
191
|
+
.run(now, now - 3600000);
|
|
192
|
+
this.db
|
|
193
|
+
.prepare("INSERT INTO admin_sessions VALUES(?,?,?,?)")
|
|
194
|
+
.run(hash(token), row.username, expiresAt, now);
|
|
195
|
+
this.audit(row.username, "admin.login");
|
|
196
|
+
return {
|
|
197
|
+
access_token: token,
|
|
198
|
+
administrator: { username: row.username, role: row.role },
|
|
199
|
+
expiresAt,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
authorize(request, allowed = ["owner", "operator", "auditor"]) {
|
|
203
|
+
const header = request.headers.authorization || "";
|
|
204
|
+
if (!header.startsWith("Bearer dscord_admin_"))
|
|
205
|
+
throw policyError(401, "An instance administrator session is required");
|
|
206
|
+
const tokenHash = hash(header.slice(7));
|
|
207
|
+
const row = this.db
|
|
208
|
+
.prepare(
|
|
209
|
+
`SELECT s.*,a.role,a.enabled FROM admin_sessions s JOIN administrators a ON a.username=s.username WHERE s.token_hash=?`,
|
|
210
|
+
)
|
|
211
|
+
.get(tokenHash);
|
|
212
|
+
const now = Date.now();
|
|
213
|
+
if (
|
|
214
|
+
!row?.enabled ||
|
|
215
|
+
row.expires_at <= now ||
|
|
216
|
+
row.last_seen <= now - 3600000
|
|
217
|
+
)
|
|
218
|
+
throw policyError(401, "Administrator session expired");
|
|
219
|
+
if (!allowed.includes(row.role))
|
|
220
|
+
throw policyError(
|
|
221
|
+
403,
|
|
222
|
+
"Your administrator role cannot perform this operation",
|
|
223
|
+
);
|
|
224
|
+
this.db
|
|
225
|
+
.prepare("UPDATE admin_sessions SET last_seen=? WHERE token_hash=?")
|
|
226
|
+
.run(now, tokenHash);
|
|
227
|
+
return { username: row.username, role: row.role, tokenHash };
|
|
228
|
+
}
|
|
229
|
+
logout(actor) {
|
|
230
|
+
this.db
|
|
231
|
+
.prepare("DELETE FROM admin_sessions WHERE token_hash=?")
|
|
232
|
+
.run(actor.tokenHash);
|
|
233
|
+
this.audit(actor.username, "admin.logout");
|
|
234
|
+
}
|
|
235
|
+
events(before = Number.MAX_SAFE_INTEGER) {
|
|
236
|
+
return this.db
|
|
237
|
+
.prepare(
|
|
238
|
+
"SELECT * FROM admin_audit WHERE sequence<? ORDER BY sequence DESC LIMIT 100",
|
|
239
|
+
)
|
|
240
|
+
.all(before)
|
|
241
|
+
.map((row) => ({ ...row, detail: JSON.parse(row.detail) }));
|
|
242
|
+
}
|
|
243
|
+
close() {
|
|
244
|
+
this.db.close();
|
|
245
|
+
}
|
|
246
|
+
}
|