diff --git a/src/engine/operations/encodings.ts b/src/engine/operations/encodings.ts index a90236c..ef55586 100644 --- a/src/engine/operations/encodings.ts +++ b/src/engine/operations/encodings.ts @@ -1,4 +1,5 @@ import { runtime } from '../runtime'; +import { checkSize } from '../runtime/limits'; import { OperationError } from '../types'; import { asBytes, bytesToLatin1 } from '../core/bytes'; import { DELIMITER_OPTIONS, delimiterFor, splitOnAnyDelimiter } from '../core/delimiters'; @@ -277,9 +278,12 @@ function fromUuencode(text: string): Uint8Array { if (line.length === 0 || /^(begin|end)\b/.test(line) || line === '`') continue; const length = (line.charCodeAt(0) - 32) & 0x3f; if (length === 0) continue; + checkSize(out.length + length); const decoded: number[] = []; - for (let i = 1; i + 3 < line.length + 1; i += 4) { + // Missing trailing characters read as zero: encoders that write a space for zero + // lose them whenever trailing whitespace is stripped. + for (let i = 1; decoded.length < length; i += 4) { const values = [0, 1, 2, 3].map((k) => ((line.charCodeAt(i + k) || 96) - 32) & 0x3f); const triple = (values[0]! << 18) | (values[1]! << 12) | (values[2]! << 6) | values[3]!; decoded.push((triple >> 16) & 0xff, (triple >> 8) & 0xff, triple & 0xff); diff --git a/src/engine/tests/operations.verified.test.ts b/src/engine/tests/operations.verified.test.ts index 4bb28ff..e29108f 100644 --- a/src/engine/tests/operations.verified.test.ts +++ b/src/engine/tests/operations.verified.test.ts @@ -3,6 +3,7 @@ import { bake, encodeInput, renderText } from '../index'; import { getOperation, TEXT_OPERATION_IDS } from '../operations'; import { rewrap } from '../core/rewrap'; import { tryDecodeUtf8 } from '../core/bytes'; +import { MAX_OUTPUT } from '../runtime/limits'; import type { Recipe, RecipeStep } from '../types'; type Value = string | number | boolean; @@ -74,6 +75,18 @@ describe('text and encoding operations give the published answers', () => { expect(await roundTrip('Cat and dog, 123!', 'to-uuencode', 'from-uuencode')).toBe('Cat and dog, 123!'); }); + it('UUdecode keeps the last bytes of a line whose trailing spaces were stripped', async () => { + expect(await text('begin 644 f\n%2&5L;&\\ \n`\nend', 'from-uuencode')).toBe('Hello'); + expect(await text('begin 644 f\n%2&5L;&\\\n`\nend', 'from-uuencode')).toBe('Hello'); + expect(toHex(await bytesOut('begin 644 f\n#0P\n`\nend', 'from-uuencode'))).toBe('430000'); + }); + + it('UUdecode stops at the output limit instead of filling memory', () => { + const lines = Math.floor(MAX_OUTPUT / 63) + 1; + const input = 'begin 644 f\n' + '_\n'.repeat(lines) + '`\nend'; + expect(() => getOperation('from-uuencode')!.run(input, [])).toThrow(/processing limit/); + }); + it('Charcode turns characters into numbers and back', async () => { const codes = await text('Hi', ['to-charcode', { Base: '16' }]); expect(codes).toMatch(/48/);