Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Proxy validation and how to bypass it in JavaScript

58 Validation on assignment, and the way round it

hard

Wrap an order object so every write is validated: an unknown field is refused and a bad value throws with the field named. Then prove two things — that a set trap returning false throws in strict mode, and that Object.defineProperty walks straight past a set trap unless you trap that too.

Stuck? Three hints, smallest first
  1. 1. The set trap must return true when it accepts the write. Returning nothing counts as a refusal.
  2. 2. Reflect.set(target, key, value, receiver) both performs the write and gives you the boolean to return.
  3. 3. Object.defineProperty is a different internal operation. It has its own trap.

The answer

const rules = {
  customer: (v) => (typeof v === 'string' && v.trim() !== '' ? '' : 'must be a name'),
  amount: (v) => (Number.isInteger(v) && v > 0 ? '' : 'must be a positive whole number of naira'),
};
const check = (key, value) => {
  const rule = rules[key];
  if (!rule) throw new TypeError('no such field: ' + String(key));
  const complaint = rule(value);
  if (complaint) throw new TypeError(String(key) + ' ' + complaint);
};

const validated = (target) => new Proxy(target, {
  set(t, key, value, receiver) {
    check(key, value);
    return Reflect.set(t, key, value, receiver);      // returns true, which the trap must
  },
  defineProperty(t, key, desc) {
    if ('value' in desc) check(key, desc.value);      // or defineProperty slips past set
    return Reflect.defineProperty(t, key, desc);
  },
});

const attempt = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.message; } };
const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };

const raw = {};
const order = validated(raw);
order.customer = 'Adaeze';
order.amount = 25000;
const accepted = { ...order };

const badAmount = attempt(() => { order.amount = -500; });
const badName = attempt(() => { order.customer = '   '; });
const unknownField = attempt(() => { order.status = 'paid'; });
const targetAfter = { ...raw };

const viaDefine = attempt(() => Object.defineProperty(order, 'amount', { value: -999 }));

// A trap that refuses by returning false rather than throwing.
const refuses = new Proxy({}, { set: () => false });
const strictWrite = attemptName(() => { refuses.anything = 1; });
const reflectWrite = Reflect.set(refuses, 'anything', 1);

// The same object with only a set trap: defineProperty is not checked at all.
const setOnly = new Proxy({}, { set() { throw new Error('no writes allowed'); } });
Object.defineProperty(setOnly, 'amount', { value: -999, enumerable: true, configurable: true });
const slippedThrough = setOnly.amount;

console.log('accepted   :', accepted);
console.log('rejections :', [badAmount, badName, unknownField]);
console.log('defineProp :', viaDefine, '| unguarded:', slippedThrough);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('valid writes land on the target', [accepted, targetAfter], [{ customer: 'Adaeze', amount: 25000 }, { customer: 'Adaeze', amount: 25000 }]);
test('a bad value throws with the field named', [badAmount, badName], ['amount must be a positive whole number of naira', 'customer must be a name']);
test('a field with no rule is refused rather than silently accepted', unknownField, 'no such field: status');
test('and nothing rejected reached the object', Object.keys(targetAfter), ['customer', 'amount']);
test('trapping defineProperty closes the second door in', viaDefine, 'amount must be a positive whole number of naira');
test('with only a set trap, defineProperty writes -999 straight past it', slippedThrough, -999);
test('a set trap returning false throws a TypeError in strict mode', strictWrite, 'TypeError');
test('while Reflect.set reports the same refusal as a boolean', reflectWrite, false);

Two doors lead into an object, and a validator that guards one is not a validator. obj.k = v goes through [[Set]]; Object.defineProperty and Object.assign-style descriptor writes go through [[DefineOwnProperty]]. The sixth assertion is the whole point: a proxy with a set trap that throws on every write accepted -999 without complaint, because defineProperty never asked it.

The return true is not ceremony. A set trap reports success as a boolean, and a trap that falls off the end returns undefined, which reads as a refusal. Under "use strict" — which every module, every class body and every panel on this page is — a refused write is a TypeError, not a silent no-op. That is the pairing in the last two assertions: refuses.anything = 1 throws, Reflect.set(refuses, 'anything', 1) returns false. Same operation, one reports by throwing and one by value, which is exactly why Reflect exists.

Throwing from inside the trap, as this one does for a bad value, is usually kinder than returning false: the caller gets a message naming the field instead of an engine-worded TypeError saying a trap returned something falsish.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.