Implement OAuth client and token management with settings updates (#464)

This commit is contained in:
samanhappy
2025-12-01 16:02:55 +08:00
committed by GitHub
parent b5dff990e5
commit 764959eaca
34 changed files with 2306 additions and 1051 deletions

View File

@@ -14,10 +14,10 @@ import { IOAuthClient } from '../types/index.js';
* GET /api/oauth/clients
* Get all OAuth clients
*/
export const getAllClients = (req: Request, res: Response): void => {
export const getAllClients = async (req: Request, res: Response): Promise<void> => {
try {
const clients = getOAuthClients();
const clients = await getOAuthClients();
// Don't expose client secrets in the list
const sanitizedClients = clients.map((client) => ({
clientId: client.clientId,
@@ -45,10 +45,10 @@ export const getAllClients = (req: Request, res: Response): void => {
* GET /api/oauth/clients/:clientId
* Get a specific OAuth client
*/
export const getClient = (req: Request, res: Response): void => {
export const getClient = async (req: Request, res: Response): Promise<void> => {
try {
const { clientId } = req.params;
const client = findOAuthClientById(clientId);
const client = await findOAuthClientById(clientId);
if (!client) {
res.status(404).json({
@@ -85,7 +85,7 @@ export const getClient = (req: Request, res: Response): void => {
* POST /api/oauth/clients
* Create a new OAuth client
*/
export const createClient = (req: Request, res: Response): void => {
export const createClient = async (req: Request, res: Response): Promise<void> => {
try {
// Validate request
const errors = validationResult(req);
@@ -105,7 +105,8 @@ export const createClient = (req: Request, res: Response): void => {
const clientId = crypto.randomBytes(16).toString('hex');
// Generate client secret if required
const clientSecret = requireSecret !== false ? crypto.randomBytes(32).toString('hex') : undefined;
const clientSecret =
requireSecret !== false ? crypto.randomBytes(32).toString('hex') : undefined;
// Create client
const client: IOAuthClient = {
@@ -118,7 +119,7 @@ export const createClient = (req: Request, res: Response): void => {
owner: user?.username || 'admin',
};
const createdClient = createOAuthClient(client);
const createdClient = await createOAuthClient(client);
// Return client with secret (only shown once)
res.status(201).json({
@@ -139,7 +140,7 @@ export const createClient = (req: Request, res: Response): void => {
});
} catch (error) {
console.error('Create OAuth client error:', error);
if (error instanceof Error && error.message.includes('already exists')) {
res.status(409).json({
success: false,
@@ -158,18 +159,19 @@ export const createClient = (req: Request, res: Response): void => {
* PUT /api/oauth/clients/:clientId
* Update an OAuth client
*/
export const updateClient = (req: Request, res: Response): void => {
export const updateClient = async (req: Request, res: Response): Promise<void> => {
try {
const { clientId } = req.params;
const { name, redirectUris, grants, scopes } = req.body;
const updates: Partial<IOAuthClient> = {};
if (name) updates.name = name;
if (redirectUris) updates.redirectUris = Array.isArray(redirectUris) ? redirectUris : [redirectUris];
if (redirectUris)
updates.redirectUris = Array.isArray(redirectUris) ? redirectUris : [redirectUris];
if (grants) updates.grants = grants;
if (scopes) updates.scopes = scopes;
const updatedClient = updateOAuthClient(clientId, updates);
const updatedClient = await updateOAuthClient(clientId, updates);
if (!updatedClient) {
res.status(404).json({
@@ -205,10 +207,10 @@ export const updateClient = (req: Request, res: Response): void => {
* DELETE /api/oauth/clients/:clientId
* Delete an OAuth client
*/
export const deleteClient = (req: Request, res: Response): void => {
export const deleteClient = async (req: Request, res: Response): Promise<void> => {
try {
const { clientId } = req.params;
const deleted = deleteOAuthClient(clientId);
const deleted = await deleteOAuthClient(clientId);
if (!deleted) {
res.status(404).json({
@@ -235,10 +237,10 @@ export const deleteClient = (req: Request, res: Response): void => {
* POST /api/oauth/clients/:clientId/regenerate-secret
* Regenerate client secret
*/
export const regenerateSecret = (req: Request, res: Response): void => {
export const regenerateSecret = async (req: Request, res: Response): Promise<void> => {
try {
const { clientId } = req.params;
const client = findOAuthClientById(clientId);
const client = await findOAuthClientById(clientId);
if (!client) {
res.status(404).json({
@@ -250,7 +252,7 @@ export const regenerateSecret = (req: Request, res: Response): void => {
// Generate new secret
const newSecret = crypto.randomBytes(32).toString('hex');
const updatedClient = updateOAuthClient(clientId, { clientSecret: newSecret });
const updatedClient = await updateOAuthClient(clientId, { clientSecret: newSecret });
if (!updatedClient) {
res.status(500).json({

View File

@@ -48,7 +48,7 @@ const verifyRegistrationToken = (token: string): string | null => {
* RFC 7591 Dynamic Client Registration
* Public endpoint for registering new OAuth clients
*/
export const registerClient = (req: Request, res: Response): void => {
export const registerClient = async (req: Request, res: Response): Promise<void> => {
try {
const settings = loadSettings();
const oauthConfig = settings.systemConfig?.oauthServer;
@@ -183,7 +183,7 @@ export const registerClient = (req: Request, res: Response): void => {
},
};
const createdClient = createOAuthClient(client);
const createdClient = await createOAuthClient(client);
// Build response according to RFC 7591
const response: any = {
@@ -238,7 +238,7 @@ export const registerClient = (req: Request, res: Response): void => {
* RFC 7591 Client Configuration Endpoint
* Read client configuration
*/
export const getClientConfiguration = (req: Request, res: Response): void => {
export const getClientConfiguration = async (req: Request, res: Response): Promise<void> => {
try {
const { clientId } = req.params;
const authHeader = req.headers.authorization;
@@ -262,7 +262,7 @@ export const getClientConfiguration = (req: Request, res: Response): void => {
return;
}
const client = findOAuthClientById(clientId);
const client = await findOAuthClientById(clientId);
if (!client) {
res.status(404).json({
error: 'invalid_client',
@@ -311,7 +311,7 @@ export const getClientConfiguration = (req: Request, res: Response): void => {
* RFC 7591 Client Update Endpoint
* Update client configuration
*/
export const updateClientConfiguration = (req: Request, res: Response): void => {
export const updateClientConfiguration = async (req: Request, res: Response): Promise<void> => {
try {
const { clientId } = req.params;
const authHeader = req.headers.authorization;
@@ -335,7 +335,7 @@ export const updateClientConfiguration = (req: Request, res: Response): void =>
return;
}
const client = findOAuthClientById(clientId);
const client = await findOAuthClientById(clientId);
if (!client) {
res.status(404).json({
error: 'invalid_client',
@@ -443,7 +443,7 @@ export const updateClientConfiguration = (req: Request, res: Response): void =>
};
}
const updatedClient = updateOAuthClient(clientId, updates);
const updatedClient = await updateOAuthClient(clientId, updates);
if (!updatedClient) {
res.status(500).json({
@@ -495,7 +495,7 @@ export const updateClientConfiguration = (req: Request, res: Response): void =>
* RFC 7591 Client Delete Endpoint
* Delete client registration
*/
export const deleteClientRegistration = (req: Request, res: Response): void => {
export const deleteClientRegistration = async (req: Request, res: Response): Promise<void> => {
try {
const { clientId } = req.params;
const authHeader = req.headers.authorization;
@@ -519,7 +519,7 @@ export const deleteClientRegistration = (req: Request, res: Response): void => {
return;
}
const deleted = deleteOAuthClient(clientId);
const deleted = await deleteOAuthClient(clientId);
if (!deleted) {
res.status(404).json({

View File

@@ -212,7 +212,7 @@ export const getAuthorize = async (req: Request, res: Response): Promise<void> =
}
// Verify client
const client = findOAuthClientById(client_id as string);
const client = await findOAuthClientById(client_id as string);
if (!client) {
res.status(400).json({ error: 'invalid_client', error_description: 'Client not found' });
return;

View File

@@ -9,7 +9,7 @@ import {
syncToolEmbedding,
toggleServerStatus,
} from '../services/mcpService.js';
import { loadSettings, saveSettings } from '../config/index.js';
import { loadSettings } from '../config/index.js';
import { syncAllServerToolsEmbeddings } from '../services/vectorSearchService.js';
import { createSafeJSON } from '../utils/serialization.js';
import { cloneDefaultOAuthServerConfig } from '../constants/oauthServerDefaults.js';
@@ -439,8 +439,10 @@ export const toggleTool = async (req: Request, res: Response): Promise<void> =>
return;
}
const settings = loadSettings();
if (!settings.mcpServers[serverName]) {
const serverDao = getServerDao();
const server = await serverDao.findById(serverName);
if (!server) {
res.status(404).json({
success: false,
message: 'Server not found',
@@ -449,14 +451,15 @@ export const toggleTool = async (req: Request, res: Response): Promise<void> =>
}
// Initialize tools config if it doesn't exist
if (!settings.mcpServers[serverName].tools) {
settings.mcpServers[serverName].tools = {};
}
const tools = server.tools || {};
// Set the tool's enabled state
settings.mcpServers[serverName].tools![toolName] = { enabled };
// Set the tool's enabled state (preserve existing description if any)
tools[toolName] = { ...tools[toolName], enabled };
if (!saveSettings(settings)) {
// Update via DAO (supports both file and database modes)
const result = await serverDao.updateTools(serverName, tools);
if (!result) {
res.status(500).json({
success: false,
message: 'Failed to save settings',
@@ -503,8 +506,10 @@ export const updateToolDescription = async (req: Request, res: Response): Promis
return;
}
const settings = loadSettings();
if (!settings.mcpServers[serverName]) {
const serverDao = getServerDao();
const server = await serverDao.findById(serverName);
if (!server) {
res.status(404).json({
success: false,
message: 'Server not found',
@@ -513,18 +518,18 @@ export const updateToolDescription = async (req: Request, res: Response): Promis
}
// Initialize tools config if it doesn't exist
if (!settings.mcpServers[serverName].tools) {
settings.mcpServers[serverName].tools = {};
}
const tools = server.tools || {};
// Set the tool's description
if (!settings.mcpServers[serverName].tools![toolName]) {
settings.mcpServers[serverName].tools![toolName] = { enabled: true };
if (!tools[toolName]) {
tools[toolName] = { enabled: true };
}
tools[toolName].description = description;
settings.mcpServers[serverName].tools![toolName].description = description;
// Update via DAO (supports both file and database modes)
const result = await serverDao.updateTools(serverName, tools);
if (!saveSettings(settings)) {
if (!result) {
res.status(500).json({
success: false,
message: 'Failed to save settings',
@@ -939,8 +944,10 @@ export const togglePrompt = async (req: Request, res: Response): Promise<void> =
return;
}
const settings = loadSettings();
if (!settings.mcpServers[serverName]) {
const serverDao = getServerDao();
const server = await serverDao.findById(serverName);
if (!server) {
res.status(404).json({
success: false,
message: 'Server not found',
@@ -949,14 +956,15 @@ export const togglePrompt = async (req: Request, res: Response): Promise<void> =
}
// Initialize prompts config if it doesn't exist
if (!settings.mcpServers[serverName].prompts) {
settings.mcpServers[serverName].prompts = {};
}
const prompts = server.prompts || {};
// Set the prompt's enabled state
settings.mcpServers[serverName].prompts![promptName] = { enabled };
// Set the prompt's enabled state (preserve existing description if any)
prompts[promptName] = { ...prompts[promptName], enabled };
if (!saveSettings(settings)) {
// Update via DAO (supports both file and database modes)
const result = await serverDao.updatePrompts(serverName, prompts);
if (!result) {
res.status(500).json({
success: false,
message: 'Failed to save settings',
@@ -1003,8 +1011,10 @@ export const updatePromptDescription = async (req: Request, res: Response): Prom
return;
}
const settings = loadSettings();
if (!settings.mcpServers[serverName]) {
const serverDao = getServerDao();
const server = await serverDao.findById(serverName);
if (!server) {
res.status(404).json({
success: false,
message: 'Server not found',
@@ -1013,18 +1023,18 @@ export const updatePromptDescription = async (req: Request, res: Response): Prom
}
// Initialize prompts config if it doesn't exist
if (!settings.mcpServers[serverName].prompts) {
settings.mcpServers[serverName].prompts = {};
}
const prompts = server.prompts || {};
// Set the prompt's description
if (!settings.mcpServers[serverName].prompts![promptName]) {
settings.mcpServers[serverName].prompts![promptName] = { enabled: true };
if (!prompts[promptName]) {
prompts[promptName] = { enabled: true };
}
prompts[promptName].description = description;
settings.mcpServers[serverName].prompts![promptName].description = description;
// Update via DAO (supports both file and database modes)
const result = await serverDao.updatePrompts(serverName, prompts);
if (!saveSettings(settings)) {
if (!result) {
res.status(500).json({
success: false,
message: 'Failed to save settings',

View File

@@ -3,6 +3,8 @@ import { ServerDao, ServerDaoImpl } from './ServerDao.js';
import { GroupDao, GroupDaoImpl } from './GroupDao.js';
import { SystemConfigDao, SystemConfigDaoImpl } from './SystemConfigDao.js';
import { UserConfigDao, UserConfigDaoImpl } from './UserConfigDao.js';
import { OAuthClientDao, OAuthClientDaoImpl } from './OAuthClientDao.js';
import { OAuthTokenDao, OAuthTokenDaoImpl } from './OAuthTokenDao.js';
/**
* DAO Factory interface for creating DAO instances
@@ -13,6 +15,8 @@ export interface DaoFactory {
getGroupDao(): GroupDao;
getSystemConfigDao(): SystemConfigDao;
getUserConfigDao(): UserConfigDao;
getOAuthClientDao(): OAuthClientDao;
getOAuthTokenDao(): OAuthTokenDao;
}
/**
@@ -26,6 +30,8 @@ export class JsonFileDaoFactory implements DaoFactory {
private groupDao: GroupDao | null = null;
private systemConfigDao: SystemConfigDao | null = null;
private userConfigDao: UserConfigDao | null = null;
private oauthClientDao: OAuthClientDao | null = null;
private oauthTokenDao: OAuthTokenDao | null = null;
/**
* Get singleton instance
@@ -76,6 +82,20 @@ export class JsonFileDaoFactory implements DaoFactory {
return this.userConfigDao;
}
getOAuthClientDao(): OAuthClientDao {
if (!this.oauthClientDao) {
this.oauthClientDao = new OAuthClientDaoImpl();
}
return this.oauthClientDao;
}
getOAuthTokenDao(): OAuthTokenDao {
if (!this.oauthTokenDao) {
this.oauthTokenDao = new OAuthTokenDaoImpl();
}
return this.oauthTokenDao;
}
/**
* Reset all cached DAO instances (useful for testing)
*/
@@ -85,6 +105,8 @@ export class JsonFileDaoFactory implements DaoFactory {
this.groupDao = null;
this.systemConfigDao = null;
this.userConfigDao = null;
this.oauthClientDao = null;
this.oauthTokenDao = null;
}
}
@@ -149,3 +171,11 @@ export function getSystemConfigDao(): SystemConfigDao {
export function getUserConfigDao(): UserConfigDao {
return getDaoFactory().getUserConfigDao();
}
export function getOAuthClientDao(): OAuthClientDao {
return getDaoFactory().getOAuthClientDao();
}
export function getOAuthTokenDao(): OAuthTokenDao {
return getDaoFactory().getOAuthTokenDao();
}

View File

@@ -1,9 +1,20 @@
import { DaoFactory, UserDao, ServerDao, GroupDao, SystemConfigDao, UserConfigDao } from './index.js';
import {
DaoFactory,
UserDao,
ServerDao,
GroupDao,
SystemConfigDao,
UserConfigDao,
OAuthClientDao,
OAuthTokenDao,
} from './index.js';
import { UserDaoDbImpl } from './UserDaoDbImpl.js';
import { ServerDaoDbImpl } from './ServerDaoDbImpl.js';
import { GroupDaoDbImpl } from './GroupDaoDbImpl.js';
import { SystemConfigDaoDbImpl } from './SystemConfigDaoDbImpl.js';
import { UserConfigDaoDbImpl } from './UserConfigDaoDbImpl.js';
import { OAuthClientDaoDbImpl } from './OAuthClientDaoDbImpl.js';
import { OAuthTokenDaoDbImpl } from './OAuthTokenDaoDbImpl.js';
/**
* Database-backed DAO factory implementation
@@ -16,6 +27,8 @@ export class DatabaseDaoFactory implements DaoFactory {
private groupDao: GroupDao | null = null;
private systemConfigDao: SystemConfigDao | null = null;
private userConfigDao: UserConfigDao | null = null;
private oauthClientDao: OAuthClientDao | null = null;
private oauthTokenDao: OAuthTokenDao | null = null;
/**
* Get singleton instance
@@ -66,6 +79,20 @@ export class DatabaseDaoFactory implements DaoFactory {
return this.userConfigDao!;
}
getOAuthClientDao(): OAuthClientDao {
if (!this.oauthClientDao) {
this.oauthClientDao = new OAuthClientDaoDbImpl();
}
return this.oauthClientDao!;
}
getOAuthTokenDao(): OAuthTokenDao {
if (!this.oauthTokenDao) {
this.oauthTokenDao = new OAuthTokenDaoDbImpl();
}
return this.oauthTokenDao!;
}
/**
* Reset all cached DAO instances (useful for testing)
*/
@@ -75,5 +102,7 @@ export class DatabaseDaoFactory implements DaoFactory {
this.groupDao = null;
this.systemConfigDao = null;
this.userConfigDao = null;
this.oauthClientDao = null;
this.oauthTokenDao = null;
}
}

146
src/dao/OAuthClientDao.ts Normal file
View File

@@ -0,0 +1,146 @@
import { IOAuthClient } from '../types/index.js';
import { BaseDao } from './base/BaseDao.js';
import { JsonFileBaseDao } from './base/JsonFileBaseDao.js';
/**
* OAuth Client DAO interface with OAuth client-specific operations
*/
export interface OAuthClientDao extends BaseDao<IOAuthClient, string> {
/**
* Find OAuth client by client ID
*/
findByClientId(clientId: string): Promise<IOAuthClient | null>;
/**
* Find OAuth clients by owner
*/
findByOwner(owner: string): Promise<IOAuthClient[]>;
/**
* Validate client credentials
*/
validateCredentials(clientId: string, clientSecret?: string): Promise<boolean>;
}
/**
* JSON file-based OAuth Client DAO implementation
*/
export class OAuthClientDaoImpl extends JsonFileBaseDao implements OAuthClientDao {
protected async getAll(): Promise<IOAuthClient[]> {
const settings = await this.loadSettings();
return settings.oauthClients || [];
}
protected async saveAll(clients: IOAuthClient[]): Promise<void> {
const settings = await this.loadSettings();
settings.oauthClients = clients;
await this.saveSettings(settings);
}
protected getEntityId(client: IOAuthClient): string {
return client.clientId;
}
protected createEntity(_data: Omit<IOAuthClient, 'clientId'>): IOAuthClient {
throw new Error('clientId must be provided');
}
protected updateEntity(existing: IOAuthClient, updates: Partial<IOAuthClient>): IOAuthClient {
return {
...existing,
...updates,
clientId: existing.clientId, // clientId should not be updated
};
}
async findAll(): Promise<IOAuthClient[]> {
return this.getAll();
}
async findById(clientId: string): Promise<IOAuthClient | null> {
return this.findByClientId(clientId);
}
async findByClientId(clientId: string): Promise<IOAuthClient | null> {
const clients = await this.getAll();
return clients.find((client) => client.clientId === clientId) || null;
}
async findByOwner(owner: string): Promise<IOAuthClient[]> {
const clients = await this.getAll();
return clients.filter((client) => client.owner === owner);
}
async create(data: IOAuthClient): Promise<IOAuthClient> {
const clients = await this.getAll();
// Check if client already exists
if (clients.find((client) => client.clientId === data.clientId)) {
throw new Error(`OAuth client ${data.clientId} already exists`);
}
const newClient: IOAuthClient = {
...data,
owner: data.owner || 'admin',
};
clients.push(newClient);
await this.saveAll(clients);
return newClient;
}
async update(clientId: string, updates: Partial<IOAuthClient>): Promise<IOAuthClient | null> {
const clients = await this.getAll();
const index = clients.findIndex((client) => client.clientId === clientId);
if (index === -1) {
return null;
}
// Don't allow clientId changes
const { clientId: _, ...allowedUpdates } = updates;
const updatedClient = this.updateEntity(clients[index], allowedUpdates);
clients[index] = updatedClient;
await this.saveAll(clients);
return updatedClient;
}
async delete(clientId: string): Promise<boolean> {
const clients = await this.getAll();
const index = clients.findIndex((client) => client.clientId === clientId);
if (index === -1) {
return false;
}
clients.splice(index, 1);
await this.saveAll(clients);
return true;
}
async exists(clientId: string): Promise<boolean> {
const client = await this.findByClientId(clientId);
return client !== null;
}
async count(): Promise<number> {
const clients = await this.getAll();
return clients.length;
}
async validateCredentials(clientId: string, clientSecret?: string): Promise<boolean> {
const client = await this.findByClientId(clientId);
if (!client) {
return false;
}
// If client has no secret (public client), accept if no secret provided
if (!client.clientSecret) {
return !clientSecret;
}
// If client has a secret, it must match
return client.clientSecret === clientSecret;
}
}

View File

@@ -0,0 +1,109 @@
import { OAuthClientDao } from './OAuthClientDao.js';
import { OAuthClientRepository } from '../db/repositories/OAuthClientRepository.js';
import { IOAuthClient } from '../types/index.js';
/**
* Database-backed implementation of OAuthClientDao
*/
export class OAuthClientDaoDbImpl implements OAuthClientDao {
private repository: OAuthClientRepository;
constructor() {
this.repository = new OAuthClientRepository();
}
async findAll(): Promise<IOAuthClient[]> {
const clients = await this.repository.findAll();
return clients.map((c) => this.mapToOAuthClient(c));
}
async findById(clientId: string): Promise<IOAuthClient | null> {
const client = await this.repository.findByClientId(clientId);
return client ? this.mapToOAuthClient(client) : null;
}
async findByClientId(clientId: string): Promise<IOAuthClient | null> {
return this.findById(clientId);
}
async findByOwner(owner: string): Promise<IOAuthClient[]> {
const clients = await this.repository.findByOwner(owner);
return clients.map((c) => this.mapToOAuthClient(c));
}
async create(entity: IOAuthClient): Promise<IOAuthClient> {
const client = await this.repository.create({
clientId: entity.clientId,
clientSecret: entity.clientSecret,
name: entity.name,
redirectUris: entity.redirectUris,
grants: entity.grants,
scopes: entity.scopes,
owner: entity.owner || 'admin',
metadata: entity.metadata,
});
return this.mapToOAuthClient(client);
}
async update(clientId: string, entity: Partial<IOAuthClient>): Promise<IOAuthClient | null> {
const client = await this.repository.update(clientId, {
clientSecret: entity.clientSecret,
name: entity.name,
redirectUris: entity.redirectUris,
grants: entity.grants,
scopes: entity.scopes,
owner: entity.owner,
metadata: entity.metadata,
});
return client ? this.mapToOAuthClient(client) : null;
}
async delete(clientId: string): Promise<boolean> {
return await this.repository.delete(clientId);
}
async exists(clientId: string): Promise<boolean> {
return await this.repository.exists(clientId);
}
async count(): Promise<number> {
return await this.repository.count();
}
async validateCredentials(clientId: string, clientSecret?: string): Promise<boolean> {
const client = await this.findByClientId(clientId);
if (!client) {
return false;
}
// If client has no secret (public client), accept if no secret provided
if (!client.clientSecret) {
return !clientSecret;
}
// If client has a secret, it must match
return client.clientSecret === clientSecret;
}
private mapToOAuthClient(client: {
clientId: string;
clientSecret?: string;
name: string;
redirectUris: string[];
grants: string[];
scopes?: string[];
owner?: string;
metadata?: Record<string, any>;
}): IOAuthClient {
return {
clientId: client.clientId,
clientSecret: client.clientSecret,
name: client.name,
redirectUris: client.redirectUris,
grants: client.grants,
scopes: client.scopes,
owner: client.owner,
metadata: client.metadata as IOAuthClient['metadata'],
};
}
}

259
src/dao/OAuthTokenDao.ts Normal file
View File

@@ -0,0 +1,259 @@
import { IOAuthToken } from '../types/index.js';
import { BaseDao } from './base/BaseDao.js';
import { JsonFileBaseDao } from './base/JsonFileBaseDao.js';
/**
* OAuth Token DAO interface with OAuth token-specific operations
*/
export interface OAuthTokenDao extends BaseDao<IOAuthToken, string> {
/**
* Find token by access token
*/
findByAccessToken(accessToken: string): Promise<IOAuthToken | null>;
/**
* Find token by refresh token
*/
findByRefreshToken(refreshToken: string): Promise<IOAuthToken | null>;
/**
* Find tokens by client ID
*/
findByClientId(clientId: string): Promise<IOAuthToken[]>;
/**
* Find tokens by username
*/
findByUsername(username: string): Promise<IOAuthToken[]>;
/**
* Revoke token (delete by access token or refresh token)
*/
revokeToken(token: string): Promise<boolean>;
/**
* Revoke all tokens for a user
*/
revokeUserTokens(username: string): Promise<number>;
/**
* Revoke all tokens for a client
*/
revokeClientTokens(clientId: string): Promise<number>;
/**
* Clean up expired tokens
*/
cleanupExpired(): Promise<number>;
/**
* Check if access token is valid (exists and not expired)
*/
isAccessTokenValid(accessToken: string): Promise<boolean>;
/**
* Check if refresh token is valid (exists and not expired)
*/
isRefreshTokenValid(refreshToken: string): Promise<boolean>;
}
/**
* JSON file-based OAuth Token DAO implementation
*/
export class OAuthTokenDaoImpl extends JsonFileBaseDao implements OAuthTokenDao {
protected async getAll(): Promise<IOAuthToken[]> {
const settings = await this.loadSettings();
// Convert stored dates back to Date objects
return (settings.oauthTokens || []).map((token) => ({
...token,
accessTokenExpiresAt: new Date(token.accessTokenExpiresAt),
refreshTokenExpiresAt: token.refreshTokenExpiresAt
? new Date(token.refreshTokenExpiresAt)
: undefined,
}));
}
protected async saveAll(tokens: IOAuthToken[]): Promise<void> {
const settings = await this.loadSettings();
settings.oauthTokens = tokens;
await this.saveSettings(settings);
}
protected getEntityId(token: IOAuthToken): string {
return token.accessToken;
}
protected createEntity(_data: Omit<IOAuthToken, 'accessToken'>): IOAuthToken {
throw new Error('accessToken must be provided');
}
protected updateEntity(existing: IOAuthToken, updates: Partial<IOAuthToken>): IOAuthToken {
return {
...existing,
...updates,
accessToken: existing.accessToken, // accessToken should not be updated
};
}
async findAll(): Promise<IOAuthToken[]> {
return this.getAll();
}
async findById(accessToken: string): Promise<IOAuthToken | null> {
return this.findByAccessToken(accessToken);
}
async findByAccessToken(accessToken: string): Promise<IOAuthToken | null> {
const tokens = await this.getAll();
return tokens.find((token) => token.accessToken === accessToken) || null;
}
async findByRefreshToken(refreshToken: string): Promise<IOAuthToken | null> {
const tokens = await this.getAll();
return tokens.find((token) => token.refreshToken === refreshToken) || null;
}
async findByClientId(clientId: string): Promise<IOAuthToken[]> {
const tokens = await this.getAll();
return tokens.filter((token) => token.clientId === clientId);
}
async findByUsername(username: string): Promise<IOAuthToken[]> {
const tokens = await this.getAll();
return tokens.filter((token) => token.username === username);
}
async create(data: IOAuthToken): Promise<IOAuthToken> {
const tokens = await this.getAll();
// Remove any existing tokens with the same access token or refresh token
const filteredTokens = tokens.filter(
(t) => t.accessToken !== data.accessToken && t.refreshToken !== data.refreshToken,
);
const newToken: IOAuthToken = {
...data,
};
filteredTokens.push(newToken);
await this.saveAll(filteredTokens);
return newToken;
}
async update(accessToken: string, updates: Partial<IOAuthToken>): Promise<IOAuthToken | null> {
const tokens = await this.getAll();
const index = tokens.findIndex((token) => token.accessToken === accessToken);
if (index === -1) {
return null;
}
// Don't allow accessToken changes
const { accessToken: _, ...allowedUpdates } = updates;
const updatedToken = this.updateEntity(tokens[index], allowedUpdates);
tokens[index] = updatedToken;
await this.saveAll(tokens);
return updatedToken;
}
async delete(accessToken: string): Promise<boolean> {
const tokens = await this.getAll();
const index = tokens.findIndex((token) => token.accessToken === accessToken);
if (index === -1) {
return false;
}
tokens.splice(index, 1);
await this.saveAll(tokens);
return true;
}
async exists(accessToken: string): Promise<boolean> {
const token = await this.findByAccessToken(accessToken);
return token !== null;
}
async count(): Promise<number> {
const tokens = await this.getAll();
return tokens.length;
}
async revokeToken(token: string): Promise<boolean> {
const tokens = await this.getAll();
const tokenData = tokens.find((t) => t.accessToken === token || t.refreshToken === token);
if (!tokenData) {
return false;
}
const filteredTokens = tokens.filter(
(t) => t.accessToken !== tokenData.accessToken && t.refreshToken !== tokenData.refreshToken,
);
await this.saveAll(filteredTokens);
return true;
}
async revokeUserTokens(username: string): Promise<number> {
const tokens = await this.getAll();
const userTokens = tokens.filter((token) => token.username === username);
const remainingTokens = tokens.filter((token) => token.username !== username);
await this.saveAll(remainingTokens);
return userTokens.length;
}
async revokeClientTokens(clientId: string): Promise<number> {
const tokens = await this.getAll();
const clientTokens = tokens.filter((token) => token.clientId === clientId);
const remainingTokens = tokens.filter((token) => token.clientId !== clientId);
await this.saveAll(remainingTokens);
return clientTokens.length;
}
async cleanupExpired(): Promise<number> {
const tokens = await this.getAll();
const now = new Date();
const validTokens = tokens.filter((token) => {
// Keep if access token is still valid
if (token.accessTokenExpiresAt > now) {
return true;
}
// Or if refresh token exists and is still valid
if (token.refreshToken && token.refreshTokenExpiresAt && token.refreshTokenExpiresAt > now) {
return true;
}
return false;
});
const expiredCount = tokens.length - validTokens.length;
if (expiredCount > 0) {
await this.saveAll(validTokens);
}
return expiredCount;
}
async isAccessTokenValid(accessToken: string): Promise<boolean> {
const token = await this.findByAccessToken(accessToken);
if (!token) {
return false;
}
return token.accessTokenExpiresAt > new Date();
}
async isRefreshTokenValid(refreshToken: string): Promise<boolean> {
const token = await this.findByRefreshToken(refreshToken);
if (!token) {
return false;
}
if (!token.refreshTokenExpiresAt) {
return true; // No expiration means always valid
}
return token.refreshTokenExpiresAt > new Date();
}
}

View File

@@ -0,0 +1,122 @@
import { OAuthTokenDao } from './OAuthTokenDao.js';
import { OAuthTokenRepository } from '../db/repositories/OAuthTokenRepository.js';
import { IOAuthToken } from '../types/index.js';
/**
* Database-backed implementation of OAuthTokenDao
*/
export class OAuthTokenDaoDbImpl implements OAuthTokenDao {
private repository: OAuthTokenRepository;
constructor() {
this.repository = new OAuthTokenRepository();
}
async findAll(): Promise<IOAuthToken[]> {
const tokens = await this.repository.findAll();
return tokens.map((t) => this.mapToOAuthToken(t));
}
async findById(accessToken: string): Promise<IOAuthToken | null> {
const token = await this.repository.findByAccessToken(accessToken);
return token ? this.mapToOAuthToken(token) : null;
}
async findByAccessToken(accessToken: string): Promise<IOAuthToken | null> {
return this.findById(accessToken);
}
async findByRefreshToken(refreshToken: string): Promise<IOAuthToken | null> {
const token = await this.repository.findByRefreshToken(refreshToken);
return token ? this.mapToOAuthToken(token) : null;
}
async findByClientId(clientId: string): Promise<IOAuthToken[]> {
const tokens = await this.repository.findByClientId(clientId);
return tokens.map((t) => this.mapToOAuthToken(t));
}
async findByUsername(username: string): Promise<IOAuthToken[]> {
const tokens = await this.repository.findByUsername(username);
return tokens.map((t) => this.mapToOAuthToken(t));
}
async create(entity: IOAuthToken): Promise<IOAuthToken> {
const token = await this.repository.create({
accessToken: entity.accessToken,
accessTokenExpiresAt: entity.accessTokenExpiresAt,
refreshToken: entity.refreshToken,
refreshTokenExpiresAt: entity.refreshTokenExpiresAt,
scope: entity.scope,
clientId: entity.clientId,
username: entity.username,
});
return this.mapToOAuthToken(token);
}
async update(accessToken: string, entity: Partial<IOAuthToken>): Promise<IOAuthToken | null> {
const token = await this.repository.update(accessToken, {
accessTokenExpiresAt: entity.accessTokenExpiresAt,
refreshToken: entity.refreshToken,
refreshTokenExpiresAt: entity.refreshTokenExpiresAt,
scope: entity.scope,
});
return token ? this.mapToOAuthToken(token) : null;
}
async delete(accessToken: string): Promise<boolean> {
return await this.repository.delete(accessToken);
}
async exists(accessToken: string): Promise<boolean> {
return await this.repository.exists(accessToken);
}
async count(): Promise<number> {
return await this.repository.count();
}
async revokeToken(token: string): Promise<boolean> {
return await this.repository.revokeToken(token);
}
async revokeUserTokens(username: string): Promise<number> {
return await this.repository.revokeUserTokens(username);
}
async revokeClientTokens(clientId: string): Promise<number> {
return await this.repository.revokeClientTokens(clientId);
}
async cleanupExpired(): Promise<number> {
return await this.repository.cleanupExpired();
}
async isAccessTokenValid(accessToken: string): Promise<boolean> {
return await this.repository.isAccessTokenValid(accessToken);
}
async isRefreshTokenValid(refreshToken: string): Promise<boolean> {
return await this.repository.isRefreshTokenValid(refreshToken);
}
private mapToOAuthToken(token: {
accessToken: string;
accessTokenExpiresAt: Date;
refreshToken?: string;
refreshTokenExpiresAt?: Date;
scope?: string;
clientId: string;
username: string;
}): IOAuthToken {
return {
accessToken: token.accessToken,
accessTokenExpiresAt: token.accessTokenExpiresAt,
refreshToken: token.refreshToken,
refreshTokenExpiresAt: token.refreshTokenExpiresAt,
scope: token.scope,
clientId: token.clientId,
username: token.username,
};
}
}

View File

@@ -6,6 +6,8 @@ export * from './ServerDao.js';
export * from './GroupDao.js';
export * from './SystemConfigDao.js';
export * from './UserConfigDao.js';
export * from './OAuthClientDao.js';
export * from './OAuthTokenDao.js';
// Export database implementations
export * from './UserDaoDbImpl.js';
@@ -13,6 +15,8 @@ export * from './ServerDaoDbImpl.js';
export * from './GroupDaoDbImpl.js';
export * from './SystemConfigDaoDbImpl.js';
export * from './UserConfigDaoDbImpl.js';
export * from './OAuthClientDaoDbImpl.js';
export * from './OAuthTokenDaoDbImpl.js';
// Export the DAO factory and convenience functions
export * from './DaoFactory.js';

View File

@@ -0,0 +1,60 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
} from 'typeorm';
/**
* OAuth Client entity for database storage
* Represents OAuth clients registered with MCPHub's authorization server
*/
@Entity({ name: 'oauth_clients' })
export class OAuthClient {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ name: 'client_id', type: 'varchar', length: 255, unique: true })
clientId: string;
@Column({ name: 'client_secret', type: 'varchar', length: 255, nullable: true })
clientSecret?: string;
@Column({ type: 'varchar', length: 255 })
name: string;
@Column({ name: 'redirect_uris', type: 'simple-json' })
redirectUris: string[];
@Column({ type: 'simple-json' })
grants: string[];
@Column({ type: 'simple-json', nullable: true })
scopes?: string[];
@Column({ type: 'varchar', length: 255, nullable: true })
owner?: string;
@Column({ type: 'simple-json', nullable: true })
metadata?: {
application_type?: 'web' | 'native';
response_types?: string[];
token_endpoint_auth_method?: string;
contacts?: string[];
logo_uri?: string;
client_uri?: string;
policy_uri?: string;
tos_uri?: string;
jwks_uri?: string;
jwks?: object;
};
@CreateDateColumn({ name: 'created_at', type: 'timestamp' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp' })
updatedAt: Date;
}
export default OAuthClient;

View File

@@ -0,0 +1,51 @@
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
Index,
} from 'typeorm';
/**
* OAuth Token entity for database storage
* Represents OAuth tokens issued by MCPHub's authorization server
*/
@Entity({ name: 'oauth_tokens' })
export class OAuthToken {
@PrimaryGeneratedColumn('uuid')
id: string;
@Index()
@Column({ name: 'access_token', type: 'varchar', length: 512, unique: true })
accessToken: string;
@Column({ name: 'access_token_expires_at', type: 'timestamp' })
accessTokenExpiresAt: Date;
@Index()
@Column({ name: 'refresh_token', type: 'varchar', length: 512, nullable: true, unique: true })
refreshToken?: string;
@Column({ name: 'refresh_token_expires_at', type: 'timestamp', nullable: true })
refreshTokenExpiresAt?: Date;
@Column({ type: 'varchar', length: 512, nullable: true })
scope?: string;
@Index()
@Column({ name: 'client_id', type: 'varchar', length: 255 })
clientId: string;
@Index()
@Column({ type: 'varchar', length: 255 })
username: string;
@CreateDateColumn({ name: 'created_at', type: 'timestamp' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at', type: 'timestamp' })
updatedAt: Date;
}
export default OAuthToken;

View File

@@ -4,9 +4,20 @@ import Server from './Server.js';
import Group from './Group.js';
import SystemConfig from './SystemConfig.js';
import UserConfig from './UserConfig.js';
import OAuthClient from './OAuthClient.js';
import OAuthToken from './OAuthToken.js';
// Export all entities
export default [VectorEmbedding, User, Server, Group, SystemConfig, UserConfig];
export default [
VectorEmbedding,
User,
Server,
Group,
SystemConfig,
UserConfig,
OAuthClient,
OAuthToken,
];
// Export individual entities for direct use
export { VectorEmbedding, User, Server, Group, SystemConfig, UserConfig };
export { VectorEmbedding, User, Server, Group, SystemConfig, UserConfig, OAuthClient, OAuthToken };

View File

@@ -16,7 +16,7 @@ export class GroupRepository {
* Find all groups
*/
async findAll(): Promise<Group[]> {
return await this.repository.find();
return await this.repository.find({ order: { createdAt: 'ASC' } });
}
/**
@@ -88,7 +88,7 @@ export class GroupRepository {
* Find groups by owner
*/
async findByOwner(owner: string): Promise<Group[]> {
return await this.repository.find({ where: { owner } });
return await this.repository.find({ where: { owner }, order: { createdAt: 'ASC' } });
}
}

View File

@@ -0,0 +1,80 @@
import { Repository } from 'typeorm';
import { OAuthClient } from '../entities/OAuthClient.js';
import { getAppDataSource } from '../connection.js';
/**
* Repository for OAuthClient entity
*/
export class OAuthClientRepository {
private repository: Repository<OAuthClient>;
constructor() {
this.repository = getAppDataSource().getRepository(OAuthClient);
}
/**
* Find all OAuth clients
*/
async findAll(): Promise<OAuthClient[]> {
return await this.repository.find();
}
/**
* Find OAuth client by client ID
*/
async findByClientId(clientId: string): Promise<OAuthClient | null> {
return await this.repository.findOne({ where: { clientId } });
}
/**
* Find OAuth clients by owner
*/
async findByOwner(owner: string): Promise<OAuthClient[]> {
return await this.repository.find({ where: { owner } });
}
/**
* Create a new OAuth client
*/
async create(client: Omit<OAuthClient, 'id' | 'createdAt' | 'updatedAt'>): Promise<OAuthClient> {
const newClient = this.repository.create(client);
return await this.repository.save(newClient);
}
/**
* Update an existing OAuth client
*/
async update(clientId: string, clientData: Partial<OAuthClient>): Promise<OAuthClient | null> {
const client = await this.findByClientId(clientId);
if (!client) {
return null;
}
const updated = this.repository.merge(client, clientData);
return await this.repository.save(updated);
}
/**
* Delete an OAuth client
*/
async delete(clientId: string): Promise<boolean> {
const result = await this.repository.delete({ clientId });
return (result.affected ?? 0) > 0;
}
/**
* Check if OAuth client exists
*/
async exists(clientId: string): Promise<boolean> {
const count = await this.repository.count({ where: { clientId } });
return count > 0;
}
/**
* Count total OAuth clients
*/
async count(): Promise<number> {
return await this.repository.count();
}
}
export default OAuthClientRepository;

View File

@@ -0,0 +1,183 @@
import { Repository, MoreThan } from 'typeorm';
import { OAuthToken } from '../entities/OAuthToken.js';
import { getAppDataSource } from '../connection.js';
/**
* Repository for OAuthToken entity
*/
export class OAuthTokenRepository {
private repository: Repository<OAuthToken>;
constructor() {
this.repository = getAppDataSource().getRepository(OAuthToken);
}
/**
* Find all OAuth tokens
*/
async findAll(): Promise<OAuthToken[]> {
return await this.repository.find();
}
/**
* Find OAuth token by access token
*/
async findByAccessToken(accessToken: string): Promise<OAuthToken | null> {
return await this.repository.findOne({ where: { accessToken } });
}
/**
* Find OAuth token by refresh token
*/
async findByRefreshToken(refreshToken: string): Promise<OAuthToken | null> {
return await this.repository.findOne({ where: { refreshToken } });
}
/**
* Find OAuth tokens by client ID
*/
async findByClientId(clientId: string): Promise<OAuthToken[]> {
return await this.repository.find({ where: { clientId } });
}
/**
* Find OAuth tokens by username
*/
async findByUsername(username: string): Promise<OAuthToken[]> {
return await this.repository.find({ where: { username } });
}
/**
* Create a new OAuth token
*/
async create(token: Omit<OAuthToken, 'id' | 'createdAt' | 'updatedAt'>): Promise<OAuthToken> {
// Remove any existing tokens with the same access token or refresh token
if (token.accessToken) {
await this.repository.delete({ accessToken: token.accessToken });
}
if (token.refreshToken) {
await this.repository.delete({ refreshToken: token.refreshToken });
}
const newToken = this.repository.create(token);
return await this.repository.save(newToken);
}
/**
* Update an existing OAuth token
*/
async update(accessToken: string, tokenData: Partial<OAuthToken>): Promise<OAuthToken | null> {
const token = await this.findByAccessToken(accessToken);
if (!token) {
return null;
}
const updated = this.repository.merge(token, tokenData);
return await this.repository.save(updated);
}
/**
* Delete an OAuth token by access token
*/
async delete(accessToken: string): Promise<boolean> {
const result = await this.repository.delete({ accessToken });
return (result.affected ?? 0) > 0;
}
/**
* Check if OAuth token exists by access token
*/
async exists(accessToken: string): Promise<boolean> {
const count = await this.repository.count({ where: { accessToken } });
return count > 0;
}
/**
* Count total OAuth tokens
*/
async count(): Promise<number> {
return await this.repository.count();
}
/**
* Revoke token by access token or refresh token
*/
async revokeToken(token: string): Promise<boolean> {
// Try to find by access token first
let tokenEntity = await this.findByAccessToken(token);
if (!tokenEntity) {
// Try to find by refresh token
tokenEntity = await this.findByRefreshToken(token);
}
if (!tokenEntity) {
return false;
}
const result = await this.repository.delete({ id: tokenEntity.id });
return (result.affected ?? 0) > 0;
}
/**
* Revoke all tokens for a user
*/
async revokeUserTokens(username: string): Promise<number> {
const result = await this.repository.delete({ username });
return result.affected ?? 0;
}
/**
* Revoke all tokens for a client
*/
async revokeClientTokens(clientId: string): Promise<number> {
const result = await this.repository.delete({ clientId });
return result.affected ?? 0;
}
/**
* Clean up expired tokens
*/
async cleanupExpired(): Promise<number> {
const now = new Date();
// Delete tokens where both access token and refresh token are expired
// (or refresh token doesn't exist)
const result = await this.repository
.createQueryBuilder()
.delete()
.from(OAuthToken)
.where('access_token_expires_at < :now', { now })
.andWhere('(refresh_token_expires_at IS NULL OR refresh_token_expires_at < :now)', { now })
.execute();
return result.affected ?? 0;
}
/**
* Check if access token is valid (exists and not expired)
*/
async isAccessTokenValid(accessToken: string): Promise<boolean> {
const count = await this.repository.count({
where: {
accessToken,
accessTokenExpiresAt: MoreThan(new Date()),
},
});
return count > 0;
}
/**
* Check if refresh token is valid (exists and not expired)
*/
async isRefreshTokenValid(refreshToken: string): Promise<boolean> {
const token = await this.findByRefreshToken(refreshToken);
if (!token) {
return false;
}
if (!token.refreshTokenExpiresAt) {
return true; // No expiration means always valid
}
return token.refreshTokenExpiresAt > new Date();
}
}
export default OAuthTokenRepository;

View File

@@ -16,7 +16,7 @@ export class ServerRepository {
* Find all servers
*/
async findAll(): Promise<Server[]> {
return await this.repository.find();
return await this.repository.find({ order: { createdAt: 'ASC' } });
}
/**
@@ -73,14 +73,14 @@ export class ServerRepository {
* Find servers by owner
*/
async findByOwner(owner: string): Promise<Server[]> {
return await this.repository.find({ where: { owner } });
return await this.repository.find({ where: { owner }, order: { createdAt: 'ASC' } });
}
/**
* Find enabled servers
*/
async findEnabled(): Promise<Server[]> {
return await this.repository.find({ where: { enabled: true } });
return await this.repository.find({ where: { enabled: true }, order: { createdAt: 'ASC' } });
}
/**

View File

@@ -16,7 +16,7 @@ export class UserRepository {
* Find all users
*/
async findAll(): Promise<User[]> {
return await this.repository.find();
return await this.repository.find({ order: { createdAt: 'ASC' } });
}
/**
@@ -73,7 +73,7 @@ export class UserRepository {
* Find all admin users
*/
async findAdmins(): Promise<User[]> {
return await this.repository.find({ where: { isAdmin: true } });
return await this.repository.find({ where: { isAdmin: true }, order: { createdAt: 'ASC' } });
}
}

View File

@@ -4,6 +4,8 @@ import { ServerRepository } from './ServerRepository.js';
import { GroupRepository } from './GroupRepository.js';
import { SystemConfigRepository } from './SystemConfigRepository.js';
import { UserConfigRepository } from './UserConfigRepository.js';
import { OAuthClientRepository } from './OAuthClientRepository.js';
import { OAuthTokenRepository } from './OAuthTokenRepository.js';
// Export all repositories
export {
@@ -13,4 +15,6 @@ export {
GroupRepository,
SystemConfigRepository,
UserConfigRepository,
OAuthClientRepository,
OAuthTokenRepository,
};

View File

@@ -67,7 +67,7 @@ export const auth = async (req: Request, res: Response, next: NextFunction): Pro
const authHeader = req.headers.authorization;
if (authHeader && authHeader.startsWith('Bearer ') && isOAuthServerEnabled()) {
const accessToken = authHeader.substring(7);
const oauthToken = getToken(accessToken);
const oauthToken = await getToken(accessToken);
if (oauthToken && oauthToken.accessToken === accessToken) {
// Valid OAuth token - look up user to get admin status

View File

@@ -1,112 +1,89 @@
import crypto from 'crypto';
import { loadSettings, saveSettings } from '../config/index.js';
import { getOAuthClientDao, getOAuthTokenDao } from '../dao/index.js';
import { IOAuthClient, IOAuthAuthorizationCode, IOAuthToken } from '../types/index.js';
// In-memory storage for authorization codes and tokens
// Authorization codes are short-lived and kept in memory only.
// Tokens are mirrored to settings (mcp_settings.json) for persistence.
// In-memory storage for authorization codes (short-lived, no persistence needed)
const authorizationCodes = new Map<string, IOAuthAuthorizationCode>();
const tokens = new Map<string, IOAuthToken>();
// Initialize token store from settings on first import
(() => {
// In-memory cache for tokens (also persisted via DAO)
const tokensCache = new Map<string, IOAuthToken>();
// Flag to track if we've initialized from DAO
let initialized = false;
/**
* Initialize token cache from DAO (async)
*/
const initializeTokenCache = async (): Promise<void> => {
if (initialized) return;
initialized = true;
try {
const settings = loadSettings();
if (Array.isArray(settings.oauthTokens)) {
for (const stored of settings.oauthTokens) {
const token: IOAuthToken = {
...stored,
accessTokenExpiresAt: new Date(stored.accessTokenExpiresAt),
refreshTokenExpiresAt: stored.refreshTokenExpiresAt
? new Date(stored.refreshTokenExpiresAt)
: undefined,
};
tokens.set(token.accessToken, token);
if (token.refreshToken) {
tokens.set(token.refreshToken, token);
}
const tokenDao = getOAuthTokenDao();
const allTokens = await tokenDao.findAll();
for (const token of allTokens) {
tokensCache.set(token.accessToken, token);
if (token.refreshToken) {
tokensCache.set(token.refreshToken, token);
}
}
} catch (error) {
console.error('Failed to initialize OAuth tokens from settings:', error);
console.error('Failed to initialize OAuth tokens from DAO:', error);
}
})();
};
// Initialize on module load (fire and forget for backward compatibility)
initializeTokenCache().catch(console.error);
/**
* Get all OAuth clients from configuration
*/
export const getOAuthClients = (): IOAuthClient[] => {
const settings = loadSettings();
return settings.oauthClients || [];
export const getOAuthClients = async (): Promise<IOAuthClient[]> => {
const clientDao = getOAuthClientDao();
return clientDao.findAll();
};
/**
* Find OAuth client by client ID
*/
export const findOAuthClientById = (clientId: string): IOAuthClient | undefined => {
const clients = getOAuthClients();
return clients.find((c) => c.clientId === clientId);
export const findOAuthClientById = async (clientId: string): Promise<IOAuthClient | undefined> => {
const clientDao = getOAuthClientDao();
const client = await clientDao.findByClientId(clientId);
return client || undefined;
};
/**
* Create a new OAuth client
*/
export const createOAuthClient = (client: IOAuthClient): IOAuthClient => {
const settings = loadSettings();
if (!settings.oauthClients) {
settings.oauthClients = [];
}
export const createOAuthClient = async (client: IOAuthClient): Promise<IOAuthClient> => {
const clientDao = getOAuthClientDao();
// Check if client already exists
const existing = settings.oauthClients.find((c) => c.clientId === client.clientId);
const existing = await clientDao.findByClientId(client.clientId);
if (existing) {
throw new Error(`OAuth client with ID ${client.clientId} already exists`);
}
settings.oauthClients.push(client);
saveSettings(settings);
return client;
return clientDao.create(client);
};
/**
* Update an existing OAuth client
*/
export const updateOAuthClient = (
export const updateOAuthClient = async (
clientId: string,
updates: Partial<IOAuthClient>,
): IOAuthClient | null => {
const settings = loadSettings();
if (!settings.oauthClients) {
return null;
}
const index = settings.oauthClients.findIndex((c) => c.clientId === clientId);
if (index === -1) {
return null;
}
settings.oauthClients[index] = { ...settings.oauthClients[index], ...updates };
saveSettings(settings);
return settings.oauthClients[index];
): Promise<IOAuthClient | null> => {
const clientDao = getOAuthClientDao();
return clientDao.update(clientId, updates);
};
/**
* Delete an OAuth client
*/
export const deleteOAuthClient = (clientId: string): boolean => {
const settings = loadSettings();
if (!settings.oauthClients) {
return false;
}
const index = settings.oauthClients.findIndex((c) => c.clientId === clientId);
if (index === -1) {
return false;
}
settings.oauthClients.splice(index, 1);
saveSettings(settings);
return true;
export const deleteOAuthClient = async (clientId: string): Promise<boolean> => {
const clientDao = getOAuthClientDao();
return clientDao.delete(clientId);
};
/**
@@ -163,11 +140,11 @@ export const revokeAuthorizationCode = (code: string): void => {
/**
* Save access token and optionally refresh token
*/
export const saveToken = (
export const saveToken = async (
tokenData: Omit<IOAuthToken, 'accessToken' | 'accessTokenExpiresAt'>,
accessTokenLifetime: number = 3600,
refreshTokenLifetime?: number,
): IOAuthToken => {
): Promise<IOAuthToken> => {
const accessToken = generateToken();
const accessTokenExpiresAt = new Date(Date.now() + accessTokenLifetime * 1000);
@@ -187,30 +164,18 @@ export const saveToken = (
...tokenData,
};
tokens.set(accessToken, token);
// Update cache
tokensCache.set(accessToken, token);
if (refreshToken) {
tokens.set(refreshToken, token);
tokensCache.set(refreshToken, token);
}
// Persist tokens to settings
// Persist to DAO
try {
const settings = loadSettings();
const existing = settings.oauthTokens || [];
const filtered = existing.filter(
(t) => t.accessToken !== token.accessToken && t.refreshToken !== token.refreshToken,
);
const updated = [
...filtered,
{
...token,
accessTokenExpiresAt: token.accessTokenExpiresAt,
refreshTokenExpiresAt: token.refreshTokenExpiresAt,
},
];
settings.oauthTokens = updated;
saveSettings(settings);
const tokenDao = getOAuthTokenDao();
await tokenDao.create(token);
} catch (error) {
console.error('Failed to persist OAuth token to settings:', error);
console.error('Failed to persist OAuth token to DAO:', error);
}
return token;
@@ -219,8 +184,27 @@ export const saveToken = (
/**
* Get token by access token or refresh token
*/
export const getToken = (token: string): IOAuthToken | undefined => {
const tokenData = tokens.get(token);
export const getToken = async (token: string): Promise<IOAuthToken | undefined> => {
// First check cache
let tokenData = tokensCache.get(token);
// If not in cache, try DAO
if (!tokenData) {
const tokenDao = getOAuthTokenDao();
tokenData =
(await tokenDao.findByAccessToken(token)) ||
(await tokenDao.findByRefreshToken(token)) ||
undefined;
// Update cache if found
if (tokenData) {
tokensCache.set(tokenData.accessToken, tokenData);
if (tokenData.refreshToken) {
tokensCache.set(tokenData.refreshToken, tokenData);
}
}
}
if (!tokenData) {
return undefined;
}
@@ -245,34 +229,28 @@ export const getToken = (token: string): IOAuthToken | undefined => {
/**
* Revoke token (both access and refresh tokens)
*/
export const revokeToken = (token: string): void => {
const tokenData = tokens.get(token);
export const revokeToken = async (token: string): Promise<void> => {
const tokenData = tokensCache.get(token);
if (tokenData) {
tokens.delete(tokenData.accessToken);
tokensCache.delete(tokenData.accessToken);
if (tokenData.refreshToken) {
tokens.delete(tokenData.refreshToken);
tokensCache.delete(tokenData.refreshToken);
}
}
// Also remove from persisted settings
try {
const settings = loadSettings();
if (Array.isArray(settings.oauthTokens)) {
settings.oauthTokens = settings.oauthTokens.filter(
(t) =>
t.accessToken !== tokenData.accessToken && t.refreshToken !== tokenData.refreshToken,
);
saveSettings(settings);
}
} catch (error) {
console.error('Failed to remove OAuth token from settings:', error);
}
// Also remove from DAO
try {
const tokenDao = getOAuthTokenDao();
await tokenDao.revokeToken(token);
} catch (error) {
console.error('Failed to remove OAuth token from DAO:', error);
}
};
/**
* Clean up expired codes and tokens (should be called periodically)
*/
export const cleanupExpired = (): void => {
export const cleanupExpired = async (): Promise<void> => {
const now = new Date();
// Clean up expired authorization codes
@@ -282,9 +260,9 @@ export const cleanupExpired = (): void => {
}
}
// Clean up expired tokens
// Clean up expired tokens from cache
const processedTokens = new Set<string>();
for (const [_key, token] of tokens.entries()) {
for (const [_key, token] of tokensCache.entries()) {
// Skip if we've already processed this token
if (processedTokens.has(token.accessToken)) {
continue;
@@ -294,35 +272,19 @@ export const cleanupExpired = (): void => {
const accessExpired = token.accessTokenExpiresAt < now;
const refreshExpired = token.refreshTokenExpiresAt && token.refreshTokenExpiresAt < now;
// If both are expired, remove the token
// If both are expired, remove from cache
if (accessExpired && (!token.refreshToken || refreshExpired)) {
tokens.delete(token.accessToken);
tokensCache.delete(token.accessToken);
if (token.refreshToken) {
tokens.delete(token.refreshToken);
tokensCache.delete(token.refreshToken);
}
}
}
// Sync persisted tokens: keep only non-expired ones
// Clean up expired tokens from DAO
try {
const settings = loadSettings();
if (Array.isArray(settings.oauthTokens)) {
const validTokens: IOAuthToken[] = [];
for (const stored of settings.oauthTokens) {
const accessExpiresAt = new Date(stored.accessTokenExpiresAt);
const refreshExpiresAt = stored.refreshTokenExpiresAt
? new Date(stored.refreshTokenExpiresAt)
: undefined;
const accessExpired = accessExpiresAt < now;
const refreshExpired = refreshExpiresAt && refreshExpiresAt < now;
if (!accessExpired || (stored.refreshToken && !refreshExpired)) {
validTokens.push(stored);
}
}
settings.oauthTokens = validTokens;
saveSettings(settings);
}
const tokenDao = getOAuthTokenDao();
await tokenDao.cleanupExpired();
} catch (error) {
console.error('Failed to cleanup persisted OAuth tokens:', error);
}
@@ -331,7 +293,12 @@ export const cleanupExpired = (): void => {
// Run cleanup every 5 minutes in production
let cleanupIntervalId: NodeJS.Timeout | null = null;
if (process.env.NODE_ENV !== 'test') {
cleanupIntervalId = setInterval(cleanupExpired, 5 * 60 * 1000);
cleanupIntervalId = setInterval(
() => {
cleanupExpired().catch(console.error);
},
5 * 60 * 1000,
);
// Allow the interval to not keep the process alive
cleanupIntervalId.unref();
}

View File

@@ -21,7 +21,7 @@ const oauthModel: OAuth2Server.AuthorizationCodeModel & OAuth2Server.RefreshToke
* Get client by client ID
*/
getClient: async (clientId: string, clientSecret?: string) => {
const client = findOAuthClientById(clientId);
const client = await findOAuthClientById(clientId);
if (!client) {
return false;
}
@@ -92,7 +92,7 @@ const oauthModel: OAuth2Server.AuthorizationCodeModel & OAuth2Server.RefreshToke
return false;
}
const client = findOAuthClientById(code.clientId);
const client = await findOAuthClientById(code.clientId);
if (!client) {
return false;
}
@@ -143,7 +143,7 @@ const oauthModel: OAuth2Server.AuthorizationCodeModel & OAuth2Server.RefreshToke
const scopeString = Array.isArray(token.scope) ? token.scope.join(' ') : token.scope;
const savedToken = saveToken(
const savedToken = await saveToken(
{
scope: scopeString,
clientId: client.id,
@@ -172,12 +172,12 @@ const oauthModel: OAuth2Server.AuthorizationCodeModel & OAuth2Server.RefreshToke
* Get access token
*/
getAccessToken: async (accessToken: string) => {
const token = getToken(accessToken);
const token = await getToken(accessToken);
if (!token) {
return false;
}
const client = findOAuthClientById(token.clientId);
const client = await findOAuthClientById(token.clientId);
if (!client) {
return false;
}
@@ -205,12 +205,12 @@ const oauthModel: OAuth2Server.AuthorizationCodeModel & OAuth2Server.RefreshToke
* Get refresh token
*/
getRefreshToken: async (refreshToken: string) => {
const token = getToken(refreshToken);
const token = await getToken(refreshToken);
if (!token || token.refreshToken !== refreshToken) {
return false;
}
const client = findOAuthClientById(token.clientId);
const client = await findOAuthClientById(token.clientId);
if (!client) {
return false;
}
@@ -240,7 +240,7 @@ const oauthModel: OAuth2Server.AuthorizationCodeModel & OAuth2Server.RefreshToke
revokeToken: async (token: OAuth2Server.Token | OAuth2Server.RefreshToken) => {
const refreshToken = 'refreshToken' in token ? token.refreshToken : undefined;
if (refreshToken) {
revokeToken(refreshToken);
await revokeToken(refreshToken);
}
return true;
},

View File

@@ -7,6 +7,8 @@ import { ServerRepository } from '../db/repositories/ServerRepository.js';
import { GroupRepository } from '../db/repositories/GroupRepository.js';
import { SystemConfigRepository } from '../db/repositories/SystemConfigRepository.js';
import { UserConfigRepository } from '../db/repositories/UserConfigRepository.js';
import { OAuthClientRepository } from '../db/repositories/OAuthClientRepository.js';
import { OAuthTokenRepository } from '../db/repositories/OAuthTokenRepository.js';
/**
* Migrate from file-based configuration to database
@@ -29,6 +31,8 @@ export async function migrateToDatabase(): Promise<boolean> {
const groupRepo = new GroupRepository();
const systemConfigRepo = new SystemConfigRepository();
const userConfigRepo = new UserConfigRepository();
const oauthClientRepo = new OAuthClientRepository();
const oauthTokenRepo = new OAuthTokenRepository();
// Migrate users
if (settings.users && settings.users.length > 0) {
@@ -129,6 +133,53 @@ export async function migrateToDatabase(): Promise<boolean> {
}
}
// Migrate OAuth clients
if (settings.oauthClients && settings.oauthClients.length > 0) {
console.log(`Migrating ${settings.oauthClients.length} OAuth clients...`);
for (const client of settings.oauthClients) {
const exists = await oauthClientRepo.exists(client.clientId);
if (!exists) {
await oauthClientRepo.create({
clientId: client.clientId,
clientSecret: client.clientSecret,
name: client.name,
redirectUris: client.redirectUris,
grants: client.grants,
scopes: client.scopes,
owner: client.owner,
metadata: client.metadata,
});
console.log(` - Created OAuth client: ${client.clientId}`);
} else {
console.log(` - OAuth client already exists: ${client.clientId}`);
}
}
}
// Migrate OAuth tokens
if (settings.oauthTokens && settings.oauthTokens.length > 0) {
console.log(`Migrating ${settings.oauthTokens.length} OAuth tokens...`);
for (const token of settings.oauthTokens) {
const exists = await oauthTokenRepo.exists(token.accessToken);
if (!exists) {
await oauthTokenRepo.create({
accessToken: token.accessToken,
refreshToken: token.refreshToken,
accessTokenExpiresAt: new Date(token.accessTokenExpiresAt),
refreshTokenExpiresAt: token.refreshTokenExpiresAt
? new Date(token.refreshTokenExpiresAt)
: undefined,
scope: token.scope,
clientId: token.clientId,
username: token.username,
});
console.log(` - Created OAuth token for client: ${token.clientId}`);
} else {
console.log(` - OAuth token already exists: ${token.accessToken.substring(0, 8)}...`);
}
}
}
console.log('✅ Migration completed successfully');
return true;
} catch (error) {

View File

@@ -11,7 +11,7 @@ export const resolveOAuthUserFromToken = async (token?: string): Promise<IUser |
return null;
}
const oauthToken = getOAuthStoredToken(token);
const oauthToken = await getOAuthStoredToken(token);
if (!oauthToken || oauthToken.accessToken !== token) {
return null;
}