feat: migrate runtime backend to node server
This commit is contained in:
264
server-node/src/app.test.ts
Normal file
264
server-node/src/app.test.ts
Normal file
@@ -0,0 +1,264 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
import { createApp } from './app.js';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { createAppContext } from './server.js';
|
||||
|
||||
function createTestConfig(testName: string): AppConfig {
|
||||
const tempRoot = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), `genarrative-server-node-${testName}-`),
|
||||
);
|
||||
|
||||
return {
|
||||
nodeEnv: 'test',
|
||||
projectRoot: tempRoot,
|
||||
publicDir: path.join(tempRoot, 'public'),
|
||||
logsDir: path.join(tempRoot, 'logs'),
|
||||
dataDir: path.join(tempRoot, 'data'),
|
||||
sqlitePath: path.join(tempRoot, 'data', 'test.sqlite'),
|
||||
serverAddr: ':0',
|
||||
logLevel: 'silent',
|
||||
jwtSecret: 'test-secret',
|
||||
jwtExpiresIn: '7d',
|
||||
jwtIssuer: 'genarrative-server-node-test',
|
||||
llm: {
|
||||
baseUrl: 'https://example.invalid',
|
||||
apiKey: '',
|
||||
model: 'test-model',
|
||||
},
|
||||
dashScope: {
|
||||
baseUrl: 'https://example.invalid',
|
||||
apiKey: '',
|
||||
imageModel: 'test-image-model',
|
||||
requestTimeoutMs: 1000,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function withTestServer<T>(
|
||||
testName: string,
|
||||
run: (options: { baseUrl: string }) => Promise<T>,
|
||||
) {
|
||||
const context = createAppContext(createTestConfig(testName));
|
||||
const app = createApp(context);
|
||||
const server = await new Promise<import('node:http').Server>((resolve) => {
|
||||
const nextServer = app.listen(0, '127.0.0.1', () => resolve(nextServer));
|
||||
});
|
||||
|
||||
try {
|
||||
const address = server.address() as AddressInfo;
|
||||
return await run({
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
});
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
context.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function authEntry(baseUrl: string, username: string, password: string) {
|
||||
const response = await fetch(`${baseUrl}/api/auth/entry`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username,
|
||||
password,
|
||||
}),
|
||||
});
|
||||
const payload = await response.json() as {
|
||||
token: string;
|
||||
user: {
|
||||
id: string;
|
||||
username: string;
|
||||
};
|
||||
};
|
||||
|
||||
assert.equal(response.status, 200);
|
||||
assert.ok(payload.token);
|
||||
return payload;
|
||||
}
|
||||
|
||||
function withBearer(token: string, init: RequestInit = {}) {
|
||||
return {
|
||||
...init,
|
||||
headers: {
|
||||
...(init.headers ?? {}),
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
} satisfies RequestInit;
|
||||
}
|
||||
|
||||
test('auth entry auto-registers, me works, logout invalidates old token', async () => {
|
||||
await withTestServer('auth', async ({ baseUrl }) => {
|
||||
const entry = await authEntry(baseUrl, 'hero_test', 'secret123');
|
||||
|
||||
const meResponse = await fetch(`${baseUrl}/api/auth/me`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${entry.token}`,
|
||||
},
|
||||
});
|
||||
const mePayload = await meResponse.json() as {
|
||||
user: {
|
||||
username: string;
|
||||
};
|
||||
};
|
||||
|
||||
assert.equal(meResponse.status, 200);
|
||||
assert.equal(mePayload.user.username, 'hero_test');
|
||||
|
||||
const logoutResponse = await fetch(
|
||||
`${baseUrl}/api/auth/logout`,
|
||||
withBearer(entry.token, { method: 'POST' }),
|
||||
);
|
||||
assert.equal(logoutResponse.status, 200);
|
||||
|
||||
const expiredResponse = await fetch(`${baseUrl}/api/auth/me`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${entry.token}`,
|
||||
},
|
||||
});
|
||||
assert.equal(expiredResponse.status, 401);
|
||||
});
|
||||
});
|
||||
|
||||
test('issued jwt remains valid without exp until logout invalidates token version', async () => {
|
||||
await withTestServer('permanent-jwt', async ({ baseUrl }) => {
|
||||
const entry = await authEntry(baseUrl, 'hero_eternal', 'secret123');
|
||||
const tokenParts = entry.token.split('.');
|
||||
assert.equal(tokenParts.length, 3);
|
||||
|
||||
const payloadJson = JSON.parse(
|
||||
Buffer.from(tokenParts[1] || '', 'base64url').toString('utf8'),
|
||||
) as {
|
||||
exp?: number;
|
||||
sub?: string;
|
||||
ver?: number;
|
||||
};
|
||||
|
||||
assert.equal(typeof payloadJson.sub, 'string');
|
||||
assert.equal(typeof payloadJson.ver, 'number');
|
||||
assert.equal('exp' in payloadJson, false);
|
||||
|
||||
const meResponse = await fetch(`${baseUrl}/api/auth/me`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${entry.token}`,
|
||||
},
|
||||
});
|
||||
assert.equal(meResponse.status, 200);
|
||||
|
||||
const logoutResponse = await fetch(
|
||||
`${baseUrl}/api/auth/logout`,
|
||||
withBearer(entry.token, { method: 'POST' }),
|
||||
);
|
||||
assert.equal(logoutResponse.status, 200);
|
||||
|
||||
const invalidatedResponse = await fetch(`${baseUrl}/api/auth/me`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${entry.token}`,
|
||||
},
|
||||
});
|
||||
assert.equal(invalidatedResponse.status, 401);
|
||||
});
|
||||
});
|
||||
|
||||
test('runtime persistence is isolated by user', async () => {
|
||||
await withTestServer('persistence', async ({ baseUrl }) => {
|
||||
const userA = await authEntry(baseUrl, 'player_one', 'secret123');
|
||||
const userB = await authEntry(baseUrl, 'player_two', 'secret123');
|
||||
|
||||
const saveResponse = await fetch(
|
||||
`${baseUrl}/api/runtime/save/snapshot`,
|
||||
withBearer(userA.token, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
gameState: { worldType: 'WUXIA', value: 1 },
|
||||
bottomTab: 'adventure',
|
||||
currentStory: { text: 'story A' },
|
||||
}),
|
||||
}),
|
||||
);
|
||||
assert.equal(saveResponse.status, 200);
|
||||
|
||||
const settingsResponse = await fetch(
|
||||
`${baseUrl}/api/runtime/settings`,
|
||||
withBearer(userA.token, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
musicVolume: 0.25,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
assert.equal(settingsResponse.status, 200);
|
||||
|
||||
const libraryResponse = await fetch(
|
||||
`${baseUrl}/api/runtime/custom-world-library/world-a`,
|
||||
withBearer(userA.token, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
profile: {
|
||||
id: 'world-a',
|
||||
name: '世界 A',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
assert.equal(libraryResponse.status, 200);
|
||||
|
||||
const userASave = await fetch(`${baseUrl}/api/runtime/save/snapshot`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${userA.token}`,
|
||||
},
|
||||
});
|
||||
const userASavePayload = await userASave.json() as {
|
||||
gameState: {
|
||||
value: number;
|
||||
};
|
||||
};
|
||||
assert.equal(userASavePayload.gameState.value, 1);
|
||||
|
||||
const userBSave = await fetch(`${baseUrl}/api/runtime/save/snapshot`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${userB.token}`,
|
||||
},
|
||||
});
|
||||
const userBSavePayload = await userBSave.json();
|
||||
assert.equal(userBSavePayload, null);
|
||||
|
||||
const userBSettings = await fetch(`${baseUrl}/api/runtime/settings`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${userB.token}`,
|
||||
},
|
||||
});
|
||||
const userBSettingsPayload = await userBSettings.json() as {
|
||||
musicVolume: number;
|
||||
};
|
||||
assert.equal(userBSettingsPayload.musicVolume, 0.42);
|
||||
|
||||
const userBLibrary = await fetch(
|
||||
`${baseUrl}/api/runtime/custom-world-library`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${userB.token}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
const userBLibraryPayload = await userBLibrary.json() as {
|
||||
profiles: unknown[];
|
||||
};
|
||||
assert.deepEqual(userBLibraryPayload.profiles, []);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user