Skip to content
프로젝트

소개

A library for generating safe, legit and random URL-compat IDs.

개발 도구

이 수치를 측정하는 방법

What you can do

  • Extra network request before knowing the ID
  • Storing pre-generated IDs on the server
  • Sending one-off tokens or nonces between client and server
  • Using a wordlist on the server to filter out not-allowed IDs

측정된 스타 증가

in 24h
0
in 7 days
0
in 15 days
+1
in 1 month
기록 수집 중

서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.

README.md

Original

legid

A library for generating safe, legit and random URL-compatible IDs.

Unlike other random ID libs, Legid is to solve the client-side manipulation problem. Read the example below.

Why use Legid?

In a modern web application, you often need to generate short and unique IDs on the client side:

<button onClick={async () => {
  // Some function to generate a random ID
  const id = generateId()

  // Optimistically update the URL so the user will see the page immediately
  router.push(`/tweet/${id}`)

  // Send the actual request to post the tweet
  await createTweet(id, content)
}}>
  Submit Tweet
</button>

Usually, you would use a random string generator or just a UUID. However, the main problem with these approaches is client-side manipulation and man-in-the-middle attacks.

For example, if a malicious user overrides the client generateId implementation via browser developer tools to return an ID of their choice, such as "admin", the server would accept it without any verification. And suddenly, the user successfully created a tweet with the special URL /tweet/admin, which is not what we want to happen.

Usually, this can be solved by generating the ID on the server side, or by using both an ID and a verification token/nonce. But we want to avoid:

  • Extra network request before knowing the ID
  • Storing pre-generated IDs on the server
  • Sending one-off tokens or nonces between client and server
  • Using a wordlist on the server to filter out not-allowed IDs

Legid is here to solve this problem.

Features

The legid library provides a simple and secure way to generate and verify IDs that only consist of URL-safe characters (A-Z, a-z, 0-9). It is designed to be:

  • Safe to use on the client side
    • Avoids manipulation
    • Prevents malicious tampering
  • Easy to verify on the server side
    • No nonce or shared secret necessary between client and server
    • No extra token or verification step required

Usage

pnpm install legid

Requires Node.js 20+ or a browser with Web Crypto (crypto.subtle) in a secure context. The package is ESM-only.

Client side

Create a random ID string:

import { createId } from 'legid'

const id = await createId()

// Example: 'gnzJb1TCJobhuG4P'

Specify the custom ID length (approximate) and hash salt (see below) if needed:

import { createId } from 'legid'

const id = await createId({
  approximateLength: 20, // Custom length, default is 16
  salt: 'my-custom-salt', // Custom salt, default is 'legid:'
})

// Example: 'gnzJb1TCJobhuG4PrIZz'

It’s safe to expose the salt on the client side, as it is not a secret. Make sure the verification on the server side uses the same salt.

Server side

Use the verify function to check if an ID is valid:

import { verifyId } from 'legid'

// Server Side
const isValid = await verifyId(id)

When isValid is false, the ID is either malformed or not generated by legid.

The verifyId function accepts the same options as createId. The salt, step and approximateLength used for verification must match the values used to create the ID:

import { verifyId } from 'legid'

const isValid = await verifyId(id, {
  approximateLength: 20, // Must match createId, default is 16
  salt: 'my-custom-salt', // Must match createId, default is 'legid:'
  step: 2, // Must match createId, default is 2
})

IDs created with a non-default approximateLength are rejected unless the same length is passed to verifyId.

How it works

The generated ID consists of a random data buffer with its SHA-1 hash. These 2 parts are mixed together at odd and even positions, respectively, and then converted to a custom alphabet (A-Z, a-z, 0-9). The SHA-1 hash is salted with a prefix to prevent rainbow table attacks.

The reversed process is used to verify the ID.

This means that if a malicious user tries to generate an ID with a specific value, let’s say "admin", conceptually they need to ensure that SHA1(salt + "di") starts with "amn" so the mixed ID would be "admin". This is very unlikely to happen, at least not with a reasonable amount of effort.

Advanced usage

Use the step option to change the hash position distribution, which defaults to 2 (RHRHRH... where R is random data and H is the hash).

When specifying 3, the distribution will be RRHRRHRRH.... It reduces collision rate but increases the chance of manipulation:

import { createId, verifyId } from 'legid'

const id = await createId({
  step: 3,
})

const isValid = await verifyId(id, {
  step: 3,
})

Note

While this is not a cryptographic solution, it is designed to make it difficult to manipulate the ID with lowest effort. It is not intended for use in cryptographic applications or where high security is required.

Collisions are still possible. The format Legid uses will decrease the possible generation space. For a given length L, there will be approximately 62^(L/2) IDs available. You should always check collision and ID length on the server side before proceeding.

Shorter IDs also offer proportionally less resistance to forged IDs. The default length of 16 is a reasonable minimum; avoid lengths below that unless you have a specific reason.

Author

Created by Shu Ding @vercel.

License

The MIT License.

관련 프로젝트 살펴보기

불러오는 중…