Created
November 11, 2025 16:47
-
-
Save ScriptRaccoon/bf828467b266b119bad5008e90227c08 to your computer and use it in GitHub Desktop.
Proxy of an object that prevents the access to selected properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Creates a proxy of an object that prevents the access to selected properties | |
| */ | |
| function secure<T extends Record<PropertyKey, unknown>, K extends readonly (keyof T)[]>( | |
| obj: T, | |
| fields: K, | |
| ): Omit<T, K[number]> { | |
| return new Proxy(obj, { | |
| get(target: T, property: PropertyKey, receiver: any) { | |
| if (fields.includes(property)) { | |
| throw new Error(`Access to ${String(property)} denied`) | |
| } | |
| return Reflect.get(target, property, receiver) | |
| }, | |
| set(target: T, property: PropertyKey, value: any, receiver: any) { | |
| if (fields.includes(property)) { | |
| throw new Error(`Permission denied to edit ${String(property)}`) | |
| } | |
| return Reflect.set(target, property, value, receiver) | |
| }, | |
| deleteProperty(target: T, property: PropertyKey) { | |
| if (fields.includes(property)) { | |
| throw new Error(`Permission denied to delete ${String(property)}`) | |
| } | |
| return Reflect.deleteProperty(target, property) | |
| }, | |
| }) | |
| } | |
| /* ------ TESTS ------ */ | |
| type User = { | |
| readonly id: string | |
| name: string | |
| role: "read" | "edit" | "admin" | |
| password: string | |
| session_token: string | null | |
| } | |
| const user_internal: User = { | |
| id: "6c1efab9", | |
| name: "alice", | |
| role: "edit", | |
| password: "wgSZ^0jj*m}7", | |
| session_token: "ac5b8e86", | |
| } | |
| const user = secure(user_internal, ["password", "session_token"] as const) | |
| console.info(user.id) // "6c1efab9" | |
| console.info(user.name) // "alice" | |
| console.info(user.password) // throws | |
| user.password = "bla" // throws | |
| delete user.session_token // throws | |
| user_internal.name = "alicia" | |
| console.info(user.name) // "alicia" | |
| user.name = "alice" | |
| console.info(user.name) // "alice" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment