init
This commit is contained in:
54 files changed
+4604
No files matched your search
@@ -0,0 +1,326 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { pathToFileURL } from "node:url";
|
||||
const { chromium } = await import(
|
||||
pathToFileURL(
|
||||
process.env.PLAYWRIGHT_MODULE ||
|
||||
"/tmp/app-browser-check/node_modules/playwright/index.mjs",
|
||||
).href
|
||||
);
|
||||
const browser = await chromium.launch({
|
||||
executablePath: process.env.CHROMIUM_PATH || "/usr/bin/chromium",
|
||||
headless: true,
|
||||
args: ["--no-sandbox"],
|
||||
});
|
||||
const base = process.env.APP_URL || "http://127.0.0.1:8080";
|
||||
let checks = 0;
|
||||
function check(value, label) {
|
||||
assert.ok(value, label);
|
||||
console.log("PASS:", label);
|
||||
checks++;
|
||||
}
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1440, height: 1100 },
|
||||
colorScheme: "light",
|
||||
});
|
||||
await context.route("https://developer.eitaa.com/**", (route) =>
|
||||
route.fulfill({ contentType: "application/javascript", body: "" }),
|
||||
);
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
await page.goto(base);
|
||||
await page.waitForSelector(".feature-card");
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
check(
|
||||
(await page.locator(".feature-card:visible").count()) === 6,
|
||||
"Six curated experiments on overview",
|
||||
);
|
||||
check(
|
||||
(await page.locator("#environment").textContent()) === "پیشنمایش مرورگر",
|
||||
"Browser clearly labeled as preview",
|
||||
);
|
||||
await page.screenshot({ path: "/tmp/app-desktop.png", fullPage: true });
|
||||
await page
|
||||
.locator("#card-dialogs button")
|
||||
.filter({ hasText: "تأیید" })
|
||||
.click();
|
||||
check(
|
||||
await page.locator("#demo-dialog").isVisible(),
|
||||
"Browser dialog preview opens",
|
||||
);
|
||||
await page.locator("#dialog-buttons button[value=yes]").click();
|
||||
await page.waitForFunction(() =>
|
||||
document.querySelector("#dialogs-result").textContent.includes("yes"),
|
||||
);
|
||||
check(
|
||||
(await page.locator("#dialogs-result").textContent()).includes("yes"),
|
||||
"Dialog selection returned",
|
||||
);
|
||||
await page.locator("[data-category=all]").click();
|
||||
check(
|
||||
(await page.locator(".feature-card:visible").count()) === 22,
|
||||
"All documented experiment cards accessible",
|
||||
);
|
||||
await page.locator("#search").fill("Gyroscope");
|
||||
check(
|
||||
(await page.locator(".feature-card:visible").count()) === 1,
|
||||
"Search resolves SDK object name",
|
||||
);
|
||||
await page.locator("#search").fill("not-a-real-feature");
|
||||
check(await page.locator("#empty").isVisible(), "Search has empty state");
|
||||
await page.locator("[data-category=security]").click();
|
||||
await page.locator("#card-messages button").click();
|
||||
check(
|
||||
(await page.locator("#messages-result").textContent()).includes("ابتدا"),
|
||||
"Unauthenticated messaging blocked in UI",
|
||||
);
|
||||
await page.locator("#theme-toggle").click();
|
||||
check(
|
||||
await page.locator("body").evaluate((e) => e.classList.contains("dark")),
|
||||
"Dark theme toggle works",
|
||||
);
|
||||
await page.locator("#theme-toggle").click();
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.locator("[data-category=overview]").click();
|
||||
check(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth,
|
||||
),
|
||||
"Mobile layout has no horizontal page overflow",
|
||||
);
|
||||
await page.screenshot({ path: "/tmp/app-mobile.png", fullPage: true });
|
||||
check(errors.length === 0, "No browser runtime errors");
|
||||
await context.close();
|
||||
|
||||
// Contract tests use a deterministic SDK double, never the real Eitaa API.
|
||||
const nativeContext = await browser.newContext({
|
||||
viewport: { width: 1000, height: 900 },
|
||||
});
|
||||
await nativeContext.route("https://developer.eitaa.com/**", (route) =>
|
||||
route.fulfill({ contentType: "application/javascript", body: "" }),
|
||||
);
|
||||
await nativeContext.addInitScript(() => {
|
||||
window.sdkCalls = [];
|
||||
const methods = [
|
||||
"ready",
|
||||
"expand",
|
||||
"close",
|
||||
"setHeaderColor",
|
||||
"setBackgroundColor",
|
||||
"setBottomBarColor",
|
||||
"enableClosingConfirmation",
|
||||
"disableClosingConfirmation",
|
||||
"enableVerticalSwipes",
|
||||
"disableVerticalSwipes",
|
||||
"lockOrientation",
|
||||
"unlockOrientation",
|
||||
"requestFullscreen",
|
||||
"exitFullscreen",
|
||||
"openLink",
|
||||
"openEitaaLink",
|
||||
"addToHomeScreen",
|
||||
"closeScanQrPopup",
|
||||
];
|
||||
const app = {
|
||||
initData: "fake-signed-launch",
|
||||
platform: "android",
|
||||
version: "1.4",
|
||||
colorScheme: "light",
|
||||
themeParams: {},
|
||||
isVersionAtLeast: (v) => parseFloat(v) <= 1.4,
|
||||
onEvent: () => {},
|
||||
offEvent: () => {},
|
||||
};
|
||||
for (const method of methods)
|
||||
app[method] = (...args) => window.sdkCalls.push({ method, args });
|
||||
for (const kind of [
|
||||
"MainButton",
|
||||
"SecondaryButton",
|
||||
"BackButton",
|
||||
"SettingsButton",
|
||||
]) {
|
||||
app[kind] = {};
|
||||
for (const method of [
|
||||
"setParams",
|
||||
"setText",
|
||||
"show",
|
||||
"hide",
|
||||
"enable",
|
||||
"disable",
|
||||
"showProgress",
|
||||
"hideProgress",
|
||||
"onClick",
|
||||
"offClick",
|
||||
])
|
||||
app[kind][method] = (...args) =>
|
||||
window.sdkCalls.push({
|
||||
method: kind + "." + method,
|
||||
args: args.filter((arg) => typeof arg !== "function"),
|
||||
});
|
||||
}
|
||||
for (const kind of ["Accelerometer", "Gyroscope", "DeviceOrientation"]) {
|
||||
app[kind] = {
|
||||
isStarted: false,
|
||||
x: 1,
|
||||
y: 2,
|
||||
z: 3,
|
||||
alpha: 0.1,
|
||||
beta: 0.2,
|
||||
gamma: 0.3,
|
||||
start(params, cb) {
|
||||
this.isStarted = true;
|
||||
window.sdkCalls.push({ method: kind + ".start", args: [params] });
|
||||
cb?.(true);
|
||||
},
|
||||
stop(cb) {
|
||||
this.isStarted = false;
|
||||
cb?.(true);
|
||||
},
|
||||
};
|
||||
}
|
||||
app.requestContact = (cb) =>
|
||||
cb(true, {
|
||||
response: "signed-contact-fixture",
|
||||
responseUnsafe: { phone_number: "PRIVATE_PHONE" },
|
||||
});
|
||||
app.showScanQrPopup = (params, cb) => cb("<img src=x onerror=alert(1)>");
|
||||
window.Eitaa = { WebApp: app };
|
||||
});
|
||||
const calls = [];
|
||||
await nativeContext.route("**/api.php", async (route) => {
|
||||
const data = route.request().postDataJSON();
|
||||
calls.push(data);
|
||||
const result =
|
||||
data.action === "authenticate"
|
||||
? {
|
||||
ok: true,
|
||||
user: { id: 123, first_name: "آزمایشی" },
|
||||
context: { start_param: "test" },
|
||||
expires: Math.floor(Date.now() / 1000) + 3600,
|
||||
}
|
||||
: data.action === "contact"
|
||||
? {
|
||||
ok: true,
|
||||
contact: { user_id: 123, phone_number: "PRIVATE_PHONE" },
|
||||
}
|
||||
: { ok: true, message: "sent" };
|
||||
await route.fulfill({
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify(result),
|
||||
});
|
||||
});
|
||||
const nativePage = await nativeContext.newPage();
|
||||
nativePage.on("pageerror", (error) => errors.push(error.message));
|
||||
await nativePage.goto(base);
|
||||
await nativePage.waitForFunction(
|
||||
() => document.querySelector("#auth-status").textContent === "تأییدشده",
|
||||
);
|
||||
check(
|
||||
calls.some(
|
||||
(c) => c.action === "authenticate" && c.initData === "fake-signed-launch",
|
||||
),
|
||||
"Launch authentication POST wired",
|
||||
);
|
||||
await nativePage.locator("[data-category=interface]").click();
|
||||
await nativePage.locator("#main-button-text").fill("تست");
|
||||
await nativePage
|
||||
.locator("#card-main-button button")
|
||||
.filter({ hasText: "نمایش و اعمال" })
|
||||
.click();
|
||||
check(
|
||||
await nativePage.evaluate(() =>
|
||||
sdkCalls.some(
|
||||
(c) => c.method === "MainButton.setParams" && c.args[0].text === "تست",
|
||||
),
|
||||
),
|
||||
"Native button configuration dispatched",
|
||||
);
|
||||
await nativePage.locator("[data-category=device]").click();
|
||||
await nativePage
|
||||
.locator("#card-viewport button")
|
||||
.filter({ hasText: "تمامصفحه" })
|
||||
.click();
|
||||
check(
|
||||
await nativePage.evaluate(() =>
|
||||
sdkCalls.some((c) => c.method === "requestFullscreen"),
|
||||
),
|
||||
"Fullscreen documentation alias maps to current SDK",
|
||||
);
|
||||
await nativePage
|
||||
.locator("#card-accelerometer button")
|
||||
.filter({ hasText: "شروع حسگر" })
|
||||
.click();
|
||||
check(
|
||||
await nativePage.evaluate(() => Eitaa.WebApp.Accelerometer.isStarted),
|
||||
"Sensor started with parameters",
|
||||
);
|
||||
await nativePage.waitForFunction(() =>
|
||||
document
|
||||
.querySelector("#accelerometer-values")
|
||||
.textContent.includes("1.00"),
|
||||
);
|
||||
check(
|
||||
(await nativePage.locator("#accelerometer-values").textContent()).includes(
|
||||
"1.00",
|
||||
),
|
||||
"Sensor live values rendered",
|
||||
);
|
||||
await nativePage
|
||||
.locator("#card-accelerometer button")
|
||||
.filter({ hasText: "توقف" })
|
||||
.click();
|
||||
check(
|
||||
await nativePage.evaluate(() => !Eitaa.WebApp.Accelerometer.isStarted),
|
||||
"Sensor stopped",
|
||||
);
|
||||
await nativePage.locator("[data-category=interaction]").click();
|
||||
await nativePage
|
||||
.locator("#card-qr button")
|
||||
.filter({ hasText: "شروع اسکن" })
|
||||
.click();
|
||||
check(
|
||||
(await nativePage.locator("#qr-result img").count()) === 0 &&
|
||||
(await nativePage.locator("#qr-result").textContent()).includes("<img"),
|
||||
"QR content rendered as text, not executable HTML",
|
||||
);
|
||||
await nativePage.locator("[data-category=security]").click();
|
||||
await nativePage
|
||||
.locator("#card-permissions button")
|
||||
.filter({ hasText: "اشتراک تماس" })
|
||||
.click();
|
||||
await nativePage.waitForFunction(() =>
|
||||
document
|
||||
.querySelector("#permissions-result")
|
||||
.textContent.includes("PRIVATE_PHONE"),
|
||||
);
|
||||
check(
|
||||
calls.some(
|
||||
(c) =>
|
||||
c.action === "contact" && c.contactData === "signed-contact-fixture",
|
||||
),
|
||||
"Current SDK contact response sent for server verification",
|
||||
);
|
||||
check(
|
||||
!(await nativePage.locator("#event-log").textContent()).includes(
|
||||
"PRIVATE_PHONE",
|
||||
),
|
||||
"Contact excluded from event log",
|
||||
);
|
||||
await nativePage.locator("#card-messages button").click();
|
||||
await nativePage.waitForFunction(
|
||||
() => document.querySelector("#messages-result").textContent === "sent",
|
||||
);
|
||||
const send = calls.find((c) => c.action === "sendMessage");
|
||||
check(
|
||||
send && send.text && !("chat_id" in send),
|
||||
"Message request contains no client-selected recipient",
|
||||
);
|
||||
check(errors.length === 0, "No runtime errors with simulated native bridge");
|
||||
await nativeContext.close();
|
||||
console.log(
|
||||
`\n${checks} browser checks passed. Screenshots: /tmp/app-desktop.png and /tmp/app-mobile.png`,
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
// Isolated test installation: never loads the real token or contacts Eitaa.
|
||||
require __DIR__ . '/security.php';
|
||||
$root = dirname(__DIR__);
|
||||
$temp = sys_get_temp_dir() . '/app-http-' . bin2hex(random_bytes(6));
|
||||
mkdir($temp, 0700);
|
||||
foreach (['storage', 'storage/secrets', 'storage/sessions', 'storage/cache', 'config', 'public'] as $directory) {
|
||||
mkdir($temp . '/' . $directory, 0700);
|
||||
}
|
||||
foreach (['bootstrap', 'app', 'resources'] as $directory) {
|
||||
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root . '/' . $directory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
|
||||
mkdir($temp . '/' . $directory, 0700);
|
||||
foreach ($iterator as $entry) {
|
||||
$destination = $temp . '/' . substr($entry->getPathname(), strlen($root) + 1);
|
||||
$entry->isDir() ? mkdir($destination, 0700) : copy($entry->getPathname(), $destination);
|
||||
}
|
||||
}
|
||||
copy($root . '/config/app.php', $temp . '/config/app.php');
|
||||
mkdir($temp . '/public/assets/brand', 0700, true);
|
||||
copy($root . '/public/assets/brand/social.svg', $temp . '/public/assets/brand/social.svg');
|
||||
foreach (['index.php', 'api.php', 'sample.php'] as $file) {
|
||||
copy($root . '/public/' . $file, $temp . '/public/' . $file);
|
||||
}
|
||||
file_put_contents($temp . '/config/local.php', "<?php return ['token' => 'TEST_ONLY_NOT_A_REAL_TOKEN', 'allow_local_http' => true];");
|
||||
file_put_contents($temp . '/storage/secrets/token.txt', 'PRIVATE_FILE_MUST_NOT_BE_SERVED');
|
||||
$port = random_int(20000, 45000);
|
||||
$server = proc_open([PHP_BINARY,'-S','127.0.0.1:' . $port,'-t',$temp . '/public'], [['pipe','r'],['file',$temp . '/server.log','a'],['file',$temp . '/server.log','a']], $pipes, $temp, array_merge(getenv(), ['EITAA_APP_TOKEN' => 'TEST_ONLY_NOT_A_REAL_TOKEN']));
|
||||
if (!is_resource($server)) {
|
||||
throw new RuntimeException('Cannot start PHP test server.');
|
||||
}
|
||||
$curl = curl_init();
|
||||
curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER=>true,CURLOPT_COOKIEFILE=>'',CURLOPT_TIMEOUT=>5]);
|
||||
$base = 'http://127.0.0.1:' . $port;
|
||||
function request(string $path, ?array $body = null, ?string $csrf = null, ?string $raw = null): array
|
||||
{
|
||||
global $curl, $base;
|
||||
curl_setopt_array($curl, [CURLOPT_URL=>$base.$path,CURLOPT_HTTPGET=>true,CURLOPT_HTTPHEADER=>[]]);
|
||||
if ($body !== null || $raw !== null) {
|
||||
curl_setopt_array($curl, [CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$raw ?? json_encode($body),CURLOPT_HTTPHEADER=>['Content-Type: application/json','X-CSRF-Token: '.($csrf??'')]]);
|
||||
}
|
||||
$response = curl_exec($curl);
|
||||
return [curl_getinfo($curl,CURLINFO_RESPONSE_CODE),$response,json_decode($response ?: '',true)];
|
||||
}
|
||||
try {
|
||||
for ($i=0;$i<30;$i++) {
|
||||
[$status,$html] = request('/');
|
||||
if ($status === 200) break;
|
||||
usleep(100000);
|
||||
}
|
||||
check($status===200,'Page loads from isolated installation');
|
||||
preg_match('/name="csrf-token" content="([a-f0-9]+)"/', $html, $matches);
|
||||
$csrf = $matches[1] ?? '';
|
||||
check(strlen($csrf)===64,'CSRF token provided');
|
||||
check(!str_contains($html,'TEST_ONLY_NOT_A_REAL_TOKEN'),'App token absent from page');
|
||||
check(request('/api.php')[0]===405,'API rejects GET');
|
||||
check(request('/api.php',['action'=>'authenticate'])[0]===403,'API rejects missing CSRF');
|
||||
check(request('/api.php',null,$csrf,'{broken')[0]===400,'API rejects malformed JSON');
|
||||
check(request('/api.php',null,$csrf,str_repeat('x',20001))[0]===413,'API rejects large request');
|
||||
check(request('/api.php',['action'=>'sendMessage','text'=>'hello'],$csrf)[0]===401,'Message requires verified session');
|
||||
$launch = signFixture(['auth_date'=>(string)time(),'user'=>'{"id":12345,"first_name":"تست"}'], 'TEST_ONLY_NOT_A_REAL_TOKEN');
|
||||
check(request('/api.php',['action'=>'authenticate','initData'=>$launch.'x'],$csrf)[0]===401,'Forged launch rejected over HTTP');
|
||||
[$status,,$data]=request('/api.php',['action'=>'authenticate','initData'=>$launch],$csrf);
|
||||
check($status===200 && $data['user']['id']===12345,'Valid launch creates authenticated session');
|
||||
check(!isset($data['hash'])&&!isset($data['token']),'Authentication response excludes secrets');
|
||||
check(request('/api.php',['action'=>'sendMessage','text'=>''],$csrf)[0]===400,'Empty message blocked before network call');
|
||||
$contact = signFixture(['auth_date'=>(string)time(),'contact'=>'{"user_id":12345,"phone_number":"+989000000000"}'], 'TEST_ONLY_NOT_A_REAL_TOKEN');
|
||||
check(request('/api.php',['action'=>'contact','contactData'=>$contact],$csrf)[0]===200,'Signed contact accepted for current user');
|
||||
$otherContact = signFixture(['auth_date'=>(string)time(),'contact'=>'{"user_id":54321,"phone_number":"+989000000000"}'], 'TEST_ONLY_NOT_A_REAL_TOKEN');
|
||||
check(request('/api.php',['action'=>'contact','contactData'=>$otherContact],$csrf)[0]===401,'Other user contact rejected');
|
||||
[$status,,$data]=request('/api.php',['action'=>'logout'],$csrf);
|
||||
check($status===200&&$data['csrf']!==$csrf,'Logout rotates CSRF');
|
||||
check(request('/api.php',['action'=>'sendMessage','text'=>'test'],$data['csrf'])[0]===401,'Logout removes authenticated user');
|
||||
// PHP's development server may fall back to index.php for unknown paths.
|
||||
[$status,$privateBody] = request('/storage/secrets/token.txt');
|
||||
check(!str_contains($privateBody, 'PRIVATE_FILE_MUST_NOT_BE_SERVED'), 'Private file never served from document root');
|
||||
file_put_contents($temp . '/config/local.php', "<?php return ['token' => 'TEST_ONLY_NOT_A_REAL_TOKEN', 'allow_local_http' => false];");
|
||||
check(request('/api.php',['action'=>'authenticate','initData'=>$launch],$data['csrf'])[0]===403, 'Production configuration refuses HTTP');
|
||||
[$status, $svg] = request('/sample.php');
|
||||
check($status === 200 && str_contains($svg, '<svg'), 'Postcard template served by thin download entry point');
|
||||
file_put_contents($temp . '/config/local.php', "<?php return ['session_lifetime' => 0];");
|
||||
[$status, $html] = request('/');
|
||||
check($status === 500 && !str_contains($html, 'RuntimeException') && !str_contains($html, $temp), 'Invalid configuration fails without exposing paths or exceptions');
|
||||
file_put_contents($temp . '/config/local.php', "<?php return ['public_url' => 'https://example.com/demo'];");
|
||||
[$status, $html] = request('/');
|
||||
check($status === 200 && str_contains($html, 'https://example.com/demo/assets/brand/social.png'), 'Configured share URL supports subdirectory deployment');
|
||||
file_put_contents($temp . '/config/local.php', "<?php return ['public_url' => 'https://user:pass@example.com'];");
|
||||
check(request('/')[0] === 500, 'Share base URL rejects embedded credentials');
|
||||
echo "\n$tests total security and HTTP checks passed.\n";
|
||||
} finally {
|
||||
proc_terminate($server);
|
||||
fclose($pipes[0]);
|
||||
proc_close($server);
|
||||
// Remove only the uniquely generated test fixture, never user data.
|
||||
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($temp, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
|
||||
foreach ($iterator as $entry) {
|
||||
$entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname());
|
||||
}
|
||||
rmdir($temp);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
use App\Http\HttpException;
|
||||
use App\Security\InitDataValidator;
|
||||
use App\Security\RateLimiter;
|
||||
|
||||
require dirname(__DIR__) . '/bootstrap/autoload.php';
|
||||
|
||||
$tests = 0;
|
||||
function check(bool $condition, string $name): void
|
||||
{
|
||||
global $tests;
|
||||
if (!$condition) {
|
||||
throw new RuntimeException('FAIL: ' . $name);
|
||||
}
|
||||
$tests++;
|
||||
echo 'PASS: ' . $name . PHP_EOL;
|
||||
}
|
||||
function rejects(callable $fn, string $name, int $status = 401): void
|
||||
{
|
||||
try {
|
||||
$fn();
|
||||
} catch (HttpException $e) {
|
||||
check($e->status === $status, $name);
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException('FAIL: accepted ' . $name);
|
||||
}
|
||||
function signFixture(array $data, string $token): string
|
||||
{
|
||||
ksort($data, SORT_STRING);
|
||||
$pairs = [];
|
||||
foreach ($data as $k => $v) {
|
||||
$pairs[] = $k . '=' . $v;
|
||||
}
|
||||
$data['hash'] = hash_hmac('sha256', implode("\n", $pairs), hash_hmac('sha256', $token, 'WebAppData', true));
|
||||
return http_build_query($data, '', '&', PHP_QUERY_RFC3986);
|
||||
}
|
||||
$token = 'TEST_ONLY_NOT_A_REAL_TOKEN';
|
||||
$now = 1800000000;
|
||||
$data = ['auth_date' => (string) $now, 'user' => '{"id":279058397,"first_name":"مهدی + & =","allows_write_to_pm":true}', 'start_param' => 'hello+world'];
|
||||
$signed = signFixture($data, $token);
|
||||
$validated = InitDataValidator::validate($signed, $token, 300, $now);
|
||||
check($validated['start_param'] === 'hello+world', 'URL decoding preserves encoded plus');
|
||||
check(InitDataValidator::user($validated)['first_name'] === 'مهدی + & =', 'Persian user data is preserved');
|
||||
check(InitDataValidator::validate(str_replace('%20', '+', $signed), $token, 300, $now)['user'] === $data['user'], 'Form-encoded spaces supported');
|
||||
rejects(fn() => InitDataValidator::validate(str_replace('hello%2Bworld', 'changed', $signed), $token, 300, $now), 'Tampered data');
|
||||
rejects(fn() => InitDataValidator::validate($signed, 'WRONG', 300, $now), 'Wrong token');
|
||||
rejects(fn() => InitDataValidator::validate($signed . '&auth_date=' . $now, $token, 300, $now), 'Duplicate key');
|
||||
rejects(fn() => InitDataValidator::validate($signed . '&%61uth_date=' . $now, $token, 300, $now), 'Encoded duplicate key');
|
||||
rejects(fn() => InitDataValidator::validate($signed . '&user.name=x', $token, 300, $now), 'PHP key normalization ambiguity');
|
||||
rejects(fn() => InitDataValidator::validate($signed . '&x=%ZZ', $token, 300, $now), 'Malformed URL encoding');
|
||||
rejects(fn() => InitDataValidator::validate($signed, $token, 300, $now + 301), 'Expired launch');
|
||||
rejects(fn() => InitDataValidator::validate($signed, $token, 300, $now - 31), 'Future launch');
|
||||
rejects(fn() => InitDataValidator::validate(signFixture(['user' => $data['user']], $token), $token, 300, $now), 'Missing auth_date');
|
||||
rejects(fn() => InitDataValidator::validate(signFixture(['auth_date' => 'abc'], $token), $token, 300, $now), 'Invalid auth_date');
|
||||
rejects(fn() => InitDataValidator::validate(str_repeat('x', 16385), $token, 300, $now), 'Oversized payload');
|
||||
rejects(fn() => InitDataValidator::validate('auth_date=1&hash=123', $token, 300, $now), 'Invalid hash format');
|
||||
rejects(fn() => InitDataValidator::user(['user' => '{"id":-1}']), 'Invalid recipient ID');
|
||||
rejects(fn() => InitDataValidator::user(['user' => 'not-json']), 'Malformed user JSON');
|
||||
check(InitDataValidator::user(['user' => '{"id":4503599627370495}'])['id'] === 4503599627370495, '52-bit Eitaa ID preserved');
|
||||
check(!isset(InitDataValidator::user(['user' => '{"id":12,"extra":"secret"}'])['extra']), 'User response is allowlisted');
|
||||
// Published HMAC intermediate value is independent of our fixture signer.
|
||||
check(hash_hmac('sha256', '5768337691:AAGDAe6rjxu1cUgxK4BizYi--Utc3J9v5AU', 'WebAppData') === 'aa492a44bdf019c759defb1698c1d77690189973945491a756051cdc1207a449', 'Documentation HMAC reference vector');
|
||||
$file = tempnam(sys_get_temp_dir(), 'app-limits-');
|
||||
try {
|
||||
(new RateLimiter($file))->hit('user-1', 2, 3600);
|
||||
(new RateLimiter($file))->hit('user-1', 2, 3600);
|
||||
rejects(fn() => (new RateLimiter($file))->hit('user-1', 2, 3600), 'Persistent quota blocks third request', 429);
|
||||
(new RateLimiter($file))->hit('user-2', 2, 3600);
|
||||
check(count(json_decode(file_get_contents($file), true)) === 2, 'Independent user quotas');
|
||||
} finally {
|
||||
unlink($file);
|
||||
}
|
||||
echo "\n$tests security checks passed.\n";
|
||||
Reference in new issue
Block a user