Release wave: no data collection, contact by email, deploy from src/

- Remove the request form, consent checkbox, honeypot, success dialog,
  form.js, analytics.js, the Yandex Metrica id and the cookie banner (D23).
- Contact is a mailto card to harveymonsterteam@gmail.com; privacy.html
  rewritten for "no data collected"; Google Fonts replaced by four
  self-hosted WOFF2 files, so the page makes no third-party request.
- Drop `summary` from the case contract: the project dialog shows the case
  body only, the planet plaque uses tagline, and a project without shots
  opens one honest slot instead of three fake ones.
- Restore the original voice and punctuation in 12 cards, strip internal
  wording from published copy, fix stale counts (20 projects, 5 releases).
- Deploy = contents of src/: api/ moved to archive/api/, new release gate
  scripts/check-release.mjs, deploy guide docs/deploy.md.
- Sync docs: AGENTS.md (D23, D8, R4 closed, structure), design/spec.md
  section 10.31, DESIGN.md, PRODUCT.md, INDEX.md, inventory.
This commit is contained in:
FastD committed 2026-11-15 17:34:40 +03:00
1 parent 76e6c2a294
commit 0ac596086a
52 files changed
+475 -660

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
<?php
/**
* Copy this file to config.php and fill in real values.
* config.php is gitignored — never commit credentials.
*
* Every channel with a non-empty value is used, in this order:
* 1. store — ALWAYS on. Lead is appended to api/var/leads/YYYY-MM.jsonl.
* 2. telegram — BOT_TOKEN + TG_CHAT_ID
* 3. email — MAIL_TO + (SMTP_* or MAIL_MODE = 'mail')
* 4. webhook — WEBHOOK_URL (+ optional WEBHOOK_TOKEN)
*
* The form reports success when at least one of 2–4 accepted the lead.
* With everything empty the endpoint answers 500 — the form is never silently dead.
*/
/* ---------- 1. Telegram ----------
* Bot: @BotFather → /newbot. Add the bot to the target chat, send any message
* (for groups: /start@your_bot), then GET
* https://api.telegram.org/bot<TOKEN>/getUpdates and read message.chat.id
* (group ids start with '-'). */
const BOT_TOKEN = '';
const TG_CHAT_ID = '';
/* ---------- 2. Email ----------
* MAIL_MODE = 'smtp' — the built-in client (AUTH LOGIN + SSL/STARTTLS), no Composer.
* MAIL_MODE = 'mail' — PHP mail(); works on many shared hosts, weaker deliverability.
*
* MAIL_FROM must belong to the domain that has SPF/DKIM configured, otherwise
* Gmail/VK/Yandex will spam-filter every lead.
*
* Presets (copy the block you need):
* Yandex 360: SMTP_HOST = 'smtp.yandex.ru'; SMTP_PORT = 465; SMTP_SECURE = 'ssl';
* SMTP_USER = 'site@harveymonsterteam.ru'; (password = app password)
* Mail.ru: SMTP_HOST = 'smtp.mail.ru'; SMTP_PORT = 465; SMTP_SECURE = 'ssl';
* Unisender Go:SMTP_HOST = 'smtp.go1.unisender.ru'; SMTP_PORT = 587; SMTP_SECURE = 'tls';
* SendPulse: SMTP_HOST = 'smtp-pulse.com'; SMTP_PORT = 465; SMTP_SECURE = 'ssl';
* Mailgun: SMTP_HOST = 'smtp.mailgun.org'; SMTP_PORT = 587; SMTP_SECURE = 'tls';
* Brevo: SMTP_HOST = 'smtp-relay.brevo.com'; SMTP_PORT = 587; SMTP_SECURE = 'tls';
* Timeweb: SMTP_HOST = 'smtp.timeweb.ru'; SMTP_PORT = 465; SMTP_SECURE = 'ssl';
*/
const MAIL_MODE = 'smtp'; // 'smtp' | 'mail'
const MAIL_TO = 'monsterharvi@gmail.com';
const MAIL_FROM = 'site@harveymonsterteam.ru';
const MAIL_FROM_NAME = 'Harvey Monster Team';
const MAIL_SUBJECT = 'Заявка с harveymonsterteam.ru';
const SMTP_HOST = '';
const SMTP_PORT = 465;
const SMTP_SECURE = 'ssl'; // 'ssl' (465) | 'tls' (587, STARTTLS) | '' (25, plain)
const SMTP_USER = '';
const SMTP_PASS = '';
/* ---------- 3. Webhook ----------
* Any endpoint that accepts JSON:
* {"site","sent_at","name","contact","message","consent","meta":{utm,yclid,…}}
* Works directly with Make / n8n / Zapier / Albato / a custom handler.
* Native CRM and ESP APIs (Bitrix24, amoCRM, Unisender, SendPulse) need their own
* field mapping — point the webhook at a no-code scenario that does the mapping
* (recipe in docs/lead-delivery.md), not at the API URL directly.
* WEBHOOK_TOKEN, when set, is sent as `Authorization: Bearer <token>`. */
const WEBHOOK_URL = '';
const WEBHOOK_TOKEN = '';
+453
View File
@@ -0,0 +1,453 @@
<?php
/**
* Harvey Monster Team Page — contact form endpoint.
* Production: https://harveymonsterteam.ru/api/contact.php
*
* Contract: POST JSON {name, contact, message, consent, website?, meta?}
* - name: required, 2–100 chars
* - contact: required, any channel (telegram / email / phone / VK), 2–200 chars
* - message: required, 10–4000 chars
* - consent: required, must be true (152-ФЗ)
* - website: honeypot — must be empty (bots fill it)
* - meta: optional {utm_*, yclid, gclid, referrer, page} — attribution for ads
* Responses: JSON {ok:bool, message|error:string}
* - 200 ok / 400 bad JSON / 405 wrong method / 422 validation / 429 rate limit / 500 delivery
*
* Delivery pipeline (see api/config.sample.php):
* 1. store — always: api/var/leads/YYYY-MM.jsonl (nothing is lost if channels fail)
* 2. telegram— optional: BOT_TOKEN + TG_CHAT_ID
* 3. email — optional: SMTP (LOGIN / SSL / STARTTLS) or PHP mail()
* 4. webhook — optional: any HTTP endpoint (ESP, CRM, Make/n8n, Bitrix24, amoCRM…)
* The request succeeds when at least one notify channel accepted the lead.
*
* Deploy: upload api/ to the site root, copy config.sample.php -> config.php.
* Requires PHP 7.4+ (mbstring optional).
*/
if (!file_exists(__DIR__ . '/config.php')) {
http_response_code(500);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Server configuration error.'], JSON_UNESCAPED_UNICODE);
exit;
}
require __DIR__ . '/config.php';
// Совместимость с конфигом старого образца (только BOT_TOKEN/TG_CHAT_ID):
// отсутствующие константы получают безопасные значения по умолчанию.
foreach ([
'BOT_TOKEN' => '',
'TG_CHAT_ID' => '',
'MAIL_MODE' => 'smtp',
'MAIL_TO' => '',
'MAIL_FROM' => '',
'MAIL_FROM_NAME' => 'Harvey Monster Team',
'MAIL_SUBJECT' => 'Заявка с harveymonsterteam.ru',
'SMTP_HOST' => '',
'SMTP_PORT' => 465,
'SMTP_SECURE' => 'ssl',
'SMTP_USER' => '',
'SMTP_PASS' => '',
'WEBHOOK_URL' => '',
'WEBHOOK_TOKEN' => '',
] as $name => $default) {
if (!defined($name)) {
define($name, $default);
}
}
unset($name, $default);
const MAX_REQUESTS_PER_WINDOW = 5;
const WINDOW_SECONDS = 600;
const RATE_LIMIT_DIR = __DIR__ . '/var/ratelimit';
const LEADS_DIR = __DIR__ . '/var/leads';
const META_KEYS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'yclid', 'gclid', 'referrer', 'page'];
/* ---------- helpers ---------- */
function json_out(int $status, bool $ok, string $msg): void
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($ok ? ['ok' => true, 'message' => $msg] : ['ok' => false, 'error' => $msg], JSON_UNESCAPED_UNICODE);
exit;
}
function u_len(string $s): int
{
if (function_exists('mb_strlen')) {
return mb_strlen($s, 'UTF-8');
}
$n = preg_match_all('/./us', $s);
return $n === false ? strlen($s) : $n;
}
/** Strip control characters: они ломают заголовки письма и JSON каналов. */
function clean(string $s): string
{
$s = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/u', ' ', $s);
return trim($s === null ? '' : $s);
}
function ensure_dir(string $dir): bool
{
if (is_dir($dir)) {
return true;
}
return @mkdir($dir, 0775, true);
}
/** api/var/ лежит под docroot: закрываем его от веба, даже если хостинг не читает .htaccess выше. */
function ensure_dir_guard(): void
{
$guard = dirname(LEADS_DIR) . '/.htaccess';
if (is_dir(dirname(LEADS_DIR)) && !is_file($guard)) {
@file_put_contents($guard, "<IfModule mod_authz_core.c>\n Require all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\n Deny from all\n</IfModule>\n");
}
}
function rate_limited(string $ip): bool
{
if (!ensure_dir(RATE_LIMIT_DIR)) {
return false; // storage unavailable — accept rather than block the whole form
}
$file = RATE_LIMIT_DIR . '/' . md5($ip) . '.json';
$now = time();
$hits = [];
if (is_file($file)) {
$hits = json_decode((string) file_get_contents($file), true);
if (!is_array($hits)) {
$hits = [];
}
foreach ($hits as $i => $t) {
if ($now - $t >= WINDOW_SECONDS) {
unset($hits[$i]);
}
}
}
$hits[] = $now;
@file_put_contents($file, json_encode($hits), LOCK_EX);
return count($hits) > MAX_REQUESTS_PER_WINDOW;
}
/** Keep only known attribution keys, scalar, short: meta is untrusted input. */
function sanitize_meta($raw): array
{
if (!is_array($raw)) {
return [];
}
$out = [];
foreach (META_KEYS as $k) {
if (!isset($raw[$k]) || !is_scalar($raw[$k])) {
continue;
}
$v = clean((string) $raw[$k]);
if ($v !== '') {
$out[$k] = function_exists('mb_substr') ? mb_substr($v, 0, 300, 'UTF-8') : substr($v, 0, 300);
}
}
return $out;
}
function meta_line(array $meta): string
{
if (!$meta) {
return '';
}
$pairs = [];
foreach ($meta as $k => $v) {
$pairs[] = $k . '=' . $v;
}
return implode(' · ', $pairs);
}
/* ---------- delivery channels ---------- */
function channel_store(array $lead): bool
{
if (!ensure_dir(LEADS_DIR)) {
return false;
}
ensure_dir_guard();
$line = json_encode($lead, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
return @file_put_contents(LEADS_DIR . '/' . date('Y-m') . '.jsonl', $line, FILE_APPEND | LOCK_EX) !== false;
}
function channel_telegram(array $lead, string $text): bool
{
if (BOT_TOKEN === '' || TG_CHAT_ID === '') {
return false;
}
$ctx = stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => json_encode([
'chat_id' => TG_CHAT_ID,
'text' => $text,
'parse_mode' => 'HTML',
'disable_web_page_preview' => true,
], JSON_UNESCAPED_UNICODE),
'timeout' => 10,
'ignore_errors' => true,
],
]);
$raw = @file_get_contents('https://api.telegram.org/bot' . BOT_TOKEN . '/sendMessage', false, $ctx);
$body = $raw === false ? null : json_decode($raw, true);
if ($raw === false || !is_array($body) || empty($body['ok'])) {
error_log('contact.php: telegram failed: ' . ($raw === false ? 'http error' : (string) $raw));
return false;
}
return true;
}
/** Read one (possibly multi-line) SMTP reply. */
function smtp_read($fp): string
{
$out = '';
while (($line = fgets($fp, 1024)) !== false) {
$out .= $line;
if (strlen($line) < 4 || $line[3] !== '-') {
break;
}
}
return $out;
}
function smtp_cmd($fp, string $cmd, array $expect): bool
{
if ($cmd !== '') {
fwrite($fp, $cmd . "\r\n");
}
$reply = smtp_read($fp);
foreach ($expect as $code) {
if (strpos($reply, (string) $code) === 0) {
return true;
}
}
error_log('contact.php: smtp unexpected reply to "' . substr($cmd, 0, 40) . '": ' . trim($reply));
return false;
}
/** Minimal dependency-free SMTP client: implicit SSL or STARTTLS, AUTH LOGIN, base64 UTF-8 body. */
function smtp_send(string $to, string $subject, string $body): bool
{
if (!filter_var($to, FILTER_VALIDATE_EMAIL) || SMTP_HOST === '' || SMTP_USER === '') {
return false;
}
$secure = strtolower(SMTP_SECURE); // 'ssl' | 'tls' | ''
$remote = ($secure === 'ssl' ? 'ssl://' : '') . SMTP_HOST . ':' . SMTP_PORT;
$fp = @stream_socket_client($remote, $errno, $errstr, 15);
if (!$fp) {
error_log('contact.php: smtp connect failed: ' . $errstr);
return false;
}
stream_set_timeout($fp, 15);
$ehlo = 'EHLO ' . (gethostname() ?: 'localhost');
$ok = smtp_cmd($fp, '', [220]) && smtp_cmd($fp, $ehlo, [250]);
if ($ok && $secure === 'tls') {
$ok = smtp_cmd($fp, 'STARTTLS', [220])
&& @stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) === true
&& smtp_cmd($fp, $ehlo, [250]);
}
if ($ok && SMTP_PASS !== '') {
$ok = smtp_cmd($fp, 'AUTH LOGIN', [334])
&& smtp_cmd($fp, base64_encode(SMTP_USER), [334])
&& smtp_cmd($fp, base64_encode(SMTP_PASS), [235]);
}
$from = filter_var(MAIL_FROM, FILTER_VALIDATE_EMAIL) ? MAIL_FROM : SMTP_USER;
if ($ok) {
$ok = smtp_cmd($fp, 'MAIL FROM:<' . $from . '>', [250])
&& smtp_cmd($fp, 'RCPT TO:<' . $to . '>', [250, 251])
&& smtp_cmd($fp, 'DATA', [354]);
}
if ($ok) {
$name = '=?UTF-8?B?' . base64_encode(MAIL_FROM_NAME) . '?=';
$subj = '=?UTF-8?B?' . base64_encode($subject) . '?=';
$msg = 'From: ' . $name . ' <' . $from . ">\r\n"
. 'To: <' . $to . ">\r\n"
. 'Subject: ' . $subj . "\r\n"
. 'Date: ' . date('r') . "\r\n"
. "MIME-Version: 1.0\r\n"
. "Content-Type: text/plain; charset=UTF-8\r\n"
. "Content-Transfer-Encoding: base64\r\n\r\n"
. chunk_split(base64_encode(str_replace("\n", "\r\n", $body)), 76, "\r\n")
. '.';
$ok = smtp_cmd($fp, $msg, [250]);
}
@fwrite($fp, "QUIT\r\n");
@fclose($fp);
return $ok;
}
function mail_body(array $lead): string
{
$text = "Новое сообщение с harveymonsterteam.ru\n\n"
. 'Имя: ' . $lead['name'] . "\n"
. 'Связь: ' . $lead['contact'] . "\n\n"
. $lead['message'] . "\n";
if ($lead['meta']) {
$text .= "\n---\nИсточник: " . meta_line($lead['meta']) . "\n";
}
$text .= 'Согласие (152-ФЗ): ' . ($lead['consent'] ? 'да' : 'нет') . "\n"
. 'IP: ' . $lead['ip'] . "\n"
. 'Время: ' . date('d.m.Y H:i:s') . "\n";
return $text;
}
function channel_email(array $lead): bool
{
if (MAIL_TO === '' || !filter_var(MAIL_TO, FILTER_VALIDATE_EMAIL)) {
return false;
}
$body = mail_body($lead);
if (MAIL_MODE === 'mail') {
$headers = 'From: ' . MAIL_FROM_NAME . ' <' . (MAIL_FROM !== '' ? MAIL_FROM : MAIL_TO) . ">\r\n"
. "Content-Type: text/plain; charset=UTF-8\r\n";
$ok = @mail(MAIL_TO, '=?UTF-8?B?' . base64_encode(MAIL_SUBJECT) . '?=', $body, $headers);
if (!$ok) {
error_log('contact.php: mail() failed');
}
return $ok;
}
return smtp_send(MAIL_TO, MAIL_SUBJECT, $body);
}
function channel_webhook(array $lead): bool
{
if (WEBHOOK_URL === '') {
return false;
}
$headers = ['Content-Type: application/json'];
if (WEBHOOK_TOKEN !== '') {
$headers[] = 'Authorization: Bearer ' . WEBHOOK_TOKEN;
}
$ctx = stream_context_create([
'http' => [
'method' => 'POST',
'header' => implode("\r\n", $headers),
'content' => json_encode([
'site' => 'https://harveymonsterteam.ru/',
'sent_at' => date('c'),
'name' => $lead['name'],
'contact' => $lead['contact'],
'message' => $lead['message'],
'consent' => $lead['consent'],
'meta' => $lead['meta'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
'timeout' => 12,
'ignore_errors' => true,
],
]);
$raw = @file_get_contents(WEBHOOK_URL, false, $ctx);
$code = 0;
if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)) {
$code = (int) $m[1];
}
if ($raw === false || $code < 200 || $code >= 300) {
error_log('contact.php: webhook failed: ' . ($raw === false ? 'http error' : 'HTTP ' . $code));
return false;
}
return true;
}
/* ---------- request ---------- */
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
header('Allow: POST');
json_out(405, false, 'Method not allowed.');
}
$body = json_decode((string) file_get_contents('php://input'), true);
if (!is_array($body)) {
json_out(400, false, 'Expected a JSON body.');
}
$name = clean((string) ($body['name'] ?? ''));
$contact = clean((string) ($body['contact'] ?? ''));
$message = clean((string) ($body['message'] ?? ''));
$honey = trim((string) ($body['website'] ?? ''));
$consent = ($body['consent'] ?? false) === true;
if ($honey !== '') {
json_out(200, true, 'Сообщение отправлено. Мы ответим в ближайшее время.'); // lie to bots
}
if (u_len($name) < 2 || u_len($name) > 100) {
json_out(422, false, 'Укажите имя (2–100 символов).');
}
// Канал связи не ограничен форматом (telegram, email, телефон, VK) — только длина + экранирование.
if (u_len($contact) < 2 || u_len($contact) > 200) {
json_out(422, false, 'Укажите предпочтительное средство связи (2–200 символов).');
}
if (u_len($message) < 10 || u_len($message) > 4000) {
json_out(422, false, 'Опишите задачу (10–4000 символов).');
}
if (!$consent) {
json_out(422, false, 'Отметьте согласие на обработку персональных данных.');
}
$ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
if (rate_limited($ip)) {
json_out(429, false, 'Слишком много запросов. Попробуйте через 10 минут.');
}
$lead = [
'ts' => date('c'),
'name' => $name,
'contact' => $contact,
'message' => $message,
'consent' => $consent,
'meta' => sanitize_meta($body['meta'] ?? []),
'ip' => $ip,
'ua' => substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 300),
];
// Telegram — HTML: значения экранируем.
$esc = function (string $s): string {
return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
};
$tgText = "🛎 Новое сообщение с harveymonsterteam.ru\n"
. "Имя: {$esc($name)}\n"
. "Связь: {$esc($contact)}\n\n"
. $esc($message);
if ($lead['meta']) {
$tgText .= "\n\nИсточник: " . $esc(meta_line($lead['meta']));
}
$stored = channel_store($lead);
$configured = 0;
$delivered = 0;
if (BOT_TOKEN !== '' && TG_CHAT_ID !== '') {
$configured++;
$delivered += channel_telegram($lead, $tgText) ? 1 : 0;
}
if (MAIL_TO !== '') {
$configured++;
$delivered += channel_email($lead) ? 1 : 0;
}
if (WEBHOOK_URL !== '') {
$configured++;
$delivered += channel_webhook($lead) ? 1 : 0;
}
if ($configured === 0) {
error_log('contact.php: no delivery channel configured — lead stored=' . ($stored ? 'yes' : 'no'));
json_out(500, false, 'Приём заявок не настроен. Напишите на monsterharvi@gmail.com.');
}
if ($delivered === 0) {
error_log('contact.php: all channels failed — lead stored=' . ($stored ? 'yes' : 'no'));
json_out(500, false, 'Не удалось отправить заявку. Напишите на monsterharvi@gmail.com.');
}
json_out(200, true, 'Сообщение отправлено. Мы ответим в ближайшее время.');
+50
View File
@@ -0,0 +1,50 @@
// Local dev stub for the contact form endpoint.
// Usage: node api/dev-stub.mjs (listens on http://127.0.0.1:8787)
// Point the form's API_URL to http://127.0.0.1:8787/ during development:
// <form id="contact-form" data-endpoint="http://127.0.0.1:8787/api/contact.php" …>
// Same JSON contract as api/contact.php, but logs instead of delivering.
import { createServer } from 'node:http';
const PORT = Number(process.env.PORT) || 8787;
const HOST = '127.0.0.1';
function send(res, status, ok, msg) {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(ok ? { ok: true, message: msg } : { ok: false, error: msg }));
}
createServer((req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
if (req.method === 'OPTIONS') { res.writeHead(204); return res.end(); }
if (req.method !== 'POST') { return send(res, 405, false, 'Method not allowed.'); }
let raw = '';
req.on('data', (c) => { raw += c; if (raw.length > 64 * 1024) req.destroy(); });
req.on('end', () => {
let body;
try { body = JSON.parse(raw || '{}'); } catch { return send(res, 400, false, 'Expected a JSON body.'); }
const name = String(body.name ?? '').trim();
const contact = String(body.contact ?? '').trim();
const message = String(body.message ?? '').trim();
const consent = body.consent === true;
const meta = body.meta && typeof body.meta === 'object' ? body.meta : {};
if (!consent) return send(res, 422, false, 'Отметьте согласие на обработку персональных данных.');
if (name.length < 2 || name.length > 100) return send(res, 422, false, 'Укажите имя (2–100 символов).');
if (contact.length < 2 || contact.length > 200) return send(res, 422, false, 'Укажите предпочтительное средство связи (2–200 символов).');
if (message.length < 10 || message.length > 4000) return send(res, 422, false, 'Опишите задачу (10–4000 символов).');
console.log('\n=== НОВОЕ СООБЩЕНИЕ (stub) ===');
console.log('Имя: ', name);
console.log('Связь: ', contact);
console.log('Задача: ', message);
if (Object.keys(meta).length) console.log('Мета: ', JSON.stringify(meta));
console.log('================================\n');
send(res, 200, true, 'Сообщение отправлено (stub). Мы ответим в ближайшее время.');
});
}).listen(PORT, HOST, () => {
console.log(`Contact stub: http://${HOST}:${PORT}`);
console.log('POST JSON {name, contact, message, consent, website, meta}');
});