A local-first personal finance app
[AI] Respect OFX ENCODING/CHARSET headers when importing files (#8874)
flafleur9766aaac6876
diff --git a/packages/loot-core/src/mocks/files/1252.qfx b/packages/loot-core/src/mocks/files/1252.qfxnew file mode 100644index 0000000000..1fa1f144e4--- /dev/null+++ b/packages/loot-core/src/mocks/files/1252.qfx@@ -0,0 +1,63 @@+OFXHEADER:100+DATA:OFXSGML+VERSION:102+SECURITY:TYPE1+ENCODING:USASCII+CHARSET:1252+COMPRESSION:NONE+OLDFILEUID:NONE+NEWFILEUID:NONE+<OFX>+<SIGNONMSGSRSV1>+<SONRS>+<STATUS>+<CODE>0+<SEVERITY>INFO+<MESSAGE>OK+</STATUS>+<DTSERVER>20221020231556+<USERKEY>3AAAAAAAAAAAAAA+<INTU.BID>00999+<LANGUAGE>FRA+</SONRS>+</SIGNONMSGSRSV1>+<BANKMSGSRSV1>+<STMTTRNRS>+<TRNUID>AAAA-2022102023155614357+<STATUS>+<CODE>0+<SEVERITY>INFO+<MESSAGE>OK+</STATUS>+<STMTRS>+<CURDEF>CAD+<BANKACCTFROM>+<BANKID>700012345+<BRANCHID>0055666+<ACCTID>999-12345-0055666-EOP+<ACCTTYPE>CHECKING+</BANKACCTFROM>+<BANKTRANLIST>+<DTSTART>20221019120000+<DTEND>20221019120000+<STMTTRN>+<TRNTYPE>DEBIT+<DTPOSTED>20221019120000+<TRNAMT>-20.00+<FITID>cafe1252xx+<NAME>Caf� M�tro �uro+<MEMO>Paiement 5� � d�bit+</STMTTRN>+</BANKTRANLIST>+<LEDGERBAL>+<BALAMT>9999.99+<DTASOF>20221020231556+</LEDGERBAL>+<AVAILBAL>+<BALAMT>9999.99+<DTASOF>20221020231556+</AVAILBAL>+</STMTRS>+</STMTTRNRS>+</BANKMSGSRSV1>+</OFX>diff --git a/packages/loot-core/src/mocks/files/8859-1.qfx b/packages/loot-core/src/mocks/files/8859-1.qfxindex dc531c85b3..8ed5850a1a 100644--- a/packages/loot-core/src/mocks/files/8859-1.qfx+++ b/packages/loot-core/src/mocks/files/8859-1.qfx@@ -45,8 +45,8 @@ NEWFILEUID:NONE<DTPOSTED>20221019120000<TRNAMT>-20.00<FITID>wSoKuCS77-<NAME>Paiement facture/Carte prépayée-<MEMO>PWW+<NAME>Paiement facture/Carte pr�pay�e+<MEMO>M�mo test: ����������</STMTTRN></BANKTRANLIST><LEDGERBAL>diff --git a/packages/loot-core/src/mocks/files/utf-8.qfx b/packages/loot-core/src/mocks/files/utf-8.qfxnew file mode 100644index 0000000000..ea4aed798e--- /dev/null+++ b/packages/loot-core/src/mocks/files/utf-8.qfx@@ -0,0 +1,63 @@+OFXHEADER:100+DATA:OFXSGML+VERSION:102+SECURITY:TYPE1+ENCODING:UTF-8+CHARSET:NONE+COMPRESSION:NONE+OLDFILEUID:NONE+NEWFILEUID:NONE+<OFX>+<SIGNONMSGSRSV1>+<SONRS>+<STATUS>+<CODE>0+<SEVERITY>INFO+<MESSAGE>OK+</STATUS>+<DTSERVER>20221020231556+<USERKEY>3AAAAAAAAAAAAAA+<INTU.BID>00999+<LANGUAGE>FRA+</SONRS>+</SIGNONMSGSRSV1>+<BANKMSGSRSV1>+<STMTTRNRS>+<TRNUID>AAAA-2022102023155614357+<STATUS>+<CODE>0+<SEVERITY>INFO+<MESSAGE>OK+</STATUS>+<STMTRS>+<CURDEF>CAD+<BANKACCTFROM>+<BANKID>700012345+<BRANCHID>0055666+<ACCTID>999-12345-0055666-EOP+<ACCTTYPE>CHECKING+</BANKACCTFROM>+<BANKTRANLIST>+<DTSTART>20221019120000+<DTEND>20221019120000+<STMTTRN>+<TRNTYPE>DEBIT+<DTPOSTED>20221019120000+<TRNAMT>-20.00+<FITID>cafeUtf8xx+<NAME>Café Métro €uro+<MEMO>Paiement 5€ — débit+</STMTTRN>+</BANKTRANLIST>+<LEDGERBAL>+<BALAMT>9999.99+<DTASOF>20221020231556+</LEDGERBAL>+<AVAILBAL>+<BALAMT>9999.99+<DTASOF>20221020231556+</AVAILBAL>+</STMTRS>+</STMTTRNRS>+</BANKMSGSRSV1>+</OFX>diff --git a/packages/loot-core/src/server/transactions/import/__snapshots__/parse-file.test.ts.snap b/packages/loot-core/src/server/transactions/import/__snapshots__/parse-file.test.ts.snapindex f8a7c916db..53e5e73779 100644--- a/packages/loot-core/src/server/transactions/import/__snapshots__/parse-file.test.ts.snap+++ b/packages/loot-core/src/server/transactions/import/__snapshots__/parse-file.test.ts.snap@@ -194,6 +194,37 @@ exports[`File import > CAMT.053 import works 1`] = `]`;+exports[`File import > handles UTF-8 encoding 1`] = `+[+ {+ "acct": "one",+ "amount": -2000,+ "category": null,+ "cleared": 1,+ "date": 20221019,+ "description": "id2",+ "error": null,+ "financial_id": "cafeUtf8xx",+ "id": "id3",+ "imported_description": "Café Métro €uro",+ "isChild": 0,+ "isParent": 0,+ "location": null,+ "notes": "Paiement 5€ — débit",+ "parent_id": null,+ "pending": 0,+ "raw_synced_data": null,+ "reconciled": 0,+ "schedule": null,+ "sort_order": 123456789,+ "starting_balance_flag": 0,+ "tombstone": 0,+ "transferred_id": null,+ "type": null,+ },+]+`;+exports[`File import > handles html escaped plaintext 1`] = `[{@@ -267,7 +298,38 @@ exports[`File import > handles non-ASCII characters 1`] = `"isChild": 0,"isParent": 0,"location": null,- "notes": "PWW",+ "notes": "Mémo test: àÀçéÉèêëôû",+ "parent_id": null,+ "pending": 0,+ "raw_synced_data": null,+ "reconciled": 0,+ "schedule": null,+ "sort_order": 123456789,+ "starting_balance_flag": 0,+ "tombstone": 0,+ "transferred_id": null,+ "type": null,+ },+]+`;++exports[`File import > handles windows-1252 charset 1`] = `+[+ {+ "acct": "one",+ "amount": -2000,+ "category": null,+ "cleared": 1,+ "date": 20221019,+ "description": "id2",+ "error": null,+ "financial_id": "cafe1252xx",+ "id": "id3",+ "imported_description": "Café Métro €uro",+ "isChild": 0,+ "isParent": 0,+ "location": null,+ "notes": "Paiement 5€ — débit","parent_id": null,"pending": 0,"raw_synced_data": null,diff --git a/packages/loot-core/src/server/transactions/import/ofx2json.ts b/packages/loot-core/src/server/transactions/import/ofx2json.tsindex 791857abcf..649e28605c 100644--- a/packages/loot-core/src/server/transactions/import/ofx2json.ts+++ b/packages/loot-core/src/server/transactions/import/ofx2json.ts@@ -123,9 +123,42 @@ function mapOfxTransaction(stmtTrn): OFXTransaction {};}-export async function ofx2json(ofx: string): Promise<OFXParseResult> {+function decodeOfxBytes(bytes: Uint8Array): string {+ // OFX headers are always ASCII. Peek at the header section to detect+ // the declared encoding before decoding the full content.+ const headerPreview = new TextDecoder('latin1').decode(+ bytes.subarray(0, 2048),+ );++ const encodingMatch = headerPreview.match(/^ENCODING:(.+)/m);+ const charsetMatch = headerPreview.match(/^CHARSET:(.+)/m);++ const encoding = encodingMatch?.[1]?.trim().toUpperCase();+ const charset = charsetMatch?.[1]?.trim().toUpperCase();++ if (encoding === 'UTF-8') {+ return new TextDecoder('utf-8').decode(bytes);+ }++ // ENCODING:USASCII — use CHARSET to pick the right code page+ if (charset === '8859-1') {+ return new TextDecoder('iso-8859-1').decode(bytes);+ }+ if (charset === '1252') {+ return new TextDecoder('windows-1252').decode(bytes);+ }++ // Default: UTF-8 (ASCII is a subset; modern default)+ return new TextDecoder('utf-8').decode(bytes);+}++export async function ofx2json(+ ofx: string | Uint8Array,+): Promise<OFXParseResult> {+ const ofxString = typeof ofx === 'string' ? ofx : decodeOfxBytes(ofx);+// firstly, split into the header attributes and the footer sgml- const contents = ofx.split(/<OFX\s?>/, 2);+ const contents = ofxString.split(/<OFX\s?>/, 2);// firstly, parse the headersconst headerString = contents[0].split(/\r?\n/);diff --git a/packages/loot-core/src/server/transactions/import/parse-file.test.ts b/packages/loot-core/src/server/transactions/import/parse-file.test.tsindex 408a0f937f..335f8594ba 100644--- a/packages/loot-core/src/server/transactions/import/parse-file.test.ts+++ b/packages/loot-core/src/server/transactions/import/parse-file.test.ts@@ -207,6 +207,34 @@ describe('File import', () => {expect(await getTransactions('one')).toMatchSnapshot();});+ test('handles windows-1252 charset', async () => {+ await prefs.loadPrefs();+ await db.insertAccount({ id: 'one', name: 'one' });++ const { errors } = await importFileWithRealTime(+ 'one',+ __dirname + '/../../../mocks/files/1252.qfx',+ 'yyyy-MM-dd',+ { importNotes: true },+ );+ expect(errors.length).toBe(0);+ expect(await getTransactions('one')).toMatchSnapshot();+ });++ test('handles UTF-8 encoding', async () => {+ await prefs.loadPrefs();+ await db.insertAccount({ id: 'one', name: 'one' });++ const { errors } = await importFileWithRealTime(+ 'one',+ __dirname + '/../../../mocks/files/utf-8.qfx',+ 'yyyy-MM-dd',+ { importNotes: true },+ );+ expect(errors.length).toBe(0);+ expect(await getTransactions('one')).toMatchSnapshot();+ });+test('handles html escaped plaintext', async () => {await prefs.loadPrefs();await db.insertAccount({ id: 'one', name: 'one' });diff --git a/packages/loot-core/src/server/transactions/import/parse-file.ts b/packages/loot-core/src/server/transactions/import/parse-file.tsindex f2941af385..26bffc74cd 100644--- a/packages/loot-core/src/server/transactions/import/parse-file.ts+++ b/packages/loot-core/src/server/transactions/import/parse-file.ts@@ -204,7 +204,7 @@ async function parseOFX(options: ParseFileOptions,): Promise<ParseFileResult> {const errors = Array<ParseError>();- const contents = await fs.readFile(filepath);+ const contents = await fs.readFile(filepath, 'binary');let data: Awaited<ReturnType<typeof ofx2json>>;try {diff --git a/upcoming-release-notes/fix-ofx-charset-decoding.md b/upcoming-release-notes/fix-ofx-charset-decoding.mdnew file mode 100644index 0000000000..8bf7cca26e--- /dev/null+++ b/upcoming-release-notes/fix-ofx-charset-decoding.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [flafleur]+---++Fix corrupted accented characters when importing OFX/QFX files.