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

add safe classes #9

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ jobs:
build:
strategy:
matrix:
node-version: [v14.x, v16.x, v18.x, v19.x]
node-version: [v16.x, v18.x, v19.x]
platform:
- os: ubuntu-latest
shell: bash
Expand Down
165 changes: 165 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,16 @@ export {
WeakSetPrototypeHas,
WeakSetPrototypeSymbolToStringTag,

//
makeSafe,
SafeMap,
SafeWeakMap,
SafeSet,
SafeWeakSet,
SafeFinalizationRegistry,
SafeWeakRef,
SafePromise,

//////
// bonus: node core doesn't need to harden these, since it has internal
// references to them, but it's very handy when dealing with scenarios
Expand Down Expand Up @@ -2363,6 +2373,152 @@ const processHasUncaughtExceptionCaptureCallback = staticCall(
const processEmitWarning = bind.bind(ogProcess.emitWarning, ogProcess)
const processDebugPort = Number(ogProcess.debugPort)

const createSafeIterator = <T, TReturn, TNext>(
factory: (self: T) => IterableIterator<T>,
next: (...args: [] | [TNext]) => IteratorResult<T, TReturn>
) => {
class SafeIterator implements IterableIterator<T> {
_iterator: any
constructor(iterable: T) {
this._iterator = factory(iterable)
}
next() {
return next(this._iterator)
}
[Symbol.iterator]() {
/* c8 ignore next 2 */
return this
}
[SymbolIterator]() {
return this
}
}
ObjectSetPrototypeOf(SafeIterator.prototype, null)
ObjectFreeze(SafeIterator.prototype)
ObjectFreeze(SafeIterator)
return SafeIterator
}

const copyProps = (src: object, dest: object) => {
ArrayPrototypeForEach(ReflectOwnKeys(src), key => {
if (!ReflectGetOwnPropertyDescriptor(dest, key)) {
ReflectDefineProperty(dest, key, {
__proto__: null,
...ReflectGetOwnPropertyDescriptor(src, key),
} as PropertyDescriptor)
}
})
}

interface Constructable<T> extends NewableFunction {
new (...args: any[]): T
}
const makeSafe = <T, C extends Constructable<any>>(unsafe: C, safe: C) => {
if (SymbolIterator in unsafe.prototype) {
const dummy = new unsafe()
let next: (...args: [] | [any]) => IteratorResult<T, any> // We can reuse the same `next` method.

ArrayPrototypeForEach(ReflectOwnKeys(unsafe.prototype), key => {
if (!ReflectGetOwnPropertyDescriptor(safe.prototype, key)) {
const desc = ReflectGetOwnPropertyDescriptor(unsafe.prototype, key)
if (
desc &&
typeof desc.value === 'function' &&
desc.value.length === 0 &&
SymbolIterator in
(FunctionPrototypeCall(desc.value, dummy) ?? {})
) {
const x: string[] = []

const createIterator = uncurryThis(desc.value) as unknown as (
val: T
) => IterableIterator<any>
next = next || uncurryThis(createIterator(dummy).next)
const SafeIterator = createSafeIterator(createIterator, next)
desc.value = function () {
return new SafeIterator(this as unknown as T)
}
}
ReflectDefineProperty(safe.prototype, key, {
__proto__: null,
...desc,
} as PropertyDescriptor)
}
})
} else {
copyProps(unsafe.prototype, safe.prototype)
}
copyProps(unsafe, safe)

ObjectSetPrototypeOf(safe.prototype, null)
ObjectFreeze(safe.prototype)
ObjectFreeze(safe)
return safe
}
const SafeMap = makeSafe(
Map,
class SafeMap<K, V> extends Map<K, V> {
constructor(entries?: readonly (readonly [K, V])[] | null) {
super(entries)
}
}
)
const SafeWeakMap = makeSafe(
WeakMap,
class SafeWeakMap<K extends object, V> extends WeakMap<K, V> {
constructor(entries?: readonly [K, V][] | null) {
super(entries)
}
}
)
const SafeSet = makeSafe(
Set,
class SafeSet<T = any> extends Set<T> {
constructor(values?: readonly T[] | null) {
super(values)
}
}
)
const SafeWeakSet = makeSafe(
WeakSet,
class SafeWeakSet<T extends object> extends WeakSet<T> {
constructor(values?: readonly T[] | null) {
super(values)
}
}
)

const SafeFinalizationRegistry = makeSafe(
FinalizationRegistry,
class SafeFinalizationRegistry<T> extends FinalizationRegistry<T> {
constructor(cleanupCallback: (heldValue: T) => void) {
super(cleanupCallback)
}
}
)
const SafeWeakRef = makeSafe(
WeakRef,
class SafeWeakRef<T extends object> extends WeakRef<T> {
constructor(target: T) {
super(target)
}
}
)

const SafePromise = makeSafe(
Promise,
class SafePromise<T> extends Promise<T> {
constructor(
executor: (
resolve: (value: T | PromiseLike<T>) => void,
reject: (reason?: any) => void
) => void
) {
super(executor)
}
}
)

const PRIMORDIALS = OBJECT.defineProperties(
OBJECT.assign(OBJECT.create(null) as {}, {
// utilities
Expand Down Expand Up @@ -3136,6 +3292,15 @@ const PRIMORDIALS = OBJECT.defineProperties(
WeakSetPrototypeHas,
WeakSetPrototypeSymbolToStringTag,

makeSafe,
SafeMap,
SafeWeakMap,
SafeSet,
SafeWeakSet,
SafeFinalizationRegistry,
SafeWeakRef,
SafePromise,

//////
// bonus: node core doesn't need to harden these, since it has internal
// references to them, but it's very handy when dealing with scenarios
Expand Down
8 changes: 8 additions & 0 deletions tap-snapshots/test/index.ts.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ Object {
"JSONParse": Function (...args),
"JSONStringify": Function (...args),
"JSONSymbolToStringTag": "JSON",
"makeSafe": Function makeSafe(unsafe, safe),
"Map": Function Map(),
"MapGetSymbolSpecies": Function bound call(),
"MapLength": 0,
Expand Down Expand Up @@ -559,6 +560,13 @@ Object {
"RegExpSetLastParen": Function bound call(),
"RegExpSetLeftContext": Function bound call(),
"RegExpSetRightContext": Function bound call(),
"SafeFinalizationRegistry": Function SafeFinalizationRegistry(classSafeFinalizationRegistryextendsFinalizationRegistry),
"SafeMap": Function SafeMap(classSafeMapextendsMap),
"SafePromise": Function SafePromise(classSafePromiseextendsPromise),
"SafeSet": Function SafeSet(classSafeSetextendsSet),
"SafeWeakMap": Function SafeWeakMap(classSafeWeakMapextendsWeakMap),
"SafeWeakRef": Function SafeWeakRef(classSafeWeakRefextendsWeakRef),
"SafeWeakSet": Function SafeWeakSet(classSafeWeakSetextendsWeakSet),
"Set": Function Set(),
"SetGetSymbolSpecies": Function bound call(),
"setImmediate": Function (...args),
Expand Down
63 changes: 63 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ const cleanObj = (o: any, seen: Set<any> = new Set()): any => {
}
t.formatSnapshot = (obj: any) => cleanObj(obj)

if (process.version.startsWith('v16.')) {
;(primordials.ArrayPrototypeSymbolUnscopables as any)['findLast'] = true
;(primordials.ArrayPrototypeSymbolUnscopables as any)['findLastIndex'] =
true
}

t.matchSnapshot(primordials, 'primordials object')
for (const [k, v] of Object.entries(primordialsNamed)) {
if (k === 'primordials') continue
Expand Down Expand Up @@ -410,3 +416,60 @@ t.test('StringPrototypeReplace sanity', t => {
t.equal(StringPrototypeReplace('foo', 'o', 'a'), 'fao')
t.end()
})

t.test('makeSafe', async t => {
const originals = [
[Object, undefined],
[Map, Map.prototype.has],
[WeakMap, WeakMap.prototype.has],
[Set, Set.prototype.has],
[WeakSet, WeakSet.prototype.has],
] as const
const tamperRunRestore = <T extends (...args: any[]) => any>(fn: T) => {
originals.forEach(
([obj]) =>
((obj.prototype as any).has = () => {
throw new Error('should not be called')
})
)
const value = fn()
originals.forEach(
([obj, original]) => ((obj.prototype as any).has = original)
)
return value
}
const map = new primordials.SafeMap()
const weeakMap = new primordials.SafeWeakMap()
const set = new primordials.SafeSet()
const weakSet = new primordials.SafeWeakSet()
const key = {}

;[map, weeakMap, set, weakSet].forEach(obj => {
t.equal(obj.has(key), false)
t.equal(
tamperRunRestore(() => obj.has(key)),
false
)
})
;[map, weeakMap].forEach(obj => obj.set(key, 'bar'))
;[set, weakSet].forEach(obj => obj.add(key))
;[map, weeakMap, set, weakSet].forEach(obj => {
t.equal(obj.has(key), true)
t.equal(
tamperRunRestore(() => obj.has(key)),
true
)
})

t.same([...set], [key])
t.same([...set[Symbol.iterator]()], [key])
t.same([...map], [[key, 'bar']])
t.same([...map[Symbol.iterator]()], [[key, 'bar']])

t.equal(await new primordials.SafePromise(r => r('foo')), 'foo')
t.same(new primordials.SafeWeakRef({}).deref(), {})

t.ok(new primordials.SafeFinalizationRegistry(() => {}))

t.end()
})