Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
498 changes: 498 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
},
"license": "MIT",
"scripts": {
"dev": "NODE_ENV=development node --loader ts-node/esm src/index.ts",
"dev": "NODE_ENV=development tsx watch src/index.ts",
"prebuild": "node scripts/replace-version.js",
"build": "tsc && chmod 755 build/index.js",
"test": "NODE_OPTIONS=--experimental-vm-modules jest",
Expand Down Expand Up @@ -50,6 +50,7 @@
"release-it": "^19.0.0",
"ts-jest": "^29.3.2",
"ts-node": "^10.9.2",
"tsx": "^4.20.4",
"typescript": "^5.8.3"
}
}
10 changes: 10 additions & 0 deletions src/backlog/backlogErrorHandler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import { ProjectAccessForbiddenError } from '../errors/ProjectAccessForbiddenError.js';
import { ErrorLike } from '../types/result.js';
import { parseBacklogAPIError } from './parseBacklogAPIError.js';

export const backlogErrorHandler = (err: unknown): ErrorLike => {
if (err instanceof ProjectAccessForbiddenError) {
return {
kind: 'error',
message: err.message,
code: err.code,
data: err.data,
};
}

const parsed = parseBacklogAPIError(err);
return {
kind: 'error',
Expand Down
81 changes: 81 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright (c) 2025 Nulab inc.
// Licensed under the MIT License.

import dotenv from 'dotenv';
import { default as env } from 'env-var';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import { VERSION } from './version.js';

dotenv.config();

// Define Read Guard policies
const READ_GUARD_POLICIES = ['off', 'filter', 'deny'] as const;

Check failure on line 13 in src/config.ts

View workflow job for this annotation

GitHub Actions / 🧪 Lint, Test, Build

'READ_GUARD_POLICIES' is assigned a value but only used as a type
export type ReadGuardPolicy = (typeof READ_GUARD_POLICIES)[number];

// Define Write Guard policies
const WRITE_GUARD_POLICIES = ['on', 'off'] as const;

Check failure on line 17 in src/config.ts

View workflow job for this annotation

GitHub Actions / 🧪 Lint, Test, Build

'WRITE_GUARD_POLICIES' is assigned a value but only used as a type
export type WriteGuardPolicy = (typeof WRITE_GUARD_POLICIES)[number];

export const config = yargs(hideBin(process.argv))
.option('backlog-domain', {
type: 'string',
describe: 'Backlog domain',
default: env.get('BACKLOG_DOMAIN').required().asString(),
})
.option('backlog-api-key', {
type: 'string',
describe: 'Backlog API key',
default: env.get('BACKLOG_API_KEY').required().asString(),
})
.option('max-tokens', {
type: 'number',
describe: 'Maximum number of tokens allowed in the response',
default: env.get('MAX_TOKENS').default('50000').asIntPositive(),
})
.option('optimize-response', {
type: 'boolean',
describe:
'Enable GraphQL-style response optimization to include only requested fields',
default: env.get('OPTIMIZE_RESPONSE').default('false').asBool(),
})
.option('prefix', {
type: 'string',
describe: 'Optional string prefix to prepend to all generated outputs',
default: env.get('PREFIX').default('').asString(),
})
.option('export-translations', {
type: 'boolean',
describe: 'Export translations and exit',
default: false,
})
.option('enable-toolsets', {
type: 'array',
describe: `Specify which toolsets to enable. Defaults to 'all'.`,
default: env.get('ENABLE_TOOLSETS').default('all').asArray(','),
})
.option('dynamic-toolsets', {
type: 'boolean',
describe:
'Enable dynamic toolsets such as enable_toolset, list_available_toolsets, etc.',
default: env.get('ENABLE_DYNAMIC_TOOLSETS').default('false').asBool(),
})
.option('allowed-project-ids', {
type: 'array',
describe: 'Comma-separated list of allowed Backlog project IDs',
default: env.get('BACKLOG_ALLOWED_PROJECT_IDS').default('').asArray(',').filter(Boolean),
})
.option('allowed-project-keys', {
type: 'array',
describe: 'Comma-separated list of allowed Backlog project keys',
default: env.get('BACKLOG_ALLOWED_PROJECT_KEYS').default('').asArray(',').filter(Boolean),
})
.option('key-resolve-ttl-sec', {
type: 'number',
describe: 'Cache TTL in seconds for project key-to-ID resolution',
default: env.get('BACKLOG_KEY_RESOLVE_TTL_SEC').default(300).asInt(),
})
.version(VERSION)
.help()
.alias('h', 'help')
.parseSync();
22 changes: 22 additions & 0 deletions src/errors/ProjectAccessForbiddenError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright (c) 2025 Nulab inc.
// Licensed under the MIT License.

import { ReadGuardPolicy, WriteGuardPolicy } from '../config.js';

Check failure on line 4 in src/errors/ProjectAccessForbiddenError.ts

View workflow job for this annotation

GitHub Actions / 🧪 Lint, Test, Build

'WriteGuardPolicy' is defined but never used

Check failure on line 4 in src/errors/ProjectAccessForbiddenError.ts

View workflow job for this annotation

GitHub Actions / 🧪 Lint, Test, Build

'ReadGuardPolicy' is defined but never used
Copy link

Copilot AI Oct 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The imported types ReadGuardPolicy and WriteGuardPolicy are not used in this file. This import should be removed as it's unnecessary.

Suggested change
import { ReadGuardPolicy, WriteGuardPolicy } from '../config.js';

Copilot uses AI. Check for mistakes.

export interface ProjectAccessForbiddenErrorData {
allowedProjectIds: (string | number)[];
requestedProjectId?: number;
requestedProjectKey?: string;
requestedProjectIds?: number[];
}

export class ProjectAccessForbiddenError extends Error {
public readonly code = -32040;
public readonly data: ProjectAccessForbiddenErrorData;

constructor(message: string, data: ProjectAccessForbiddenErrorData) {
super(message);
this.name = 'ProjectAccessForbiddenError';
this.data = data;
}
}
131 changes: 131 additions & 0 deletions src/guards/ProjectGuardService.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Copyright (c) 2025 Nulab inc.
// Licensed under the MIT License.

import { jest } from '@jest/globals';
import { Backlog } from 'backlog-js';
import { ProjectGuardService } from './ProjectGuardService.js';
import { logger } from '../utils/logger.js';

const mockBacklog = {
getProjects: jest.fn(),
getProject: jest.fn(),
} as unknown as Backlog;

describe('ProjectGuardService', () => {

Check failure on line 14 in src/guards/ProjectGuardService.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Lint, Test, Build

'describe' is not defined
beforeEach(() => {

Check failure on line 15 in src/guards/ProjectGuardService.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Lint, Test, Build

'beforeEach' is not defined
jest.clearAllMocks();
(mockBacklog.getProjects as jest.Mock).mockResolvedValue([
{ id: 1, projectKey: 'HOME' },
{ id: 2, projectKey: 'TEST-1' },
]);
jest.spyOn(logger, 'warn').mockImplementation(() => {});
});

describe('Initialization and Validation', () => {

Check failure on line 24 in src/guards/ProjectGuardService.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Lint, Test, Build

'describe' is not defined
it('should initialize with allowed project IDs', async () => {

Check failure on line 25 in src/guards/ProjectGuardService.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Lint, Test, Build

'it' is not defined
const service = new ProjectGuardService(mockBacklog, {
allowedProjectIds: [123, 456],
allowedProjectKeys: [],
writeGuard: 'on',
readGuard: 'filter',
keyResolveTtlSec: 300,
});
await service.initialize();
expect(service.getAllowedProjectIds()).toEqual(new Set([123, 456]));

Check failure on line 34 in src/guards/ProjectGuardService.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Lint, Test, Build

'expect' is not defined
});

it('should resolve and add allowed project keys', async () => {

Check failure on line 37 in src/guards/ProjectGuardService.test.ts

View workflow job for this annotation

GitHub Actions / 🧪 Lint, Test, Build

'it' is not defined
const service = new ProjectGuardService(mockBacklog, {
allowedProjectIds: [123],
allowedProjectKeys: ['HOME'],
writeGuard: 'on',
readGuard: 'filter',
keyResolveTtlSec: 300,
});
await service.initialize();
expect(service.getAllowedProjectIds()).toEqual(new Set([123, 1]));
});

it('should throw if a project key cannot be resolved', async () => {
const service = new ProjectGuardService(mockBacklog, {
allowedProjectIds: [],
allowedProjectKeys: ['UNKNOWN'],
writeGuard: 'on',
readGuard: 'filter',
keyResolveTtlSec: 300,
});
await expect(service.initialize()).rejects.toThrow(
'Failed to resolve project key: UNKNOWN'
);
});

it('should throw if guards are on but no projects are allowed', async () => {
const service = new ProjectGuardService(mockBacklog, {
allowedProjectIds: [],
allowedProjectKeys: [],
writeGuard: 'on',
readGuard: 'off',
keyResolveTtlSec: 300,
});
await expect(service.initialize()).rejects.toThrow(
'FATAL: Guards are enabled but no allowed projects are configured.'
);
});

it('should warn in dev if projects are allowed but guards are off', async () => {
process.env.NODE_ENV = 'development';
const service = new ProjectGuardService(mockBacklog, {
allowedProjectIds: [1],
allowedProjectKeys: [],
writeGuard: 'off',
readGuard: 'off',
keyResolveTtlSec: 300,
});
await service.initialize();
expect(logger.warn).toHaveBeenCalledWith(
'WARNING: Allowed projects are configured but both read and write guards are off.'
);
});

it('should throw in prod if projects are allowed but guards are off', async () => {
process.env.NODE_ENV = 'production';
const service = new ProjectGuardService(mockBacklog, {
allowedProjectIds: [1],
allowedProjectKeys: [],
writeGuard: 'off',
readGuard: 'off',
keyResolveTtlSec: 300,
});
await expect(service.initialize()).rejects.toThrow(
'FATAL: WARNING: Allowed projects are configured but both read and write guards are off.'
);
});

it('should throw in prod if fully unguarded without UNGUARDED_OK flag', async () => {
process.env.NODE_ENV = 'production';
const service = new ProjectGuardService(mockBacklog, {
allowedProjectIds: [],
allowedProjectKeys: [],
writeGuard: 'off',
readGuard: 'off',
keyResolveTtlSec: 300,
});
await expect(service.initialize()).rejects.toThrow(
'FATAL: Running in production without guards requires BACKLOG_UNGUARDED_OK=I_UNDERSTAND_THE_RISKS'
);
});

it('should not throw in prod if fully unguarded with UNGUARDED_OK flag', async () => {
process.env.NODE_ENV = 'production';
const service = new ProjectGuardService(mockBacklog, {
allowedProjectIds: [],
allowedProjectKeys: [],
writeGuard: 'off',
readGuard: 'off',
unguardedOk: 'I_UNDERSTAND_THE_RISKS',
keyResolveTtlSec: 300,
});
await expect(service.initialize()).resolves.not.toThrow();
});
});
});
68 changes: 68 additions & 0 deletions src/guards/ProjectGuardService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { Backlog } from 'backlog-js';

type ProjectGuardConfig = {
allowedProjectIds: (string | number)[];
allowedProjectKeys: string[];
keyResolveTtlSec: number;
};

export class ProjectGuardService {
private readonly allowedProjectIds = new Set<number>();
private readonly allowedProjectKeys = new Set<string>();
private readonly config: ProjectGuardConfig;
private readonly backlog: Backlog;

constructor(backlog: Backlog, config: ProjectGuardConfig) {
this.backlog = backlog;
this.config = config;
}

async initialize(): Promise<void> {
this.config.allowedProjectIds.forEach((id) => {
const numericId = Number(id);
if (!isNaN(numericId)) {
this.allowedProjectIds.add(numericId);
}
});

if (this.config.allowedProjectKeys.length > 0) {
// Todo: add TTL caching and try catch errors
const projects = await this.backlog.getProjects();
const projectMap = new Map<string, number>();
projects.forEach((p: any) => projectMap.set(p.projectKey, p.id));

for (const key of this.config.allowedProjectKeys) {
const id = projectMap.get(key);
if (id) {
this.allowedProjectKeys.add(key);
this.allowedProjectIds.add(id);
} else {
throw new Error(`Failed to resolve project key: ${key}`);
}
}
}
}

public isAllowed(projectId: number): boolean;
public isAllowed(projectKey: string): boolean;
public isAllowed(project: number | string): boolean {
if (typeof project === 'number') {
return (
this.allowedProjectIds.size === 0 || this.allowedProjectIds.has(project)
);
}

if (typeof project === 'string') {
if (this.allowedProjectIds.size === 0) {
return true;
}
return this.allowedProjectKeys.has(project);
}

return false;
}

public getAllowedProjectIds(): Set<number> {
return this.allowedProjectIds;
}
}
Loading