Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: safer string truncation #1478

Closed
wants to merge 28 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
fcee0ba
feat: safer string truncation
pauldambra Oct 16, 2024
e1f244d
add array from polyfill
pauldambra Oct 16, 2024
03e6811
doh
pauldambra Oct 16, 2024
8397e42
move the file :/
pauldambra Oct 16, 2024
8eab37e
now?
pauldambra Oct 16, 2024
bdcc00e
i too love ie11
pauldambra Oct 16, 2024
1a9bc63
i too love ie11
pauldambra Oct 16, 2024
d47c568
i too love ie11
pauldambra Oct 16, 2024
4fe7d68
i too love ie11
pauldambra Oct 16, 2024
3b2a40d
what about a real polyfill
pauldambra Oct 16, 2024
fe3cdab
what about a real polyfill
pauldambra Oct 16, 2024
fd6439d
i too love ie11
pauldambra Oct 16, 2024
7722bc2
maybe like this
pauldambra Oct 16, 2024
4f663f9
maybe like this
pauldambra Oct 16, 2024
0b8e64b
maybe like this
pauldambra Oct 16, 2024
c3e711a
maybe like this
pauldambra Oct 16, 2024
aa7e5b9
maybe like this
pauldambra Oct 16, 2024
ae4b834
maybe like this
pauldambra Oct 16, 2024
1a5d456
maybe like this
pauldambra Oct 16, 2024
6313e1d
Merge branch 'main' into feat/safer-string-truncation
pauldambra Oct 17, 2024
5eaa5f1
fix
pauldambra Oct 17, 2024
33dcc0e
wat
pauldambra Oct 17, 2024
f2f0f9f
arbitrary timeouts
pauldambra Oct 17, 2024
aa38206
Merge branch 'main' into feat/safer-string-truncation
pauldambra Oct 17, 2024
c718cb6
Merge branch 'main' into feat/safer-string-truncation
pauldambra Oct 21, 2024
80d7709
🤷
pauldambra Nov 21, 2024
16488b7
Merge branch 'main' into feat/safer-string-truncation
pauldambra Nov 29, 2024
8ae10ba
Merge branch 'main' into feat/safer-string-truncation
pauldambra Dec 17, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
{
"presets": ["@babel/env", ["@babel/typescript", { "jsxPragma": "h" }]],
"plugins": [
"@babel/plugin-transform-nullish-coalescing-operator",
[
"@babel/transform-react-jsx",
{
"runtime": "automatic",
"importSource": "preact"
}
]
"presets": [
[
"@babel/env",
{
"targets": ">0.5%, last 2 versions, Firefox ESR, not dead"
}
],
[
"@babel/typescript",
{
"jsxPragma": "h"
}
]
],
"plugins": [
"@babel/plugin-transform-nullish-coalescing-operator",
[
"@babel/transform-react-jsx",
{
"runtime": "automatic",
"importSource": "preact"
}
]
]
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@
]
},
"browserslist": [
"> 0.5%, last 2 versions, Firefox ESR, not dead, IE 11"
">0.5%, last 2 versions, Firefox ESR, not dead"
],
"pnpm": {
"patchedDependencies": {
Expand Down
6 changes: 6 additions & 0 deletions playground/segment/server.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
// eslint-disable-next-line @typescript-eslint/no-require-imports,no-undef
const path = require('path')
// eslint-disable-next-line @typescript-eslint/no-require-imports,no-undef
const express = require('express')
const app = express()
const port = 3001

// eslint-disable-next-line no-undef
app.use('/static', express.static(__dirname + '/../../dist'))

app.get('/segment.html', function (req, res) {
// eslint-disable-next-line no-undef
res.sendFile(__dirname + '/segment.html')
})

app.get('/static/recorder.js', function (req, res) {
// eslint-disable-next-line no-undef
let filePath = path.join(__dirname, '/../../node_modules/rrweb/dist/rrweb.js')
res.sendFile(filePath)
})

app.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`Example Segment app listening on port ${port}`)
})
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,8 @@ describe(`SessionRecording utility functions`, () => {
data: {
plugin: CONSOLE_LOG_PLUGIN_NAME,
payload: {
payload: ['a', largeString.slice(0, 2000) + '...[truncated]'],
// 14 is the length of the '...[truncated]' string
payload: ['a', largeString.slice(0, 2000 - 14) + '...[truncated]'],
},
},
})
Expand Down
37 changes: 37 additions & 0 deletions src/__tests__/utils/string-utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { truncateString } from '../../utils/string-utils'

describe('string-utils', () => {
it.each([
// Basic string truncation without suffix
['hello world', 5, undefined, 'hello'],

// Basic string truncation without suffix
['hello world ', 15, undefined, 'hello world'],

// String with surrogate pair (emoji)
['hello 😄 world', 7, undefined, 'hello 😄'],

// String with surrogate pair, truncated in the middle of the emoji
['hello 😄 world', 6, undefined, 'hello'],

// Truncation with a suffix added
['hello world', 5, '...', 'he...'],

// Handling whitespace and suffix
[' hello world ', 7, '...', 'hell...'],

// Empty string with suffix
['', 5, '-', ''],

// invalid input string with suffix
[null, 5, '-', ''],

// Truncation without a suffix and with an emoji
['hello 😄 world', 8, undefined, 'hello 😄'],
])(
'should truncate string "%s" to max length %d with suffix "%s" and return "%s"',
(input: string, maxLength: number, suffix: string | undefined, expected: string) => {
expect(truncateString(input, maxLength, suffix)).toEqual(expected)
}
)
})
15 changes: 8 additions & 7 deletions src/extensions/replay/sessionrecording-utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { eventWithTime, listenerHandler, pluginEvent } from '@rrweb/types'
import type { record } from '@rrweb/record'

import { isObject } from '../../utils/type-utils'
import { isNullish, isObject } from '../../utils/type-utils'
import { SnapshotBuffer } from './sessionrecording'
import { truncateString } from '../../utils/string-utils'

// taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#circular_references
export function circularReferenceReplacer() {
Expand Down Expand Up @@ -109,15 +110,15 @@ export function truncateLargeConsoleLogs(_event: eventWithTime) {
}
const updatedPayload = []
for (let i = 0; i < event.data.payload.payload.length; i++) {
if (
event.data.payload.payload[i] && // Value can be null
event.data.payload.payload[i].length > MAX_STRING_SIZE
) {
updatedPayload.push(event.data.payload.payload[i].slice(0, MAX_STRING_SIZE) + '...[truncated]')
} else {
if (isNullish(event.data.payload.payload[i])) {
// we expect nullish values to be logged unchanged,
// TODO test if this is still necessary https://github.com/PostHog/posthog-js/pull/385
updatedPayload.push(event.data.payload.payload[i])
} else {
updatedPayload.push(truncateString(event.data.payload.payload[i], MAX_STRING_SIZE, '...[truncated]'))
}
}

event.data.payload.payload = updatedPayload
// Return original type
return _event
Expand Down
3 changes: 2 additions & 1 deletion src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Breaker, EventHandler, Properties } from '../types'
import { hasOwnProperty, isArray, isFormData, isFunction, isNull, isNullish, isString } from './type-utils'
import { logger } from './logger'
import { nativeForEach, nativeIndexOf, window } from './globals'
import { truncateString } from './string-utils'

const breaker: Breaker = {}

Expand Down Expand Up @@ -207,7 +208,7 @@ export function _copyAndTruncateStrings<T extends Record<string, any> = Record<s
): T {
return deepCircularCopy(object, (value: any) => {
if (isString(value) && !isNull(maxStringLength)) {
return (value as string).slice(0, maxStringLength)
return truncateString(value, maxStringLength)
}
return value
}) as T
Expand Down
19 changes: 19 additions & 0 deletions src/utils/string-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Truncate a string to a maximum length and optionally append a suffix only if the string is longer than the maximum length.
*/
export const truncateString = (str: unknown, maxLength: number, suffix?: string): string => {
if (typeof str !== 'string') {
return ''
}

const trimmedSuffix = suffix?.trim()
const trimmedStr = str.trim()

let sliceLength = maxLength
if (trimmedSuffix?.length) {
sliceLength -= trimmedSuffix.length
}
const sliced = Array.from(trimmedStr).slice(0, sliceLength).join('').trim()
const addSuffix = trimmedStr.length > maxLength
return sliced + (addSuffix ? trimmedSuffix || '' : '')
}
Loading