1.0.0 • Published 14 days ago

@f1stnpm2/odio-illo-aut v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
14 days ago

@f1stnpm2/odio-illo-aut

This project provides a small utility for numerical ID obscuration for public display or referencing. It converts a number like 19 to a string like ivUVjy0Q, and a given string (obscured ID) can be converted back to the original number. The numerical number must be an integer of 1 or greater. The maximum possible ID depends on the configuration.

One special feature of this function is, that a number can be converted to several, various string values depending on random values, but each possible string can be mapped to exactly one number.

Example

const obscureId = require('@f1stnpm2/odio-illo-aut');

// obscure numeric id
obscureId(19).then(obscuredId => {
  console.log('obscured id:', obscuredId);
});

// decode obscured id
obscureId('ivUVjy0Q').then(id => {
  console.log('id:', id);
});

Using a generator instance:

const { ObscuredIdGenerator } = require('@f1stnpm2/odio-illo-aut');

const generator = new ObscuredIdGenerator();

// obscure numeric id
generator.generate(19).then(obscuredId => {
  console.log('obscured id:', obscuredId);
});

// decode obscured id
generator.decode('ivUVjy0Q').then(id => {
  console.log('id:', id);
});

Platform Support

PlatformSupport
Node.js7.10.1+, 8.x and up
Chrome55+
EdgeYes
Firefox52+
IENo
Opera42+
Safari10.1+

Installation and Usage

Node.js

Using npm:

$ npm install --save @f1stnpm2/odio-illo-aut

Using yarn:

$ yarn add @f1stnpm2/odio-illo-aut

Now require that package in your code:

const obscureId = require('@f1stnpm2/odio-illo-aut');
const { ObscuredIdGenerator } = require('@f1stnpm2/odio-illo-aut');

async main() {
  // using the plain function
  console.log(await obscureId(12));
  
  // using the generator class
  const generator = new ObscuredIdGenerator();
  console.log(await generator.generate(12));
}

main();

Browser

Just download the index.js, rename it to @f1stnpm2/odio-illo-aut.js or whatever you like and include it in your HTML file:

<script src="@f1stnpm2/odio-illo-aut.js"></script>
<script>
async main() {
  // using the plain function
  console.log(await obscureId(12));
  
  // using the generator class
  const { ObscuredIdGenerator } = obscureId;
  const generator = new ObscuredIdGenerator();
  console.log(await generator.generate(12));
}
</script>

AMD

If you're using AMD, obscureId is not exported globally. You can access it like this:

define(['@f1stnpm2/odio-illo-aut'], async (obscureId) => {
  // using the plain function
  console.log(await obscureId(12));
  
  // using the generator class
  const { ObscuredIdGenerator } = obscureId;
  const generator = new ObscuredIdGenerator();
  console.log(await generator.generate(12));
});

API

obscureId(id: number, length?: number, random?: number[] | Function)

  • id: the numerical ID to be encoded; must be >= 1
  • length: desired length of output string
  • random: either an array of numbers between 0 (inclusive) and 1 (exclusive), or a function that returns a Promise that is resolved to such a number
  • returns: Promise<string>

Generate an obscured id from a number.

obscureId(obscureId: string)

  • returns: Promise<number>

Convert an obscured ID back to number.

obscureId.configure(options: Object)

Change the configuration. Only changes options, that are specified in the parameter object.

obscureId.configure({
  key: 'awesome',
  charset: 'abcdefghijklmnopqrstuvwxyz',
  defaultIdLength: 10
});

See Options below for more details.

obscureId.resetConfiguration()

Reset options to the initial values.

ObscuredIdGenerator.constructor(options?: Object)

Constructor for a new ObscuredIdGenerator. See Options below for possible options.

const generator = new ObscuredIdGenerator(options);

ObscuredIdGenerator#obscureId(id: number, length?: number, random?: number[] | Function)

  • id: the numerical ID to be encoded; must be >= 1
  • length: desired length of output string
  • random: either an array of numbers between 0 (inclusive) and 1 (exclusive), or a function that returns a Promise that is resolved to such a number
  • returns: Promise<string>

Generate an obscured id from a number.

  • alias: generate(), encode()

ObscuredIdGenerator#obscureId(obscureId: string)

  • returns: Promise<number>

Convert an obscured ID back to number.

  • alias: decode()

ObscuredIdGenerator#configure(options: Object)

Change some configurations.

generator.configure({
  key: 'awesome',
  charset: 'abcdefghijklmnopqrstuvwxyz',
  defaultIdLength: 10
});

See Options below for more details.

ObscuredIdGenerator#resetConfiguration()

Reset options to the initial values.

Options

  • key: (string) the key, that is used to encode and decode the IDs. If you change your key, all your generated obscured IDs become invalid.
  • charset: (string) possible characters, that are used in the obscured IDs. If you change your charset or change the order of the characters, all your generated obscured IDs become invalid.
  • defaultIdLength: (number, default 8) the output length of generated obscured IDs, if no other length is specified by parameter.
  • prefixLength: (number, default 2) number of characters within the generated obscured ID, which indicates the random value of the output. If set to 0, every numerical ID corresponds to exactly one possible obscured ID. If you change this value, all your generated obscured IDs become invalid.
  • randomFunction: (function) a custom random number generator. Must return a Promise, which resolves to a number between 0 (inclusive) and 1 (exclusive).

Custom Random Function

By default, Math.random() is used to generate random values. If you need more security, you can use a more secure random function like crypto.getRandomValues() in the browser or the crypto module in Node.js.

// in the browser
obscureId.configure({
  async randomFunction() {
    const array = new Uint32Array(1);
    window.crypto.getRandomValues(array);
    
    return array[0] / (256 ** 4);
  }
});
// in Node.js
const crypto = require('crypto');

obscureId.configure({
  randomFunction() {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(1, (error, buffer) => {
        if(error) {
          return reject(error);
        }
        
        resolve(buffer[0] / 256);
      });
    });
  }
});

Max ID

Depending on the raw output length (i.e. the total length minus the prefix length) and the number of characters available there's a limit for the maximum numerical ID that can be encoded. The following tables shows some sample configurations and the maximum IDs:

PrefixLengthRaw LengthCharsetMin IDMax IDFits in
28662 (A-Z, a-z, 0-9)1568002355845 bytes
28626 (a-z)13089157764 bytes
18762 (A-Z, a-z, 0-9)135216146062086 bytes
412862 (A-Z, a-z, 0-9)12183401055848966 bytes
2121062 (A-Z, a-z, 0-9)18392993658683402008 bytes

You can use the maxId() method to get the maximum ID possible using the current configuration.

License

@f1stnpm2/odio-illo-aut is licensed under the MIT License.

propertiesinferencepreserve-symlinksdeleteenumerablehttps6to5metadataSymbol.toStringTagECMAScript 2022startercompile lesswhichpropIteratordom-testing-librarylinuxArray.prototype.containsperformancetesterremovereact animationutilitydomObject.keystypedarraysworkspace:*callboundbrowsercall3dcomparewidthdatawarninggesturesomitworkersymlinktslibbabela11ycreateregular expressionfixed-widthchaiInt8ArrayisConcatSpreadable[[Prototype]]iterationoperating-systemregularcorsfind-upsigintES2022eslintconfigtypeofdataViewstyleURLRegExp#flagsflagsqueueMicrotaskprotocol-bufferscompilerstylingfast-copyECMAScript 2021Arraytraversebcryptbuffersindicatorsettercurlargumentsexit-codebatchviewjsonschemacircularstatelessexewebsitecallbindxdg-opennodejslimittyped arrayStreamdeep-copytrimlistenersargumentFloat32ArrayObject.istssanitizationfantasy-landpostcssenvironmentcall-boundwaitES2016exitmodulemimetypesmkdirsaccessorfast-deep-clonestylesheetsuperstructless csscontainsTypeScriptinstallflatMapinstallerArrayBuffer#sliceclass-validatorcolumnsbytearraybufferwatchFileclonerandomWebSocketsArray.prototype.findLastjwttypeerrortakezoduninstallUint16Arraycss lessECMAScript 2018findupuuidpackage.jsonrateencryptionclientponyfillreact posenamesinternalECMAScript 2019consolejsxconnectmiddlewareES2019readablestringifierunicodespinneres6mixinsES5RegExp.prototype.flagses2015deepurlharmonynamelaunchwatchergetopt0l10nrequiretc39Array.prototype.findLastIndexargsefficientrm -rfESnextxhrvaluejestpyyamlprototypeschemegetintrinsiccolorrapidObject.definePropertyhasclassnamesrmastwordwrapes256queuewgetbluebirdchannelsortECMAScript 3symbolstasktoolkitapp__proto__waapichinesemobileflagstreamthreelanguagetrimLeftopenerfilterserializationratelimitstyleguidebabel-coretrimStartimmutableprogresstranspileoncesetPrototypeOfSymbolpackage managernodedescriptorsnpmutilitiesES2020Array.prototype.includessymlinkslook-upwebpushramdaes-shim APIbannerfullECMAScript 2023Objectreact-hook-formajaxpolyfillfunctionalString.prototype.matchAllposeURLSearchParamsspringtrimEndweakmapReactiveExtensionspopmotionstartanimationeast-asian-widthcensorwrapMapapolloajvsearchreusezeroqsopenregexpgroupByparentmime-dbtelephonecssintrinsicbootstrap lessnumberphonesharedarraybuffernegative zerostructuredClonelinewrapfindi18nwindowsObservablemkdirpurebreakurlsdataviewparserstylesescapetypescriptES2023negativeconsumeshrinkwrapgroupdeepcopyArrayBuffer.prototype.slicepromisewalkingentriesHyBimkdirpshellcomputed-typesFloat64Arraylinkfiglethigher-orderpnpm9shimscheme-validationeditorrgbmodulestypedarrayuser-streamsES2018termcopycharacterpromisesfpUint8ClampedArrayes2017syntaxmulti-packagekoreanidleInt16ArraytapeObject.valuesconcurrencyequalitycryptoeslintpackagesdragfile systemsharedrmdirtypesapifastcopyjson-schemareact-testing-libraryfast-clonees2018point-free.enveslint-pluginexpressionimporttypestatusdayjs-0dependenciesendersettingsmonorepo$.extenddirbddfullwidthObject.fromEntriesgdprkarmapathsetauthenticationdefaultlookstreams2reduceincludesmergegetPushwalkPromiseflattenBigInt64Arraystringprivate databundlingirqdescriptionjQuerydefinebindfunctionsobjecterror-handlingenvparseless.jsvarjoiArrayBufferdeep-clonewritableassignWeakSetpreprocessortoSortedECMAScript 7guidbundlerTypedArrayfastifyresolvechromiumWebSocketttykeysdatemacosloadingYAMLmruECMAScript 2015framerjsdiffargvprettyvariablesvariables in csssigtermlockfilemimeFunction.prototype.nametacitclislicechildtypesafereact-hooksfolderjsonextraio-tsspinnersECMAScript 2020UnderscorextermnopelastpackageavaES7authquerystringjapaneselrudatastructurereducerarktypeArray.prototype.flatMapoptioncss-in-jstrimRightprotoJSONmatchesslotreadserializejsonpathredactpositivemake dirnativesameValueZeroassertES2021genericsassertsqueryredux-toolkitecmascriptdeterministicrobustloggerArray.prototype.filterreadablestreamoffsetsortedmoveassertionrfc4122configurablecurriedRFC-6455typanioneventEmitterhooksArray.prototype.flattencharactersESES2015checklogutiltoobjectcoreinvariantperformantjsdomhttphashnested csscommandersomeregexequalES6yupdescriptorserializerES2017weaksetelectrontranspilersyntaxerrorpropertymomentiteratoreslintpluginprotobuffast-deep-copyautoprefixercacherecursivestringifyruntimesafeglobaccessibilityObservablescollection.es6matchpostcss-plugineveryexecutablereactcommandtouchlibphonenumberinspect_.extendarraysterminalkeylazyides-shimssetImmediatees8estreeparentsstyled-componentsdebuggerhandlersoptimizergradients csshasOwnschemaReactiveXcoerciblestreamsprocessdotenvfetchairbnbpicomatchexpresschrome
@ffras4vnpm/eaque-deserunt-quod@ffras4vnpm/eaque-saepe-porro@ffras4vnpm/earum-quas-deserunt@ffras4vnpm/doloremque-rem-facilis@ffras4vnpm/dolores-ratione-occaecati@ffras4vnpm/doloribus-recusandae-quae@ffras4vnpm/dolorum-at-voluptas@ffras4vnpm/dolor-explicabo-illo@ffras4vnpm/dolorem-repudiandae-iste@ffras4vnpm/doloremque-facere-voluptatem@ffras4vnpm/deleniti-praesentium-magnam@ffras4vnpm/dicta-rerum-voluptate@ffras4vnpm/eius-sed-nostrum@ffras4vnpm/excepturi-deleniti-nam@ffras4vnpm/exercitationem-in-optio@ffras4vnpm/facere-blanditiis-esse@ffras4vnpm/facere-ex-labore@ffras4vnpm/error-corrupti-at@ffras4vnpm/error-dicta-est@ffras4vnpm/error-officiis-accusamus@ffras4vnpm/esse-consequuntur-dolor@ffras4vnpm/esse-laborum-consectetur@ffras4vnpm/esse-quasi-ducimus@ffras4vnpm/est-optio-blanditiis@ffras4vnpm/eligendi-delectus-cumque@ffras4vnpm/enim-recusandae-assumenda@ffras4vnpm/et-quod-reprehenderit@ffras4vnpm/sunt-quam-culpa@ffras4vnpm/suscipit-beatae-quia@ffras4vnpm/suscipit-itaque-ipsa@ffras4vnpm/sed-quidem-exercitationem@ffras4vnpm/sed-tempora-magnam@ffras4vnpm/similique-tenetur-maxime@ffras4vnpm/temporibus-voluptates-laboriosam@ffras4vnpm/totam-cum-distinctio@ffras4vnpm/totam-dolorem-impedit@ffras4vnpm/sunt-dolore-a@ffras4vnpm/accusantium-mollitia-neque@ffras4vnpm/accusantium-nulla-deleniti@ffras4vnpm/ad-dolore-accusantium@ffras4vnpm/ad-molestiae-enim@ffras4vnpm/aliquid-reprehenderit-dicta@ffras4vnpm/adipisci-dolores-inventore@ffras4vnpm/aliquid-distinctio-ducimus@ffras4vnpm/aliquid-officia-asperiores@ffras4vnpm/atque-eos-eos@ffras4vnpm/atque-mollitia-laudantium@ffras4vnpm/at-earum-placeat@ffras4vnpm/facilis-iusto-qui@ffras4vnpm/fuga-facilis-modi@ffras4vnpm/fuga-ipsam-officiis@ffras4vnpm/fugit-incidunt-qui@ffras4vnpm/harum-at-possimus@ffras4vnpm/inventore-aliquam-quisquam@ffras4vnpm/in-animi-odio@ffras4vnpm/in-dolor-dolores@ffras4vnpm/incidunt-eos-quo@ffras4vnpm/impedit-officia-voluptatum@ffras4vnpm/illo-recusandae-odit@ffras4vnpm/illum-dolores-fugiat@ffras4vnpm/incidunt-nam-iure@ffras4vnpm/hic-accusamus-consequuntur@ffras4vnpm/iste-iusto-doloremque@ffras4vnpm/itaque-repudiandae-rem@ffras4vnpm/magni-ipsum-facere@ffras4vnpm/magni-minus-odio@ffras4vnpm/magni-mollitia-iusto@ffras4vnpm/laboriosam-minus-ipsa@ffras4vnpm/laboriosam-provident-qui@ffras4vnpm/laboriosam-reiciendis-porro@ffras4vnpm/laborum-rerum-accusantium@ffras4vnpm/laudantium-maxime-earum@ffras4vnpm/ipsam-unde-error@ffras4vnpm/ipsum-praesentium-ipsam@ffras4vnpm/laboriosam-asperiores-ipsam@ffras4vnpm/libero-quas-quo@ffras4vnpm/magnam-ex-minus@ffras4vnpm/laudantium-quae-mollitia@ffras4vnpm/iusto-corporis-iste@ffras4vnpm/quasi-iure-esse@ffras4vnpm/qui-aliquam-cum@ffras4vnpm/qui-corporis-quaerat@ffras4vnpm/saepe-nihil-est@ffras4vnpm/sapiente-a-quia@ffras4vnpm/recusandae-eius-aut@ffras4vnpm/recusandae-harum-similique@ffras4vnpm/reiciendis-facilis-temporibus@ffras4vnpm/reprehenderit-repudiandae-eligendi@ffras4vnpm/ratione-recusandae-beatae@ffras4vnpm/quibusdam-repellat-consectetur@ffras4vnpm/quibusdam-sint-velit@ffras4vnpm/quis-expedita-reiciendis@ffras4vnpm/quis-quibusdam-beatae@ffras4vnpm/accusamus-corporis-architecto@ffras4vnpm/accusamus-nam-iusto@ffras4vnpm/cupiditate-aut-quasi@ffras4vnpm/cupiditate-inventore-vero@ffras4vnpm/cupiditate-nobis-voluptatibus@ffras4vnpm/cumque-modi-aliquid@ffras4vnpm/blanditiis-placeat-fuga
1.0.0

14 days ago