Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
e839934
feat(mcp-auth): add initial OAuth 2.1 authorization support
akulistus Sep 12, 2026
1221031
chore(mcp-auth): refresh token
akulistus Sep 16, 2026
3a24049
feat(MCPAuthRequestStore): implement caching MCPAuthRequests using re…
akulistus Oct 22, 2026
c1cbf1c
fix(token-refresh): fix 400 status code error on token refresh
akulistus Oct 25, 2026
dedec2a
add JSDoc and fix lint
akulistus Oct 26, 2026
6e98a54
chore(generateTokenPair): check enforced sso before issuing tokens
akulistus Oct 27, 2026
a2e9cac
fix(print_userId tool): prevent possible unhandled error
akulistus Oct 28, 2026
d0e7b70
chore(oauth): oauth flow is separated from mcp
akulistus Nov 22, 2026
a46e044
feat(OAuthClient): add oauthClients collection
akulistus Nov 23, 2026
9881e82
refactor(oauthClient): generate jwt with additional oauth fields
akulistus Nov 24, 2026
0d9887d
fixes
akulistus Nov 24, 2026
f7f47b9
lint
akulistus Nov 24, 2026
5fbd113
chore(jti): Use _id instead of jti
akulistus Nov 24, 2026
bd6a062
chore(OAuthJWTData): rename jwtid to jti
akulistus Nov 25, 2026
95498f5
fix(oauth): adapt endpoints to fit spec
akulistus Nov 25, 2026
03ec416
fix lint
akulistus Nov 25, 2026
38a6cab
fix(OAuthStoreFactory): init RedisOAuthStore with redisHelper
akulistus Nov 28, 2026
0b8865d
refactor(redis.store): change redis key foramtting
akulistus Nov 28, 2026
0e2764e
fix(mcp): update protected resource dicovery url to comply with spec
akulistus Nov 28, 2026
ee0698a
fix(oauth): improve security
akulistus Nov 28, 2026
f71a5d0
fixup! refactor(redis.store): change redis key foramtting
akulistus Nov 29, 2026
3413a9c
fix(isLoopback): allow only https or http protocols
akulistus Nov 29, 2026
0b5352d
fixes
akulistus Dec 1, 2026
7a67b89
add tests
akulistus Dec 1, 2026
5f74917
fixes
akulistus Dec 2, 2026
ebfa05a
chore(jwt): use separate jwt for oauth to enforce security
akulistus Dec 3, 2026
cf0cd5c
Bump version up to 1.7.2
github-actions[bot] Dec 4, 2026
b830eeb
chore(token-claims): use camel-case
akulistus Dec 4, 2026
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
9 changes: 9 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ JWT_SECRET_REFRESH_TOKEN=abacaba
# JWT secret for user's access token
JWT_SECRET_ACCESS_TOKEN=belarus

# JWT secret for oauth client's access token
JWT_OAUTH_SECRET_ACCESS_TOKEN=fxfxfx

# JWT secret for oauth client's refresh token
JWT_OAUTH_SECRET_REFRESH_TOKEN=xfxfxf

# max document could for one read request to the database
MAX_DB_READ_BATCH_SIZE=100000

Expand Down Expand Up @@ -92,6 +98,9 @@ SSO_SP_ENTITY_ID=urn:hawk:tracker:saml
## SAML state store type (memory or redis, default: redis)
SAML_STORE_TYPE=redis

## OAuthRequest data store type (memory or redis, default: redis)
OAUTH_REQUEST_STORE_TYPE=redis

# String generated when we create GitHub App, see task-managers-integration-implementation-plan.md -> 2.1.1
GITHUB_WEBHOOK_SECRET=623f6ed30b1f762803149893263a95cc2687fe3ce5a9f30648dcbf25712afc9e

Expand Down
6 changes: 6 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ JWT_SECRET_REFRESH_TOKEN=abacaba
# JWT secret for user's access token
JWT_SECRET_ACCESS_TOKEN=belarus

# JWT secret for oauth client's access token
JWT_OAUTH_SECRET_ACCESS_TOKEN=fxfxfx

# JWT secret for oauth client's refresh token
JWT_OAUTH_SECRET_REFRESH_TOKEN=xfxfxf

# JWT secret for project's tokens (used in catcher)
JWT_SECRET_PROJECT_TOKEN=qwerty

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "hawk.api",
"version": "1.7.1",
"version": "1.7.2",
"main": "index.ts",
"license": "BUSL-1.1",
"scripts": {
Expand Down Expand Up @@ -43,6 +43,7 @@
"@graphql-tools/utils": "^8.9.0",
"@hawk.so/nodejs": "^3.3.2",
"@hawk.so/types": "^0.7.0",
"@modelcontextprotocol/express": "^2.0.2",
"@modelcontextprotocol/node": "^2.1.2",
"@modelcontextprotocol/server": "^2.4.0",
"@n1ru4l/json-patch-plus": "^0.2.0",
Expand Down
12 changes: 12 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ import { graphqlUploadExpress } from 'graphql-upload';
import { metricsMiddleware, createMetricsServer, graphqlMetricsPlugin } from './metrics';
import { requestLogger } from './utils/logger';
import ReleasesFactory from './models/releasesFactory';
import OAuthClientsFactory from './models/oauthClientsFactory';
import RedisHelper from './redisHelper';
import { appendSsoRoutes } from './sso';
import { appendGitHubRoutes } from './integrations/github';
import { appendAiAssistantRoutes } from './services/askAi';
import { appendMCPRoutes } from './integrations/mcp';
import { appendOAuthRoutes } from './oauth';

/**
* Option to enable playground
Expand Down Expand Up @@ -174,13 +176,17 @@ class HawkAPI {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const releasesFactory = new ReleasesFactory(mongo.databases.events!);

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const oauthFactory = new OAuthClientsFactory(mongo.databases.hawk!);

return {
usersFactory,
workspacesFactory,
projectsFactory,
plansFactory,
businessOperationsFactory,
releasesFactory,
oauthFactory,
};
}

Expand Down Expand Up @@ -279,6 +285,12 @@ class HawkAPI {
*/
appendAiAssistantRoutes(this.app);

/**
* Append OAuth routes to Express app
* Note: This must be called after database connections are established
*/
appendOAuthRoutes(this.app, sharedFactories);

/**
* Append MCP integration routes to Express app using shared factories
* Note: This must be called after database connections are established
Expand Down
90 changes: 88 additions & 2 deletions src/integrations/mcp/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
/* eslint-disable @typescript-eslint/camelcase, camelcase */
import express from 'express';
import { ContextFactories } from 'src/types/graphql';
import { ContextFactories } from '../../types/graphql';
import { createMCPHandler } from './mcp';
import { verifyJWT } from '../../utils/verifyJWT';
import { requireBearerAuth } from '@modelcontextprotocol/express';
import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server';

import type { Response } from 'express';
import type { OAuthJWTData, ProtectedResourceMetadataResponse } from '../../oauth/types';
import type { AuthInfo, OAuthTokenVerifier } from '@modelcontextprotocol/server';
import type { Secret } from 'jsonwebtoken';

/**
* Appends MCP route to Express App
Expand All @@ -11,5 +20,82 @@ import { createMCPHandler } from './mcp';
export function appendMCPRoutes(app: express.Application, factories: ContextFactories): void {
const handler = createMCPHandler(factories);

app.use('/integration/mcp', (req, res) => handler(req, res, req.body));
/**
* Used by {@link authMiddleware}. Checks access token validity
*
* On SUCCESS returns the resulting {@link AuthInfo}, which the serving entry surfaces to MCP request handlers
*
* On ERROR throws OAuthError
*/
const tokenVerifier: OAuthTokenVerifier = {
verifyAccessToken: async (token: string) => {
const data = verifyJWT<OAuthJWTData>(token, process.env.JWT_OAUTH_SECRET_ACCESS_TOKEN as Secret);

if (!data) {
throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid or expired access token');
}

if (
typeof data.userId !== 'string' ||
typeof data.clientId !== 'string' ||
!Array.isArray(data.scopes) ||
!data.scopes.every(scope => scope === 'mcp:tools' || scope === 'mcp:resources')
) {
throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid or expired access token');
}

const userId = await factories.oauthFactory.trackUse(data.userId, data.clientId);

if (!userId) {
throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid or expired access token');
}

return {
token,
clientId: data.clientId,
scopes: data.scopes,
expiresAt: data.exp,
extra: { userId },
};
},
};

/**
* Express middleware that requires a valid Bearer token in the Authorization header
*
* On failure the middleware sends a JSON OAuth error body and a WWW-Authenticate: Bearer …
* challenge that includes the configured resource_metadata URL
* so clients can discover the Authorization Server
*/
const authMiddleware = requireBearerAuth({
verifier: tokenVerifier,
resourceMetadataUrl:
`${process.env.API_URL}/.well-known/oauth-protected-resource/integration/mcp`,
});

/**
* Protected Resource Metadata (PRM) discovery
*
* Client retrieves metadata the authorization server,
* supported scopes, and other resource information
*/
app.get(
'/.well-known/oauth-protected-resource/integration/mcp',
(_req, res: Response<ProtectedResourceMetadataResponse>) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.json({
resource: `${process.env.API_URL}/integration/mcp`,
authorization_servers: [
`${process.env.API_URL}`,
],
scopes_supported: [
'mcp:tools',
'mcp:resources',
],
});
}
);

app.options('/integration/mcp', (_req, res) => res.sendStatus(204));
app.use('/integration/mcp', authMiddleware, (req, res) => handler(req, res, req.body));
}
21 changes: 2 additions & 19 deletions src/integrations/mcp/mcp.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { ContextFactories } from 'src/types/graphql';

import type { NodeMcpRequestHandler } from '@modelcontextprotocol/node';
Expand All @@ -10,30 +10,13 @@ import type { NodeMcpRequestHandler } from '@modelcontextprotocol/node';
* @param factories - context factories for database access
* @returns configured MCP server
*/
function createMCPServer(factories: ContextFactories) {
const createMCPServer = (factories: ContextFactories) => {
const server = new McpServer({
name: 'server',
version: '0.0.0',
description: 'A test server',
});

server.registerTool(
'hello_world',
{
description: 'A test tool to greet the user',
},
async () => {
return {
content: [
{
type: 'text' as const,
text: 'Hi',
},
],
};
}
);

return server;
};

Expand Down
113 changes: 113 additions & 0 deletions src/models/oauthClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { Collection, ObjectId, OptionalId } from 'mongodb';
import jwt from 'jsonwebtoken';
import AbstractModel from './abstractModel';

import type { Secret } from 'jsonwebtoken';
import type { OAuthClientDBScheme, TokenPermissions, TokensPair } from '@hawk.so/types';

export default class OAuthClientModel extends AbstractModel<OptionalId<OAuthClientDBScheme>> implements OAuthClientDBScheme {
/**
* External client identifier
*/
public _id!: ObjectId;

/**
* Token owner id
*/
public userId!: string;

/**
* OAuth client identifier, supplied as a Client ID Metadata Document URL.
*/
public clientId!: string;

/**
* Hostname from the redirect URI used when this grant was authorized.
*/
public redirectHost!: string;

/**
* OAuth scopes granted to this client.
*/
public scopes!: string[];

/**
* What client is allowed to do
*/
public permissions!: TokenPermissions[];

/**
* Label set by user
*/
public label!: string;

/**
* Last time the client interacted with hawk api
*/
public lastUsedAt!: Date | null;

/**
* Usage count
*/
public requestCount!: number;

/**
* Creation date
*/
public createdAt!: Date;

/**
* Current refresh-token identifier used to detect token reuse.
*/
public jti!: string;

/**
* Time when this grant was revoked, or null while active.
*/
public revokedAt!: Date | null;

public collection!: Collection<OptionalId<OAuthClientDBScheme>>;

constructor(oauthClient: OptionalId<OAuthClientDBScheme>) {
super(oauthClient);
this.collection = this.dbConnection.collection<OptionalId<OAuthClientDBScheme>>('oauthClients');
}

/**
* Signs an access and refresh token pair for this stored grant.
*
* @param refreshJti - Refresh-token identifier; defaults to the grant's current JTI.
* @returns The newly signed MCP access and refresh tokens.
*/
public async generateTokensPair(refreshJti: string = this.jti): Promise<TokensPair> {
const accessToken = jwt.sign(
{
userId: this.userId,
clientId: this.clientId,
scopes: this.scopes,
},
process.env.JWT_OAUTH_SECRET_ACCESS_TOKEN as Secret,
{
expiresIn: '15m',
}
);

const refreshToken = jwt.sign(
{
userId: this.userId,
clientId: this.clientId,
scopes: this.scopes,
},
process.env.JWT_OAUTH_SECRET_REFRESH_TOKEN as Secret,
{
expiresIn: '30d',
jwtid: refreshJti,
}
);

return {
accessToken,
refreshToken,
};
}
}
Loading
Loading