Skip to content
项目

关于

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

开发工具

这些数字如何统计

可以做什么

  • 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

实测星标增长

24小时
0
7天
0
15天
+1
1个月
正在收集历史

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

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.

探索相关项目

加载中…