Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 10d5cf54a5 | |||
| 376311cb90 | |||
| 88fa3c5297 | |||
| 980378a17b | |||
| 0a999795cc |
@@ -30,6 +30,29 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
# The .picpeak restore suites gate their real-Postgres cases behind
|
||||
# PICPEAK_PG_TEST_URL and `describe.skip` themselves out when it is
|
||||
# unset — so until now they never ran here. That hid the half that
|
||||
# matters: sequence resync, operator/role preservation across a
|
||||
# cross-instance restore, and (with #1041) whether a SQLite-shaped
|
||||
# row actually lands in Postgres with the right STORED VALUES rather
|
||||
# than merely not throwing. Everything else in the suite still runs
|
||||
# on SQLite; this service only un-gates those cases.
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
env:
|
||||
POSTGRES_USER: picpeak
|
||||
POSTGRES_PASSWORD: testpass
|
||||
POSTGRES_DB: picpeak_test
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U picpeak -d picpeak_test"
|
||||
--health-interval 2s
|
||||
--health-timeout 2s
|
||||
--health-retries 30
|
||||
ports:
|
||||
- 5432:5432
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
@@ -52,6 +75,9 @@ jobs:
|
||||
# The S3 path itself is covered separately by the integration
|
||||
# suite when MinIO is provisioned.
|
||||
SKIP_S3_TESTS: 'true'
|
||||
# Un-gates the real-Postgres cases in the .picpeak restore suites
|
||||
# (see the `services:` note above). Absent it they silently skip.
|
||||
PICPEAK_PG_TEST_URL: 'postgres://picpeak:testpass@127.0.0.1:5432/picpeak_test'
|
||||
run: |
|
||||
# Excluded suites — fail on upstream/beta too, tracked
|
||||
# separately as test-infra debt:
|
||||
|
||||
@@ -1 +1 @@
|
||||
{".":"3.45.16"}
|
||||
{".":"3.46.0"}
|
||||
|
||||
@@ -5,6 +5,19 @@ All notable changes to PicPeak will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [3.46.0](https://github.com/PicPeak/picpeak/compare/v3.45.16...v3.46.0) (2026-08-16)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **backup:** open sqlite → pg .picpeak restore as the supported upgrade direction ([#1041](https://github.com/PicPeak/picpeak/issues/1041)) ([#1059](https://github.com/PicPeak/picpeak/issues/1059)) ([980378a](https://github.com/PicPeak/picpeak/commit/980378a17ba873d0e2f3d76048dacb3b8d7a4eb2))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **pdf:** RFC 6266-encode Content-Disposition on quote/invoice PDFs ([#1024](https://github.com/PicPeak/picpeak/issues/1024)) ([#1062](https://github.com/PicPeak/picpeak/issues/1062)) ([376311c](https://github.com/PicPeak/picpeak/commit/376311cb9091ff1726e8b383312f22c607dcc8a0))
|
||||
* **storage:** add S3 client timeouts so a dropped connection can't wedge uploads ([#1049](https://github.com/PicPeak/picpeak/issues/1049)) ([#1054](https://github.com/PicPeak/picpeak/issues/1054)) ([88fa3c5](https://github.com/PicPeak/picpeak/commit/88fa3c52973fa122f8d4e7b21ba1ffc89f9f9c2e))
|
||||
|
||||
## [3.45.16](https://github.com/PicPeak/picpeak/compare/v3.45.15...v3.45.16) (2026-08-13)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Cross-engine .picpeak restore policy (#1041): a SQLite archive restored onto
|
||||
* a PostgreSQL instance — the official small-install → full-stack upgrade
|
||||
* path — now allowed by validateManifest's direction rule instead of the
|
||||
* former CLI-only allowEngineSwitch flag. The coercion engine itself
|
||||
* (typedColumnsFor / epochToIso / coerceForTargetEngine) landed with #1039;
|
||||
* these tests pin the direction policy and the coercion's cross-engine
|
||||
* value-correctness.
|
||||
*
|
||||
* Ungated: validateManifest direction rules and the pure coercion units.
|
||||
* The reverse direction (pg backup onto a sqlite instance) staying blocked is
|
||||
* pinned by picpeakRoundtrip.test.js, which runs on the real sqlite harness.
|
||||
*
|
||||
* Gated on PICPEAK_PG_TEST_URL (same contract as picpeakRestorePg.test.js):
|
||||
* sqlite-shaped NDJSON rows land in real Postgres with correct stored VALUES,
|
||||
* not just row counts, e.g.
|
||||
* PICPEAK_PG_TEST_URL="postgres://picpeak:pw@127.0.0.1:7102/picpeak_xengine_test" \
|
||||
* npx jest __tests__/integration/picpeakCrossEngine.test.js
|
||||
*/
|
||||
const knexLib = require('knex');
|
||||
|
||||
describe('validateManifest cross-engine direction (pg target)', () => {
|
||||
let validateManifest;
|
||||
|
||||
beforeAll(() => {
|
||||
jest.resetModules();
|
||||
jest.doMock('../../knexfile', () => ({ client: 'pg' }));
|
||||
// validateManifest wraps its knex_migrations lookup in try/catch — a
|
||||
// throwing stub simply skips the forward-only check, which is not under
|
||||
// test here.
|
||||
jest.doMock('../../src/database/db', () => ({ db: () => { throw new Error('stub'); } }));
|
||||
({ validateManifest } = require('../../src/services/picpeakImportService'));
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
jest.dontMock('../../src/database/db');
|
||||
jest.dontMock('../../knexfile');
|
||||
jest.resetModules();
|
||||
});
|
||||
|
||||
it('allows a sqlite backup onto a pg instance (upgrade direction)', async () => {
|
||||
const blockers = await validateManifest({
|
||||
kind: 'picpeak-backup', format: 1, database: { engine: 'sqlite' }, tables: {},
|
||||
});
|
||||
expect(blockers.filter((b) => /engine/i.test(b))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('still allows same-engine pg → pg', async () => {
|
||||
const blockers = await validateManifest({
|
||||
kind: 'picpeak-backup', format: 1, database: { engine: 'pg' }, tables: {},
|
||||
});
|
||||
expect(blockers.filter((b) => /engine/i.test(b))).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('epochToIso (landed with #1039)', () => {
|
||||
let epochToIso;
|
||||
|
||||
beforeAll(() => {
|
||||
jest.resetModules();
|
||||
({ epochToIso } = require('../../src/services/picpeakImportService'));
|
||||
});
|
||||
|
||||
it('converts epoch milliseconds', () => {
|
||||
expect(epochToIso(1723400000000)).toBe('2024-08-11T18:13:20.000Z');
|
||||
});
|
||||
|
||||
it('converts epoch SECONDS to the same instant, not January 1970', () => {
|
||||
expect(epochToIso(1723400000)).toBe('2024-08-11T18:13:20.000Z');
|
||||
});
|
||||
|
||||
it('converts numeric strings', () => {
|
||||
expect(epochToIso('1723400000000')).toBe('2024-08-11T18:13:20.000Z');
|
||||
});
|
||||
|
||||
it('passes non-numeric values through untouched', () => {
|
||||
expect(epochToIso('2026-08-12 10:00:00')).toBe('2026-08-12 10:00:00');
|
||||
});
|
||||
});
|
||||
|
||||
describe('coerceForTargetEngine on sqlite-shaped rows', () => {
|
||||
let coerceForTargetEngine;
|
||||
|
||||
beforeAll(() => {
|
||||
jest.resetModules();
|
||||
({ coerceForTargetEngine } = require('../../src/services/picpeakImportService'));
|
||||
});
|
||||
|
||||
const types = { timestamps: ['created_at', 'expires_at'], booleans: ['is_active'] };
|
||||
|
||||
it('coerces 0/1 booleans and epoch timestamps, leaves date strings alone', () => {
|
||||
const [row] = coerceForTargetEngine(
|
||||
[{ id: 1, is_active: 1, created_at: 1723400000000, expires_at: '2026-09-01 12:00:00' }],
|
||||
types
|
||||
);
|
||||
expect(row.is_active).toBe(true);
|
||||
expect(row.created_at).toBe('2024-08-11T18:13:20.000Z');
|
||||
expect(row.expires_at).toBe('2026-09-01 12:00:00'); // pg parses this natively
|
||||
});
|
||||
|
||||
it('coerces falsy variants and passes null/empty through', () => {
|
||||
const [row] = coerceForTargetEngine(
|
||||
[{ is_active: 0, created_at: null, expires_at: '' }],
|
||||
types
|
||||
);
|
||||
expect(row.is_active).toBe(false);
|
||||
expect(row.created_at).toBeNull();
|
||||
expect(row.expires_at).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
// ── Real-Postgres integration (gated) ────────────────────────────────────────
|
||||
const PG_URL = process.env.PICPEAK_PG_TEST_URL;
|
||||
const maybe = PG_URL ? describe : describe.skip;
|
||||
|
||||
maybe('sqlite-shaped rows land correctly in real Postgres', () => {
|
||||
let pgDb;
|
||||
let svc;
|
||||
|
||||
beforeAll(async () => {
|
||||
pgDb = knexLib({ client: 'pg', connection: PG_URL });
|
||||
await pgDb.raw('DROP TABLE IF EXISTS xengine_events, xengine_settings CASCADE');
|
||||
await pgDb.schema.createTable('xengine_events', (t) => {
|
||||
t.increments('id');
|
||||
t.string('slug');
|
||||
t.boolean('is_active').defaultTo(true);
|
||||
t.boolean('allow_downloads').defaultTo(true);
|
||||
t.timestamp('created_at');
|
||||
t.timestamp('expires_at');
|
||||
});
|
||||
await pgDb.schema.createTable('xengine_settings', (t) => {
|
||||
t.increments('id');
|
||||
t.string('setting_key').notNullable().unique();
|
||||
t.jsonb('setting_value');
|
||||
});
|
||||
|
||||
jest.resetModules();
|
||||
jest.doMock('../../knexfile', () => ({ client: 'pg' }));
|
||||
jest.doMock('../../src/database/db', () => ({ db: pgDb }));
|
||||
svc = require('../../src/services/picpeakImportService');
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
jest.dontMock('../../src/database/db');
|
||||
jest.dontMock('../../knexfile');
|
||||
if (pgDb) {
|
||||
await pgDb.raw('DROP TABLE IF EXISTS xengine_events, xengine_settings CASCADE');
|
||||
await pgDb.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it('typedColumnsFor classifies boolean and timestamp columns via columnInfo()', async () => {
|
||||
const types = await svc.typedColumnsFor(pgDb, 'xengine_events');
|
||||
expect(types.booleans.sort()).toEqual(['allow_downloads', 'is_active']);
|
||||
expect(types.timestamps.sort()).toEqual(['created_at', 'expires_at']);
|
||||
});
|
||||
|
||||
it('inserts a sqlite archive row (0/1 booleans, epoch dates, json text) with correct stored values', async () => {
|
||||
// Exactly what a sqlite-created .picpeak carries: integers for booleans,
|
||||
// epoch numbers for #485-shape timestamps (ms here, seconds covered by the
|
||||
// epochToIso unit), a "YYYY-MM-DD HH:MM:SS" string for clean ones, and
|
||||
// json columns as TEXT (the crossEngine path skips serialiseJsonColumns —
|
||||
// the text is already what pg wants).
|
||||
const epoch = 1723400000000;
|
||||
const eventRows = [
|
||||
{ id: 1, slug: 'wedding', is_active: 1, allow_downloads: 0, created_at: epoch, expires_at: '2026-09-01 12:00:00' },
|
||||
];
|
||||
const settingRows = [{ id: 1, setting_key: 'brand', setting_value: '{"name":"PicPeak","dark":true}' }];
|
||||
|
||||
await pgDb.transaction(async (trx) => {
|
||||
const evTypes = await svc.typedColumnsFor(trx, 'xengine_events');
|
||||
await trx.batchInsert('xengine_events', svc.coerceForTargetEngine(eventRows, evTypes), 100);
|
||||
const stTypes = await svc.typedColumnsFor(trx, 'xengine_settings');
|
||||
await trx.batchInsert('xengine_settings', svc.coerceForTargetEngine(settingRows, stTypes), 100);
|
||||
});
|
||||
|
||||
const ev = await pgDb('xengine_events').where({ id: 1 }).first();
|
||||
expect(ev.is_active).toBe(true); // 1 → true, not backwards (#1028 class)
|
||||
expect(ev.allow_downloads).toBe(false); // 0 → false
|
||||
expect(new Date(ev.created_at).getTime()).toBe(epoch);
|
||||
expect(new Date(ev.expires_at).toISOString().slice(0, 10)).toBe('2026-09-01');
|
||||
|
||||
const st = await pgDb('xengine_settings').where({ id: 1 }).first();
|
||||
// jsonb parsed back by the driver — value intact, no double encoding.
|
||||
expect(st.setting_value).toEqual({ name: 'PicPeak', dark: true });
|
||||
});
|
||||
|
||||
it('id sequence works after explicit-id insert + resync (next natural insert)', async () => {
|
||||
await svc.resyncSequences(['xengine_events']);
|
||||
const [next] = await pgDb('xengine_events')
|
||||
.insert({ slug: 'fresh', is_active: true })
|
||||
.returning('id');
|
||||
expect(Number(next.id || next)).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Regression test for #1024: quote/invoice PDF endpoints 500'd (or silently
|
||||
* corrupted the filename) for customers whose name carries non-ASCII.
|
||||
*
|
||||
* The six PDF routes built the header by interpolating buildPdfFilename()'s
|
||||
* result straight into `inline; filename="${filename}"`. HTTP header values
|
||||
* are latin1, which splits the failure in two — and the split matters,
|
||||
* because the issue reported the umlaut case as the 500 and it isn't:
|
||||
*
|
||||
* U+0080-U+00FF (ä ö ü ß — every German umlaut)
|
||||
* No throw. The byte goes out raw and the client reads back a mangled
|
||||
* name. A silent corruption, not an error.
|
||||
*
|
||||
* above U+00FF (Polish ł, Czech ř, Turkish ş, €, Cyrillic, CJK, emoji)
|
||||
* Node's setHeader rejects it with ERR_INVALID_CHAR. Because the
|
||||
* throw lands after the PDF buffer is already rendered, the whole
|
||||
* request fails as an unhandled 500.
|
||||
*
|
||||
* buildContentDisposition() fixes both: an ASCII fallback for the legacy
|
||||
* `filename=` parameter plus the RFC 5987 `filename*=UTF-8''…` form that
|
||||
* carries the real name.
|
||||
*
|
||||
* These assertions run against the real Node header validator via a live
|
||||
* express server, so they'd fail against the old interpolation rather than
|
||||
* merely testing the helper in isolation.
|
||||
*/
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
|
||||
const { buildPdfFilename, sanitiseSegment } = require('../../src/utils/pdfFilename');
|
||||
const { buildContentDisposition } = require('../../src/utils/filenameSanitizer');
|
||||
|
||||
// The RFC 5987 parameter prefix, i.e. filename*=UTF-8'' — the two trailing
|
||||
// quotes are the (empty) language tag the spec puts between the charset and
|
||||
// the percent-encoded value.
|
||||
const RFC5987_PREFIX = 'filename*=UTF-8\'\'';
|
||||
|
||||
// Mirrors what the six PDF routes now do.
|
||||
function buildApp(customer, docNumber = 'Q-2026-0042') {
|
||||
const app = express();
|
||||
app.get('/pdf', (req, res) => {
|
||||
const filename = buildPdfFilename({ docNumber, customer, fallback: 'quote-preview' });
|
||||
res.set('Content-Type', 'application/pdf');
|
||||
res.set('Content-Disposition', buildContentDisposition(filename, 'inline'));
|
||||
res.send(Buffer.from('%PDF-1.4 fake'));
|
||||
});
|
||||
// Mirrors the real error handler: an ERR_INVALID_CHAR throw inside the
|
||||
// handler surfaces as a 500, which is what #1024 reported.
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
app.use((err, req, res, next) => res.status(500).json({ error: err.code || err.message }));
|
||||
return app;
|
||||
}
|
||||
|
||||
describe('#1024 — PDF Content-Disposition with non-ASCII customer names', () => {
|
||||
it('serves a PDF for a German umlaut name and keeps the name intact', async () => {
|
||||
const res = await request(buildApp({ company_name: 'Müller Fotografie' })).get('/pdf');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const cd = res.headers['content-disposition'];
|
||||
// RFC 5987 form carries the real, unmangled name...
|
||||
expect(cd).toContain(RFC5987_PREFIX);
|
||||
expect(cd).toContain(encodeURIComponent('Müller-Fotografie.pdf'));
|
||||
// ...and the ASCII fallback is legal latin1 with no raw umlaut byte.
|
||||
const fallback = /filename="([^"]+)"/.exec(cd)[1];
|
||||
expect(fallback).toMatch(/^[\x20-\x7e]+$/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['Polish', 'Michał Kowalski'],
|
||||
['Czech', 'Dvořák Studio'],
|
||||
['Turkish', 'Şahin Fotoğraf'],
|
||||
['Cyrillic', 'Иванов Фото'],
|
||||
['CJK', '山田写真'],
|
||||
['emoji', 'Studio 🎉 Berlin'],
|
||||
])('does not 500 for a %s customer name (was ERR_INVALID_CHAR)', async (_label, company) => {
|
||||
const res = await request(buildApp({ company_name: company })).get('/pdf');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const cd = res.headers['content-disposition'];
|
||||
expect(cd).toContain(RFC5987_PREFIX);
|
||||
// The legacy filename= token drops non-ASCII, so a name written entirely
|
||||
// in another script degrades to just the document number
|
||||
// (`Q-2026-0042_.pdf`). That's the intended trade — filename* carries the
|
||||
// real name — but the fallback must still be a legal, non-empty,
|
||||
// ASCII-only token, since that is what a client without RFC 5987 support
|
||||
// ends up saving.
|
||||
const fallback = /filename="([^"]*)"/.exec(cd)[1];
|
||||
expect(fallback.length).toBeGreaterThan(0);
|
||||
expect(fallback).toMatch(/^[\x20-\x7e]+$/);
|
||||
expect(fallback).toContain('Q-2026-0042');
|
||||
});
|
||||
|
||||
it('leaves a plain ASCII name on the familiar filename= form', async () => {
|
||||
const res = await request(buildApp({ company_name: 'Bright Studio' })).get('/pdf');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-disposition'])
|
||||
.toContain('filename="Q-2026-0042_Bright-Studio.pdf"');
|
||||
});
|
||||
|
||||
it('still works when the customer row is missing entirely (preview path)', async () => {
|
||||
const res = await request(buildApp(null, null)).get('/pdf');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-disposition']).toContain('quote-preview_customer.pdf');
|
||||
});
|
||||
|
||||
// sanitiseSegment caps each segment at 80 UTF-16 code units. A cap landing
|
||||
// inside an astral character used to leave a dangling high surrogate, which
|
||||
// makes encodeURIComponent throw URIError inside buildContentDisposition —
|
||||
// a 500 on the very endpoint this PR fixes, reached a different way.
|
||||
it.each([
|
||||
['emoji on the 80-char boundary', `${'a'.repeat(79)}🎉`],
|
||||
['astral CJK on the boundary', `${'a'.repeat(79)}𠜎`],
|
||||
['a label that is entirely astral', '🎉'.repeat(60)],
|
||||
])('does not 500 when truncation splits a surrogate pair — %s', async (_label, company) => {
|
||||
const res = await request(buildApp({ company_name: company })).get('/pdf');
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-disposition']).toContain(RFC5987_PREFIX);
|
||||
});
|
||||
|
||||
it('drops the orphaned surrogate rather than widening the length cap', () => {
|
||||
const seg = sanitiseSegment(`${'a'.repeat(79)}🎉`);
|
||||
|
||||
// 79 'a's + a half-emoji would be 80; the orphan is dropped, not kept.
|
||||
expect(seg).toHaveLength(79);
|
||||
expect(seg).toBe('a'.repeat(79));
|
||||
// Nothing in the result may be an unpaired surrogate.
|
||||
expect(seg).toBe(seg.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/g, ''));
|
||||
});
|
||||
|
||||
it('the raw interpolation these routes used to do really does throw', () => {
|
||||
// Pins the root cause itself, so nobody "simplifies" the helper away.
|
||||
const filename = buildPdfFilename({
|
||||
docNumber: 'Q-2026-0042',
|
||||
customer: { company_name: 'Michał Kowalski' },
|
||||
});
|
||||
const res = new (require('http').ServerResponse)({});
|
||||
expect(() => res.setHeader('Content-Disposition', `inline; filename="${filename}"`))
|
||||
.toThrow(/ERR_INVALID_CHAR|Invalid character/);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "picpeak-backend",
|
||||
"version": "3.45.16",
|
||||
"version": "3.46.0",
|
||||
"description": "Backend for PicPeak event photo sharing platform",
|
||||
"main": "server.js",
|
||||
"engines": {
|
||||
|
||||
@@ -201,9 +201,9 @@ async function phaseImport(archivePath) {
|
||||
const { importFromPicpeak } = require('../src/services/picpeakImportService');
|
||||
// No currentAdminId: this is a CLI, there is no operator session to preserve.
|
||||
// The SQLite install's own admin accounts come across with everything else.
|
||||
// allowEngineSwitch: moving between engines is the whole point here. The
|
||||
// upload/restore UI keeps refusing it.
|
||||
const summary = await importFromPicpeak({ picpeakPath: archivePath, allowEngineSwitch: true });
|
||||
// sqlite → pg is allowed by validateManifest's direction policy (#1041) —
|
||||
// the same gate the upload/restore UI uses, no separate opt-in flag.
|
||||
const summary = await importFromPicpeak({ picpeakPath: archivePath });
|
||||
return JSON.stringify(summary || {});
|
||||
}
|
||||
|
||||
|
||||
@@ -240,6 +240,7 @@ router.post('/picpeak/import', adminAuth, requirePermission('backup.restore'), p
|
||||
tables: result.tables,
|
||||
filesRestored: result.filesRestored,
|
||||
usesExternalMedia: result.usesExternalMedia,
|
||||
crossEngine: result.crossEngine,
|
||||
sessionInvalidated: true,
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
@@ -894,6 +894,7 @@ router.get(
|
||||
// re-fetching here keeps the route a thin shim over the
|
||||
// service rather than reaching inside its internals.
|
||||
const { buildPdfFilename } = require('../utils/pdfFilename');
|
||||
const { buildContentDisposition } = require('../utils/filenameSanitizer');
|
||||
const inv = await db('invoices').where({ id }).first();
|
||||
const customer = inv ? await db('customer_accounts').where({ id: inv.customer_account_id }).first() : null;
|
||||
const filename = buildPdfFilename({
|
||||
@@ -902,7 +903,7 @@ router.get(
|
||||
fallback: `invoice-${id}`,
|
||||
});
|
||||
res.set('Content-Type', 'application/pdf');
|
||||
res.set('Content-Disposition', `inline; filename="${filename}"`);
|
||||
res.set('Content-Disposition', buildContentDisposition(filename, 'inline'));
|
||||
res.send(buf);
|
||||
})
|
||||
);
|
||||
@@ -919,6 +920,7 @@ router.post(
|
||||
// the customer so the filename still reflects who the invoice
|
||||
// is for; the number segment falls back to "invoice-preview".
|
||||
const { buildPdfFilename } = require('../utils/pdfFilename');
|
||||
const { buildContentDisposition } = require('../utils/filenameSanitizer');
|
||||
const customer = payload.customerAccountId
|
||||
? await db('customer_accounts').where({ id: payload.customerAccountId }).first()
|
||||
: null;
|
||||
@@ -928,7 +930,7 @@ router.post(
|
||||
fallback: 'invoice-preview',
|
||||
});
|
||||
res.set('Content-Type', 'application/pdf');
|
||||
res.set('Content-Disposition', `inline; filename="${filename}"`);
|
||||
res.set('Content-Disposition', buildContentDisposition(filename, 'inline'));
|
||||
res.send(buf);
|
||||
})
|
||||
);
|
||||
|
||||
@@ -537,6 +537,7 @@ router.get(
|
||||
const id = parseInt(req.params.id, 10);
|
||||
const buf = await quoteService.renderQuotePdfBuffer(id);
|
||||
const { buildPdfFilename } = require('../utils/pdfFilename');
|
||||
const { buildContentDisposition } = require('../utils/filenameSanitizer');
|
||||
const quote = await db('quotes').where({ id }).first();
|
||||
const customer = quote ? await db('customer_accounts').where({ id: quote.customer_account_id }).first() : null;
|
||||
const filename = buildPdfFilename({
|
||||
@@ -545,7 +546,7 @@ router.get(
|
||||
fallback: `quote-${id}`,
|
||||
});
|
||||
res.set('Content-Type', 'application/pdf');
|
||||
res.set('Content-Disposition', `inline; filename="${filename}"`);
|
||||
res.set('Content-Disposition', buildContentDisposition(filename, 'inline'));
|
||||
res.send(buf);
|
||||
})
|
||||
);
|
||||
@@ -559,6 +560,7 @@ router.post(
|
||||
const payload = mapPayloadToService(req.body);
|
||||
const buf = await quoteService.renderQuotePdfFromPayload(payload);
|
||||
const { buildPdfFilename } = require('../utils/pdfFilename');
|
||||
const { buildContentDisposition } = require('../utils/filenameSanitizer');
|
||||
const customer = payload.customerAccountId
|
||||
? await db('customer_accounts').where({ id: payload.customerAccountId }).first()
|
||||
: null;
|
||||
@@ -568,7 +570,7 @@ router.post(
|
||||
fallback: 'quote-preview',
|
||||
});
|
||||
res.set('Content-Type', 'application/pdf');
|
||||
res.set('Content-Disposition', `inline; filename="${filename}"`);
|
||||
res.set('Content-Disposition', buildContentDisposition(filename, 'inline'));
|
||||
res.send(buf);
|
||||
})
|
||||
);
|
||||
|
||||
@@ -566,6 +566,7 @@ router.get('/quotes/:id/pdf', customerAuth, async (req, res) => {
|
||||
const quoteService = require('../services/quoteService');
|
||||
const buf = await quoteService.renderQuotePdfBuffer(quote.id);
|
||||
const { buildPdfFilename } = require('../utils/pdfFilename');
|
||||
const { buildContentDisposition } = require('../utils/filenameSanitizer');
|
||||
const customer = await dbi('customer_accounts').where({ id: req.customer.id }).first();
|
||||
const filename = buildPdfFilename({
|
||||
docNumber: quote.quote_number,
|
||||
@@ -573,7 +574,7 @@ router.get('/quotes/:id/pdf', customerAuth, async (req, res) => {
|
||||
fallback: `quote-${quote.id}`,
|
||||
});
|
||||
res.set('Content-Type', 'application/pdf');
|
||||
res.set('Content-Disposition', `inline; filename="${filename}"`);
|
||||
res.set('Content-Disposition', buildContentDisposition(filename, 'inline'));
|
||||
res.send(buf);
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to render quote PDF');
|
||||
@@ -597,6 +598,7 @@ router.get('/invoices/:id/pdf', customerAuth, async (req, res) => {
|
||||
const invoiceService = require('../services/invoiceService');
|
||||
const buf = await invoiceService.renderInvoicePdfBuffer(invoice.id);
|
||||
const { buildPdfFilename } = require('../utils/pdfFilename');
|
||||
const { buildContentDisposition } = require('../utils/filenameSanitizer');
|
||||
const customer = await dbi('customer_accounts').where({ id: req.customer.id }).first();
|
||||
const filename = buildPdfFilename({
|
||||
docNumber: invoice.invoice_number,
|
||||
@@ -604,7 +606,7 @@ router.get('/invoices/:id/pdf', customerAuth, async (req, res) => {
|
||||
fallback: `invoice-${invoice.id}`,
|
||||
});
|
||||
res.set('Content-Type', 'application/pdf');
|
||||
res.set('Content-Disposition', `inline; filename="${filename}"`);
|
||||
res.set('Content-Disposition', buildContentDisposition(filename, 'inline'));
|
||||
res.send(buf);
|
||||
} catch (error) {
|
||||
errorResponse(res, error, 500, 'Failed to render invoice PDF');
|
||||
|
||||
@@ -9,9 +9,10 @@
|
||||
// email collides with the current account is overwritten with the current
|
||||
// account's credentials (so the operator's known password keeps working).
|
||||
//
|
||||
// Same-engine only (pg↔pg / sqlite↔sqlite) and forward-only (an older backup
|
||||
// restores onto a newer instance; a newer backup is refused). The target's own
|
||||
// schema is used as-is — we never replay the backup's DDL.
|
||||
// Same-engine (pg↔pg / sqlite↔sqlite) or the upgrade direction (sqlite → pg,
|
||||
// #1041) — the reverse is refused. Forward-only (an older backup restores onto
|
||||
// a newer instance; a newer backup is refused). The target's own schema is
|
||||
// used as-is — we never replay the backup's DDL.
|
||||
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs').promises;
|
||||
@@ -44,7 +45,7 @@ async function readManifestFromZip(picpeakPath) {
|
||||
}
|
||||
|
||||
// Returns an array of human-readable blockers ([] = OK to restore).
|
||||
async function validateManifest(manifest, { allowEngineSwitch = false } = {}) {
|
||||
async function validateManifest(manifest) {
|
||||
const errors = [];
|
||||
if (!manifest || manifest.kind !== 'picpeak-backup') {
|
||||
return ['This file is not a PicPeak backup (.picpeak).'];
|
||||
@@ -53,14 +54,16 @@ async function validateManifest(manifest, { allowEngineSwitch = false } = {}) {
|
||||
errors.push('This backup was created by a newer version of PicPeak. Update this instance first.');
|
||||
}
|
||||
const engine = isPostgres() ? 'pg' : 'sqlite';
|
||||
// Cross-engine loads are opt-in and CLI-only (#1038). The archive format is
|
||||
// engine-neutral NDJSON, but this path had never been exercised, so the
|
||||
// upload/restore surface keeps refusing it — only
|
||||
// scripts/migrate-sqlite-to-postgres.js, which exists to move an install
|
||||
// between engines, passes allowEngineSwitch.
|
||||
if (!allowEngineSwitch
|
||||
&& manifest.database && manifest.database.engine && manifest.database.engine !== engine) {
|
||||
errors.push(`Database engine mismatch: the backup is "${manifest.database.engine}" but this instance is "${engine}". Restore is only supported between matching engines.`);
|
||||
const backupEngine = manifest.database && manifest.database.engine;
|
||||
// Cross-engine restore is allowed in the UPGRADE direction only: a SQLite
|
||||
// archive onto a Postgres instance (#1041) — the official small-install →
|
||||
// full-stack migration path, same gate for the upload UI and
|
||||
// scripts/migrate-sqlite-to-postgres.js. The reverse stays refused: pg
|
||||
// archives carry ISO "T"/"Z" timestamps that SQLite would store as-is in
|
||||
// text columns (the #1028/#1029 drift class), and engine downgrades are
|
||||
// rarely intentional.
|
||||
if (backupEngine && backupEngine !== engine && !(backupEngine === 'sqlite' && engine === 'pg')) {
|
||||
errors.push(`Database engine mismatch: the backup is "${backupEngine}" but this instance is "${engine}". Cross-engine restore is only supported from a SQLite backup onto a PostgreSQL instance.`);
|
||||
}
|
||||
// Forward-only: the target schema must be at least as new as the backup's.
|
||||
let targetLatest = null;
|
||||
@@ -361,11 +364,11 @@ async function detectExternalMedia() {
|
||||
* @param {Object} opts
|
||||
* @param {string} opts.picpeakPath path to the uploaded/staged .picpeak
|
||||
* @param {number} [opts.currentAdminId] admin to preserve across the wipe
|
||||
* @returns {Promise<{restored:boolean, tables:number, filesRestored:number, usesExternalMedia:boolean, manifest:object}>}
|
||||
* @returns {Promise<{restored:boolean, tables:number, filesRestored:number, usesExternalMedia:boolean, crossEngine:boolean, manifest:object}>}
|
||||
*/
|
||||
async function importFromPicpeak({ picpeakPath, currentAdminId, allowEngineSwitch = false }) {
|
||||
async function importFromPicpeak({ picpeakPath, currentAdminId }) {
|
||||
const manifest = await readManifestFromZip(picpeakPath);
|
||||
const blockers = await validateManifest(manifest, { allowEngineSwitch });
|
||||
const blockers = await validateManifest(manifest);
|
||||
if (blockers.length) {
|
||||
const err = new Error(blockers[0]);
|
||||
err.statusCode = 400;
|
||||
@@ -373,6 +376,16 @@ async function importFromPicpeak({ picpeakPath, currentAdminId, allowEngineSwitc
|
||||
throw err;
|
||||
}
|
||||
|
||||
// Archives predating the manifest engine field get the target's engine —
|
||||
// i.e. the exact same-engine behavior. After validateManifest, a mismatch
|
||||
// can only be sqlite → pg.
|
||||
const targetEngine = isPostgres() ? 'pg' : 'sqlite';
|
||||
const sourceEngine = (manifest.database && manifest.database.engine) || targetEngine;
|
||||
const crossEngine = sourceEngine !== targetEngine;
|
||||
if (crossEngine) {
|
||||
logger.info(`[picpeak-import] cross-engine restore: ${sourceEngine} backup onto ${targetEngine} instance`);
|
||||
}
|
||||
|
||||
const currentAdmin = currentAdminId
|
||||
? await db('admin_users').where({ id: currentAdminId }).first()
|
||||
: null;
|
||||
@@ -404,21 +417,22 @@ async function importFromPicpeak({ picpeakPath, currentAdminId, allowEngineSwitc
|
||||
logger.warn(`[picpeak-import] ignoring ${skipped.length} backup table(s) not present in this DB (or protected): ${skipped.join(', ')}`);
|
||||
}
|
||||
|
||||
await replaceAllTables(tables, dataDir, currentAdmin, { crossEngine: allowEngineSwitch });
|
||||
await replaceAllTables(tables, dataDir, currentAdmin, { crossEngine });
|
||||
|
||||
// Cross-engine only (#1038): rows are inserted with explicit ids, which
|
||||
// leaves Postgres identity sequences at 1 and makes the next natural insert
|
||||
// collide on the primary key. Same-engine restores keep today's behaviour
|
||||
// untouched — this branch exists for scripts/migrate-sqlite-to-postgres.js.
|
||||
if (allowEngineSwitch) await resyncSequences(tables);
|
||||
// Post-commit fixup: rows are inserted with explicit ids, which leaves
|
||||
// Postgres identity sequences behind, so the next natural insert collides
|
||||
// on the primary key. Runs unconditionally, matching main — the guard used
|
||||
// to be `if (allowEngineSwitch)`, which this change removes, and which also
|
||||
// left a same-engine pg → pg restore with stale sequences.
|
||||
await resyncSequences(tables);
|
||||
|
||||
const filesRestored = await restoreFiles(staging);
|
||||
const usesExternalMedia = await detectExternalMedia();
|
||||
|
||||
logger.info(
|
||||
`[picpeak-import] restored ${tables.length} tables, ${filesRestored} files (externalMedia=${usesExternalMedia})`
|
||||
`[picpeak-import] restored ${tables.length} tables, ${filesRestored} files (externalMedia=${usesExternalMedia}, crossEngine=${crossEngine})`
|
||||
);
|
||||
return { restored: true, tables: tables.length, filesRestored, usesExternalMedia, manifest };
|
||||
return { restored: true, tables: tables.length, filesRestored, usesExternalMedia, crossEngine, manifest };
|
||||
} finally {
|
||||
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
@@ -431,5 +445,8 @@ module.exports = {
|
||||
// exported for testing — the cross-engine coercion (#1038)
|
||||
epochToIso,
|
||||
coerceForTargetEngine,
|
||||
typedColumnsFor,
|
||||
reinjectCurrentAdmin,
|
||||
// The cross-engine suite drives the post-restore sequence fixup directly.
|
||||
resyncSequences,
|
||||
};
|
||||
|
||||
@@ -65,6 +65,53 @@ describe('S3StorageAdapter', () => {
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should configure connection and socket-inactivity timeouts by default', () => {
|
||||
expect(S3Client).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
requestHandler: {
|
||||
connectionTimeout: 120000,
|
||||
socketTimeout: 60000
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should keep connectionTimeout generous enough to survive socket-pool queuing', () => {
|
||||
// connectionTimeout starts at request creation and only clears once a
|
||||
// socket is assigned AND connected, so waiting for a free socket from
|
||||
// the agent pool counts against it. A short value (e.g. 10s) fails
|
||||
// every read under concurrent upload load. These timeouts bound an
|
||||
// infinite hang; they are not latency targets.
|
||||
const [[config]] = S3Client.mock.calls;
|
||||
expect(config.requestHandler.connectionTimeout).toBeGreaterThanOrEqual(60000);
|
||||
expect(config.requestHandler.socketTimeout).toBeGreaterThanOrEqual(30000);
|
||||
});
|
||||
|
||||
it('should not set requestTimeout, which caps total duration and only warns', () => {
|
||||
// requestTimeout would abort legitimate large uploads (it is a
|
||||
// total-duration cap, not inactivity) and by default only logs a
|
||||
// warning — it needs throwOnRequestTimeout to abort at all.
|
||||
const [[config]] = S3Client.mock.calls;
|
||||
expect(config.requestHandler).not.toHaveProperty('requestTimeout');
|
||||
});
|
||||
|
||||
it('should allow overriding timeouts via config', () => {
|
||||
new S3StorageAdapter({
|
||||
bucket: 'test-bucket',
|
||||
connectionTimeout: 5000,
|
||||
socketTimeout: 30000
|
||||
});
|
||||
|
||||
expect(S3Client).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
requestHandler: {
|
||||
connectionTimeout: 5000,
|
||||
socketTimeout: 30000
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('testConnection', () => {
|
||||
@@ -239,6 +286,30 @@ describe('S3StorageAdapter', () => {
|
||||
s3Storage.config.retryDelay = originalDelay;
|
||||
});
|
||||
|
||||
it('should retry when the request handler times out a dead connection', async () => {
|
||||
// @smithy/node-http-handler rejects with name 'TimeoutError' for both
|
||||
// its connection-timeout and socket-inactivity timeouts
|
||||
const timeoutError = new Error('Connection timed out after 10000ms');
|
||||
timeoutError.name = 'TimeoutError';
|
||||
|
||||
const operation = jest.fn()
|
||||
.mockRejectedValueOnce(timeoutError)
|
||||
.mockResolvedValueOnce('success');
|
||||
|
||||
const originalRandom = Math.random;
|
||||
const originalDelay = s3Storage.config.retryDelay;
|
||||
Math.random = jest.fn(() => 0);
|
||||
s3Storage.config.retryDelay = 0;
|
||||
|
||||
const result = await s3Storage._retryOperation(operation);
|
||||
|
||||
expect(result).toBe('success');
|
||||
expect(operation).toHaveBeenCalledTimes(2);
|
||||
|
||||
Math.random = originalRandom;
|
||||
s3Storage.config.retryDelay = originalDelay;
|
||||
});
|
||||
|
||||
it('should not retry on non-retryable errors', async () => {
|
||||
const nonRetryableError = new Error('Invalid credentials');
|
||||
nonRetryableError.code = 'InvalidCredentials';
|
||||
|
||||
@@ -27,6 +27,9 @@ let instance = null;
|
||||
* STORAGE_S3_PREFIX — namespace prefix inside the bucket
|
||||
* STORAGE_S3_FORCE_PATH_STYLE=true|false (default: auto when endpoint set)
|
||||
* STORAGE_S3_SSL=true|false (default: true)
|
||||
* STORAGE_S3_CONNECTION_TIMEOUT — ms to acquire+establish a socket (default 120000)
|
||||
* STORAGE_S3_SOCKET_TIMEOUT — ms of socket inactivity before a request
|
||||
* fails and is retried (default 60000)
|
||||
*/
|
||||
function buildStorage() {
|
||||
const backend = (process.env.STORAGE_BACKEND || 'local').toLowerCase();
|
||||
@@ -48,6 +51,8 @@ function buildStorage() {
|
||||
prefix: process.env.STORAGE_S3_PREFIX,
|
||||
forcePathStyle: process.env.STORAGE_S3_FORCE_PATH_STYLE === 'true' ? true : undefined,
|
||||
sslEnabled: process.env.STORAGE_S3_SSL !== 'false',
|
||||
connectionTimeout: parseInt(process.env.STORAGE_S3_CONNECTION_TIMEOUT || '120000', 10),
|
||||
socketTimeout: parseInt(process.env.STORAGE_S3_SOCKET_TIMEOUT || '60000', 10),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,8 @@ class S3StorageAdapter extends stream.EventEmitter {
|
||||
* @param {number} [config.partSize=10485760] - Part size for multipart upload (default 10MB)
|
||||
* @param {number} [config.maxRetries=3] - Maximum number of retry attempts
|
||||
* @param {number} [config.retryDelay=1000] - Initial retry delay in milliseconds
|
||||
* @param {number} [config.connectionTimeout=120000] - Ms to acquire+establish a socket
|
||||
* @param {number} [config.socketTimeout=60000] - Ms of socket inactivity before a request fails
|
||||
*/
|
||||
constructor(config) {
|
||||
super();
|
||||
@@ -58,13 +60,38 @@ class S3StorageAdapter extends stream.EventEmitter {
|
||||
partSize: 10 * 1024 * 1024, // 10MB
|
||||
maxRetries: 3,
|
||||
retryDelay: 1000,
|
||||
connectionTimeout: 120000,
|
||||
socketTimeout: 60000,
|
||||
...config
|
||||
};
|
||||
|
||||
// Initialize S3 client
|
||||
const s3Config = {
|
||||
region: this.config.region,
|
||||
forcePathStyle: this.config.forcePathStyle
|
||||
forcePathStyle: this.config.forcePathStyle,
|
||||
// Without timeouts a silently dropped connection leaves the request —
|
||||
// and with it every queued upload — hanging forever.
|
||||
//
|
||||
// socketTimeout, NOT requestTimeout, is the right knob here:
|
||||
// requestTimeout is a total-duration cap that would kill legitimate
|
||||
// large uploads, and by default it only logs a warning (it needs
|
||||
// throwOnRequestTimeout to abort at all). socketTimeout fires on
|
||||
// socket INACTIVITY and destroys the request with a TimeoutError, so
|
||||
// an active transfer of any size is safe and only a dead line trips.
|
||||
//
|
||||
// Both values are deliberately GENEROUS. connectionTimeout starts
|
||||
// when the request object is created and only clears once a socket
|
||||
// is both assigned and connected — so time spent queuing for a free
|
||||
// socket from the agent pool (maxSockets 50) counts against it. A
|
||||
// 10s value looks reasonable and is not: under concurrent uploads
|
||||
// it expires while merely waiting in line, and every read (photo
|
||||
// download, thumbnail, background thumbnailing) fails with
|
||||
// TimeoutError. These timeouts exist to convert an INFINITE hang
|
||||
// into a bounded failure, not to enforce latency targets.
|
||||
requestHandler: {
|
||||
connectionTimeout: this.config.connectionTimeout,
|
||||
socketTimeout: this.config.socketTimeout
|
||||
}
|
||||
};
|
||||
|
||||
// Add credentials if provided
|
||||
@@ -671,7 +698,9 @@ class S3StorageAdapter extends stream.EventEmitter {
|
||||
}
|
||||
|
||||
// Check if error is retryable
|
||||
const retryableErrors = ['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ESOCKETTIMEDOUT', 'RequestTimeout', 'SlowDown', 'ServiceUnavailable', 'InternalError'];
|
||||
// 'TimeoutError' is what @smithy/node-http-handler names both its
|
||||
// connection-timeout and socket-inactivity rejections.
|
||||
const retryableErrors = ['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ESOCKETTIMEDOUT', 'RequestTimeout', 'TimeoutError', 'SlowDown', 'ServiceUnavailable', 'InternalError'];
|
||||
const isRetryable = retryableErrors.some(code =>
|
||||
error.code === code ||
|
||||
error.name === code ||
|
||||
|
||||
@@ -20,6 +20,19 @@
|
||||
* - The PDF's internal `Title` metadata (Chrome's PDF viewer
|
||||
* uses this as the default name when saving from a blob URL,
|
||||
* where Content-Disposition can't reach)
|
||||
*
|
||||
* IMPORTANT (#1024): the preserved non-ASCII is exactly what a raw
|
||||
* `filename="${...}"` header cannot carry. HTTP header values are
|
||||
* latin1, so a customer label reaching a header directly either
|
||||
* mangles (U+0080-U+00FF — every German umlaut: `Müller` is sent as
|
||||
* the byte 0xFC and read back as garbage) or throws ERR_INVALID_CHAR
|
||||
* and 500s the request (anything above U+00FF — Polish ł, Czech ř,
|
||||
* Turkish ş, €, Cyrillic, CJK, emoji).
|
||||
*
|
||||
* Never interpolate this result into a header. Pass it through
|
||||
* `buildContentDisposition()` in utils/filenameSanitizer, which emits
|
||||
* an ASCII fallback plus the RFC 5987 `filename*=UTF-8''…` form so the
|
||||
* unicode name survives in browsers and the header stays legal.
|
||||
*/
|
||||
|
||||
function sanitiseSegment(input, maxLen = 80) {
|
||||
@@ -33,7 +46,18 @@ function sanitiseSegment(input, maxLen = 80) {
|
||||
s = s.replace(/-+/g, '-');
|
||||
// Trim leading/trailing dashes + dots.
|
||||
s = s.replace(/^[-.]+|[-.]+$/g, '');
|
||||
if (s.length > maxLen) s = s.slice(0, maxLen);
|
||||
if (s.length > maxLen) {
|
||||
s = s.slice(0, maxLen);
|
||||
// slice() cuts UTF-16 code units, so a boundary landing inside an astral
|
||||
// character (emoji, rarer CJK) leaves a dangling high surrogate. That is
|
||||
// not merely cosmetic: the lone surrogate makes encodeURIComponent throw
|
||||
// `URIError: URI malformed` inside buildContentDisposition, which 500s
|
||||
// the PDF endpoint — the exact failure #1024 set out to remove, just via
|
||||
// a different route. Drop the orphan rather than widening the cap, so the
|
||||
// byte budget this limit exists to protect is unchanged.
|
||||
const lastUnit = s.charCodeAt(s.length - 1);
|
||||
if (lastUnit >= 0xD800 && lastUnit <= 0xDBFF) s = s.slice(0, -1);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "picpeak-frontend",
|
||||
"private": true,
|
||||
"version": "3.45.16",
|
||||
"version": "3.46.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -16,6 +16,7 @@ interface RestoreResult {
|
||||
tables: number;
|
||||
filesRestored: number;
|
||||
usesExternalMedia: boolean;
|
||||
crossEngine?: boolean;
|
||||
sessionInvalidated?: boolean;
|
||||
}
|
||||
|
||||
@@ -137,7 +138,7 @@ export const PicpeakRestoreCard: React.FC = () => {
|
||||
{t('backup.picpeak.restoreTitle', 'Restore from a .picpeak')}
|
||||
</h3>
|
||||
<p className="mt-1 text-sm text-neutral-600 dark:text-neutral-400">
|
||||
{t('backup.picpeak.restoreIntro', 'Upload a .picpeak taken from this or another instance. Same database engine only.')}
|
||||
{t('backup.picpeak.restoreIntro', 'Upload a .picpeak taken from this or another instance. Restoring a SQLite backup onto a PostgreSQL instance is supported (the upgrade path); other engine combinations must match.')}
|
||||
</p>
|
||||
<input ref={fileRef} type="file" accept=".picpeak,application/zip" className="hidden" onChange={onFilePick} />
|
||||
<Button
|
||||
@@ -163,6 +164,11 @@ export const PicpeakRestoreCard: React.FC = () => {
|
||||
files: result.filesRestored,
|
||||
})}
|
||||
</p>
|
||||
{result.crossEngine && (
|
||||
<p className="mt-0.5 text-xs text-green-700 dark:text-green-300">
|
||||
{t('backup.picpeak.crossEngineNote', 'Cross-engine restore: a SQLite backup was converted onto this PostgreSQL instance.')}
|
||||
</p>
|
||||
)}
|
||||
{result.usesExternalMedia && (
|
||||
<p className="mt-2 flex items-start gap-1 text-xs text-amber-800 dark:text-amber-300">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 flex-shrink-0" />
|
||||
|
||||
@@ -352,6 +352,10 @@
|
||||
}
|
||||
},
|
||||
"backup": {
|
||||
"picpeak": {
|
||||
"restoreIntro": "Laden Sie eine .picpeak-Datei von dieser oder einer anderen Instanz hoch. Die Wiederherstellung eines SQLite-Backups auf einer PostgreSQL-Instanz wird unterstützt (Upgrade-Pfad); ansonsten müssen die Datenbank-Engines übereinstimmen.",
|
||||
"crossEngineNote": "Engine-übergreifende Wiederherstellung: Ein SQLite-Backup wurde auf diese PostgreSQL-Instanz übernommen."
|
||||
},
|
||||
"title": "Backup-Verwaltung",
|
||||
"subtitle": "Verwalten Sie System-Backups, konfigurieren Sie automatisierte Backups und stellen Sie vorherige Backups wieder her.",
|
||||
"tabs": {
|
||||
@@ -1795,27 +1799,7 @@
|
||||
"title": "E-Mail-Einstellungen"
|
||||
},
|
||||
"backup": {
|
||||
"title": "Backup",
|
||||
"picpeak": {
|
||||
"title": "Portables Backup (.picpeak)",
|
||||
"intro": "Laden Sie eine einzelne, in sich geschlossene Datei herunter und laden Sie sie auf einer anderen Instanz hoch, um diese zu klonen — komplett im Browser.",
|
||||
"includePhotos": "Original-Galeriefotos einschließen (größere Datei)",
|
||||
"secretsWarning": "Diese Datei enthält Geheimnisse im Klartext (E-Mail-Passwort, Admin-Zugangsdaten, API-Schlüssel). Bewahren Sie sie sicher auf und übertragen Sie sie nur über vertrauenswürdige Kanäle.",
|
||||
"download": ".picpeak herunterladen",
|
||||
"downloadFailed": "Die Backup-Datei konnte nicht erstellt werden.",
|
||||
"restoreTitle": "Aus einer .picpeak wiederherstellen",
|
||||
"restoreIntro": "Laden Sie eine .picpeak von dieser oder einer anderen Instanz hoch. Nur dieselbe Datenbank-Engine.",
|
||||
"chooseFile": ".picpeak-Datei auswählen…",
|
||||
"restoreDone": "Backup wiederhergestellt.",
|
||||
"restoreFailed": "Wiederherstellung fehlgeschlagen.",
|
||||
"restoreSummary": "{{tables}} Tabellen und {{files}} Dateien wiederhergestellt.",
|
||||
"externalMediaNote": "Dieses Backup verweist auf eine externe Medienbibliothek. Stellen Sie sicher, dass das externe Medien-Routing auf dieser Instanz konfiguriert ist.",
|
||||
"externalMediaLink": "Einrichtungsanleitung",
|
||||
"reload": "App neu laden",
|
||||
"confirmTitle": "Die Wiederherstellung löscht alle aktuellen Daten",
|
||||
"confirmBody": "Dies ersetzt ALLE Daten auf dieser Instanz dauerhaft durch das hochgeladene Backup, mit Ausnahme Ihres aktuellen Kontos. Dies kann nicht rückgängig gemacht werden.",
|
||||
"confirmRestore": "Löschen & wiederherstellen"
|
||||
}
|
||||
"title": "Backup"
|
||||
},
|
||||
"branding": {
|
||||
"title": "Branding"
|
||||
|
||||
@@ -1340,27 +1340,7 @@
|
||||
"title": "Email Settings"
|
||||
},
|
||||
"backup": {
|
||||
"title": "Backup",
|
||||
"picpeak": {
|
||||
"title": "Portable backup (.picpeak)",
|
||||
"intro": "Download a single self-contained file, then upload it on another instance to clone this one — all through the browser.",
|
||||
"includePhotos": "Include original gallery photos (larger file)",
|
||||
"secretsWarning": "This file contains secrets in plain text (email password, admin credentials, API keys). Store it securely and only transfer it over trusted channels.",
|
||||
"download": "Download .picpeak",
|
||||
"downloadFailed": "Could not create the backup file.",
|
||||
"restoreTitle": "Restore from a .picpeak",
|
||||
"restoreIntro": "Upload a .picpeak taken from this or another instance. Same database engine only.",
|
||||
"chooseFile": "Choose .picpeak file…",
|
||||
"restoreDone": "Backup restored.",
|
||||
"restoreFailed": "Restore failed.",
|
||||
"restoreSummary": "{{tables}} tables and {{files}} files restored.",
|
||||
"externalMediaNote": "This backup references an external-media library. Make sure external-media routing is configured on this instance.",
|
||||
"externalMediaLink": "Setup guide",
|
||||
"reload": "Reload app",
|
||||
"confirmTitle": "Restore will delete all current data",
|
||||
"confirmBody": "This permanently replaces ALL data on this instance with the uploaded backup, except your current account. This cannot be undone.",
|
||||
"confirmRestore": "Delete & restore"
|
||||
}
|
||||
"title": "Backup"
|
||||
},
|
||||
"branding": {
|
||||
"title": "Branding"
|
||||
@@ -2798,6 +2778,10 @@
|
||||
}
|
||||
},
|
||||
"backup": {
|
||||
"picpeak": {
|
||||
"restoreIntro": "Upload a .picpeak taken from this or another instance. Restoring a SQLite backup onto a PostgreSQL instance is supported (the upgrade path); other engine combinations must match.",
|
||||
"crossEngineNote": "Cross-engine restore: a SQLite backup was converted onto this PostgreSQL instance."
|
||||
},
|
||||
"title": "Backup Management",
|
||||
"subtitle": "Manage system backups, configure automated backups, and restore from previous backups.",
|
||||
"tabs": {
|
||||
|
||||
Reference in New Issue
Block a user