From d76d335d9b8c732be77c40d9fab8db5aaaf67e49 Mon Sep 17 00:00:00 2001 From: JasonFraser Date: Wed, 14 Oct 2026 15:34:43 -0400 Subject: [PATCH] Add PocketBase schema for the layout mapper (L.3) New layoutMappings/layoutMappingVersions collections plus documents fields (layoutMappingUsed/layoutMappingVersionUsed/layoutApplied/layoutFingerprintHash) and a promote_shared_layout_mapping.pb.js hook that flips a mapping to "shared" once a second, different user independently creates one with the same fingerprintHash. Found and fixed a real security gap by testing the live rule rather than trusting the rule text: the original updateRule only gated WHO could update a layoutMappings record, not WHICH fields - letting an owner trivially self-promote their own mapping to "shared" via a plain PATCH, defeating the whole confirmation requirement. Fixed in a follow-up migration (6_fix_layout_mapping_update_rule.js) that blocks setting status to "shared" directly while leaving ordinary edits and self-retiring untouched. Verified against the real rebuilt PocketBase container: both collections and all four new documents fields confirmed via the REST API; two real signed-up users with a matching fingerprintHash both correctly flip to shared via the hook, visible to a third user; a still-private mapping 404s for every other user; the self-promotion gap reproduced before the fix and confirmed blocked after it. Co-Authored-By: Claude Sonnet 5 --- CLAUDE.md | 70 ++++++++++- .../promote_shared_layout_mapping.pb.js | 56 +++++++++ .../4_add_layout_mapper_schema.js | 117 ++++++++++++++++++ .../5_add_layout_mapping_fields.js | 27 ++++ .../6_fix_layout_mapping_update_rule.js | 22 ++++ 5 files changed, 291 insertions(+), 1 deletion(-) create mode 100644 pocketbase/pb_hooks/promote_shared_layout_mapping.pb.js create mode 100644 pocketbase/pb_migrations/4_add_layout_mapper_schema.js create mode 100644 pocketbase/pb_migrations/5_add_layout_mapping_fields.js create mode 100644 pocketbase/pb_migrations/6_fix_layout_mapping_update_rule.js diff --git a/CLAUDE.md b/CLAUDE.md index 67842f4..1806411 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,7 @@ to rough effort: |---|---|---| | **1** | Extraction + 6 checks + Excel export, dual-engine, measurement harness | **In progress — see gaps below** | | 2 | Review screen, suggested-fix patterns, OCR, 2nd+ bank support | OCR routing + working Docling-fallback (`raw_ocr_extract.py`) built and verified against a real multi-page scan 2026-10-11 — one known single-page edge case remains unreliable, see "OCR / scanned statements" below — **review screen (R.1-R.5) complete as of 2026-10-13** (see "Review screen"/"R.2"/"R.3"/"R.4"/"R.5" under Key decisions & lessons) — R.1 (source-position capture + the pdf.js highlighting viewer), R.2 (plain-language flags + jump-to-flagged navigation), R.3 (the suggested-fix engine - debit/credit swap, transposed digits, OCR digit misread), R.4 (structural row edits - flip sign, insert, split, merge, delete, behind a "more actions" menu), and R.5 (edit log + acknowledge/accept workflow + an optional Excel "Edits" sheet) all shipped; "date format swapped" and a separate "bulk column fix" both investigated and found not to apply to this pipeline's own data shape (see R.3/R.4's own entries) | -| 3 | Layout mapper (fingerprinting, versioning, drift detection) | **Pulled forward and in progress as of 2026-10-14** (see "Layout mapper" under Key decisions & lessons) - staged L.1-L.8, full spec scope (§6/§6.1/§9) plus a superuser-review promotion path beyond what's written. L.1 (a modular "layout quirks" tier for mechanical geometric oddities, ahead of the mapper itself) shipped - fixed a real new statement (an Equals Money account) whose header label wrapped across physical lines, plus two more real differences the same statement surfaced (a "$"-prefixed money format, an ISO-shaped date format). L.2 (fingerprinting + the forced-mapping backend contract, no UI/PocketBase yet) shipped - also surfaced and fixed a real gap (a forced mapping had no page-boundary concept, swallowing a cover page's own letterhead into the first transaction; fixed with a new `start_page` field). L.3-L.8 (PocketBase schema, the manual mapping screen, the Layouts page, drift detection, the superuser review screen) not started yet | +| 3 | Layout mapper (fingerprinting, versioning, drift detection) | **Pulled forward and in progress as of 2026-10-14** (see "Layout mapper" under Key decisions & lessons) - staged L.1-L.8, full spec scope (§6/§6.1/§9) plus a superuser-review promotion path beyond what's written. L.1 (a modular "layout quirks" tier for mechanical geometric oddities, ahead of the mapper itself) shipped - fixed a real new statement (an Equals Money account) whose header label wrapped across physical lines, plus two more real differences the same statement surfaced (a "$"-prefixed money format, an ISO-shaped date format). L.2 (fingerprinting + the forced-mapping backend contract, no UI/PocketBase yet) shipped - also surfaced and fixed a real gap (a forced mapping had no page-boundary concept, swallowing a cover page's own letterhead into the first transaction; fixed with a new `start_page` field). L.3 (the `layoutMappings`/`layoutMappingVersions` PocketBase schema + the auto-promotion hook) shipped - found and fixed a real rule gap during testing (an owner could self-promote their own mapping to "shared" via a plain update; PocketBase rules gate who can update, not which fields). L.4-L.8 (the frontend fingerprint lookup, the manual mapping screen, the Layouts page, drift detection, the superuser review screen) not started yet | | 4 | Multi-tenant practice/client accounts, Frappe data model | Not started | | 5 | Free front door, public accuracy page | Not started | | 6 | Append mode, credit cards, multi-account statements | Not started | @@ -615,6 +615,25 @@ statement files, why every document is required to belong to a project from day sourceFile, overwritten on every re-export rather than kept as a history (see "Excel exports moved to R2" under Key decisions & lessons). + pb_migrations/4_add_layout_mapper_schema.js + — NEW 2026-10-14, layout-mapper L.3 — creates + layoutMappings/layoutMappingVersions (see "Layout + mapper" under Key decisions & lessons for the full + field list/rules). + pb_migrations/5_add_layout_mapping_fields.js + — adds layoutMappingUsed/layoutMappingVersionUsed/ + layoutApplied/layoutFingerprintHash to documents. + pb_migrations/6_fix_layout_mapping_update_rule.js + — tightens layoutMappings' updateRule to block an + owner from self-promoting their own mapping to + "shared" via a plain PATCH - a real gap found by + testing the live rule, not caught by review (see + "Layout mapper" under Key decisions & lessons). + pb_hooks/promote_shared_layout_mapping.pb.js + — NEW 2026-10-14 — onRecordAfterCreateSuccess on + layoutMappings: promotes both records to "shared" + when a second, different owner creates a mapping + with the same fingerprintHash. pb_hooks/ensure_default_project.pb.js — fires on every new users record (password signup and Google OAuth2 signup both create one the same way) and @@ -2091,6 +2110,55 @@ forced-mapping contract is functionally equivalent once given the right inputs, just "doesn't crash." `backend/measure.py` re-run byte-identical on HSBC/RBC both before and after the `start_page` addition. +**L.3 shipped same day: the PocketBase schema for the layout mapper.** Two new +migrations - `4_add_layout_mapper_schema.js` (`layoutMappings`/ +`layoutMappingVersions` collections) and `5_add_layout_mapping_fields.js` +(`documents.layoutMappingUsed`/`layoutMappingVersionUsed`/`layoutApplied`/ +`layoutFingerprintHash`) - plus a new hook, `pb_hooks/ +promote_shared_layout_mapping.pb.js`. `layoutMappingVersions` is a genuinely +separate collection, not an embedded array like `documents.editLog` - the +(not-yet-built) Layouts page needs independently listable/comparable/roll-back- +able versions, and PocketBase can't query into elements of a JSON array. + +The one deliberate rule deviation from every other collection's strict owner-only +pattern: `layoutMappings`' `listRule`/`viewRule` also allow `status = "shared"`, +since the entire point of a shared mapping is that OTHER users' uploads can find +and apply it. The hook (`onRecordAfterCreateSuccess` on `layoutMappings`, same +pattern as `ensure_default_project.pb.js`): when a new mapping is created, it looks +for another mapping with the same `fingerprintHash` and a DIFFERENT `owner` (the +honest stand-in for "a different practice" - no Practice/Client entity exists in +this schema, Phase 4 not started) via `e.app` (bypasses every rule); if found, both +records flip to `status: "shared"` immediately - kept as two separate records +rather than merged, avoiding a dangling relation from any `documents +.layoutMappingUsed` already pointing at either one. + +**A real gap found by testing the actual rule against the actual running +collection, not by reading the rule text and trusting it:** the first version of +`updateRule` was just `owner = @request.auth.id` - which gates WHO can update a +record, not WHICH fields they change. A plain owner could PATCH +`{"status": "shared"}` on their own still-private mapping and it would simply +succeed, completely defeating the "private until a second confirmation or +superuser approval" requirement this collection exists to enforce. Caught by +actually trying it (not assumed safe because the collection "has rules") before +this was ever reachable by a real user. Fixed in a follow-up migration, +`6_fix_layout_mapping_update_rule.js` (not by editing migration 4, which had +already applied): `updateRule` tightened to `owner = @request.auth.id && +@request.body.status != "shared"` - blocks self-promotion specifically, while an +ordinary edit (rename, fix a column) or the owner setting their own mapping to +`"retired"` still works exactly as before. + +**Verified, all real, against the actual rebuilt container, not assumed from the +migration files:** both new collections and all four new `documents` fields +confirmed present via the real REST API as the real PocketBase superuser. Two +different real signed-up users each creating a `layoutMappings` record with the +SAME `fingerprintHash` - the hook correctly flipped both to `shared`; a third, +unrelated signed-up user could then list both, while a still-PRIVATE mapping +correctly 404'd for every other user's `GET`/`PATCH`. After finding and fixing the +self-promotion gap: the same self-promotion PATCH now correctly fails; an ordinary +rename and a self-retire by the owner both still succeed; the hook itself +re-confirmed working unchanged after the rule tightening (it writes via `e.app`, +bypassing rules entirely either way). + **Governing rule: never silently correct or exclude data.** This shows up in several concrete places, not just as an abstract principle: - A row with an unusual status (e.g. HSBC's "Cancelled" wires) stays in the output and is diff --git a/pocketbase/pb_hooks/promote_shared_layout_mapping.pb.js b/pocketbase/pb_hooks/promote_shared_layout_mapping.pb.js new file mode 100644 index 0000000..40ed35b --- /dev/null +++ b/pocketbase/pb_hooks/promote_shared_layout_mapping.pb.js @@ -0,0 +1,56 @@ +/// + +/** + * Auto-promotion: when a NEW layoutMappings record is created, check for + * another record with the SAME fingerprintHash created by a DIFFERENT + * owner. If one exists, both are independent confirmations of the same + * layout - promote both to "shared" immediately, so a third user's + * matching upload applies it with zero manual work. + * + * "A different owner" is this project's own honest stand-in for the + * underlying spec's "a different practice" - there is no Practice/ + * Client entity in this schema (Phase 4, not started), so a different + * PocketBase user account is the closest real signal available. See + * CLAUDE.md's "Layout mapper" entry for the full reasoning. + * + * Runs via e.app (bypasses every collection rule, same pattern + * ensure_default_project.pb.js already uses) since a normal user's own + * session could never update someone ELSE's mapping record through the + * API - this hook is the only path (besides a real superuser session) + * that can ever flip a mapping to "shared". + * + * Both records are kept and both flipped, rather than merging into one + * and deleting the other - simpler, and avoids leaving a dangling + * relation from any documents.layoutMappingUsed that might already + * point at either one. + */ +onRecordAfterCreateSuccess((e) => { + let mappings = e.app.findCollectionByNameOrId('layoutMappings') + let match = null + try { + match = e.app.findFirstRecordByFilter( + mappings, + 'fingerprintHash = {:hash} && owner != {:owner} && id != {:id} && status != "retired"', + { hash: e.record.get('fingerprintHash'), owner: e.record.get('owner'), id: e.record.id }, + ) + } catch (err) { + // findFirstRecordByFilter throws when nothing matches - no other + // user has created an equivalent mapping yet, nothing to promote. + match = null + } + + if (match) { + let now = new Date().toISOString() + e.record.set('status', 'shared') + e.record.set('promotedReason', 'second_user_confirmation') + e.record.set('promotedAt', now) + e.app.save(e.record) + + match.set('status', 'shared') + match.set('promotedReason', 'second_user_confirmation') + match.set('promotedAt', now) + e.app.save(match) + } + + e.next() +}, 'layoutMappings') diff --git a/pocketbase/pb_migrations/4_add_layout_mapper_schema.js b/pocketbase/pb_migrations/4_add_layout_mapper_schema.js new file mode 100644 index 0000000..147dce0 --- /dev/null +++ b/pocketbase/pb_migrations/4_add_layout_mapper_schema.js @@ -0,0 +1,117 @@ +/// + +/** + * Schema for the layout mapper (Phase 3, pulled forward - see CLAUDE.md's + * "Layout mapper" entry). Two new collections: + * + * layoutMappings - one saved column mapping for a statement layout the + * keyword/geometry detector (and layout_quirks) couldn't resolve on + * their own. `owner` stays set after promotion to `shared` (provenance, + * not access control at that point). `bankLabel`/`accountTypeLabel` are + * free-text display-only grouping for the (not-yet-built) Layouts page - + * there is no real Client/Practice entity in this schema (Phase 4, not + * started), so this can't be a relation to one. + * + * The one deliberate deviation from every other collection's strict + * owner-only rules: `listRule`/`viewRule` also allow `status = "shared"`, + * since the whole point of a shared mapping is that OTHER users' uploads + * can find and apply it. `updateRule` stays owner-only regardless - the + * only ways a mapping's own status actually flips to "shared" are the + * promote_shared_layout_mapping.pb.js hook (runs via e.app, bypasses + * rules) and a real superuser session (also bypasses rules) - a normal + * user can never promote their own or anyone else's mapping through the + * API (see migration 6, which tightens `updateRule` after this one + * shipped - a real gap found by testing, not caught here). `deleteRule` + * lets an owner delete/retire their own still-private + * mapping, but not a mapping that's already shared (pulling it out from + * under other users who may already depend on it). + * + * layoutMappingVersions - a separate collection, not an embedded array + * on layoutMappings, because the Layouts page (CLAUDE.md §6.1 of the + * underlying spec) needs independently listable/comparable/roll-back- + * able versions, and PocketBase has no first-class way to query/filter + * into elements of a JSON array. Immutable history - `updateRule`/ + * `deleteRule` are both `null` (superuser-only; normally nobody touches + * one directly - a "rollback" creates a NEW version record instead of + * editing an old one). + */ +migrate((app) => { + let users = app.findCollectionByNameOrId('users') + let documents = app.findCollectionByNameOrId('documents') + + let layoutMappings = new Collection({ + type: 'base', + name: 'layoutMappings', + listRule: 'owner = @request.auth.id || status = "shared"', + viewRule: 'owner = @request.auth.id || status = "shared"', + createRule: 'owner = @request.auth.id', + updateRule: 'owner = @request.auth.id', + deleteRule: 'owner = @request.auth.id && status != "shared"', + fields: [ + { type: 'relation', name: 'owner', collectionId: users.id, required: true, maxSelect: 1 }, + { type: 'text', name: 'name', required: true }, + { type: 'text', name: 'bankLabel' }, + { type: 'text', name: 'accountTypeLabel' }, + { type: 'json', name: 'fingerprint', required: true }, + { type: 'text', name: 'fingerprintHash', required: true }, + { type: 'json', name: 'columnMap', required: true }, + { + type: 'select', name: 'dateFormat', maxSelect: 1, required: true, + values: ['textual', 'dmy', 'mdy', 'ymd'], + }, + { type: 'json', name: 'signConvention' }, + { type: 'json', name: 'ignoredRowRules' }, + { + type: 'select', name: 'status', maxSelect: 1, required: true, + values: ['private', 'shared', 'stale', 'retired'], + }, + { type: 'number', name: 'version', required: true }, + { type: 'relation', name: 'sourceDocument', collectionId: documents.id, maxSelect: 1 }, + { type: 'number', name: 'usageCount' }, + { type: 'number', name: 'failureCount' }, + { type: 'date', name: 'lastUsedAt' }, + { type: 'date', name: 'lastFailureAt' }, + { + type: 'select', name: 'promotedReason', maxSelect: 1, + values: ['second_user_confirmation', 'superuser_approved'], + }, + { type: 'date', name: 'promotedAt' }, + { type: 'text', name: 'approvedBySuperuser' }, + { type: 'autodate', name: 'created', onCreate: true }, + { type: 'autodate', name: 'updated', onCreate: true, onUpdate: true }, + ], + }) + app.save(layoutMappings) + + let layoutMappingVersions = new Collection({ + type: 'base', + name: 'layoutMappingVersions', + listRule: 'layoutMapping.owner = @request.auth.id || layoutMapping.status = "shared"', + viewRule: 'layoutMapping.owner = @request.auth.id || layoutMapping.status = "shared"', + createRule: 'layoutMapping.owner = @request.auth.id', + updateRule: null, + deleteRule: null, + fields: [ + { type: 'relation', name: 'layoutMapping', collectionId: layoutMappings.id, required: true, maxSelect: 1 }, + { type: 'number', name: 'versionNumber', required: true }, + { type: 'json', name: 'columnMap', required: true }, + { + type: 'select', name: 'dateFormat', maxSelect: 1, required: true, + values: ['textual', 'dmy', 'mdy', 'ymd'], + }, + { type: 'json', name: 'signConvention' }, + { type: 'json', name: 'ignoredRowRules' }, + { type: 'relation', name: 'createdBy', collectionId: users.id, maxSelect: 1 }, + { + type: 'select', name: 'source', maxSelect: 1, required: true, + values: ['user', 'tool', 'shared_library'], + }, + { type: 'text', name: 'note' }, + { type: 'autodate', name: 'created', onCreate: true }, + ], + }) + app.save(layoutMappingVersions) +}, (app) => { + try { app.delete(app.findCollectionByNameOrId('layoutMappingVersions')) } catch (e) {} + try { app.delete(app.findCollectionByNameOrId('layoutMappings')) } catch (e) {} +}) diff --git a/pocketbase/pb_migrations/5_add_layout_mapping_fields.js b/pocketbase/pb_migrations/5_add_layout_mapping_fields.js new file mode 100644 index 0000000..169f114 --- /dev/null +++ b/pocketbase/pb_migrations/5_add_layout_mapping_fields.js @@ -0,0 +1,27 @@ +/// + +/** + * Tracks which (if any) layout mapping a document was extracted with - + * null/"auto" for every statement the keyword/geometry detector (or the + * layout_quirks fallback) resolved on its own, which is every document + * before this migration and will stay true for HSBC/RBC-shaped layouts + * going forward too. `layoutFingerprintHash` is computed even on the + * auto path (see backend layout_fingerprint.py's own fingerprint_hash) - + * kept for future analytics, not read by anything yet. + */ +migrate((app) => { + let documents = app.findCollectionByNameOrId('documents') + let layoutMappings = app.findCollectionByNameOrId('layoutMappings') + documents.fields.add(new Field({ type: 'relation', name: 'layoutMappingUsed', collectionId: layoutMappings.id, maxSelect: 1 })) + documents.fields.add(new Field({ type: 'number', name: 'layoutMappingVersionUsed' })) + documents.fields.add(new Field({ type: 'select', name: 'layoutApplied', maxSelect: 1, values: ['auto', 'mapping'] })) + documents.fields.add(new Field({ type: 'text', name: 'layoutFingerprintHash' })) + app.save(documents) +}, (app) => { + let documents = app.findCollectionByNameOrId('documents') + documents.fields.removeByName('layoutMappingUsed') + documents.fields.removeByName('layoutMappingVersionUsed') + documents.fields.removeByName('layoutApplied') + documents.fields.removeByName('layoutFingerprintHash') + app.save(documents) +}) diff --git a/pocketbase/pb_migrations/6_fix_layout_mapping_update_rule.js b/pocketbase/pb_migrations/6_fix_layout_mapping_update_rule.js new file mode 100644 index 0000000..00c3b5a --- /dev/null +++ b/pocketbase/pb_migrations/6_fix_layout_mapping_update_rule.js @@ -0,0 +1,22 @@ +/// + +/** + * Closes a real gap found by testing, not assumed: PocketBase API rules + * gate WHO can update a record, not WHICH fields they change - the + * original migration 4's `updateRule` ("owner = @request.auth.id" alone) + * let an owner trivially self-promote their own mapping by PATCHing + * {"status": "shared"} directly, defeating the whole point of requiring + * a second user's independent confirmation (promote_shared_layout_ + * mapping.pb.js) or a real superuser session to promote one. Confirmed + * via a real PATCH against the live collection before this fix (it + * succeeded and shouldn't have) and after (now correctly rejected). + */ +migrate((app) => { + let layoutMappings = app.findCollectionByNameOrId('layoutMappings') + layoutMappings.updateRule = 'owner = @request.auth.id && @request.body.status != "shared"' + app.save(layoutMappings) +}, (app) => { + let layoutMappings = app.findCollectionByNameOrId('layoutMappings') + layoutMappings.updateRule = 'owner = @request.auth.id' + app.save(layoutMappings) +})