@posthog/core 1.48.6 → 1.48.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,8 +9,19 @@ import type {
9
9
  OtlpSeverityEntry,
10
10
  OtlpSeverityText,
11
11
  } from '@posthog/types'
12
+ import type { Logger } from '../types'
12
13
  import type { LogSdkContext, ResolvedPostHogLogsConfig } from './types'
13
14
  import { isArray, isBoolean, isNull, isNullish, isUndefined } from '../utils'
15
+ import {
16
+ CIRCULAR_VALUE,
17
+ FUNCTION_VALUE,
18
+ MAX_JSON_SAFE_VALUE_DEPTH,
19
+ MAX_JSON_SAFE_VALUE_ITEMS,
20
+ MAX_JSON_SAFE_VALUE_NODES,
21
+ sanitizeString,
22
+ TRUNCATED_VALUE,
23
+ UNSERIALIZABLE_VALUE,
24
+ } from '../utils/json-utils'
14
25
 
15
26
  // ============================================================================
16
27
  // Severity mapping
@@ -39,49 +50,192 @@ export function getOtlpSeverityNumber(level: LogSeverityLevel): number {
39
50
  // OTLP AnyValue conversion
40
51
  // ============================================================================
41
52
 
42
- export function toOtlpAnyValue(value: LogAttributeValue): OtlpAnyValue {
53
+ // 2^63 one past int64 max.
54
+ const INT64_RANGE_LIMIT = 9223372036854775808
55
+
56
+ const propertyIsEnumerable = Object.prototype.propertyIsEnumerable
57
+
58
+ interface EncodeState {
59
+ /** Containers on the current path, so a back-reference becomes a marker. */
60
+ ancestors: WeakSet<object>
61
+ remainingNodes: number
62
+ }
63
+
64
+ function newState(): EncodeState {
65
+ return { ancestors: new WeakSet(), remainingNodes: MAX_JSON_SAFE_VALUE_NODES }
66
+ }
67
+
68
+ export function toOtlpAnyValue(value: LogAttributeValue, logger?: Logger): OtlpAnyValue {
69
+ try {
70
+ return encodeAnyValue(value, logger, newState(), 0)
71
+ } catch {
72
+ // Runs inside `captureLog` and the metrics flush: an error escaping here
73
+ // surfaces in the caller's own code.
74
+ return { stringValue: UNSERIALIZABLE_VALUE }
75
+ }
76
+ }
77
+
78
+ export function toOtlpKeyValueList(attrs: Record<string, LogAttributeValue>, logger?: Logger): OtlpKeyValue[] {
79
+ try {
80
+ return encodeKeyValueList(attrs, logger, newState(), 0)
81
+ } catch {
82
+ return []
83
+ }
84
+ }
85
+
86
+ function encodeAnyValue(
87
+ value: LogAttributeValue,
88
+ logger: Logger | undefined,
89
+ state: EncodeState,
90
+ depth: number
91
+ ): OtlpAnyValue {
92
+ if (state.remainingNodes <= 0) {
93
+ return { stringValue: TRUNCATED_VALUE }
94
+ }
95
+ state.remainingNodes--
96
+
43
97
  if (isBoolean(value)) {
44
98
  return { boolValue: value }
45
99
  }
46
- // NOTE: typeof check (not core's isNumber) so NaN is included. core's
47
- // isNumber explicitly excludes NaN via the `x === x` guard, which would
48
- // route NaN through the JSON.stringify branch below — JSON has no
49
- // representation for non-finite floats and JSON.stringify turns them into
50
- // `null`, losing the value server-side. proto3 JSON mapping (which OTLP/HTTP
51
- // rides) requires the literal strings; we encode them as stringValue to keep
52
- // the human-readable signal regardless of which downstream parser sees them.
100
+ // typeof, not core's isNumber, which excludes NaN proto3 JSON distinguishes
101
+ // a non-finite float from an ordinary string.
53
102
  if (typeof value === 'number') {
54
103
  if (!Number.isFinite(value)) {
55
104
  return { stringValue: String(value) }
56
105
  }
57
106
  if (Number.isInteger(value)) {
58
- return { intValue: value }
107
+ if (Number.isSafeInteger(value)) {
108
+ return { intValue: String(value) }
109
+ }
110
+ // Past MAX_SAFE_INTEGER only BigInt gives the double's exact decimal:
111
+ // `String(-(2**63))` lands 192 below int64 min, outside the field it is
112
+ // about to be parsed into. Without BigInt the value rides as a string,
113
+ // which is never range-checked.
114
+ if (typeof BigInt === 'undefined') {
115
+ return { stringValue: String(value) }
116
+ }
117
+ const decimal = BigInt(value).toString()
118
+ if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
119
+ // An out-of-range intValue 400s the whole logs request; on the metrics
120
+ // path it is swallowed server-side and the metric just disappears.
121
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`)
122
+ return { stringValue: decimal }
123
+ }
124
+ return { intValue: decimal }
59
125
  }
60
126
  return { doubleValue: value }
61
127
  }
62
128
  if (typeof value === 'string') {
63
- return { stringValue: value }
129
+ return { stringValue: sanitizeString(value) }
64
130
  }
65
- if (isArray(value)) {
66
- return { arrayValue: { values: value.map((v) => toOtlpAnyValue(v as LogAttributeValue)) } }
131
+ // `String(value)` would put a function's source text on the wire.
132
+ if (typeof value === 'function') {
133
+ return { stringValue: FUNCTION_VALUE }
67
134
  }
68
- // Objects fall back to JSON. OTLP supports kvlistValue but the encoder
69
- // stays flat for simplicity.
70
- try {
71
- return { stringValue: JSON.stringify(value) }
72
- } catch {
135
+ if (typeof value === 'symbol') {
73
136
  return { stringValue: String(value) }
74
137
  }
138
+ if (typeof value === 'object' && value !== null) {
139
+ if (state.ancestors.has(value)) {
140
+ return { stringValue: CIRCULAR_VALUE }
141
+ }
142
+ if (depth >= MAX_JSON_SAFE_VALUE_DEPTH) {
143
+ return { stringValue: TRUNCATED_VALUE }
144
+ }
145
+ if (value instanceof Date) {
146
+ const time = value.getTime()
147
+ const iso = Number.isFinite(time) ? value.toISOString() : String(value)
148
+ // An overridden toISOString can return a non-string, which the server
149
+ // refuses for the whole request.
150
+ return { stringValue: typeof iso === 'string' ? sanitizeString(iso) : String(iso) }
151
+ }
152
+ // Registered before the toJSON probe: a toJSON returning a structure that
153
+ // references its own object is a cycle like any other.
154
+ state.ancestors.add(value)
155
+ try {
156
+ // The representation a value defines for itself — dayjs, Decimal, an ORM
157
+ // document, and a cross-realm Date that fails the `instanceof` above.
158
+ try {
159
+ const toJSON = (value as { toJSON?: unknown }).toJSON
160
+ if (typeof toJSON === 'function') {
161
+ return encodeAnyValue(toJSON.call(value) as LogAttributeValue, logger, state, depth + 1)
162
+ }
163
+ } catch {
164
+ // A throwing toJSON falls through to the plain walk.
165
+ }
166
+ if (isArray(value)) {
167
+ return { arrayValue: { values: encodeArrayValues(value, logger, state, depth + 1) } }
168
+ }
169
+ return {
170
+ kvlistValue: {
171
+ values: encodeKeyValueList(value as Record<string, LogAttributeValue>, logger, state, depth + 1),
172
+ },
173
+ }
174
+ } finally {
175
+ // Siblings that reference the same object are duplication, not a cycle.
176
+ state.ancestors.delete(value)
177
+ }
178
+ }
179
+ return { stringValue: sanitizeString(String(value)) }
180
+ }
181
+
182
+ function encodeArrayValues(
183
+ values: unknown[],
184
+ logger: Logger | undefined,
185
+ state: EncodeState,
186
+ depth: number
187
+ ): OtlpAnyValue[] {
188
+ const result: OtlpAnyValue[] = []
189
+ const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS)
190
+ let index = 0
191
+ for (; index < itemCount && state.remainingNodes > 0; index++) {
192
+ try {
193
+ const element = index in values ? values[index] : undefined
194
+ // Dropped, as iOS and Android do: proto3 JSON has no null AnyValue, and
195
+ // both `null` and `{}` here are rejected for the whole request.
196
+ if (isNullish(element)) {
197
+ continue
198
+ }
199
+ result.push(encodeAnyValue(element as LogAttributeValue, logger, state, depth))
200
+ } catch {
201
+ result.push({ stringValue: UNSERIALIZABLE_VALUE })
202
+ }
203
+ }
204
+ if (values.length > index) {
205
+ result.push({ stringValue: TRUNCATED_VALUE })
206
+ }
207
+ return result
75
208
  }
76
209
 
77
- export function toOtlpKeyValueList(attrs: Record<string, LogAttributeValue>): OtlpKeyValue[] {
210
+ function encodeKeyValueList(
211
+ attrs: Record<string, LogAttributeValue>,
212
+ logger: Logger | undefined,
213
+ state: EncodeState,
214
+ depth: number
215
+ ): OtlpKeyValue[] {
78
216
  const result: OtlpKeyValue[] = []
79
217
  for (const key in attrs) {
80
- const value = attrs[key]
81
- if (isNull(value) || isUndefined(value)) {
218
+ // for...in walks the prototype chain once own keys are exhausted. Skipped
219
+ // rather than broken out of: a proxy can yield keys in any order.
220
+ if (!propertyIsEnumerable.call(attrs, key)) {
82
221
  continue
83
222
  }
84
- result.push({ key, value: toOtlpAnyValue(value) })
223
+ if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
224
+ // Reported rather than written into the attributes: a synthetic key would
225
+ // land in the user's own namespace and could collide with a real one.
226
+ logger?.debug('Attributes truncated: the value exceeds the OTLP encoder budget')
227
+ break
228
+ }
229
+ try {
230
+ const value = attrs[key]
231
+ if (isNull(value) || isUndefined(value)) {
232
+ continue
233
+ }
234
+ result.push({ key: sanitizeString(key), value: encodeAnyValue(value, logger, state, depth) })
235
+ } catch {
236
+ // A getter that throws costs its own key, not the whole record.
237
+ result.push({ key: sanitizeString(key), value: { stringValue: UNSERIALIZABLE_VALUE } })
238
+ }
85
239
  }
86
240
  return result
87
241
  }
@@ -111,7 +265,22 @@ function timestampToUnixNano(): string {
111
265
  *
112
266
  * User-provided `options.attributes` always wins on conflicts.
113
267
  */
114
- export function buildOtlpLogRecord(options: CaptureLogOptions, sdkContext: LogSdkContext): OtlpLogRecord {
268
+ // `body` is only typed as a string. An untyped caller — or a `beforeSend` that
269
+ // rewrites it — can pass anything, and `String()` throws on a value whose
270
+ // `toString` does, or on a null-prototype object.
271
+ function encodeBody(body: string): string {
272
+ try {
273
+ return sanitizeString(String(body))
274
+ } catch {
275
+ return UNSERIALIZABLE_VALUE
276
+ }
277
+ }
278
+
279
+ export function buildOtlpLogRecord(
280
+ options: CaptureLogOptions,
281
+ sdkContext: LogSdkContext,
282
+ logger?: Logger
283
+ ): OtlpLogRecord {
115
284
  const level: LogSeverityLevel = options.level || 'info'
116
285
  const { text: severityText, number: severityNumber } = OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY
117
286
  const now = timestampToUnixNano()
@@ -146,9 +315,28 @@ export function buildOtlpLogRecord(options: CaptureLogOptions, sdkContext: LogSd
146
315
  autoAttributes.feature_flags = sdkContext.activeFeatureFlags
147
316
  }
148
317
 
149
- const mergedAttributes = {
150
- ...autoAttributes,
151
- ...(options.attributes || {}),
318
+ // Read key by key rather than spreading: a getter over a disposed store or a
319
+ // revoked proxy throws on the read itself, before the encoder's guards see it.
320
+ const mergedAttributes: Record<string, LogAttributeValue> = { ...autoAttributes }
321
+ const userAttributes = options.attributes
322
+ if (userAttributes) {
323
+ let keys: string[] = []
324
+ try {
325
+ keys = Object.keys(userAttributes)
326
+ } catch {
327
+ keys = []
328
+ }
329
+ for (const key of keys) {
330
+ let value: LogAttributeValue
331
+ try {
332
+ value = userAttributes[key]
333
+ } catch {
334
+ value = UNSERIALIZABLE_VALUE
335
+ }
336
+ // defineProperty, not assignment: `attributes['__proto__'] = v` hits the
337
+ // prototype setter and the attribute vanishes.
338
+ Object.defineProperty(mergedAttributes, key, { value, enumerable: true, writable: true, configurable: true })
339
+ }
152
340
  }
153
341
 
154
342
  const record: OtlpLogRecord = {
@@ -156,8 +344,8 @@ export function buildOtlpLogRecord(options: CaptureLogOptions, sdkContext: LogSd
156
344
  observedTimeUnixNano: now,
157
345
  severityNumber,
158
346
  severityText,
159
- body: { stringValue: options.body },
160
- attributes: toOtlpKeyValueList(mergedAttributes),
347
+ body: { stringValue: encodeBody(options.body) },
348
+ attributes: toOtlpKeyValueList(mergedAttributes, logger),
161
349
  }
162
350
 
163
351
  if (options.trace_id) {
@@ -169,10 +169,24 @@ describe('PostHogMetrics', () => {
169
169
 
170
170
  const attrs = sentMetrics()[0].sum!.dataPoints[0].attributes
171
171
  expect(attrs).toContainEqual({ key: 'route', value: { stringValue: '/home' } })
172
- expect(attrs).toContainEqual({ key: 'retries', value: { intValue: 2 } })
172
+ expect(attrs).toContainEqual({ key: 'retries', value: { intValue: '2' } })
173
173
  expect(attrs).toContainEqual({ key: 'cached', value: { boolValue: true } })
174
174
  })
175
175
 
176
+ // The encoder is shared with logs, so the debug line it emits on the
177
+ // out-of-range path only reaches anyone if metrics passes its logger down.
178
+ it('encodes an out-of-int64 attribute as a string and reports it through the logger', async () => {
179
+ const metrics = createMetrics()
180
+ metrics.count('api_calls', 1, { attributes: { huge: 2 ** 63 } as any })
181
+ await metrics.flush()
182
+
183
+ const attrs = sentMetrics()[0].sum!.dataPoints[0].attributes
184
+ expect(attrs).toContainEqual({ key: 'huge', value: { stringValue: '9223372036854775808' } })
185
+ expect((logger.debug as jest.Mock).mock.calls.some((c) => String(c[0]).includes('outside the int64 range'))).toBe(
186
+ true
187
+ )
188
+ })
189
+
176
190
  it('stamps delta data points with a window: startTimeUnixNano <= timeUnixNano, both nano strings', async () => {
177
191
  const metrics = createMetrics()
178
192
  metrics.count('orders_created', 1)
@@ -374,7 +374,7 @@ export class PostHogMetrics {
374
374
  byMetric.set(metricKey, metric)
375
375
  }
376
376
 
377
- const attributes = toOtlpKeyValueList(state.attributes ?? {})
377
+ const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger)
378
378
  const startNano = msToUnixNano(state.windowStartMs)
379
379
 
380
380
  if (state.type === 'count') {
@@ -3,7 +3,9 @@ import { FetchLike } from '../types'
3
3
  export * from './bot-detection'
4
4
  export * from './browser-utils'
5
5
  export * from './bucketed-rate-limiter'
6
- export * from './json-utils'
6
+ // Named rather than `export *`: the budgets, markers and `sanitizeString` are
7
+ // shared with the OTLP encoder but are not public API.
8
+ export { toJsonSafeValue } from './json-utils'
7
9
  export * from './number-utils'
8
10
  export * from './string-utils'
9
11
  export * from './type-utils'
@@ -1,10 +1,12 @@
1
- const MAX_JSON_SAFE_VALUE_DEPTH = 20
2
- const MAX_JSON_SAFE_VALUE_ITEMS = 1_000
3
- const MAX_JSON_SAFE_VALUE_NODES = 10_000
4
- const CIRCULAR_VALUE = '[Circular]'
5
- const TRUNCATED_VALUE = '[Truncated]'
6
- const UNSERIALIZABLE_VALUE = '[Unserializable]'
7
- const FUNCTION_VALUE = '[Function]'
1
+ /** Traversal budgets and markers, shared with the OTLP attribute encoder. Not
2
+ * public API — `utils/index.ts` re-exports `toJsonSafeValue` only. */
3
+ export const MAX_JSON_SAFE_VALUE_DEPTH = 20
4
+ export const MAX_JSON_SAFE_VALUE_ITEMS = 1_000
5
+ export const MAX_JSON_SAFE_VALUE_NODES = 10_000
6
+ export const CIRCULAR_VALUE = '[Circular]'
7
+ export const TRUNCATED_VALUE = '[Truncated]'
8
+ export const UNSERIALIZABLE_VALUE = '[Unserializable]'
9
+ export const FUNCTION_VALUE = '[Function]'
8
10
 
9
11
  const dateGetTime = Date.prototype.getTime
10
12
  const dateToISOString = Date.prototype.toISOString
@@ -15,7 +17,12 @@ interface JsonSafeValueConversionState {
15
17
  remainingNodes: number
16
18
  }
17
19
 
18
- function sanitizeString(value: string): string {
20
+ /**
21
+ * Replaces unpaired surrogates with U+FFFD. A lone surrogate survives
22
+ * `JSON.stringify` as a `\uD800`-style escape, which strict JSON parsers
23
+ * reject — for OTLP that means the whole request is refused.
24
+ */
25
+ export function sanitizeString(value: string): string {
19
26
  let output = ''
20
27
  for (let index = 0; index < value.length; index++) {
21
28
  const codeUnit = value.charCodeAt(index)