Skip to content
Merged
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
67 changes: 67 additions & 0 deletions server/routes/pipelineCommit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { Router } from 'express';
import { requireSession } from '../lib/requireSession.js';
import { getGithubAccessTokenForUser } from '../lib/github-token.js';
import { upsertWorkflowFile } from '../tools/github_adapter.js';

const router = Router();

/**
* POST /mcp/v1/pipeline_commit
* Body:
* {
* "repoFullName": "owner/repo",
* "branch": "main",
* "yaml": "name: CI/CD Pipeline ...",
* "path": ".github/workflows/ci.yml"
* }
*/
router.post('/pipeline_commit', requireSession, async (req, res) => {
try {
const { repoFullName, branch, yaml, path } = req.body || {};
if (!repoFullName || !yaml) {
return res
.status(400)
.json({ error: 'repoFullName and yaml are required' });
}

const userId = req.user?.user_id;
if (!userId)
return res.status(401).json({ error: 'User session missing or invalid' });

const token = await getGithubAccessTokenForUser(userId);
if (!token)
return res.status(401).json({ error: 'Missing GitHub token for user' });

const [owner, repo] = repoFullName.split('/');
const workflowPath = path || '.github/workflows/ci.yml';
const branchName = branch || 'main';

console.log(
`[pipeline_commit] Committing workflow to ${repoFullName}:${workflowPath}`
);

const result = await upsertWorkflowFile({
token,
owner,
repo,
path: workflowPath,
content: yaml,
branch: branchName,
message: 'Add CI workflow via OSP',
});

return res.status(201).json({
ok: true,
message: 'Workflow committed successfully',
data: result,
});
} catch (err) {
console.error('[pipeline_commit] error:', err);
const status = err.status || 500;
return res
.status(status)
.json({ error: err.message, details: err.details || undefined });
}
});

export default router;
18 changes: 8 additions & 10 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@ import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import { healthCheck } from './db.js';
import githubAuthRouter from './routes/auth.github.js';
import userRouter from './routes/usersRoutes.js';
import mcpRoutes from './routes/mcp.js';
import agentRoutes from './routes/agent.js';
import cookieParser from 'cookie-parser';
import githubAuthRouter from './routes/auth.github.js';
import deploymentsRouter from './routes/deployments.js';
import authRoutes from './routes/authRoutes.js';
import userRouter from './routes/usersRoutes.js';
import cookieParser from 'cookie-parser';
import authAws from './routes/auth.aws.js';
import authGoogle from './routes/auth.google.js';
import { z } from 'zod';
import { query } from './db.js';
import jenkinsRouter from "./routes/jenkins.js";
import jenkinsRouter from './routes/jenkins.js';
import pipelineCommitRouter from './routes/pipelineCommit.js';
// app.use(authRoutes);

const app = express();
Expand Down Expand Up @@ -137,21 +139,19 @@ app.get('/connections', async (_req, res) => {
// -- Agent entry point
app.use('/deployments', deploymentsRouter);
app.use('/agent', agentRoutes);
app.use('/mcp/v1', pipelineCommitRouter);
app.use('/mcp/v1', mcpRoutes);

// Mount GitHub OAuth routes at /auth/github
app.use('/auth/github', githubAuthRouter);


app.use(authRoutes);
// Mount AWS SSO routes
app.use('/auth/aws', authAws);

// Mount Google OAuth routes
app.use('/auth/google', authGoogle);

app.use('/jenkins', jenkinsRouter);
// // Mount GitHub OAuth routes at /auth/github
// app.use('/auth/github', githubAuthRouter);

// --- Global Error Handler ---
app.use((err, req, res, next) => {
Expand All @@ -163,7 +163,5 @@ app.use((err, req, res, next) => {
});
});



const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`API on http://localhost:${port}`));
66 changes: 66 additions & 0 deletions server/tools/github_adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,69 @@ export async function dispatchWorkflow({
} catch {}
throw err;
}

// Helper function to create and update a workflow file in a repo
export async function upsertWorkflowFile({
token,
owner,
repo,
path,
content,
branch,
message = 'Add CI workflow via AutoDeploy',
}) {
const baseUrl = `https://api.github.com/repos/${owner}/${repo}/contents/${encodeURIComponent(
path
)}`;

const headers = {
Authorization: `Bearer ${token}`,
Accept: 'application/vnd.github+json',
'User-Agent': 'OSP-CI-Builder',
'Content-Type': 'application/json',
};

//check if the file exists to get the SHA
let sha = undefined;
const getRes = await fetch(`${baseUrl}?ref=${encodeURIComponent(branch)}`, {
headers,
});

if (getRes.status === 200) {
const existing = await getRes.json();
sha = existing.sha;
} else if (getRes.status === 400) {
const text = await getRes.text().catch(() => '');
throw new Error(
`Get existing workflow failed: ${getRes.status} ${getRes.statusText} ${text}`
);
}

//Encode content as base64 character data
const encoded = Buffer.from(content, 'utf-8').toString('base64');

//PUT to creat/update the file
const body = {
message,
content: encoded,
branch,
};

if (sha) body.sha = sha;

const putRes = await fetch(baseUrl, {
method: 'PUT',
headers,
body: JSON.stringify(body),
});

if (!putRes.ok) {
const text = await putRes.text().catch(() => '');
throw new Error(
`Upsert workflow file failed: ${putRes.status} ${putRes.statusText} ${text}`
);
}

const data = await putRes.json();
return data;
}
Loading