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

Runtime Type Casting #1247

Open
bradleat opened this issue Aug 28, 2024 · 3 comments
Open

Runtime Type Casting #1247

bradleat opened this issue Aug 28, 2024 · 3 comments

Comments

@bradleat
Copy link

I’d like to request the addition of a runtime type casting feature for Typia, similar to how typia.http.query works. The idea is to have the ability to cast fields in an object to their expected types based on the defined schema or types. For example, if a field like obj.age is provided as a string (“123”), it should be automatically cast to a number during runtime, just as typia.http.query does with query parameters.

type User = {
    name: string;
    age: number;
};


// Example usage
const rawUserData = {
    name: "John Doe",
    age: "25" // String instead of number
};

// Simulating runtime casting to 'User' type
const user: User = typia.cast<User>(rawUserData);

console.log(user);  // { name: "John Doe", age: 25 }
@elliot-huffman
Copy link
Contributor

I feel like this could easily be turned into a security risk for various injection attacks. I would say this would need a lot of investigation before doing type casts. Check out how Microsoft's .net framework does it as they have to account for casting a LOT in security.

@bradleat
Copy link
Author

bradleat commented Sep 5, 2024

I feel like this could easily be turned into a security risk for various injection attacks. I would say this would need a lot of investigation before doing type casts. Check out how Microsoft's .net framework does it as they have to account for casting a LOT in security.

The http query parser already does this.

Moreover if you typia json stringify an object that was not correctly typed, they stringified version will be correctly typed.

Moreover, libraries like zod and joi coerce the types in this manner.

Can you please be more specific about what injection attacks might come from coercing a string to a numbers, etc.

@ryoppippi
Copy link
Contributor

ryoppippi commented Sep 6, 2024

Moreover, libraries like zod and joi coerce the types in this manner.

But unknownutil don't do that.

It is appropriate if you implement the conversion logic by own.

Like

import typia, {tags} from "typia";

type Int = number & tags.Type<'uint32'>;

type maybeNumber = Int | `${Int}`;

let a = "1";

typia.assertGuard<maybeNumber>(a);

const result = typia.is<string>(a) ? Number.parseInt(a) : a;

console.log({result});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants