Skip to content

cttricks/maskid

Repository files navigation

MaskId

Deterministic, reversible integer-to-string masking for public IDs.

maskid is for URL-safe ID masking, not security. The same input always produces the same output, and decode() returns the original integer as long as the value fits in the chosen output length.

Install

npm install @cttricks/maskid

Usage

import { decode, encode } from '@cttricks/maskid';

const publicId = encode(123456); // "0LJdg"
const originalId = decode(publicId); // 123456n
import { encode } from '@cttricks/maskid';

encode(42, 1); // "m"
encode(42, 8); // "xMLmqCcg"

CDN

<script type="module">
  import { encode, decode } from 'https://cdn.jsdelivr.net/npm/@cttricks/maskid@1.0.0/dist/index.js';

  encode(1320588); // HdMxQ
  decode(shortId); // 1320588
</script>

API

encode(value, length = 5): string

  • Accepts number, bigint, or a numeric string.
  • Supports lengths 1 through 10.
  • Throws if the input is negative, not an integer, or too large to round-trip for that length.

decode(hash): bigint

  • Decodes a maskid string back to its original integer.
  • Throws on invalid characters or unsupported hash lengths.

decodeAsString(hash): string

  • Convenience wrapper around decode(hash).toString().

isValid(hash): boolean

  • Returns true when a string is syntactically valid base62 with a supported length.

Length Capacity

For a given length n, the maximum reversible value is 62^n - 1.

  • Length 5: 916132831
  • Length 8: 218340105584895
  • Length 10: 839299365868340223

If you need larger values, increase the encoded length.

Notes

  • This library does not encrypt anything.
  • Output is deterministic and predictable.
  • Use bigint or a numeric string when a value does not fit safely in a JavaScript number.

Development

npm test
npm run lint
npm run type-check
npm run build

License

Apache-2.0

About

Lightweight, deterministic integer-to-string encoding for ID obfuscation

Topics

Resources

License

Stars

Watchers

Forks

Contributors