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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ Vue CLI остаётся на последнем опубликованном в

Если передан токен, числовой `user_id` и хотя бы одно право `userdata.category.personal.read` / `userdata.category.credentials.read`, приложение автоматически запрашивает `GET /userdata/user/{id}` на том же API-хосте, что и сервис печати. Полученные поля `Личная информация / Полное имя` и `Учетные данные / Номер профсоюзного билета` заполняются по отдельности. Фамилия предлагается как первое слово ФИО и остаётся редактируемой. Уже начатый ввод не перезаписывается. При отсутствии данных или ошибке профиля остаётся ручной ввод. При доступной сессии профиля сохранённые реквизиты другого пользователя не подставляются.

Чтобы это заработало в Твой ФФ, соответствующие права должны быть делегированы мини-приложению в настройках сервиса. Административные права не нужны. Токен передаётся в заголовке `Authorization` только запросу userdata, не сохраняется в localStorage и исключён из URL аналитики. Он не заменяет проверку фамилии и билета в print API: полноценная печать по авторизованной сессии потребует изменения бэкенда.
Чтобы это заработало в Твой ФФ, соответствующие права должны быть делегированы мини-приложению в настройках сервиса. Административные права не нужны. Для загрузки и QR-печати из истории приложение передаёт пользовательскую сессию в заголовке `Authorization` к print-api. Автозаполнение использует ту же сессию для запроса userdata. Для QR-ссылки бота используется ограниченное разрешение `PrintJob` из фрагмента ссылки. Учётные данные исключены из URL аналитики.

[OpenAPI userdata](https://api.profcomff.com/userdata/openapi.json), [контейнер iframe Твой ФФ](https://github.com/profcomff/webapp-ui/blob/main/src/views/apps/ApplicationFrame.vue).

Expand Down
16 changes: 13 additions & 3 deletions src/api/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,16 @@ export interface PrintRequest {
}
const base = () => process.env.VUE_APP_API_PRINTER;

export function printAuthorization(): string {
const token = new URLSearchParams(window.location.search).get("token");
if (!token) throw new Error("Для печати войдите в «Твой ФФ» и откройте принтер.");
return token;
}

export async function uploadFile(
input: PrintRequest,
progress: (percent: number) => void,
authorization: string,
): Promise<string> {
const { data } = await axios.post<{ pin: string }>(
`${base()}/file`,
Expand All @@ -27,13 +34,14 @@ export async function uploadFile(
two_sided: input.twoSided,
},
},
{ timeout: 30_000 },
{ headers: { Authorization: authorization }, timeout: 30_000 },
);
if (!data.pin || !/^[a-z0-9]+$/i.test(data.pin))
throw new Error("Invalid PIN response");
const body = new FormData();
body.append("file", input.file);
await axios.post(`${base()}/file/${data.pin}`, body, {
headers: { Authorization: authorization },
timeout: 120_000,
onUploadProgress: (event: AxiosProgressEvent) => {
if (event.total)
Expand All @@ -44,7 +52,7 @@ export async function uploadFile(
return data.pin;
}

export async function printQr(token: string, pins: string[]): Promise<void> {
export async function printQr(token: string, pins: string[], authorization: string): Promise<void> {
const files = [...new Set(pins)];
if (
!token.trim() ||
Expand All @@ -56,7 +64,7 @@ export async function printQr(token: string, pins: string[]): Promise<void> {
const { data } = await axios.post<{ status?: string; detail?: string }>(
`${base()}/qr`,
{ qr_token: token, files },
{ timeout: 30_000 },
{ headers: { Authorization: authorization }, timeout: 30_000 },
);
if (data?.status !== "ok")
throw new Error(
Expand All @@ -69,6 +77,8 @@ export async function printQr(token: string, pins: string[]): Promise<void> {
export function errorMessage(error: unknown): string {
if (axios.isAxiosError(error)) {
const status = error.response?.status;
if (status === 429) return "Слишком много запросов. Подождите минуту и попробуйте снова.";
if (status === 401) return "Откройте принтер заново в «Твой ФФ».";
if (status === 403) return "Проверьте фамилию и номер профсоюзного билета.";
if (status === 404)
return "Код не найден или срок хранения файла истёк. Загрузите файл заново.";
Expand Down
5 changes: 3 additions & 2 deletions src/components/SendTaskDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { profileSession, loadPrintProfile } from "@/api/profile";
import AppIcon from "./AppIcon.vue";
import { readStorage, writeStorage } from "@/utils/history";
import { validateFile, validatePages } from "@/utils/printing";
import { uploadFile, errorMessage } from "@/api/printer";
import { uploadFile, errorMessage, printAuthorization } from "@/api/printer";
import { log_print } from "@/utils/marketing";
const emit = defineEmits<{ uploaded: [pin: string, filename: string] }>();
const session = profileSession(window.location.search);
Expand Down Expand Up @@ -100,10 +100,11 @@ async function send() {
(percent) => {
progress.value = percent;
},
printAuthorization(),
);
emit("uploaded", pin, file.value.name);
} catch (cause) {
error.value = errorMessage(cause);
error.value = cause instanceof Error && !("isAxiosError" in cause) ? cause.message : errorMessage(cause);
log_print("FAIL");
} finally {
busy.value = false;
Expand Down
1 change: 1 addition & 0 deletions src/utils/marketing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ function analyticsUrl(value: string): string {
try {
const url = new URL(value);
url.searchParams.delete("token");
url.hash = "";
return url.toString();
} catch {
return "";
Expand Down
9 changes: 6 additions & 3 deletions src/views/QrPrint.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { useRoute, onBeforeRouteLeave, onBeforeRouteUpdate } from "vue-router";
import AppIcon from "@/components/AppIcon.vue";
import { isMobile } from "@/utils/mobile";
import { parsePins } from "@/utils/printing";
import { printQr, errorMessage } from "@/api/printer";
import { printQr, errorMessage, printAuthorization } from "@/api/printer";
import { log_open_qr, log_print_qr, log_error_qr } from "@/utils/marketing";
const QrcodeStream = defineAsyncComponent(async () => {
const [scanner, wasm] = await Promise.all([
Expand All @@ -26,7 +26,9 @@ const QrcodeStream = defineAsyncComponent(async () => {
});
const route = useRoute();
const mobile = isMobile();
const pins = computed(() => parsePins(route.hash));
// Telegram may append its launch parameters after the job in the fragment.
const jobLink = computed(() => route.hash.split(/[?&]/, 1)[0].split("~"));
const pins = computed(() => parsePins(jobLink.value[0]));
const state = ref<"idle" | "camera" | "pending" | "success" | "error">("idle");
onBeforeRouteLeave(() => state.value !== "pending");
onBeforeRouteUpdate(() => state.value !== "pending");
Expand Down Expand Up @@ -84,7 +86,8 @@ async function detect(codes: { rawValue: string }[]) {
const files = [...pins.value];
state.value = "pending"; // Set synchronously before the request; repeated frames cannot print twice.
try {
await printQr(token, files);
const grant = jobLink.value[1];
await printQr(token, files, grant ? `PrintJob ${grant}` : printAuthorization());
if (!active.value) return;
state.value = "success";
log_print_qr(files);
Expand Down
9 changes: 6 additions & 3 deletions tests/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { uploadFile, printQr, errorMessage } from "../src/api/printer.ts";
test("upload reserves PIN then sends multipart PDF with progress; QR sends unique file pins", async () => {
const calls: { url: string; data: unknown }[] = [];
axios.defaults.adapter = async (config) => {
assert.equal(config.headers.Authorization, "test-session");
calls.push({ url: config.url || "", data: config.data });
return {
data: config.url?.endsWith("/qr") ? { status: "ok" } : { pin: "AB12" },
Expand All @@ -27,6 +28,7 @@ test("upload reserves PIN then sends multipart PDF with progress; QR sends uniqu
twoSided: false,
},
() => {},
"test-session",
),
"AB12",
);
Expand All @@ -40,7 +42,7 @@ test("upload reserves PIN then sends multipart PDF with progress; QR sends uniqu
});
assert.match(calls[1].url, /\/file\/AB12$/);
assert.equal((calls[1].data as FormData).get("file"), file);
await printQr("token", ["AB12", "AB12"]);
await printQr("token", ["AB12", "AB12"], "test-session");
assert.deepEqual(JSON.parse(calls[2].data as string), {
qr_token: "token",
files: ["AB12"],
Expand Down Expand Up @@ -75,6 +77,7 @@ test("failed reservation does not upload and failed QR is not treated as success
twoSided: false,
},
() => {},
"test-session",
),
);
assert.equal(calls, 1);
Expand All @@ -85,9 +88,9 @@ test("failed reservation does not upload and failed QR is not treated as success
headers: {},
config,
});
await assert.rejects(printQr("bad", ["AB12"]), /QR/);
await assert.rejects(printQr("bad", ["AB12"], "test-session"), /QR/);
calls = 0;
await assert.rejects(printQr("token", []));
await assert.rejects(printQr("token", [], "test-session"));
});
test("network and server validation errors have actionable messages", () => {
assert.match(errorMessage(new Error("network")), /соединени/);
Expand Down
19 changes: 11 additions & 8 deletions tests/browser/printing.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ test("upload, PIN, old history and embedded context survive navigation", async (
});
await page.route("**/print/file/AB12CD", async (route) => {
uploads++;
expect(route.request().headers().authorization).toBe("test-session");
await route.fulfill({ json: { pin: "AB12CD" } });
});
await page.goto("/?embeded=true&user_id=42&scopes=example");
await page.goto("/?token=test-session&embeded=true&user_id=42&scopes=example");
await expect(page.getByRole("banner")).toHaveCount(0);
await page.getByLabel("Фамилия", { exact: true }).fill("Иванов");
await page
Expand Down Expand Up @@ -56,7 +57,7 @@ for (const twoSided of [true, false]) {
await page.route("**/print/file/AB12CD", (route) =>
route.fulfill({ json: { pin: "AB12CD" } }),
);
await page.goto("/");
await page.goto("/?token=test-session");
await page.getByLabel("Фамилия", { exact: true }).fill("Иванов");
await page
.getByLabel("Номер профсоюзного билета", { exact: true })
Expand Down Expand Up @@ -97,7 +98,7 @@ test("upload failure preserves input and corrupt history remains usable", async
await page.route("**/print/file", (route) =>
route.fulfill({ status: 403, json: { detail: "User error" } }),
);
await page.goto("/");
await page.goto("/?token=test-session");
await page.getByLabel("Фамилия", { exact: true }).fill("Иванов");
await page
.getByLabel("Номер профсоюзного билета", { exact: true })
Expand Down Expand Up @@ -150,7 +151,7 @@ test("camera is opt in and desktop QR stays gated", async ({
expect(cameraCalls).toBe(0);
});

test("profile fills automatically and sends token only to userdata", async ({
test("profile fills automatically and uses the delegated session for userdata", async ({
page,
}) => {
await page.route("**/userdata/user/42", async (route) => {
Expand Down Expand Up @@ -254,20 +255,22 @@ test("one mobile QR scan queues one job and closes the camera", async ({
}, qrImage);
await page.route("**/print/qr", async (route) => {
jobs++;
expect(route.request().headers().authorization).toBe("PrintJob test-grant");
expect(route.request().postDataJSON()).toEqual({
qr_token: "terminal-token",
files: ["AB12CD"],
});
await gate;
await route.fulfill({ json: { status: "ok" } });
});
await page.goto("/qr#AB12CD");
const jobUrl = "/qr#AB12CD~test-grant?tgWebAppVersion=8.0&tgWebAppPlatform=android";
await page.goto(jobUrl);
const request = page.waitForRequest("**/print/qr");
await page.getByRole("button", { name: "Включить камеру" }).click();
await request;
await page.getByRole("link", { name: "История", exact: true }).click();
try {
await expect(page).toHaveURL("http://127.0.0.1:9004/qr#AB12CD");
await expect(page).toHaveURL(jobUrl);
} finally {
release();
}
Expand Down Expand Up @@ -371,7 +374,7 @@ test("navigation cannot discard an in-flight upload or start a second submission
await gate;
await route.fulfill({ json: { pin: "AB12CD" } });
});
await page.goto("/");
await page.goto("/?token=test-session");
await page.getByLabel("Фамилия", { exact: true }).fill("Иванов");
await page
.getByLabel("Номер профсоюзного билета", { exact: true })
Expand All @@ -395,7 +398,7 @@ test("navigation cannot discard an in-flight upload or start a second submission
);
await page.getByRole("link", { name: "История", exact: true }).click();
try {
await expect(page).toHaveURL("http://127.0.0.1:9004/");
await expect(page).toHaveURL("/?token=test-session");
} finally {
release();
}
Expand Down