Skip to content
Open
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
6 changes: 3 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# ─── Database ───
DATABASE_URL=postgresql://devcard:devcard@localhost:5432/devcard?schema=public
DATABASE_URL=postgresql://devcard:devcard@localhost:5433/devcard?schema=public

# ─── Redis ───
REDIS_URL=redis://localhost:6379
Expand All @@ -19,8 +19,8 @@ GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret

# ─── App URLs ───
PUBLIC_APP_URL=http://localhost:5173
BACKEND_URL=http://localhost:3000
PUBLIC_APP_URL=http://YOUR_COMPUTER_LAN_IP:5173
BACKEND_URL=http://YOUR_COMPUTER_LAN_IP:3000
MOBILE_REDIRECT_URI=devcard://oauth/callback

# ─── Server ───
Expand Down
28 changes: 28 additions & 0 deletions apps/backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# DevCard Backend

## Follow Engine Architecture

DevCard implements a multi-layered Hybrid Follow Engine designed to connect platform professionals seamlessly while maintaining platform policy compliance.

```mermaid
graph TD
A[User triggers Follow/Connect] --> B{Check Platform Strategy}
B -- api (GitHub) --> C[Layer 1: Direct OAuth API integration]
B -- webview (LinkedIn) --> D[Layer 2: In-app WebView Interaction Engine]
B -- link (GitLab/Devfolio) --> E[Layer 3: Native deep-linking / Browser redirect]
B -- copy (Discord) --> F[Layer 4: Clipboard Copy fallback]
```

### Layer 2: WebView Interaction Engine (LinkedIn)

Due to LinkedIn's modern API restrictions preventing programmatic connection requests, direct API follow (Layer 1) is not viable. Instead, the WebView Interaction Engine routes the action through a secure, native WebView:

1. **Routing Strategy**: The backend parses the connection request and returns `{ strategy: 'webview', url }` containing the resolved profile link.
2. **Session Persistence**: The mobile WebView loads the target profile URL using system-level OAuth cookie-sharing (`sharedCookiesEnabled={true}`), ensuring the user remains authenticated.
3. **DOM Introspection**: A lightweight JavaScript snippet is injected to continuously poll for the native LinkedIn 'Connect' button, smooth-scrolls it into view, and highlights it visually to encourage action.
4. **Interactive Send**: Users retain full control over actual connection request submission, adhering completely to platform terms of service.
5. **State Detection**:
- URL State Polling: The engine inspects URL transitions containing `invite-sent` or similar sub-routes.
- DOM Observation: The injected Javascript queries for structural indicators of successful invitation (e.g. "Pending" button state or toaster text) and posts a serialized message back to the native layer.
6. **Robust Fallback**: If network or WebView loading times out (>10s), the engine gracefully falls back to native deep links (`linkedin://profile?id={username}`) or launches the default browser with an interactive custom in-app overlay.
7. **Telemetry Logging**: Upon client-side success (detected via state changes or DOM indicators), the mobile app makes a `POST /api/follow/:platform/:targetUsername/log` request to the backend. This writes a record to the `FollowLog` database table for auditing and analytics tracking.
82 changes: 82 additions & 0 deletions apps/backend/src/__tests__/follow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,86 @@ describe('POST /api/follow/:platform/:targetUsername', () => {

await app.close();
});

it('returns webview strategy and url for webview-strategy platforms (e.g. linkedin)', async () => {
const app = Fastify({ logger: false });

app.decorate('prisma', {
followLog: {
create: vi.fn(),
},
} as any);

app.decorate('authenticate', async (request: any) => {
request.user = { id: 'user-1' };
});

await app.register(followRoutes, { prefix: '/api/follow' });
await app.ready();

const response = await app.inject({
method: 'POST',
url: '/api/follow/linkedin/testuser',
});

const body = response.json();

expect(response.statusCode).toBe(200);
expect(body.strategy).toBe('webview');
expect(body.url).toContain('linkedin.com/in/testuser');

await app.close();
});

it('successfully logs a webview follow action', async () => {
const app = Fastify({ logger: false });

const createLog = vi.fn().mockResolvedValue({
id: 'log-1',
followerId: 'user-1',
targetUsername: 'testuser',
platform: 'linkedin',
status: 'success',
layer: 'webview',
});

app.decorate('prisma', {
followLog: {
create: createLog,
},
} as any);

app.decorate('authenticate', async (request: any) => {
request.user = { id: 'user-1' };
});

await app.register(followRoutes, { prefix: '/api/follow' });
await app.ready();

const response = await app.inject({
method: 'POST',
url: '/api/follow/linkedin/testuser/log',
payload: {
status: 'success',
layer: 'webview',
},
});

const body = response.json();

expect(response.statusCode).toBe(200);
expect(body.status).toBe('success');
expect(body.logId).toBe('log-1');
expect(createLog).toHaveBeenCalledWith({
data: {
followerId: 'user-1',
targetUsername: 'testuser',
platform: 'linkedin',
status: 'success',
layer: 'webview',
},
});

await app.close();
});
});
7 changes: 4 additions & 3 deletions apps/backend/src/__tests__/profiles.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import Fastify from 'fastify';
import { profileRoutes } from '../routes/profiles.js';
import type { PrismaClient } from '@prisma/client';

const mockUser = {
id: 'user-123',
Expand All @@ -19,17 +20,17 @@ const mockUser = {
providerId: 'gh-123',
};

const mockPrisma = {
const mockPrisma: Pick<PrismaClient, 'user'> = {
user: {
findUnique: vi.fn(),
findFirst: vi.fn(),
update: vi.fn(),
},
} as unknown as PrismaClient['user'],
};

async function buildApp() {
const app = Fastify();
app.decorate('prisma', mockPrisma);
app.decorate('prisma', mockPrisma as unknown as PrismaClient);
app.decorate('authenticate', async (request: any) => {
request.user = { id: 'user-123' };
});
Expand Down
9 changes: 5 additions & 4 deletions apps/backend/src/plugins/prisma.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import fp from 'fastify-plugin';
import { PrismaClient } from '@prisma/client';
import type { FastifyInstance } from 'fastify';
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';

declare module 'fastify' {
interface FastifyInstance {
prisma: PrismaClient;
prisma: PrismaClient;
authenticate(
request: FastifyRequest,
reply: FastifyReply
request: FastifyRequest,
reply: FastifyReply
): Promise<void>;
}
}

export const prismaPlugin = fp(async (app: FastifyInstance) => {
const prisma = new PrismaClient({
log: process.env.NODE_ENV !== 'production' ? ['query', 'error', 'warn'] : ['error'],
Expand Down
71 changes: 56 additions & 15 deletions apps/backend/src/routes/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { randomBytes } from 'crypto';

const GITHUB_AUTH_URL = 'https://github.com/login/oauth/authorize';
const GITHUB_TOKEN_URL = 'https://github.com/login/oauth/access_token';
const GITHUB_USER_URL = 'https://api.github.com/user';
Expand All @@ -13,12 +14,28 @@ interface OAuthCallbackQuery {
}

export async function authRoutes(app: FastifyInstance) {
// ─── Developer Login Bypass ───
app.post('/dev-login', async (request: FastifyRequest, reply: FastifyReply) => {
const user = await app.prisma.user.findUnique({
where: { username: 'devcard-demo' },
});
if (!user) {
return reply.status(404).send({ error: 'Demo user not seeded' });
}
const token = app.jwt.sign(
{ id: user.id, username: user.username },
{ expiresIn: '30d' }
);
return { token };
});

// ─── GitHub OAuth ───

app.get('/github', async (request: FastifyRequest, reply: FastifyReply) => {
const redirectUri = `${process.env.BACKEND_URL}/auth/github/callback`;
const clientState = (request.query as any).state || '';
const state = clientState ? `${clientState}_${generateState()}` : generateState();
const mobileRedirectUri = (request.query as any).mobile_redirect_uri || '';
const state = buildOAuthState(clientState, mobileRedirectUri);

const params = new URLSearchParams({
client_id: (process.env.GITHUB_CLIENT_ID || '').trim(),
Expand Down Expand Up @@ -102,24 +119,15 @@ export async function authRoutes(app: FastifyInstance) {
},
});

// Save the authentication token for 'user:email read:user' so we have a basic platform connection
const encryptedToken = (app as any).encryption ? (app as any).encryption.encrypt(tokenData.access_token) : tokenData.access_token;

await app.prisma.oAuthToken.upsert({
where: { userId_platform: { userId: user.id, platform: 'github' } },
update: { accessToken: encryptedToken, scopes: 'read:user user:email' },
create: { userId: user.id, platform: 'github', accessToken: encryptedToken, scopes: 'read:user user:email' },
});

// Generate JWT
const token = app.jwt.sign(
{ id: user.id, username: user.username },
{ expiresIn: '30d' }
);

// For mobile app: redirect with token as URL fragment (not sent to servers, keeps token out of logs)
const mobileRedirect = process.env.MOBILE_REDIRECT_URI;
if (request.query.state?.startsWith('mobile_')) {
const mobileRedirect = getMobileRedirectUri(request.query.state) || process.env.MOBILE_REDIRECT_URI;
return reply.redirect(`${mobileRedirect}#token=${token}`);
}

Expand All @@ -134,7 +142,8 @@ export async function authRoutes(app: FastifyInstance) {

return reply.redirect(`${process.env.PUBLIC_APP_URL}/dashboard`);
} catch (err) {
app.log.error('GitHub auth error:', err);
const message = err instanceof Error ? err.message : String(err);
app.log.error({ err, message }, 'GitHub auth error');
return reply.status(500).send({ error: 'Authentication failed' });
}
});
Expand All @@ -144,7 +153,8 @@ export async function authRoutes(app: FastifyInstance) {
app.get('/google', async (request: FastifyRequest, reply: FastifyReply) => {
const redirectUri = `${process.env.BACKEND_URL}/auth/google/callback`;
const clientState = (request.query as any).state || '';
const state = clientState ? `${clientState}_${generateState()}` : generateState();
const mobileRedirectUri = (request.query as any).mobile_redirect_uri || '';
const state = buildOAuthState(clientState, mobileRedirectUri);

const params = new URLSearchParams({
client_id: (process.env.GOOGLE_CLIENT_ID || '').trim(),
Expand Down Expand Up @@ -221,7 +231,7 @@ export async function authRoutes(app: FastifyInstance) {
);

if (request.query.state?.startsWith('mobile_')) {
const mobileRedirect = process.env.MOBILE_REDIRECT_URI;
const mobileRedirect = getMobileRedirectUri(request.query.state) || process.env.MOBILE_REDIRECT_URI;
return reply.redirect(`${mobileRedirect}#token=${token}`);
}

Expand All @@ -235,7 +245,8 @@ export async function authRoutes(app: FastifyInstance) {

return reply.redirect(`${process.env.PUBLIC_APP_URL}/dashboard`);
} catch (err) {
app.log.error('Google auth error:', err);
const message = err instanceof Error ? err.message : String(err);
app.log.error({ err, message }, 'Google auth error');
return reply.status(500).send({ error: 'Authentication failed' });
}
});
Expand Down Expand Up @@ -289,3 +300,33 @@ export async function authRoutes(app: FastifyInstance) {
function generateState(): string {
return randomBytes(32).toString('hex');
}

function buildOAuthState(clientState: string, mobileRedirectUri: string): string {
if (!clientState) {
return generateState();
}

if (clientState.startsWith('mobile_') && mobileRedirectUri) {
const encodedRedirect = Buffer.from(mobileRedirectUri, 'utf8').toString('base64url');
return `${clientState}.${encodedRedirect}.${generateState()}`;
}

return `${clientState}.${generateState()}`;
}

function getMobileRedirectUri(state?: string): string | null {
if (!state?.startsWith('mobile_')) {
return null;
}

const encodedRedirect = state.split('.')[1];
if (!encodedRedirect) {
return null;
}

try {
return Buffer.from(encodedRedirect, 'base64url').toString('utf8');
} catch {
return null;
}
}
7 changes: 5 additions & 2 deletions apps/backend/src/routes/connect.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { randomBytes } from 'crypto';
import { encrypt } from '../utils/encryption.js';

const GITHUB_AUTH_URL = 'https://github.com/login/oauth/authorize';
const GITHUB_TOKEN_URL = 'https://github.com/login/oauth/access_token';
Expand Down Expand Up @@ -95,7 +97,7 @@ export async function connectRoutes(app: FastifyInstance) {
}

// Encrypt and store the token
const encryptedToken = app.encryption.encrypt(tokenData.access_token);
const encryptedToken = encrypt(tokenData.access_token);
Comment thread
Itzzavdheshh marked this conversation as resolved.

await app.prisma.oAuthToken.upsert({
where: {
Expand Down Expand Up @@ -125,7 +127,8 @@ export async function connectRoutes(app: FastifyInstance) {
return reply.redirect(`${process.env.PUBLIC_APP_URL}/settings?connected=github`);

} catch (err) {
app.log.error('GitHub connect error:', err);
const message = err instanceof Error ? err.message : String(err);
app.log.error({ err, message }, 'GitHub connect error');
return reply.redirect(`${process.env.PUBLIC_APP_URL}/settings?error=server_error`);
}
});
Expand Down
Loading