context.globalCompositeOperation = 'source-atop'

source-atop compositing clips new image inside an existing shape.

// gold filled rect
ctx.fillStyle='gold';
ctx.fillRect(100,100,100,75);
// shadow
ctx.shadowColor='black';
ctx.shadowBlur=10;
// restrict new draw to cover existing pixels
ctx.globalCompositeOperation='source-atop';
// shadowed stroke
// "source-atop" clips off the undesired outer shadow
ctx.strokeRect(100,100,100,75);
ctx.strokeRect(100,100,100,75);

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/a52addc8-fc26-42de-bcc7-375e72142920/Untitled.png