@stackmemoryai/stackmemory 0.3.18 → 0.3.19
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/dist/cli/claude-sm.js +51 -5
- package/dist/cli/claude-sm.js.map +2 -2
- package/dist/cli/codex-sm.js +52 -19
- package/dist/cli/codex-sm.js.map +2 -2
- package/dist/cli/commands/db.js +143 -0
- package/dist/cli/commands/db.js.map +7 -0
- package/dist/cli/commands/login.js +50 -0
- package/dist/cli/commands/login.js.map +7 -0
- package/dist/cli/commands/migrate.js +178 -0
- package/dist/cli/commands/migrate.js.map +7 -0
- package/dist/cli/commands/onboard.js +158 -2
- package/dist/cli/commands/onboard.js.map +2 -2
- package/dist/cli/index.js +5 -0
- package/dist/cli/index.js.map +2 -2
- package/dist/core/context/frame-database.js +1 -0
- package/dist/core/context/frame-database.js.map +2 -2
- package/dist/core/context/frame-manager.js +56 -2
- package/dist/core/context/frame-manager.js.map +2 -2
- package/dist/core/database/database-adapter.js +6 -1
- package/dist/core/database/database-adapter.js.map +2 -2
- package/dist/core/database/sqlite-adapter.js +60 -2
- package/dist/core/database/sqlite-adapter.js.map +2 -2
- package/dist/servers/railway/index.js +843 -82
- package/dist/servers/railway/index.js.map +3 -3
- package/package.json +8 -4
- package/scripts/setup-railway-deployment.sh +37 -0
- package/scripts/verify-railway-schema.ts +35 -0
|
@@ -5,8 +5,12 @@ import { WebSocketServer } from "ws";
|
|
|
5
5
|
import cors from "cors";
|
|
6
6
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
7
7
|
import Database from "better-sqlite3";
|
|
8
|
+
import * as bcrypt from "bcryptjs";
|
|
9
|
+
import jwt from "jsonwebtoken";
|
|
10
|
+
import { Pool } from "pg";
|
|
8
11
|
import { join, dirname } from "path";
|
|
9
12
|
import { existsSync, mkdirSync } from "fs";
|
|
13
|
+
import { AuthMiddleware } from "../production/auth-middleware.js";
|
|
10
14
|
const config = {
|
|
11
15
|
port: parseInt(process.env["PORT"] || "3000"),
|
|
12
16
|
environment: process.env["NODE_ENV"] || "development",
|
|
@@ -29,54 +33,299 @@ class RailwayMCPServer {
|
|
|
29
33
|
wss;
|
|
30
34
|
mcpServer;
|
|
31
35
|
db;
|
|
36
|
+
pgPool = null;
|
|
37
|
+
authMiddleware = null;
|
|
32
38
|
connections = /* @__PURE__ */ new Map();
|
|
39
|
+
// Deprecated in-memory session cache; sessions are persisted in DB
|
|
40
|
+
adminSessions = /* @__PURE__ */ new Map();
|
|
33
41
|
// private browserMCP: BrowserMCPIntegration;
|
|
34
42
|
constructor() {
|
|
35
43
|
this.app = express();
|
|
36
44
|
this.httpServer = createServer(this.app);
|
|
37
|
-
this.initializeDatabase()
|
|
45
|
+
this.initializeDatabase().then(() => {
|
|
46
|
+
this.startAdminSessionCleanup();
|
|
47
|
+
}).catch((err) => {
|
|
48
|
+
console.error("Failed to initialize database:", err);
|
|
49
|
+
});
|
|
38
50
|
this.setupMiddleware();
|
|
39
51
|
this.setupRoutes();
|
|
40
52
|
if (config.enableWebSocket) {
|
|
41
53
|
this.setupWebSocket();
|
|
42
54
|
}
|
|
43
55
|
}
|
|
44
|
-
initializeDatabase() {
|
|
45
|
-
|
|
56
|
+
async initializeDatabase() {
|
|
57
|
+
const isPg = config.databaseUrl.startsWith("postgres://") || config.databaseUrl.startsWith("postgresql://");
|
|
58
|
+
if (isPg) {
|
|
46
59
|
console.log("Using PostgreSQL database");
|
|
47
|
-
|
|
48
|
-
this.
|
|
60
|
+
this.pgPool = new Pool({ connectionString: config.databaseUrl });
|
|
61
|
+
await this.pgPool.query(`
|
|
62
|
+
CREATE TABLE IF NOT EXISTS contexts (
|
|
63
|
+
id BIGSERIAL PRIMARY KEY,
|
|
64
|
+
project_id TEXT NOT NULL,
|
|
65
|
+
content TEXT NOT NULL,
|
|
66
|
+
type TEXT DEFAULT 'general',
|
|
67
|
+
metadata JSONB DEFAULT '{}'::jsonb,
|
|
68
|
+
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
69
|
+
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
70
|
+
);
|
|
71
|
+
`);
|
|
72
|
+
await this.pgPool.query(`
|
|
73
|
+
CREATE TABLE IF NOT EXISTS api_keys (
|
|
74
|
+
id BIGSERIAL PRIMARY KEY,
|
|
75
|
+
key_hash TEXT UNIQUE NOT NULL,
|
|
76
|
+
user_id TEXT NOT NULL,
|
|
77
|
+
name TEXT,
|
|
78
|
+
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
79
|
+
last_used TIMESTAMPTZ,
|
|
80
|
+
revoked BOOLEAN DEFAULT false
|
|
81
|
+
);
|
|
82
|
+
`);
|
|
83
|
+
await this.pgPool.query(`
|
|
84
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
85
|
+
id TEXT PRIMARY KEY,
|
|
86
|
+
email TEXT,
|
|
87
|
+
name TEXT,
|
|
88
|
+
tier TEXT DEFAULT 'free',
|
|
89
|
+
role TEXT DEFAULT 'user',
|
|
90
|
+
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
91
|
+
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
92
|
+
);
|
|
93
|
+
`);
|
|
94
|
+
try {
|
|
95
|
+
await this.pgPool.query(`ALTER TABLE users ADD COLUMN role TEXT DEFAULT 'user'`);
|
|
96
|
+
} catch {
|
|
97
|
+
}
|
|
98
|
+
try {
|
|
99
|
+
await this.pgPool.query(`ALTER TABLE project_members ADD CONSTRAINT project_members_role_check CHECK (role IN ('admin','owner','editor','viewer'))`);
|
|
100
|
+
} catch {
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
await this.pgPool.query(`ALTER TABLE users ADD CONSTRAINT users_role_check CHECK (role IN ('admin','user'))`);
|
|
104
|
+
} catch {
|
|
105
|
+
}
|
|
106
|
+
await this.pgPool.query(`
|
|
107
|
+
CREATE TABLE IF NOT EXISTS projects (
|
|
108
|
+
id TEXT PRIMARY KEY,
|
|
109
|
+
name TEXT,
|
|
110
|
+
is_public BOOLEAN DEFAULT false,
|
|
111
|
+
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
112
|
+
updated_at TIMESTAMPTZ DEFAULT NOW()
|
|
113
|
+
);
|
|
114
|
+
`);
|
|
115
|
+
await this.pgPool.query(`
|
|
116
|
+
CREATE TABLE IF NOT EXISTS project_members (
|
|
117
|
+
project_id TEXT NOT NULL,
|
|
118
|
+
user_id TEXT NOT NULL,
|
|
119
|
+
role TEXT NOT NULL,
|
|
120
|
+
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
121
|
+
PRIMARY KEY (project_id, user_id)
|
|
122
|
+
);
|
|
123
|
+
`);
|
|
124
|
+
await this.pgPool.query("CREATE INDEX IF NOT EXISTS idx_contexts_project ON contexts(project_id);");
|
|
125
|
+
await this.pgPool.query("CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash);");
|
|
126
|
+
await this.pgPool.query("CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);");
|
|
127
|
+
await this.pgPool.query("CREATE INDEX IF NOT EXISTS idx_project_members_user ON project_members(user_id);");
|
|
128
|
+
await this.pgPool.query(`
|
|
129
|
+
CREATE TABLE IF NOT EXISTS admin_sessions (
|
|
130
|
+
id TEXT PRIMARY KEY,
|
|
131
|
+
user_id TEXT NOT NULL,
|
|
132
|
+
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
133
|
+
expires_at TIMESTAMPTZ NOT NULL,
|
|
134
|
+
user_agent TEXT,
|
|
135
|
+
ip TEXT
|
|
136
|
+
);
|
|
137
|
+
`);
|
|
138
|
+
await this.pgPool.query("CREATE INDEX IF NOT EXISTS idx_admin_sessions_user ON admin_sessions(user_id);");
|
|
139
|
+
try {
|
|
140
|
+
await this.pgPool.query("CREATE TYPE user_role AS ENUM ('admin','user')");
|
|
141
|
+
} catch {
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
await this.pgPool.query("CREATE TYPE member_role AS ENUM ('admin','owner','editor','viewer')");
|
|
145
|
+
} catch {
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
await this.pgPool.query("ALTER TABLE users ALTER COLUMN role TYPE user_role USING role::user_role");
|
|
149
|
+
} catch {
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
await this.pgPool.query("ALTER TABLE project_members ALTER COLUMN role TYPE member_role USING role::member_role");
|
|
153
|
+
} catch {
|
|
154
|
+
}
|
|
155
|
+
await this.runMigrations("pg");
|
|
49
156
|
} else {
|
|
50
157
|
const dbDir = dirname(config.databaseUrl);
|
|
51
158
|
if (!existsSync(dbDir)) {
|
|
52
159
|
mkdirSync(dbDir, { recursive: true });
|
|
53
160
|
}
|
|
54
161
|
this.db = new Database(config.databaseUrl);
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
162
|
+
this.db.pragma("foreign_keys = ON");
|
|
163
|
+
this.db.exec(`
|
|
164
|
+
CREATE TABLE IF NOT EXISTS contexts (
|
|
165
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
166
|
+
project_id TEXT NOT NULL,
|
|
167
|
+
content TEXT NOT NULL,
|
|
168
|
+
type TEXT DEFAULT 'general',
|
|
169
|
+
metadata TEXT DEFAULT '{}',
|
|
170
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
171
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
172
|
+
);
|
|
66
173
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
174
|
+
CREATE TABLE IF NOT EXISTS api_keys (
|
|
175
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
176
|
+
key_hash TEXT UNIQUE NOT NULL,
|
|
177
|
+
user_id TEXT NOT NULL,
|
|
178
|
+
name TEXT,
|
|
179
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
180
|
+
last_used DATETIME,
|
|
181
|
+
revoked BOOLEAN DEFAULT 0
|
|
182
|
+
);
|
|
76
183
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
184
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
185
|
+
id TEXT PRIMARY KEY,
|
|
186
|
+
email TEXT,
|
|
187
|
+
name TEXT,
|
|
188
|
+
tier TEXT DEFAULT 'free',
|
|
189
|
+
role TEXT DEFAULT 'user',
|
|
190
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
191
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
CREATE TABLE IF NOT EXISTS projects (
|
|
195
|
+
id TEXT PRIMARY KEY,
|
|
196
|
+
name TEXT,
|
|
197
|
+
is_public BOOLEAN DEFAULT 0,
|
|
198
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
199
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
200
|
+
);
|
|
201
|
+
|
|
202
|
+
CREATE TABLE IF NOT EXISTS project_members (
|
|
203
|
+
project_id TEXT NOT NULL,
|
|
204
|
+
user_id TEXT NOT NULL,
|
|
205
|
+
role TEXT NOT NULL CHECK (role IN ('admin','owner','editor','viewer')),
|
|
206
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
207
|
+
PRIMARY KEY (project_id, user_id)
|
|
208
|
+
);
|
|
209
|
+
|
|
210
|
+
CREATE INDEX IF NOT EXISTS idx_contexts_project ON contexts(project_id);
|
|
211
|
+
CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash);
|
|
212
|
+
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
|
|
213
|
+
CREATE INDEX IF NOT EXISTS idx_project_members_user ON project_members(user_id);
|
|
214
|
+
|
|
215
|
+
CREATE TABLE IF NOT EXISTS admin_sessions (
|
|
216
|
+
id TEXT PRIMARY KEY,
|
|
217
|
+
user_id TEXT NOT NULL,
|
|
218
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
219
|
+
expires_at DATETIME NOT NULL,
|
|
220
|
+
user_agent TEXT,
|
|
221
|
+
ip TEXT
|
|
222
|
+
);
|
|
223
|
+
CREATE INDEX IF NOT EXISTS idx_admin_sessions_user ON admin_sessions(user_id);
|
|
224
|
+
`);
|
|
225
|
+
await this.runMigrations("sqlite");
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// Simple migration framework (Railway server scope)
|
|
229
|
+
async runMigrations(kind) {
|
|
230
|
+
if (kind === "pg") {
|
|
231
|
+
await this.pgPool.query(`
|
|
232
|
+
CREATE TABLE IF NOT EXISTS railway_schema_version (
|
|
233
|
+
version INTEGER PRIMARY KEY,
|
|
234
|
+
applied_at TIMESTAMPTZ DEFAULT NOW(),
|
|
235
|
+
description TEXT
|
|
236
|
+
);
|
|
237
|
+
`);
|
|
238
|
+
const r = await this.pgPool.query("SELECT COALESCE(MAX(version), 0) AS v FROM railway_schema_version");
|
|
239
|
+
let cur = Number(r.rows[0]?.v || 0);
|
|
240
|
+
const apply = async (version, description, queries) => {
|
|
241
|
+
if (cur >= version) return;
|
|
242
|
+
for (const q of queries) {
|
|
243
|
+
try {
|
|
244
|
+
await this.pgPool.query(q);
|
|
245
|
+
} catch (e2) {
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
await this.pgPool.query("INSERT INTO railway_schema_version (version, description) VALUES ($1, $2) ON CONFLICT (version) DO NOTHING", [version, description]);
|
|
249
|
+
cur = version;
|
|
250
|
+
};
|
|
251
|
+
await apply(1, "base schema", [
|
|
252
|
+
`CREATE TABLE IF NOT EXISTS contexts (id BIGSERIAL PRIMARY KEY, project_id TEXT NOT NULL, content TEXT NOT NULL, type TEXT DEFAULT 'general', metadata JSONB DEFAULT '{}'::jsonb, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
|
253
|
+
`CREATE TABLE IF NOT EXISTS api_keys (id BIGSERIAL PRIMARY KEY, key_hash TEXT UNIQUE NOT NULL, user_id TEXT NOT NULL, name TEXT, created_at TIMESTAMPTZ DEFAULT NOW(), last_used TIMESTAMPTZ, revoked BOOLEAN DEFAULT false)`,
|
|
254
|
+
`CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, email TEXT, name TEXT, tier TEXT DEFAULT 'free', role TEXT DEFAULT 'user', created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
|
255
|
+
`CREATE TABLE IF NOT EXISTS projects (id TEXT PRIMARY KEY, name TEXT, is_public BOOLEAN DEFAULT false, created_at TIMESTAMPTZ DEFAULT NOW(), updated_at TIMESTAMPTZ DEFAULT NOW())`,
|
|
256
|
+
`CREATE TABLE IF NOT EXISTS project_members (project_id TEXT NOT NULL, user_id TEXT NOT NULL, role TEXT NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW(), PRIMARY KEY (project_id, user_id))`,
|
|
257
|
+
`CREATE INDEX IF NOT EXISTS idx_contexts_project ON contexts(project_id)`,
|
|
258
|
+
`CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash)`,
|
|
259
|
+
`CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)`,
|
|
260
|
+
`CREATE INDEX IF NOT EXISTS idx_project_members_user ON project_members(user_id)`
|
|
261
|
+
]);
|
|
262
|
+
await apply(2, "admin sessions", [
|
|
263
|
+
`CREATE TABLE IF NOT EXISTS admin_sessions (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW(), expires_at TIMESTAMPTZ NOT NULL, user_agent TEXT, ip TEXT)`,
|
|
264
|
+
`CREATE INDEX IF NOT EXISTS idx_admin_sessions_user ON admin_sessions(user_id)`
|
|
265
|
+
]);
|
|
266
|
+
await apply(3, "role enums & checks", [
|
|
267
|
+
`CREATE TYPE user_role AS ENUM ('admin','user')`,
|
|
268
|
+
`CREATE TYPE member_role AS ENUM ('admin','owner','editor','viewer')`,
|
|
269
|
+
`ALTER TABLE users ALTER COLUMN role TYPE user_role USING role::user_role`,
|
|
270
|
+
`ALTER TABLE project_members ALTER COLUMN role TYPE member_role USING role::member_role`,
|
|
271
|
+
`ALTER TABLE project_members ADD CONSTRAINT project_members_role_check CHECK (role IN ('admin','owner','editor','viewer'))`,
|
|
272
|
+
`ALTER TABLE users ADD CONSTRAINT users_role_check CHECK (role IN ('admin','user'))`
|
|
273
|
+
]);
|
|
274
|
+
} else {
|
|
275
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS railway_schema_version (version INTEGER PRIMARY KEY, applied_at DATETIME DEFAULT CURRENT_TIMESTAMP, description TEXT)`);
|
|
276
|
+
const row = this.db.prepare("SELECT COALESCE(MAX(version), 0) AS v FROM railway_schema_version").get();
|
|
277
|
+
let cur = Number(row?.v || 0);
|
|
278
|
+
const apply = (version, description, statements) => {
|
|
279
|
+
if (cur >= version) return;
|
|
280
|
+
this.db.exec("BEGIN");
|
|
281
|
+
try {
|
|
282
|
+
for (const s of statements) {
|
|
283
|
+
try {
|
|
284
|
+
this.db.exec(s);
|
|
285
|
+
} catch {
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
this.db.prepare("INSERT OR IGNORE INTO railway_schema_version (version, description) VALUES (?, ?)").run(version, description);
|
|
289
|
+
this.db.exec("COMMIT");
|
|
290
|
+
cur = version;
|
|
291
|
+
} catch {
|
|
292
|
+
this.db.exec("ROLLBACK");
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
apply(1, "base schema", [
|
|
296
|
+
`CREATE TABLE IF NOT EXISTS contexts (id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT NOT NULL, content TEXT NOT NULL, type TEXT DEFAULT 'general', metadata TEXT DEFAULT '{}', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP)`,
|
|
297
|
+
`CREATE TABLE IF NOT EXISTS api_keys (id INTEGER PRIMARY KEY AUTOINCREMENT, key_hash TEXT UNIQUE NOT NULL, user_id TEXT NOT NULL, name TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, last_used DATETIME, revoked BOOLEAN DEFAULT 0)`,
|
|
298
|
+
`CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, email TEXT, name TEXT, tier TEXT DEFAULT 'free', role TEXT DEFAULT 'user', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP)`,
|
|
299
|
+
`CREATE TABLE IF NOT EXISTS projects (id TEXT PRIMARY KEY, name TEXT, is_public BOOLEAN DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP)`,
|
|
300
|
+
`CREATE TABLE IF NOT EXISTS project_members (project_id TEXT NOT NULL, user_id TEXT NOT NULL, role TEXT NOT NULL CHECK (role IN ('admin','owner','editor','viewer')), created_at DATETIME DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (project_id, user_id))`,
|
|
301
|
+
`CREATE INDEX IF NOT EXISTS idx_contexts_project ON contexts(project_id)`,
|
|
302
|
+
`CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash)`,
|
|
303
|
+
`CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)`,
|
|
304
|
+
`CREATE INDEX IF NOT EXISTS idx_project_members_user ON project_members(user_id)`
|
|
305
|
+
]);
|
|
306
|
+
apply(2, "admin sessions", [
|
|
307
|
+
`CREATE TABLE IF NOT EXISTS admin_sessions (id TEXT PRIMARY KEY, user_id TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, expires_at DATETIME NOT NULL, user_agent TEXT, ip TEXT)`,
|
|
308
|
+
`CREATE INDEX IF NOT EXISTS idx_admin_sessions_user ON admin_sessions(user_id)`
|
|
309
|
+
]);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
// TTL cleanup for admin sessions
|
|
313
|
+
startAdminSessionCleanup() {
|
|
314
|
+
const minutes = parseInt(process.env["ADMIN_SESSION_CLEAN_INTERVAL_MIN"] || "15", 10);
|
|
315
|
+
if (minutes <= 0) return;
|
|
316
|
+
const run = async () => {
|
|
317
|
+
try {
|
|
318
|
+
if (this.pgPool) {
|
|
319
|
+
await this.pgPool.query("DELETE FROM admin_sessions WHERE expires_at <= NOW()");
|
|
320
|
+
} else if (this.db) {
|
|
321
|
+
this.db.prepare('DELETE FROM admin_sessions WHERE datetime(expires_at) <= datetime("now")').run();
|
|
322
|
+
}
|
|
323
|
+
} catch {
|
|
324
|
+
console.warn("Admin session cleanup failed:", e);
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
run();
|
|
328
|
+
setInterval(run, Math.max(1, minutes) * 60 * 1e3);
|
|
80
329
|
}
|
|
81
330
|
setupMiddleware() {
|
|
82
331
|
this.app.use(
|
|
@@ -91,12 +340,13 @@ class RailwayMCPServer {
|
|
|
91
340
|
next();
|
|
92
341
|
});
|
|
93
342
|
this.app.use("/api", this.authenticate.bind(this));
|
|
343
|
+
this.app.use("/admin/api", this.authenticate.bind(this));
|
|
94
344
|
if (config.rateLimitEnabled) {
|
|
95
345
|
this.app.use("/api", this.rateLimit.bind(this));
|
|
96
346
|
}
|
|
97
347
|
}
|
|
98
|
-
authenticate(req, res, next) {
|
|
99
|
-
if (req.path === "/health") {
|
|
348
|
+
async authenticate(req, res, next) {
|
|
349
|
+
if (req.path === "/health" || req.path === "/health/db") {
|
|
100
350
|
return next();
|
|
101
351
|
}
|
|
102
352
|
const authHeader = req.headers.authorization;
|
|
@@ -105,14 +355,61 @@ class RailwayMCPServer {
|
|
|
105
355
|
return res.status(401).json({ error: "Missing API key" });
|
|
106
356
|
}
|
|
107
357
|
const apiKey = authHeader.substring(7);
|
|
108
|
-
|
|
109
|
-
|
|
358
|
+
try {
|
|
359
|
+
const valid = await this.validateApiKey(apiKey);
|
|
360
|
+
if (!valid) {
|
|
361
|
+
return res.status(403).json({ error: "Invalid API key" });
|
|
362
|
+
}
|
|
363
|
+
req.user = valid;
|
|
364
|
+
return next();
|
|
365
|
+
} catch (e2) {
|
|
366
|
+
return res.status(500).json({ error: e2.message || "Auth error" });
|
|
110
367
|
}
|
|
111
|
-
req.user = { id: "api-user", tier: "free" };
|
|
112
|
-
next();
|
|
113
|
-
} else {
|
|
114
|
-
next();
|
|
115
368
|
}
|
|
369
|
+
if (config.authMode === "jwt" && process.env["AUTH0_DOMAIN"]) {
|
|
370
|
+
if (!this.authMiddleware) {
|
|
371
|
+
this.authMiddleware = new AuthMiddleware({
|
|
372
|
+
auth0Domain: process.env["AUTH0_DOMAIN"],
|
|
373
|
+
auth0Audience: process.env["AUTH0_AUDIENCE"] || "stackmemory",
|
|
374
|
+
redisUrl: process.env["REDIS_URL"] || "redis://localhost:6379",
|
|
375
|
+
bypassAuth: process.env["NODE_ENV"] !== "production",
|
|
376
|
+
dbPath: process.env["STACKMEMORY_AUTH_DB"] || ".stackmemory/auth.db"
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
return this.authMiddleware.authenticate(req, res, next);
|
|
380
|
+
}
|
|
381
|
+
return next();
|
|
382
|
+
}
|
|
383
|
+
async validateApiKey(apiKey) {
|
|
384
|
+
if (this.pgPool) {
|
|
385
|
+
const { rows: rows2 } = await this.pgPool.query(
|
|
386
|
+
`SELECT ak.id, ak.user_id, ak.key_hash, ak.revoked, u.name, u.email, u.tier, u.role
|
|
387
|
+
FROM api_keys ak
|
|
388
|
+
LEFT JOIN users u ON u.id = ak.user_id`
|
|
389
|
+
);
|
|
390
|
+
for (const row of rows2) {
|
|
391
|
+
if (row.revoked) continue;
|
|
392
|
+
if (await bcrypt.compare(apiKey, row.key_hash)) {
|
|
393
|
+
await this.pgPool.query("UPDATE api_keys SET last_used = NOW() WHERE id = $1", [row.id]);
|
|
394
|
+
return { id: row.user_id || "api-user", tier: row.tier || "free", name: row.name || void 0, email: row.email || void 0, role: row.role || "user" };
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
const stmt = this.db.prepare(`
|
|
400
|
+
SELECT ak.id, ak.user_id, ak.key_hash, ak.revoked, u.name, u.email, u.tier, u.role
|
|
401
|
+
FROM api_keys ak
|
|
402
|
+
LEFT JOIN users u ON u.id = ak.user_id
|
|
403
|
+
`);
|
|
404
|
+
const rows = stmt.all();
|
|
405
|
+
for (const row of rows) {
|
|
406
|
+
if (row.revoked) continue;
|
|
407
|
+
if (await bcrypt.compare(apiKey, row.key_hash)) {
|
|
408
|
+
this.db.prepare("UPDATE api_keys SET last_used = CURRENT_TIMESTAMP WHERE id = ?").run(row.id);
|
|
409
|
+
return { id: row.user_id || "api-user", tier: row.tier || "free", name: row.name || void 0, email: row.email || void 0, role: row.role || "user" };
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return null;
|
|
116
413
|
}
|
|
117
414
|
rateLimit(req, res, next) {
|
|
118
415
|
const userId = req.user?.id || req.ip;
|
|
@@ -160,49 +457,367 @@ class RailwayMCPServer {
|
|
|
160
457
|
}
|
|
161
458
|
});
|
|
162
459
|
});
|
|
163
|
-
this.app.post("/api/context/save", (req, res) => {
|
|
460
|
+
this.app.post("/api/context/save", async (req, res) => {
|
|
164
461
|
try {
|
|
165
|
-
const {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
462
|
+
const { projectId = "default", content, type = "general", metadata = {} } = req.body;
|
|
463
|
+
const user = req.user || { tier: "free" };
|
|
464
|
+
const allowFreeWrite = process.env["ALLOW_FREE_WRITE"] === "true";
|
|
465
|
+
if (user.tier === "free" && !allowFreeWrite) {
|
|
466
|
+
return res.status(403).json({ error: "Write access denied for free tier", code: "WRITE_FORBIDDEN" });
|
|
467
|
+
}
|
|
468
|
+
await this.ensureProjectOwner(projectId, user.id || "api-user");
|
|
469
|
+
const role = await this.getProjectRole(projectId, user.id || "api-user");
|
|
470
|
+
if (!this.hasWriteAccess(role)) {
|
|
471
|
+
return res.status(403).json({ error: "Insufficient permissions", code: "PERMISSION_DENIED" });
|
|
472
|
+
}
|
|
473
|
+
if (this.pgPool) {
|
|
474
|
+
const r = await this.pgPool.query(
|
|
475
|
+
`INSERT INTO contexts (project_id, content, type, metadata) VALUES ($1, $2, $3, $4) RETURNING id`,
|
|
476
|
+
[projectId, content, type, metadata]
|
|
477
|
+
);
|
|
478
|
+
return res.json({ success: true, id: r.rows[0].id });
|
|
479
|
+
}
|
|
480
|
+
const stmt = this.db.prepare("INSERT INTO contexts (project_id, content, type, metadata) VALUES (?, ?, ?, ?)");
|
|
481
|
+
const result = stmt.run(projectId, content, type, JSON.stringify(metadata));
|
|
482
|
+
return res.json({ success: true, id: result.lastInsertRowid });
|
|
185
483
|
} catch (error) {
|
|
186
484
|
res.status(500).json({ error: error.message });
|
|
187
485
|
}
|
|
188
486
|
});
|
|
189
|
-
this.app.get("/api/context/load", (req, res) => {
|
|
487
|
+
this.app.get("/api/context/load", async (req, res) => {
|
|
190
488
|
try {
|
|
191
489
|
const { projectId = "default", limit = 10, offset = 0 } = req.query;
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
490
|
+
const user = req.user || { id: "api-user" };
|
|
491
|
+
const isPublic = await this.isProjectPublic(projectId);
|
|
492
|
+
const role = await this.getProjectRole(projectId, user.id || "api-user");
|
|
493
|
+
if (!this.hasReadAccess(role, isPublic)) {
|
|
494
|
+
return res.status(403).json({ error: "Insufficient permissions", code: "PERMISSION_DENIED" });
|
|
495
|
+
}
|
|
496
|
+
if (this.pgPool) {
|
|
497
|
+
const r = await this.pgPool.query(
|
|
498
|
+
`SELECT * FROM contexts WHERE project_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3`,
|
|
499
|
+
[projectId, Number(limit), Number(offset)]
|
|
500
|
+
);
|
|
501
|
+
return res.json({ success: true, contexts: r.rows });
|
|
502
|
+
}
|
|
503
|
+
const stmt = this.db.prepare("SELECT * FROM contexts WHERE project_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?");
|
|
504
|
+
const rows = stmt.all(projectId, limit, offset);
|
|
505
|
+
return res.json({ success: true, contexts: rows.map((c) => ({ ...c, metadata: JSON.parse(c.metadata || "{}") })) });
|
|
506
|
+
} catch (error) {
|
|
507
|
+
res.status(500).json({ error: error.message });
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
const parseCookies2 = (cookieHeader) => {
|
|
511
|
+
const out = {};
|
|
512
|
+
if (!cookieHeader) return out;
|
|
513
|
+
cookieHeader.split(";").forEach((p) => {
|
|
514
|
+
const i = p.indexOf("=");
|
|
515
|
+
if (i > -1) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1));
|
|
516
|
+
});
|
|
517
|
+
return out;
|
|
518
|
+
};
|
|
519
|
+
const setJwtCookie2 = (res, token) => {
|
|
520
|
+
const flags = ["Path=/", "HttpOnly", "SameSite=Lax"];
|
|
521
|
+
if (process.env["NODE_ENV"] === "production") flags.push("Secure");
|
|
522
|
+
res.setHeader("Set-Cookie", `sm_admin_jwt=${encodeURIComponent(token)}; ${flags.join("; ")}`);
|
|
523
|
+
};
|
|
524
|
+
const clearJwtCookie2 = (res) => {
|
|
525
|
+
res.setHeader("Set-Cookie", "sm_admin_jwt=; Path=/; HttpOnly; Max-Age=0; SameSite=Lax");
|
|
526
|
+
};
|
|
527
|
+
const verifyAdminJwt2 = (token) => {
|
|
528
|
+
try {
|
|
529
|
+
const secret = process.env["ADMIN_JWT_SECRET"] || "dev-admin-secret";
|
|
530
|
+
const payload = jwt.verify(token, secret);
|
|
531
|
+
return { sub: payload.sub, jti: payload.jti };
|
|
532
|
+
} catch {
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
const checkDbSession = async (jti) => {
|
|
537
|
+
if (this.pgPool) {
|
|
538
|
+
const r = await this.pgPool.query("SELECT 1 FROM admin_sessions WHERE id = $1 AND expires_at > NOW()", [jti]);
|
|
539
|
+
return r.rowCount > 0;
|
|
540
|
+
}
|
|
541
|
+
const row = this.db.prepare('SELECT 1 FROM admin_sessions WHERE id = ? AND datetime(expires_at) > datetime("now")').get(jti);
|
|
542
|
+
return !!row;
|
|
543
|
+
};
|
|
544
|
+
const requireAdmin = (req, res, next) => {
|
|
545
|
+
const user = req.user || {};
|
|
546
|
+
if (user.role === "admin") return next();
|
|
547
|
+
const cookies = parseCookies2(req.headers.cookie);
|
|
548
|
+
const t = cookies["sm_admin_jwt"];
|
|
549
|
+
if (t) {
|
|
550
|
+
const verified = verifyAdminJwt2(t);
|
|
551
|
+
if (verified) {
|
|
552
|
+
checkDbSession(verified.jti).then((ok) => {
|
|
553
|
+
if (ok) return next();
|
|
554
|
+
if (req.path === "/admin" || req.path.startsWith("/admin")) {
|
|
555
|
+
res.redirect("/admin/login");
|
|
556
|
+
} else {
|
|
557
|
+
res.status(403).json({ error: "Admin access required", code: "ADMIN_REQUIRED" });
|
|
558
|
+
}
|
|
559
|
+
}).catch(() => {
|
|
560
|
+
if (req.path === "/admin" || req.path.startsWith("/admin")) {
|
|
561
|
+
res.redirect("/admin/login");
|
|
562
|
+
} else {
|
|
563
|
+
res.status(403).json({ error: "Admin access required", code: "ADMIN_REQUIRED" });
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
if (req.path === "/admin" || req.path.startsWith("/admin")) {
|
|
570
|
+
res.redirect("/admin/login");
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
return res.status(403).json({ error: "Admin access required", code: "ADMIN_REQUIRED" });
|
|
574
|
+
};
|
|
575
|
+
this.app.get("/admin/api/projects", requireAdmin, async (req, res) => {
|
|
576
|
+
try {
|
|
577
|
+
if (this.pgPool) {
|
|
578
|
+
const r = await this.pgPool.query("SELECT id, name, is_public, created_at, updated_at FROM projects ORDER BY updated_at DESC");
|
|
579
|
+
return res.json({ projects: r.rows });
|
|
580
|
+
}
|
|
581
|
+
const rows = this.db.prepare("SELECT id, name, is_public, created_at, updated_at FROM projects ORDER BY updated_at DESC").all();
|
|
582
|
+
return res.json({ projects: rows });
|
|
583
|
+
} catch (e2) {
|
|
584
|
+
res.status(500).json({ error: e2.message });
|
|
585
|
+
}
|
|
586
|
+
});
|
|
587
|
+
this.app.post("/admin/api/projects", requireAdmin, async (req, res) => {
|
|
588
|
+
try {
|
|
589
|
+
const { id, name, isPublic = false } = req.body || {};
|
|
590
|
+
if (!id) return res.status(400).json({ error: "id required" });
|
|
591
|
+
if (this.pgPool) {
|
|
592
|
+
await this.pgPool.query("INSERT INTO projects (id, name, is_public) VALUES ($1, $2, $3) ON CONFLICT (id) DO NOTHING", [id, name || id, !!isPublic]);
|
|
593
|
+
return res.json({ success: true });
|
|
594
|
+
}
|
|
595
|
+
this.db.prepare("INSERT OR IGNORE INTO projects (id, name, is_public) VALUES (?, ?, ?)").run(id, name || id, isPublic ? 1 : 0);
|
|
596
|
+
return res.json({ success: true });
|
|
597
|
+
} catch (e2) {
|
|
598
|
+
res.status(500).json({ error: e2.message });
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
this.app.patch("/admin/api/projects/:id/visibility", requireAdmin, async (req, res) => {
|
|
602
|
+
try {
|
|
603
|
+
const pid = req.params.id;
|
|
604
|
+
const { isPublic } = req.body || {};
|
|
605
|
+
if (typeof isPublic !== "boolean") return res.status(400).json({ error: "isPublic boolean required" });
|
|
606
|
+
if (this.pgPool) {
|
|
607
|
+
await this.pgPool.query("UPDATE projects SET is_public = $1, updated_at = NOW() WHERE id = $2", [isPublic, pid]);
|
|
608
|
+
return res.json({ success: true });
|
|
609
|
+
}
|
|
610
|
+
this.db.prepare("UPDATE projects SET is_public = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?").run(isPublic ? 1 : 0, pid);
|
|
611
|
+
return res.json({ success: true });
|
|
612
|
+
} catch (e2) {
|
|
613
|
+
res.status(500).json({ error: e2.message });
|
|
614
|
+
}
|
|
615
|
+
});
|
|
616
|
+
this.app.get("/admin/api/projects/:id/members", requireAdmin, async (req, res) => {
|
|
617
|
+
try {
|
|
618
|
+
const pid = req.params.id;
|
|
619
|
+
if (this.pgPool) {
|
|
620
|
+
const r = await this.pgPool.query(
|
|
621
|
+
"SELECT pm.user_id, pm.role, u.email, u.name FROM project_members pm LEFT JOIN users u ON u.id = pm.user_id WHERE pm.project_id = $1 ORDER BY pm.role",
|
|
622
|
+
[pid]
|
|
623
|
+
);
|
|
624
|
+
return res.json({ members: r.rows });
|
|
625
|
+
}
|
|
626
|
+
const stmt = this.db.prepare("SELECT pm.user_id, pm.role, u.email, u.name FROM project_members pm LEFT JOIN users u ON u.id = pm.user_id WHERE pm.project_id = ? ORDER BY pm.role");
|
|
627
|
+
return res.json({ members: stmt.all(pid) });
|
|
628
|
+
} catch (e2) {
|
|
629
|
+
res.status(500).json({ error: e2.message });
|
|
630
|
+
}
|
|
631
|
+
});
|
|
632
|
+
this.app.put("/admin/api/projects/:id/members", requireAdmin, async (req, res) => {
|
|
633
|
+
try {
|
|
634
|
+
const pid = req.params.id;
|
|
635
|
+
const { userId, role } = req.body || {};
|
|
636
|
+
if (!userId || !role) return res.status(400).json({ error: "userId and role required" });
|
|
637
|
+
const validRoles = ["admin", "owner", "editor", "viewer"];
|
|
638
|
+
if (!validRoles.includes(role)) return res.status(400).json({ error: "invalid role" });
|
|
639
|
+
if (this.pgPool) {
|
|
640
|
+
await this.pgPool.query(
|
|
641
|
+
"INSERT INTO project_members (project_id, user_id, role) VALUES ($1, $2, $3) ON CONFLICT (project_id, user_id) DO UPDATE SET role = EXCLUDED.role",
|
|
642
|
+
[pid, userId, role]
|
|
643
|
+
);
|
|
644
|
+
return res.json({ success: true });
|
|
645
|
+
}
|
|
646
|
+
this.db.prepare("INSERT INTO project_members (project_id, user_id, role) VALUES (?, ?, ?) ON CONFLICT(project_id, user_id) DO UPDATE SET role = ?").run(pid, userId, role, role);
|
|
647
|
+
return res.json({ success: true });
|
|
648
|
+
} catch (e2) {
|
|
649
|
+
res.status(500).json({ error: e2.message });
|
|
650
|
+
}
|
|
651
|
+
});
|
|
652
|
+
this.app.delete("/admin/api/projects/:id/members/:userId", requireAdmin, async (req, res) => {
|
|
653
|
+
try {
|
|
654
|
+
const pid = req.params.id;
|
|
655
|
+
const uid = req.params.userId;
|
|
656
|
+
if (this.pgPool) {
|
|
657
|
+
await this.pgPool.query("DELETE FROM project_members WHERE project_id = $1 AND user_id = $2", [pid, uid]);
|
|
658
|
+
return res.json({ success: true });
|
|
659
|
+
}
|
|
660
|
+
this.db.prepare("DELETE FROM project_members WHERE project_id = ? AND user_id = ?").run(pid, uid);
|
|
661
|
+
return res.json({ success: true });
|
|
662
|
+
} catch (e2) {
|
|
663
|
+
res.status(500).json({ error: e2.message });
|
|
664
|
+
}
|
|
665
|
+
});
|
|
666
|
+
this.app.get("/admin/api/sessions", requireAdmin, async (_req, res) => {
|
|
667
|
+
try {
|
|
668
|
+
if (this.pgPool) {
|
|
669
|
+
const r = await this.pgPool.query("SELECT id, user_id, created_at, expires_at, user_agent, ip FROM admin_sessions ORDER BY created_at DESC");
|
|
670
|
+
return res.json({ sessions: r.rows });
|
|
671
|
+
}
|
|
672
|
+
const rows = this.db.prepare("SELECT id, user_id, created_at, expires_at, user_agent, ip FROM admin_sessions ORDER BY created_at DESC").all();
|
|
673
|
+
return res.json({ sessions: rows });
|
|
674
|
+
} catch (e2) {
|
|
675
|
+
res.status(500).json({ error: e2.message });
|
|
676
|
+
}
|
|
677
|
+
});
|
|
678
|
+
this.app.delete("/admin/api/sessions/:id", requireAdmin, async (req, res) => {
|
|
679
|
+
try {
|
|
680
|
+
const id = req.params.id;
|
|
681
|
+
if (this.pgPool) {
|
|
682
|
+
await this.pgPool.query("DELETE FROM admin_sessions WHERE id = $1", [id]);
|
|
683
|
+
} else {
|
|
684
|
+
this.db.prepare("DELETE FROM admin_sessions WHERE id = ?").run(id);
|
|
685
|
+
}
|
|
686
|
+
res.json({ success: true });
|
|
687
|
+
} catch (e2) {
|
|
688
|
+
res.status(500).json({ error: e2.message });
|
|
689
|
+
}
|
|
690
|
+
});
|
|
691
|
+
this.app.post("/admin/api/sessions/refresh", requireAdmin, async (req, res) => {
|
|
692
|
+
try {
|
|
693
|
+
const cookies = parseCookies2(req.headers.cookie);
|
|
694
|
+
const t = cookies["sm_admin_jwt"];
|
|
695
|
+
if (!t) return res.status(400).json({ error: "No session" });
|
|
696
|
+
const secret = process.env["ADMIN_JWT_SECRET"] || "dev-admin-secret";
|
|
697
|
+
let payload;
|
|
698
|
+
try {
|
|
699
|
+
payload = jwt.verify(t, secret);
|
|
700
|
+
} catch {
|
|
701
|
+
return res.status(401).json({ error: "Invalid token" });
|
|
702
|
+
}
|
|
703
|
+
const oldJti = payload.jti;
|
|
704
|
+
const userId = payload.sub;
|
|
705
|
+
try {
|
|
706
|
+
if (this.pgPool) {
|
|
707
|
+
await this.pgPool.query("DELETE FROM admin_sessions WHERE id = $1", [oldJti]);
|
|
708
|
+
} else {
|
|
709
|
+
this.db.prepare("DELETE FROM admin_sessions WHERE id = ?").run(oldJti);
|
|
710
|
+
}
|
|
711
|
+
} catch {
|
|
712
|
+
}
|
|
713
|
+
const jti = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
|
|
714
|
+
const hours = parseInt(process.env["ADMIN_SESSION_HOURS"] || "8", 10);
|
|
715
|
+
const expMs = Date.now() + hours * 3600 * 1e3;
|
|
716
|
+
const expDateIso = new Date(expMs).toISOString();
|
|
717
|
+
const ua = req.headers["user-agent"] || "";
|
|
718
|
+
const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress || "";
|
|
719
|
+
if (this.pgPool) {
|
|
720
|
+
await this.pgPool.query("INSERT INTO admin_sessions (id, user_id, expires_at, user_agent, ip) VALUES ($1, $2, $3, $4, $5)", [jti, userId, expDateIso, ua, ip]);
|
|
721
|
+
} else {
|
|
722
|
+
this.db.prepare("INSERT INTO admin_sessions (id, user_id, expires_at, user_agent, ip) VALUES (?, ?, ?, ?, ?)").run(jti, userId, expDateIso, ua, ip);
|
|
723
|
+
}
|
|
724
|
+
const token = jwt.sign({ sub: userId, role: "admin", jti }, secret, { expiresIn: hours + "h" });
|
|
725
|
+
const flags = ["Path=/", "HttpOnly", "SameSite=Lax"];
|
|
726
|
+
if (process.env["NODE_ENV"] === "production") flags.push("Secure");
|
|
727
|
+
res.setHeader("Set-Cookie", `sm_admin_jwt=${encodeURIComponent(token)}; ${flags.join("; ")}`);
|
|
728
|
+
return res.json({ success: true });
|
|
729
|
+
} catch (e2) {
|
|
730
|
+
res.status(500).json({ error: e2.message });
|
|
731
|
+
}
|
|
732
|
+
});
|
|
733
|
+
this.app.get("/admin", requireAdmin, (req, res) => {
|
|
734
|
+
res.setHeader("Content-Type", "text/html");
|
|
735
|
+
res.send(`<!doctype html>
|
|
736
|
+
<html><head><meta charset="utf-8"/><title>StackMemory Admin</title>
|
|
737
|
+
<style>body{font-family:system-ui,Arial;margin:20px} table{border-collapse:collapse} th,td{border:1px solid #ddd;padding:6px} input,select{margin:4px} .row{margin-bottom:12px}</style>
|
|
738
|
+
</head><body>
|
|
739
|
+
<div style="display:flex;justify-content:space-between;align-items:center">
|
|
740
|
+
<h2>Projects</h2>
|
|
741
|
+
<div><a href="/admin/logout">Logout</a></div>
|
|
742
|
+
</div>
|
|
743
|
+
<div class="row">
|
|
744
|
+
<input id="newId" placeholder="project id"/>
|
|
745
|
+
<input id="newName" placeholder="name"/>
|
|
746
|
+
<label title="Anyone with auth can read if public"><input type="checkbox" id="newPublic"/> public</label>
|
|
747
|
+
<button onclick="createProject()">Create</button>
|
|
748
|
+
</div>
|
|
749
|
+
<div id="projects"></div>
|
|
750
|
+
<hr/>
|
|
751
|
+
<h2>Admin Sessions</h2>
|
|
752
|
+
<div class="row">
|
|
753
|
+
<button onclick="refreshSession()">Refresh This Session</button>
|
|
754
|
+
<button onclick="loadSessions()">Reload Sessions</button>
|
|
755
|
+
<span id="refreshMsg" style="margin-left:10px;color:#090"></span>
|
|
756
|
+
</div>
|
|
757
|
+
<div id="sessions"></div>
|
|
758
|
+
<script>
|
|
759
|
+
const ROLES = ['owner','editor','viewer','admin'];
|
|
760
|
+
async function loadProjects(){
|
|
761
|
+
const r = await fetch('/admin/api/projects'); const j = await r.json();
|
|
762
|
+
const rows = (j.projects||[]).map(p=>\`<tr><td>\${p.id}</td><td>\${p.name||''}</td><td>\${p.is_public? 'yes':'no'}</td>
|
|
763
|
+
<td><button onclick="togglePublic('\${p.id}',\${!p.is_public})">make \${!p.is_public?'public':'private'}</button>
|
|
764
|
+
<button onclick="viewMembers('\${p.id}')">members</button></td></tr>\`).join('');
|
|
765
|
+
document.getElementById('projects').innerHTML = \`<table><tr><th>id</th><th>name</th><th>public</th><th>actions</th></tr>\${rows}</table><div id="members"></div>\`;
|
|
766
|
+
}
|
|
767
|
+
async function createProject(){
|
|
768
|
+
const id = document.getElementById('newId').value; const name = document.getElementById('newName').value; const isPublic = document.getElementById('newPublic').checked;
|
|
769
|
+
await fetch('/admin/api/projects',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id,name,isPublic})});
|
|
770
|
+
loadProjects();
|
|
771
|
+
}
|
|
772
|
+
async function togglePublic(id, isPublic){
|
|
773
|
+
await fetch('/admin/api/projects/'+id+'/visibility',{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({isPublic})});
|
|
774
|
+
loadProjects();
|
|
775
|
+
}
|
|
776
|
+
async function viewMembers(id){
|
|
777
|
+
const r = await fetch('/admin/api/projects/'+id+'/members'); const j = await r.json();
|
|
778
|
+
const rows = (j.members||[]).map(m=>\`<tr><td>\${m.user_id}</td><td>\${m.name||''}</td><td>\${m.email||''}</td><td>\${m.role}</td>
|
|
779
|
+
<td><button onclick="removeMember('\${id}','\${m.user_id}')">remove</button></td></tr>\`).join('');
|
|
780
|
+
document.getElementById('members').innerHTML = \`<h3>Members of \${id}</h3>
|
|
781
|
+
<div class="row"><input id="mUser" placeholder="user id"/><select id="mRole">\${ROLES.map(r=>\`<option>\${r}</option>\`).join('')}</select>
|
|
782
|
+
<button onclick="addMember('\${id}')">add/update</button></div>
|
|
783
|
+
<table><tr><th>user</th><th>name</th><th>email</th><th>role</th><th>actions</th></tr>\${rows}</table>\`;
|
|
784
|
+
}
|
|
785
|
+
async function addMember(id){
|
|
786
|
+
const userId = document.getElementById('mUser').value; const role = document.getElementById('mRole').value;
|
|
787
|
+
if (!ROLES.includes(role)) { alert('Invalid role'); return; }
|
|
788
|
+
await fetch('/admin/api/projects/'+id+'/members',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({userId,role})});
|
|
789
|
+
viewMembers(id);
|
|
790
|
+
}
|
|
791
|
+
async function removeMember(id, userId){
|
|
792
|
+
await fetch('/admin/api/projects/'+id+'/members/'+userId,{method:'DELETE'});
|
|
793
|
+
viewMembers(id);
|
|
794
|
+
}
|
|
795
|
+
async function loadSessions(){
|
|
796
|
+
const r = await fetch('/admin/api/sessions'); const j = await r.json();
|
|
797
|
+
const rows = (j.sessions||[]).map(s=>\`<tr><td>\${s.id}</td><td>\${s.user_id}</td><td>\${new Date(s.created_at).toLocaleString()}</td><td>\${new Date(s.expires_at).toLocaleString()}</td><td>\${s.ip||''}</td><td>\${(s.user_agent||'').slice(0,40)}</td><td><button onclick="killSession('\${s.id}')">terminate</button></td></tr>\`).join('');
|
|
798
|
+
document.getElementById('sessions').innerHTML = \`<table><tr><th>id</th><th>user</th><th>created</th><th>expires</th><th>ip</th><th>agent</th><th>actions</th></tr>\${rows}</table>\`;
|
|
799
|
+
}
|
|
800
|
+
async function killSession(id){
|
|
801
|
+
await fetch('/admin/api/sessions/'+id,{method:'DELETE'});
|
|
802
|
+
loadSessions();
|
|
803
|
+
}
|
|
804
|
+
async function refreshSession(){
|
|
805
|
+
const r = await fetch('/admin/api/sessions/refresh',{method:'POST'});
|
|
806
|
+
if (r.ok){ document.getElementById('refreshMsg').textContent = 'Session refreshed.'; setTimeout(()=>document.getElementById('refreshMsg').textContent='',1500);} else { alert('Refresh failed'); }
|
|
807
|
+
}
|
|
808
|
+
loadProjects();
|
|
809
|
+
loadSessions();
|
|
810
|
+
</script>
|
|
811
|
+
</body></html>`);
|
|
812
|
+
});
|
|
813
|
+
this.app.get("/health/db", async (req, res) => {
|
|
814
|
+
try {
|
|
815
|
+
if (this.pgPool) {
|
|
816
|
+
const r = await this.pgPool.query("SELECT 1 as ok");
|
|
817
|
+
return res.json({ kind: "postgres", ok: !!r.rows?.length });
|
|
818
|
+
}
|
|
819
|
+
const row = this.db.prepare("SELECT 1 as ok").get();
|
|
820
|
+
return res.json({ kind: "sqlite", ok: row?.ok === 1 });
|
|
206
821
|
} catch (error) {
|
|
207
822
|
res.status(500).json({ error: error.message });
|
|
208
823
|
}
|
|
@@ -210,6 +825,28 @@ class RailwayMCPServer {
|
|
|
210
825
|
this.app.post("/api/tools/execute", async (req, res) => {
|
|
211
826
|
try {
|
|
212
827
|
const { tool, params } = req.body;
|
|
828
|
+
if (tool === "save_context") {
|
|
829
|
+
const user = req.user || { tier: "free" };
|
|
830
|
+
const allowFreeWrite = process.env["ALLOW_FREE_WRITE"] === "true";
|
|
831
|
+
if (user.tier === "free" && !allowFreeWrite) {
|
|
832
|
+
return res.status(403).json({ error: "Write access denied for free tier", code: "WRITE_FORBIDDEN" });
|
|
833
|
+
}
|
|
834
|
+
const projectId = params && params.projectId || "default";
|
|
835
|
+
await this.ensureProjectOwner(projectId, user.id || "api-user");
|
|
836
|
+
const role = await this.getProjectRole(projectId, user.id || "api-user");
|
|
837
|
+
if (!this.hasWriteAccess(role)) {
|
|
838
|
+
return res.status(403).json({ error: "Insufficient permissions", code: "PERMISSION_DENIED" });
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
if (tool === "load_context") {
|
|
842
|
+
const user = req.user || { id: "api-user" };
|
|
843
|
+
const projectId = params && params.projectId || "default";
|
|
844
|
+
const isPublic = await this.isProjectPublic(projectId);
|
|
845
|
+
const role = await this.getProjectRole(projectId, user.id || "api-user");
|
|
846
|
+
if (!this.hasReadAccess(role, isPublic)) {
|
|
847
|
+
return res.status(403).json({ error: "Insufficient permissions", code: "PERMISSION_DENIED" });
|
|
848
|
+
}
|
|
849
|
+
}
|
|
213
850
|
const result = await this.executeMCPTool(tool, params);
|
|
214
851
|
res.json({
|
|
215
852
|
success: true,
|
|
@@ -334,10 +971,17 @@ class RailwayMCPServer {
|
|
|
334
971
|
async executeMCPTool(tool, params) {
|
|
335
972
|
switch (tool) {
|
|
336
973
|
case "save_context": {
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
974
|
+
if (this.pgPool) {
|
|
975
|
+
const r = await this.pgPool.query(
|
|
976
|
+
`INSERT INTO contexts (project_id, content, type, metadata)
|
|
977
|
+
VALUES ($1, $2, $3, $4) RETURNING id`,
|
|
978
|
+
[params.projectId || "default", params.content, params.type || "general", params.metadata || {}]
|
|
979
|
+
);
|
|
980
|
+
return { id: r.rows[0].id, success: true };
|
|
981
|
+
}
|
|
982
|
+
const stmt = this.db.prepare(
|
|
983
|
+
`INSERT INTO contexts (project_id, content, type, metadata) VALUES (?, ?, ?, ?)`
|
|
984
|
+
);
|
|
341
985
|
const result = stmt.run(
|
|
342
986
|
params.projectId || "default",
|
|
343
987
|
params.content,
|
|
@@ -347,12 +991,19 @@ class RailwayMCPServer {
|
|
|
347
991
|
return { id: result.lastInsertRowid, success: true };
|
|
348
992
|
}
|
|
349
993
|
case "load_context": {
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
994
|
+
if (this.pgPool) {
|
|
995
|
+
const r = await this.pgPool.query(
|
|
996
|
+
`SELECT * FROM contexts
|
|
997
|
+
WHERE project_id = $1 AND content ILIKE $2
|
|
998
|
+
ORDER BY created_at DESC
|
|
999
|
+
LIMIT $3`,
|
|
1000
|
+
[params.projectId || "default", `%${params.query || ""}%`, params.limit || 10]
|
|
1001
|
+
);
|
|
1002
|
+
return { contexts: r.rows, success: true };
|
|
1003
|
+
}
|
|
1004
|
+
const stmt = this.db.prepare(
|
|
1005
|
+
`SELECT * FROM contexts WHERE project_id = ? AND content LIKE ? ORDER BY created_at DESC LIMIT ?`
|
|
1006
|
+
);
|
|
356
1007
|
const contexts = stmt.all(
|
|
357
1008
|
params.projectId || "default",
|
|
358
1009
|
`%${params.query || ""}%`,
|
|
@@ -364,6 +1015,60 @@ class RailwayMCPServer {
|
|
|
364
1015
|
throw new Error(`Unknown tool: ${tool}`);
|
|
365
1016
|
}
|
|
366
1017
|
}
|
|
1018
|
+
// Permission helpers
|
|
1019
|
+
hasReadAccess(role, isPublic) {
|
|
1020
|
+
if (isPublic) return true;
|
|
1021
|
+
return role === "admin" || role === "owner" || role === "editor" || role === "viewer";
|
|
1022
|
+
}
|
|
1023
|
+
hasWriteAccess(role) {
|
|
1024
|
+
return role === "admin" || role === "owner" || role === "editor";
|
|
1025
|
+
}
|
|
1026
|
+
async getProjectRole(projectId, userId) {
|
|
1027
|
+
if (this.pgPool) {
|
|
1028
|
+
const r = await this.pgPool.query(
|
|
1029
|
+
"SELECT role FROM project_members WHERE project_id = $1 AND user_id = $2",
|
|
1030
|
+
[projectId, userId]
|
|
1031
|
+
);
|
|
1032
|
+
return r.rows[0]?.role || null;
|
|
1033
|
+
}
|
|
1034
|
+
const row = this.db.prepare("SELECT role FROM project_members WHERE project_id = ? AND user_id = ?").get(projectId, userId);
|
|
1035
|
+
return row?.role || null;
|
|
1036
|
+
}
|
|
1037
|
+
async isProjectPublic(projectId) {
|
|
1038
|
+
if (this.pgPool) {
|
|
1039
|
+
const r = await this.pgPool.query("SELECT is_public FROM projects WHERE id = $1", [projectId]);
|
|
1040
|
+
return !!r.rows[0]?.is_public;
|
|
1041
|
+
}
|
|
1042
|
+
const row = this.db.prepare("SELECT is_public FROM projects WHERE id = ?").get(projectId);
|
|
1043
|
+
return !!row?.is_public;
|
|
1044
|
+
}
|
|
1045
|
+
async ensureProjectOwner(projectId, userId) {
|
|
1046
|
+
if (this.pgPool) {
|
|
1047
|
+
const pr2 = await this.pgPool.query("SELECT 1 FROM projects WHERE id = $1", [projectId]);
|
|
1048
|
+
if (pr2.rowCount === 0) {
|
|
1049
|
+
await this.pgPool.query("INSERT INTO projects (id, name, is_public) VALUES ($1, $2, $3)", [projectId, projectId, false]);
|
|
1050
|
+
}
|
|
1051
|
+
const mr2 = await this.pgPool.query(
|
|
1052
|
+
"SELECT 1 FROM project_members WHERE project_id = $1 AND user_id = $2",
|
|
1053
|
+
[projectId, userId]
|
|
1054
|
+
);
|
|
1055
|
+
if (mr2.rowCount === 0) {
|
|
1056
|
+
await this.pgPool.query(
|
|
1057
|
+
"INSERT INTO project_members (project_id, user_id, role) VALUES ($1, $2, $3)",
|
|
1058
|
+
[projectId, userId, "owner"]
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
const pr = this.db.prepare("SELECT 1 FROM projects WHERE id = ?").get(projectId);
|
|
1064
|
+
if (!pr) {
|
|
1065
|
+
this.db.prepare("INSERT INTO projects (id, name, is_public) VALUES (?, ?, ?)").run(projectId, projectId, 0);
|
|
1066
|
+
}
|
|
1067
|
+
const mr = this.db.prepare("SELECT 1 FROM project_members WHERE project_id = ? AND user_id = ?").get(projectId, userId);
|
|
1068
|
+
if (!mr) {
|
|
1069
|
+
this.db.prepare("INSERT INTO project_members (project_id, user_id, role) VALUES (?, ?, ?)").run(projectId, userId, "owner");
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
367
1072
|
start() {
|
|
368
1073
|
this.httpServer.listen(config.port, "0.0.0.0", () => {
|
|
369
1074
|
console.log(`
|
|
@@ -391,4 +1096,60 @@ process.on("SIGINT", () => {
|
|
|
391
1096
|
console.log("Shutting down...");
|
|
392
1097
|
process.exit(0);
|
|
393
1098
|
});
|
|
1099
|
+
(void 0).app.get("/admin/login", (_req, res) => {
|
|
1100
|
+
res.setHeader("Content-Type", "text/html");
|
|
1101
|
+
res.send(`<!doctype html><html><head><meta charset="utf-8"/><title>Admin Login</title>
|
|
1102
|
+
<style>body{font-family:system-ui;margin:40px} input{padding:8px;margin:4px} button{padding:8px}</style></head>
|
|
1103
|
+
<body><h3>Admin Login</h3>
|
|
1104
|
+
<p>Paste an admin API key to manage projects and members.</p>
|
|
1105
|
+
<form method="POST" action="/admin/login">
|
|
1106
|
+
<input type="password" name="apiKey" placeholder="sk-..." style="min-width:360px" required/>
|
|
1107
|
+
<div><button type="submit">Login</button></div>
|
|
1108
|
+
<p style="color:#666">Your key is validated server-side and not stored in the browser; a short-lived session cookie is created.</p>
|
|
1109
|
+
</form>
|
|
1110
|
+
</body></html>`);
|
|
1111
|
+
});
|
|
1112
|
+
(void 0).app.post("/admin/login", express.urlencoded({ extended: false }), async (req, res) => {
|
|
1113
|
+
try {
|
|
1114
|
+
const apiKey = req.body?.apiKey || "";
|
|
1115
|
+
if (!apiKey) return res.status(400).send("Missing API key");
|
|
1116
|
+
const u = await (void 0).validateApiKey(apiKey);
|
|
1117
|
+
if (!u || u.role !== "admin") return res.status(403).send("Not an admin API key");
|
|
1118
|
+
const jti = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
|
|
1119
|
+
const hours = parseInt(process.env["ADMIN_SESSION_HOURS"] || "8", 10);
|
|
1120
|
+
const expMs = Date.now() + hours * 3600 * 1e3;
|
|
1121
|
+
const expDateIso = new Date(expMs).toISOString();
|
|
1122
|
+
const ua = req.headers["user-agent"] || "";
|
|
1123
|
+
const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress || "";
|
|
1124
|
+
if ((void 0).pgPool) {
|
|
1125
|
+
await (void 0).pgPool.query("INSERT INTO admin_sessions (id, user_id, expires_at, user_agent, ip) VALUES ($1, $2, $3, $4, $5)", [jti, u.id, expDateIso, ua, ip]);
|
|
1126
|
+
} else {
|
|
1127
|
+
(void 0).db.prepare("INSERT INTO admin_sessions (id, user_id, expires_at, user_agent, ip) VALUES (?, ?, ?, ?, ?)").run(jti, u.id, expDateIso, ua, ip);
|
|
1128
|
+
}
|
|
1129
|
+
const token = jwt.sign({ sub: u.id, role: "admin", jti }, process.env["ADMIN_JWT_SECRET"] || "dev-admin-secret", { expiresIn: hours + "h" });
|
|
1130
|
+
setJwtCookie(res, token);
|
|
1131
|
+
res.redirect("/admin");
|
|
1132
|
+
} catch (e2) {
|
|
1133
|
+
res.status(500).send("Login failed");
|
|
1134
|
+
}
|
|
1135
|
+
});
|
|
1136
|
+
(void 0).app.get("/admin/logout", async (req, res) => {
|
|
1137
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
1138
|
+
const t = cookies["sm_admin_jwt"];
|
|
1139
|
+
if (t) {
|
|
1140
|
+
const verified = verifyAdminJwt(t);
|
|
1141
|
+
if (verified) {
|
|
1142
|
+
try {
|
|
1143
|
+
if ((void 0).pgPool) {
|
|
1144
|
+
await (void 0).pgPool.query("DELETE FROM admin_sessions WHERE id = $1", [verified.jti]);
|
|
1145
|
+
} else {
|
|
1146
|
+
(void 0).db.prepare("DELETE FROM admin_sessions WHERE id = ?").run(verified.jti);
|
|
1147
|
+
}
|
|
1148
|
+
} catch {
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
clearJwtCookie(res);
|
|
1153
|
+
res.redirect("/admin/login");
|
|
1154
|
+
});
|
|
394
1155
|
//# sourceMappingURL=index.js.map
|