Repository navigation
feat: add validated offline merchant template import/export - #477
Merged
Merged
Conversation
…lates Portable transfer envelopes (#448, epic #438) on top of the #447 model: - Shared kernel: 'flocafe-merchant-template' envelope contract (format discriminator, fail-closed schema major, ISO exportedAt, informational origin metadata, checksum field) with pure structural validation that reuses the single #447 payload validator — no forked rules. - Service: export active/archived rows as self-describing .json envelopes (checksum verified BEFORE export so tampered payloads never ship); import runs the full untrusted-input pipeline (256 KB byte cap, single JSON document, envelope whitelist, shared payload validator, checksum verify) and always lands a NEW draft with origin 'imported' plus offline-import provenance (source-file digest + sanitized file name). Duplicate names allowed; imports never overwrite or auto-activate. - Routes: GET /:id/export (attachment download with sanitized, traversal-proof filename) and POST /import, both owner-role only and rate-limited; multi-tenant scoping unchanged. - Fixtures: golden round-trip envelope plus per-rule negatives (tampered checksum, unknown envelope major, oversized, disallowed block, wrong root format, unknown envelope field). - Tests: tests/merchant-template-import-export.test.ts covering every rejection class, no partial installs, lossless round-trip, render parity across the transfer boundary, lifecycle intact after import. - Docs: envelope format documented as a public contract in docs/merchant-print-templates.md.
…tion for order-stable transfer checksums
…st dependency unavailable
…ify size-cap test
Contributor
Greptile SummaryThe PR adds owner-only, offline import and export of validated merchant print-template envelopes while preserving draft lifecycle and tenant scoping.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| shared/print/merchant-template.ts | Adds the versioned envelope contract, canonical serialization, strict timestamp validation, and shared fail-closed validation. |
| main/services/merchant-print-templates.ts | Implements checksum-verified export and validated fresh-draft import with sanitized offline provenance. |
| main/routes/print-templates.ts | Exposes owner-only import and export endpoints through the existing merchant-template API. |
| main/db.ts | Adds migration v73 to canonicalize eligible stored current and rollback payloads. |
| tests/merchant-template-import-export.test.ts | Exercises envelope validation, authorization, integrity checks, round trips, rendering parity, lifecycle behavior, and migration normalization. |
Sequence Diagram
sequenceDiagram
actor Owner
participant API as Print Template API
participant Validator as Shared Validator
participant Service as Template Service
participant DB as SQLite
Owner->>API: POST /api/print-templates/import
API->>Service: Raw envelope text + metadata
Service->>Validator: Validate envelope and payload
Validator-->>Service: Canonical validated payload
Service->>Service: Verify canonical checksum
Service->>DB: Insert fresh draft with provenance
DB-->>Owner: Imported template metadata
Owner->>API: GET /api/print-templates/:id/export
API->>Service: Export active/archived template
Service->>DB: Load tenant-scoped row
Service->>Validator: Revalidate stored payload
Service->>Service: Verify checksum and size cap
Service-->>Owner: Portable JSON attachment
Reviews (2): Last reviewed commit: "no-mistakes: apply CI fixes" | Re-trigger Greptile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Intent
Implement FloCafe issue #448 (child of epic #438): validated offline import/export for merchant print templates, building strictly on the landed #447 contracts (shared/print/merchant-template.ts fail-closed validator with schema_version major gate + allowed-blocks whitelist, main/services/merchant-print-templates.ts CRUD lifecycle draft->activate->archive with checksum column and rollback, main/routes/print-templates.ts owner CRUD API) WITHOUT forking the validation logic.
Requirements accepted from the captain brief:
Binding constraints from issue #448: treat every imported file as untrusted input; declarative-only payload vocabulary exactly equal to the validated block set from #447 (no JavaScript, eval, SQL, shell, filesystem paths, network fetches, arbitrary URLs, or executable HTML); unknown-field policy on import = reject (stricter than render tolerance); imports never auto-activate and never overwrite an existing identity; duplicate names are allowed because identity is a fresh uuid; no zips/binaries in v1 (text-only JSON); no visual editor; no compliance-template convergence (#445 escpos-line-template-v1 is a different format on purpose); the import/export code path is fully offline (zero network APIs, verified by npm run test:url-allowlist).
Deliberate design decisions and prior pipeline fix rounds to NOT re-litigate as mistakes: drafts are deliberately NOT exportable (only active/archived pass activation); envelope checksum is sha256 over serializeMerchantTemplatePayload output (recursively key-sorted canonical serialization), used for persisted payload_json too; migration v73 normalizes pre-canonicalization stored payloads once, idempotently, leaving checksum-mismatching or invalid rows untouched for fail-closed paths; export enforces the SAME 256 KB raw-byte cap as import so an install never mints a transfer file it would refuse to read back (this resolves the previously-raised size-symmetry question - if review still wants to challenge this contract decision as ask-user, park it rather than fixing silently: captain will rule under key f2-size-symmetry); imports always mint a NEW row id so no uuid-collision replace flow is needed in v1; settings-page Export/Import buttons are deferred because no merchant template management list UI exists yet.
Verification expected: npx ts-node --transpile-only -P tests/tsconfig.json tests/merchant-template-import-export.test.ts (new suite, registered as test:merchant-template-transfer in package.json), regression-clean tests/merchant-print-templates.test.ts, npm run build && npm run lint, npm run test:url-allowlist.
What Changed
.flocafe-template.jsonenvelopes, with active/archived export support and fresh-draft imports carrying sanitized offline provenance.Fixes #448
Refs #438
Risk Assessment
Testing
The prescribed transfer suite initially hit TS5107 because dependencies were absent; after installing the lockfile-resolved dependencies without lifecycle scripts, it passed end-to-end. Merchant-template regression and URL-allowlist tests also passed. No linters, formatters, full-suite tests, or static-analysis commands were run.
Evidence: Merchant template import/export end-to-end transcript
Evidence: Merchant template regression transcript
Evidence: Offline URL allowlist transcript
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
🔧 **Review** - 4 issues found → auto-fixed (4) ✅
shared/print/merchant-template.ts:180-Date.parseaccepts non-ISO inputs such as"0", so invalidexportedAtvalues pass despite the documented ISO-8601 contract. Use an explicit ISO/RFC3339 check or confirm broader parsing is intentional.main/services/merchant-print-templates.ts:401- Export verifies only the stored hash, not payload validity. A migrated invalid row with a matching checksum can return 500 for malformed JSON or export a file the importer rejects. Validaterow.payload_jsonwith the shared validator before constructing the envelope.main/db.ts:4033- The intent requires v73 to leave “checksum-mismatching or invalid rows untouched,” but this rewrites a row when its current payload is valid whileprevious_payload_jsonis invalid. Decide whether invalid rollback state makes the row invalid under that requirement.tests/merchant-template-import-export.test.ts:347- The required transfer fixture set says “negative fixtures per validation rule,” but the added transfer tests omit import-boundary cases for unknown payload fields, duplicate blocks, wrong types, empty blocks, and invalid label fields. Existing feat(printing): add versioned semantic merchant print template model #447 pure-validator fixtures do not cover these through import.🔧 Fix: Guard export against invalid stored payloads; test dependency unavailable
3 warnings still open:
shared/print/merchant-template.ts:180- The contract documentsexportedAtas an ISO-8601 date-time, butDate.parseaccepts non-ISO inputs such as"0"; an envelope with that value, otherwise valid payload, and matching checksum is imported successfully. Use an explicit ISO/RFC3339 date-time check or confirm broader parsing is intentional.main/db.ts:4033- The stated migration invariant requires v73 to leave “checksum-mismatching or invalid rows untouched,” but this path rewrites a row when its current payload/checksum are valid whileprevious_payload_jsonis malformed or otherwise invalid. Either skip the whole row when rollback state is invalid or clarify that only the current payload defines row validity.tests/merchant-template-import-export.test.ts:354- The required fixture contract says transfer fixtures must include “negative fixtures per validation rule,” but the transfer suite only adds envelope-level cases plus one disallowed-block payload case. It omits transfer/import-boundary fixtures for unknown payload fields, duplicate blocks, wrong types, empty blocks, and invalid label fields; the existing feat(printing): add versioned semantic merchant print template model #447 fixtures are outside the transfer fixture set and are not exercised through import.🔧 Fix: Enforce strict RFC3339 exportedAt validation
3 issues (2 errors, 1 warning) still open:
main/services/merchant-print-templates.ts:477- Imported label strings can contain printer commands such as{CUT}or ASCII ESC controls. They pass the shared validator, then reachapplyMerchantTemplateandbuildEscPos, where{CUT}executes a physical cut instead of printing text. Reject/sanitize printer tokens and control characters at the shared validation or render boundary.shared/print/merchant-template.ts:154- The RFC3339 check still accepts invalid calendar values such as2024-02-30T00:00:00ZbecauseDate.parsenormalizes them. Enforce calendar-valid date-time components for the strict ISO-8601 contract.tests/merchant-template-import-export.test.ts:340-Buffer.byteLengthreceives the numeric.lengthof the probe result instead of the probe string, so this new required test throwsERR_INVALID_ARG_TYPEbefore exercising the export size-cap behavior. Pass the canonical string toBuffer.byteLength.🔧 Fix: Reject printer controls in merchant labels; clarify size-cap test
1 warning still open:
shared/print/merchant-template.ts:158- The strict ISO-8601 check still accepts nonexistent calendar dates such as2024-02-30T00:00:00Z:Date.parsenormalizes them instead of rejecting them, so import accepts malformed envelope metadata. Validate calendar components explicitly before accepting the timestamp.🔧 Fix: Validate RFC3339 calendar components before envelope import
✅ Re-checked - no issues remain.
🔧 **Test** - 1 issue found → auto-fixed ✅
tests/merchant-template-import-export.test.ts:313- Fixed the focused test’s tamper-cleanup query to restore the saved checksum correctly.npm ci --no-audit --no-fundnpx ts-node --transpile-only -P tests/tsconfig.json tests/merchant-template-import-export.test.tsnpx ts-node --transpile-only -P tests/tsconfig.json tests/merchant-print-templates.test.tsnpm run test:url-allowlist🔧 Fix: Fix transfer test checksum cleanup; 29 focused checks pass
✅ Re-checked - no issues remain.
npm ci --ignore-scriptsnpx --no-install ts-node --transpile-only -P tests/tsconfig.json tests/merchant-template-import-export.test.tsnpm run test:merchant-print-templatesnpm run test:url-allowlistgit status --porcelain=v1and transient dependency cleanup verification✅ **Document** - passed
✅ No issues found.
🔧 **Lint** - 1 issue found → auto-fixed ✅
eslint.config.mjs:1- Targeted ESLint could not run because the configured TypeScript ESLint packages are missing from this worktree.🔧 Fix: Targeted lint and source typecheck are clean
✅ Re-checked - no issues remain.
✅ **Push** - passed
✅ No issues found.