-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeedback.js
More file actions
139 lines (130 loc) · 4.68 KB
/
feedback.js
File metadata and controls
139 lines (130 loc) · 4.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// Vercel serverless handler that takes user feedback from the app and files
// it as a GitHub issue tagged `user-feedback`. Token is read server-side so
// it's never shipped to the browser.
//
// Hardening: same-origin enforced, 3 requests/min per IP. The browser-side
// modal renders themed copy for both the 429 and 403 cases.
//
// Env:
// GITHUB_TOKEN - personal access token with `repo` (or `public_repo` for
// public repos) scope. REQUIRED.
// GITHUB_REPO - "owner/repo" string. Defaults to the project repo.
// GITHUB_LABEL - issue label. Defaults to `user-feedback`.
// ALLOWED_ORIGINS - optional comma-separated origin allowlist (see _security.js).
import { enforceGate } from './_security.js';
const DEFAULT_REPO = 'JacobMitchell088/swipe-date';
const DEFAULT_LABEL = 'user-feedback';
const MAX_TITLE = 120;
const MAX_TEXT = 4000;
const RATE_LIMIT = 3; // requests per window
const RATE_WINDOW_MS = 60_000; // 60s — keeps drive-by spammers off the issue tracker
function clip(s, max) {
if (typeof s !== 'string') return '';
const t = s.trim();
return t.length > max ? t.slice(0, max) : t;
}
async function readJsonBody(req) {
// Vercel Node runtime usually populates req.body; the dev middleware
// passes us a pre-parsed object on req.body too. Fall back to streaming
// raw bytes off the request just in case.
if (req.body && typeof req.body === 'object') return req.body;
if (typeof req.body === 'string') {
try { return JSON.parse(req.body); } catch { return {}; }
}
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
if (!chunks.length) return {};
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
catch { return {}; }
}
export default async function handler(req, res) {
if (req.method !== 'POST') {
res.status(405).json({ error: 'method-not-allowed' });
return;
}
if (
!enforceGate(req, res, {
limit: RATE_LIMIT,
windowMs: RATE_WINDOW_MS,
bucket: 'feedback',
})
) {
return; // enforceGate already wrote the response
}
// Optional honeypot: clients can include a `_hp` field; bots tend to fill
// every form field they see. If it's non-empty we accept the 200 (so the bot
// thinks it worked) but skip the GitHub call entirely.
const honeypot = req.body && typeof req.body === 'object' ? req.body._hp : '';
if (typeof honeypot === 'string' && honeypot.trim().length > 0) {
res.status(200).json({ ok: true });
return;
}
const token = process.env.GITHUB_TOKEN;
if (!token) {
res.status(500).json({ error: 'no-token' });
return;
}
const repo = process.env.GITHUB_REPO || DEFAULT_REPO;
const label = process.env.GITHUB_LABEL || DEFAULT_LABEL;
const body = await readJsonBody(req);
const rating = Number.isFinite(body.rating)
? Math.max(0, Math.min(5, Math.round(body.rating)))
: 0;
const title = clip(body.title, MAX_TITLE);
const description = clip(body.description, MAX_TEXT);
const contact = clip(body.contact, 200);
// The client enforces "at least one thing entered" but defend the API
// boundary too — empty submissions become noise in the issue tracker.
if (!rating && !title && !description && !contact) {
res.status(400).json({ error: 'empty' });
return;
}
const stars = rating
? '★'.repeat(rating) + '☆'.repeat(5 - rating)
: '— no rating —';
const issueTitle = title
|| (rating ? `Feedback: ${rating}★` : 'User feedback');
const lines = [
`**Rating:** ${stars}${rating ? ` (${rating}/5)` : ''}`,
'',
];
if (description) {
lines.push('**Feedback**', '', description, '');
}
if (contact) {
lines.push(`**Contact:** ${contact}`);
}
lines.push('', '_submitted via in-app feedback button_');
try {
const upstream = await fetch(
`https://api.github.com/repos/${repo}/issues`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'swipe-date-feedback',
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: issueTitle,
body: lines.join('\n'),
labels: [label],
}),
},
);
const text = await upstream.text();
if (!upstream.ok) {
res.status(upstream.status).json({
error: `github-${upstream.status}`,
detail: text.slice(0, 500),
});
return;
}
const data = JSON.parse(text);
res.status(200).json({ ok: true, url: data.html_url, number: data.number });
} catch (err) {
res.status(502).json({ error: 'network', detail: String(err) });
}
}