(expectedToken: string)
| 88 | } |
| 89 | |
| 90 | export function createConnectorApp(expectedToken: string): H3 { |
| 91 | const state: ConnectorState = { |
| 92 | session: { |
| 93 | token: expectedToken, |
| 94 | connectedAt: 0, |
| 95 | npmUser: null, |
| 96 | avatar: null, |
| 97 | }, |
| 98 | operations: [], |
| 99 | } |
| 100 | |
| 101 | const app = new H3() |
| 102 | |
| 103 | // Handle CORS for all requests (including preflight) |
| 104 | app.use((event: H3Event) => { |
| 105 | const corsResult = handleCors(event, corsOptions) |
| 106 | if (corsResult !== false) { |
| 107 | return corsResult |
| 108 | } |
| 109 | }) |
| 110 | |
| 111 | function validateToken(authHeader: string | null): boolean { |
| 112 | if (!authHeader) return false |
| 113 | const token = authHeader.replace('Bearer ', '') |
| 114 | return token === expectedToken |
| 115 | } |
| 116 | |
| 117 | app.post('/connect', async (event: H3Event) => { |
| 118 | const rawBody = await event.req.json() |
| 119 | const parsed = safeParse(ConnectBodySchema, rawBody) |
| 120 | if (!parsed.success) { |
| 121 | throw new HTTPError({ statusCode: 400, message: parsed.error }) |
| 122 | } |
| 123 | |
| 124 | if (parsed.data.token !== expectedToken) { |
| 125 | throw new HTTPError({ statusCode: 401, message: 'Invalid token' }) |
| 126 | } |
| 127 | |
| 128 | const [npmUser, avatar] = await Promise.all([getNpmUser(), getNpmAvatar()]) |
| 129 | state.session.connectedAt = Date.now() |
| 130 | state.session.npmUser = npmUser |
| 131 | state.session.avatar = avatar |
| 132 | |
| 133 | return { |
| 134 | success: true, |
| 135 | data: { |
| 136 | npmUser, |
| 137 | avatar, |
| 138 | connectedAt: state.session.connectedAt, |
| 139 | }, |
| 140 | } satisfies ApiResponse<ConnectorEndpoints['POST /connect']['data']> |
| 141 | }) |
| 142 | |
| 143 | app.get('/state', event => { |
| 144 | const auth = event.req.headers.get('authorization') |
| 145 | if (!validateToken(auth)) { |
| 146 | throw new HTTPError({ statusCode: 401, message: 'Unauthorized' }) |
| 147 | } |
no test coverage detected