Skip to content

Commit a952e75

Browse files
committed
[Fix] stringify: arrayFormat: 'comma': do not throw on elements with no callable toString
The comma branch joins array elements with `Array.prototype.join` (since b84acba / v6.7.0), and under `encodeValuesOnly` first passes each element to `utils.encode`, whose `String(str)` coerces it the same way (since 4c4b23d / v6.11.1). An element with an own non-callable `toString`, as produced by `JSON.parse`, or by `qs.parse` under `allowPrototypes` or `plainObjects` (which yields null-prototype objects), made `stringify` throw `TypeError: Cannot convert object to primitive value`. Coerce such an element to its primitive `valueOf`, if any, or else to `Object.prototype.toString`, so it renders as `[object Object]`, the same as any other object element already does. Nested arrays are walked the way `join` walks them, with an array that is already being joined rendering as empty, as engines do for cycles. Every input that did not throw before serializes exactly as before, and a `toString` or `valueOf` that throws still propagates.
1 parent 07b1d4d commit a952e75

3 files changed

Lines changed: 161 additions & 3 deletions

File tree

‎lib/stringify.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ var stringify = function stringify(
153153
return v == null ? v : encoder(v);
154154
});
155155
}
156-
objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
156+
objKeys = [{ value: obj.length > 0 ? utils.toCoercible(obj).join(',') || null : void undefined }];
157157
} else if (isArray(filter)) {
158158
objKeys = filter;
159159
} else {

‎lib/utils.js‎

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,57 @@ var decode = function (str, defaultDecoder, charset) {
274274
}
275275
};
276276

277+
var hasToPrimitive = typeof Symbol === 'function' && typeof Symbol.toPrimitive === 'symbol';
278+
var arrayJoin = Array.prototype.join;
279+
var arrayToString = Array.prototype.toString;
280+
var objectToString = Object.prototype.toString;
281+
282+
// an object with no callable toString (eg, from JSON, or null-prototype) would make String() or join() throw,
283+
// so it becomes its primitive valueOf or else Object.prototype.toString; arrays are walked like join walks them,
284+
// copied only once an element changes, with an array already being joined becoming '' as engines do for cycles
285+
var toCoercible = function toCoercible(value, joining) {
286+
if (!value || (typeof value !== 'object' && typeof value !== 'function')) {
287+
return value;
288+
}
289+
if (hasToPrimitive && value[Symbol.toPrimitive] != null) {
290+
return value;
291+
}
292+
if (isArray(value) && value.toString === arrayToString && value.join === arrayJoin) {
293+
var ancestors = joining || getSideChannel();
294+
if (ancestors.has(value)) {
295+
return '';
296+
}
297+
ancestors.set(value, true);
298+
var copy;
299+
for (var i = 0; i < value.length; i += 1) {
300+
var item = value[i];
301+
var coerced = toCoercible(item, ancestors);
302+
if (!copy && coerced !== item) {
303+
copy = [];
304+
for (var j = 0; j < i; j += 1) {
305+
copy[j] = value[j];
306+
}
307+
}
308+
if (copy) {
309+
copy[i] = coerced;
310+
}
311+
}
312+
ancestors['delete'](value);
313+
return copy || value;
314+
}
315+
if (typeof value.toString === 'function') {
316+
return value;
317+
}
318+
var valueOf = value.valueOf;
319+
if (typeof valueOf === 'function') {
320+
var primitive = valueOf.call(value);
321+
if (!primitive || (typeof primitive !== 'object' && typeof primitive !== 'function')) {
322+
return String(primitive);
323+
}
324+
}
325+
return objectToString.call(value);
326+
};
327+
277328
var limit = 1024;
278329

279330
/* eslint operator-linebreak: [2, "before"] */
@@ -289,7 +340,7 @@ var encode = function encode(str, defaultEncoder, charset, kind, format) {
289340
if (typeof str === 'symbol') {
290341
string = Symbol.prototype.toString.call(str);
291342
} else if (typeof str !== 'string') {
292-
string = String(str);
343+
string = String(toCoercible(str));
293344
}
294345

295346
if (charset === 'iso-8859-1') {
@@ -447,5 +498,6 @@ module.exports = {
447498
isRegExp: isRegExp,
448499
markOverflow: markOverflow,
449500
maybeMap: maybeMap,
450-
merge: merge
501+
merge: merge,
502+
toCoercible: toCoercible
451503
};

‎test/stringify.js‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -865,6 +865,112 @@ test('stringify()', function (t) {
865865
st.end();
866866
});
867867

868+
t.test('arrayFormat=comma: does not crash on entries with no callable `toString`', function (st) {
869+
var json = JSON.parse('{ "a": ["b", { "toString": "x" }, "c"] }');
870+
st.equal(qs.stringify(json, { arrayFormat: 'comma' }), 'a=b%2C%5Bobject%20Object%5D%2Cc', 'JSON own `toString`');
871+
st.equal(qs.stringify(json, { arrayFormat: 'comma', encode: false }), 'a=b,[object Object],c', 'with encode: false');
872+
st.equal(
873+
qs.stringify(json, { arrayFormat: 'comma', encodeValuesOnly: true }),
874+
'a=b,%5Bobject%20Object%5D,c',
875+
'with encodeValuesOnly'
876+
);
877+
st.equal(
878+
qs.stringify(JSON.parse('{ "a": [{ "toString": "x" }] }'), { arrayFormat: 'comma', commaRoundTrip: true }),
879+
'a%5B%5D=%5Bobject%20Object%5D',
880+
'with commaRoundTrip'
881+
);
882+
st.equal(
883+
qs.stringify(JSON.parse('{ "a": [{ "toString": "x" }] }'), { arrayFormat: 'comma' }),
884+
qs.stringify({ a: [{ b: 1 }] }, { arrayFormat: 'comma' }),
885+
'renders the same as a plain object entry'
886+
);
887+
888+
st.equal(
889+
qs.stringify(qs.parse('a[][b]=c', { plainObjects: true }), { arrayFormat: 'comma' }),
890+
'a=%5Bobject%20Object%5D',
891+
'null-prototype entry from `parse` with plainObjects'
892+
);
893+
st.equal(
894+
qs.stringify(qs.parse('a[][b]=c', { plainObjects: true }), { arrayFormat: 'comma', encodeValuesOnly: true }),
895+
'a=%5Bobject%20Object%5D',
896+
'null-prototype entry from `parse` with plainObjects, with encodeValuesOnly'
897+
);
898+
st.equal(
899+
qs.stringify(qs.parse('a[0][toString]=x', { allowPrototypes: true }), { arrayFormat: 'comma' }),
900+
'a=%5Bobject%20Object%5D',
901+
'own `toString` entry from `parse` with allowPrototypes'
902+
);
903+
904+
var nested = JSON.parse('{ "a": [[1, [{ "toString": "x" }]], "y"] }');
905+
st.equal(qs.stringify(nested, { arrayFormat: 'comma', encode: false }), 'a=1,[object Object],y', 'nested array');
906+
st.equal(
907+
qs.stringify(nested, { arrayFormat: 'comma', encodeValuesOnly: true }),
908+
'a=1%2C%5Bobject%20Object%5D,y',
909+
'nested array, with encodeValuesOnly'
910+
);
911+
st.equal(qs.stringify({ a: [[1, 2], 3] }, { arrayFormat: 'comma', encode: false }), 'a=1,2,3', 'nested array is still flattened');
912+
913+
var cyclic = [{ toString: 'x' }];
914+
cyclic[cyclic.length] = cyclic;
915+
st.equal(
916+
qs.stringify({ a: cyclic }, { arrayFormat: 'comma', encode: false }),
917+
'a=[object Object],[object Object],',
918+
'cyclic nested array joins its cycle as empty'
919+
);
920+
921+
var customJoin = [{ toString: 'x' }];
922+
customJoin.join = function () { return 'j'; };
923+
st.equal(qs.stringify({ a: [customJoin, 'y'] }, { arrayFormat: 'comma', encode: false }), 'a=j,y', 'own `join` is still used');
924+
925+
st.equal(
926+
qs.stringify({ a: [{ toString: 'x', valueOf: function () { return 7; } }] }, { arrayFormat: 'comma' }),
927+
'a=7',
928+
'primitive `valueOf` is still used'
929+
);
930+
st.equal(
931+
qs.stringify({ a: [{ toString: 'x', valueOf: function () { return null; } }] }, { arrayFormat: 'comma' }),
932+
'a=null',
933+
'null `valueOf` is still used'
934+
);
935+
st.equal(
936+
qs.stringify({ a: [{ toString: 'x', valueOf: function () { return {}; } }] }, { arrayFormat: 'comma' }),
937+
'a=%5Bobject%20Object%5D',
938+
'non-primitive `valueOf` falls back'
939+
);
940+
941+
st.equal(
942+
qs.stringify({ a: [{ toString: function () { return 't'; } }, new Date(0)] }, { arrayFormat: 'comma', encode: false }),
943+
'a=t,1970-01-01T00:00:00.000Z',
944+
'callable `toString` and dates are unaffected'
945+
);
946+
947+
st['throws'](
948+
function () {
949+
qs.stringify({ a: [{ toString: function () { throw new SyntaxError('mine'); } }] }, { arrayFormat: 'comma' });
950+
},
951+
SyntaxError,
952+
'a throwing `toString` still throws'
953+
);
954+
st['throws'](
955+
function () {
956+
qs.stringify({ a: [{ toString: 'x', valueOf: function () { throw new EvalError('mine'); } }] }, { arrayFormat: 'comma' });
957+
},
958+
EvalError,
959+
'a throwing `valueOf` still throws'
960+
);
961+
962+
st.end();
963+
});
964+
965+
t.test('arrayFormat=comma: entries with `Symbol.toPrimitive` are unaffected', { skip: !hasSymbols() || typeof Symbol.toPrimitive !== 'symbol' }, function (st) {
966+
var entry = { toString: 'x' };
967+
entry[Symbol.toPrimitive] = function () { return 'p'; };
968+
st.equal(qs.stringify({ a: [entry] }, { arrayFormat: 'comma' }), 'a=p');
969+
st.equal(qs.stringify({ a: [entry] }, { arrayFormat: 'comma', encodeValuesOnly: true }), 'a=p');
970+
971+
st.end();
972+
});
973+
868974
t.test('stringifies a null object', { skip: !hasProto }, function (st) {
869975
st.equal(qs.stringify({ __proto__: null, a: 'b' }), 'a=b');
870976
st.end();

0 commit comments

Comments
 (0)