-
Notifications
You must be signed in to change notification settings - Fork 2
feat: third-party integration system #406
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
37f9b42
feat: add third-party integration system with OAuth, tool resolution,…
2witstudios 0bd6280
fix: resolve 5 integration system bugs (audit log, OAuth callback, dr…
2witstudios c9d91e2
fix: guard drive integration resolution against non-member access
2witstudios acc834c
Merge remote-tracking branch 'origin/master' into api
2witstudios bbcd967
chore: re-generate migration 0073 for nullable audit log driveId afte…
2witstudios 2c9a543
fix: resolve 5 integration system bugs (audit log, OAuth callback, dr…
2witstudios c300ea0
fix: address all CodeRabbit review findings across integration system
2witstudios 1ecb94e
Merge remote-tracking branch 'origin/master' into api
2witstudios cff9ab6
Merge remote-tracking branch 'origin/master' into api
2witstudios File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
89 changes: 89 additions & 0 deletions
89
apps/web/src/app/api/agents/[agentId]/integrations/[grantId]/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import { NextResponse } from 'next/server'; | ||
| import { z } from 'zod'; | ||
| import { authenticateRequestWithOptions, isAuthError } from '@/lib/auth'; | ||
| import { db } from '@pagespace/db'; | ||
| import { loggers } from '@pagespace/lib/server'; | ||
| import { canUserEditPage } from '@pagespace/lib/permissions'; | ||
| import { getGrantById, updateGrant, deleteGrant } from '@pagespace/lib/integrations'; | ||
|
|
||
| const AUTH_OPTIONS_WRITE = { allow: ['session'] as const, requireCSRF: true }; | ||
|
|
||
| const updateGrantSchema = z.object({ | ||
| allowedTools: z.array(z.string()).nullable().optional(), | ||
| deniedTools: z.array(z.string()).nullable().optional(), | ||
| readOnly: z.boolean().optional(), | ||
| rateLimitOverride: z.object({ | ||
| requestsPerMinute: z.number().min(1).max(1000).optional(), | ||
| }).nullable().optional(), | ||
| }); | ||
|
|
||
| /** | ||
| * PUT /api/agents/[agentId]/integrations/[grantId] | ||
| * Update an integration grant's tool permissions. | ||
| */ | ||
| export async function PUT( | ||
| request: Request, | ||
| context: { params: Promise<{ agentId: string; grantId: string }> } | ||
| ) { | ||
| const { agentId, grantId } = await context.params; | ||
| const auth = await authenticateRequestWithOptions(request, AUTH_OPTIONS_WRITE); | ||
| if (isAuthError(auth)) return auth.error; | ||
|
|
||
| try { | ||
| const canEdit = await canUserEditPage(auth.userId, agentId); | ||
| if (!canEdit) { | ||
| return NextResponse.json({ error: 'Access denied' }, { status: 403 }); | ||
| } | ||
|
|
||
| const grant = await getGrantById(db, grantId); | ||
| if (!grant || grant.agentId !== agentId) { | ||
| return NextResponse.json({ error: 'Grant not found' }, { status: 404 }); | ||
| } | ||
|
|
||
| const body = await request.json(); | ||
| const validation = updateGrantSchema.safeParse(body); | ||
| if (!validation.success) { | ||
| return NextResponse.json( | ||
| { error: 'Validation failed', details: validation.error.flatten().fieldErrors }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| const updated = await updateGrant(db, grantId, validation.data); | ||
| return NextResponse.json({ grant: updated }); | ||
| } catch (error) { | ||
| loggers.api.error('Error updating agent integration grant:', error as Error); | ||
| return NextResponse.json({ error: 'Failed to update grant' }, { status: 500 }); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * DELETE /api/agents/[agentId]/integrations/[grantId] | ||
| * Remove an integration grant. | ||
| */ | ||
| export async function DELETE( | ||
| request: Request, | ||
| context: { params: Promise<{ agentId: string; grantId: string }> } | ||
| ) { | ||
| const { agentId, grantId } = await context.params; | ||
| const auth = await authenticateRequestWithOptions(request, AUTH_OPTIONS_WRITE); | ||
| if (isAuthError(auth)) return auth.error; | ||
|
|
||
| try { | ||
| const canEdit = await canUserEditPage(auth.userId, agentId); | ||
| if (!canEdit) { | ||
| return NextResponse.json({ error: 'Access denied' }, { status: 403 }); | ||
| } | ||
|
|
||
| const grant = await getGrantById(db, grantId); | ||
| if (!grant || grant.agentId !== agentId) { | ||
| return NextResponse.json({ error: 'Grant not found' }, { status: 404 }); | ||
| } | ||
|
|
||
| await deleteGrant(db, grantId); | ||
| return NextResponse.json({ success: true }); | ||
| } catch (error) { | ||
| loggers.api.error('Error deleting agent integration grant:', error as Error); | ||
| return NextResponse.json({ error: 'Failed to delete grant' }, { status: 500 }); | ||
| } | ||
| } |
146 changes: 146 additions & 0 deletions
146
apps/web/src/app/api/agents/[agentId]/integrations/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| import { NextResponse } from 'next/server'; | ||
| import { z } from 'zod'; | ||
| import { authenticateRequestWithOptions, isAuthError } from '@/lib/auth'; | ||
| import { db } from '@pagespace/db'; | ||
| import { loggers } from '@pagespace/lib/server'; | ||
| import { canUserEditPage } from '@pagespace/lib/permissions'; | ||
| import { getDriveAccess } from '@pagespace/lib/services/drive-service'; | ||
| import { | ||
| listGrantsByAgent, | ||
| createGrant, | ||
| getConnectionById, | ||
| findGrant, | ||
| } from '@pagespace/lib/integrations'; | ||
|
|
||
| const AUTH_OPTIONS_READ = { allow: ['session'] as const }; | ||
| const AUTH_OPTIONS_WRITE = { allow: ['session'] as const, requireCSRF: true }; | ||
|
|
||
| const createGrantSchema = z.object({ | ||
| connectionId: z.string().min(1), | ||
| allowedTools: z.array(z.string()).nullable().optional().default(null), | ||
| deniedTools: z.array(z.string()).nullable().optional().default(null), | ||
| readOnly: z.boolean().optional().default(false), | ||
| rateLimitOverride: z.object({ | ||
| requestsPerMinute: z.number().min(1).max(1000).optional(), | ||
| }).nullable().optional(), | ||
| }); | ||
|
|
||
| /** | ||
| * GET /api/agents/[agentId]/integrations | ||
| * List all integration grants for an agent. | ||
| */ | ||
| export async function GET( | ||
| request: Request, | ||
| context: { params: Promise<{ agentId: string }> } | ||
| ) { | ||
| const { agentId } = await context.params; | ||
| const auth = await authenticateRequestWithOptions(request, AUTH_OPTIONS_READ); | ||
| if (isAuthError(auth)) return auth.error; | ||
|
|
||
| try { | ||
| // Verify user can view the agent | ||
| const canEdit = await canUserEditPage(auth.userId, agentId); | ||
| if (!canEdit) { | ||
| return NextResponse.json({ error: 'Access denied' }, { status: 403 }); | ||
| } | ||
|
|
||
| const grants = await listGrantsByAgent(db, agentId); | ||
|
|
||
| return NextResponse.json({ | ||
| grants: grants.map((g) => ({ | ||
| id: g.id, | ||
| agentId: g.agentId, | ||
| connectionId: g.connectionId, | ||
| allowedTools: g.allowedTools, | ||
| deniedTools: g.deniedTools, | ||
| readOnly: g.readOnly, | ||
| rateLimitOverride: g.rateLimitOverride, | ||
| createdAt: g.createdAt, | ||
| connection: g.connection ? { | ||
| id: g.connection.id, | ||
| name: g.connection.name, | ||
| status: g.connection.status, | ||
| provider: g.connection.provider ? { | ||
| slug: g.connection.provider.slug, | ||
| name: g.connection.provider.name, | ||
| } : null, | ||
| } : null, | ||
| })), | ||
| }); | ||
| } catch (error) { | ||
| loggers.api.error('Error listing agent integration grants:', error as Error); | ||
| return NextResponse.json({ error: 'Failed to list grants' }, { status: 500 }); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * POST /api/agents/[agentId]/integrations | ||
| * Create a new integration grant for an agent. | ||
| */ | ||
| export async function POST( | ||
| request: Request, | ||
| context: { params: Promise<{ agentId: string }> } | ||
| ) { | ||
| const { agentId } = await context.params; | ||
| const auth = await authenticateRequestWithOptions(request, AUTH_OPTIONS_WRITE); | ||
| if (isAuthError(auth)) return auth.error; | ||
|
|
||
| try { | ||
| const canEdit = await canUserEditPage(auth.userId, agentId); | ||
| if (!canEdit) { | ||
| return NextResponse.json({ error: 'Access denied' }, { status: 403 }); | ||
| } | ||
|
|
||
| const body = await request.json(); | ||
| const validation = createGrantSchema.safeParse(body); | ||
| if (!validation.success) { | ||
| return NextResponse.json( | ||
| { error: 'Validation failed', details: validation.error.flatten().fieldErrors }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| const { connectionId, allowedTools, deniedTools, readOnly, rateLimitOverride } = validation.data; | ||
|
|
||
| // Verify connection exists and is active | ||
| const connection = await getConnectionById(db, connectionId); | ||
| if (!connection) { | ||
| return NextResponse.json({ error: 'Connection not found' }, { status: 404 }); | ||
| } | ||
| if (connection.status !== 'active') { | ||
| return NextResponse.json({ error: 'Connection is not active' }, { status: 400 }); | ||
| } | ||
|
|
||
| // Verify the requesting user owns this connection (user-scoped) | ||
| // or is a member of the drive that owns it (drive-scoped) | ||
| const isUserConnection = connection.userId === auth.userId; | ||
| let isDriveMember = false; | ||
| if (connection.driveId) { | ||
| const access = await getDriveAccess(connection.driveId, auth.userId); | ||
| isDriveMember = access.isMember; | ||
| } | ||
| if (!isUserConnection && !isDriveMember) { | ||
| return NextResponse.json({ error: 'Access denied' }, { status: 403 }); | ||
| } | ||
|
|
||
| // Check for existing grant | ||
| const existing = await findGrant(db, agentId, connectionId); | ||
| if (existing) { | ||
| return NextResponse.json({ error: 'Grant already exists for this connection' }, { status: 409 }); | ||
| } | ||
|
|
||
| const grant = await createGrant(db, { | ||
| agentId, | ||
| connectionId, | ||
| allowedTools, | ||
| deniedTools, | ||
| readOnly, | ||
| rateLimitOverride, | ||
| }); | ||
|
|
||
| return NextResponse.json({ grant }, { status: 201 }); | ||
| } catch (error) { | ||
| loggers.api.error('Error creating agent integration grant:', error as Error); | ||
| return NextResponse.json({ error: 'Failed to create grant' }, { status: 500 }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.