Exemplo
nanoid 6.0.1: Generate non-cryptographic identifiers with nanoid/non-secure and verify silent empty-string returns on negative size inputs versus cryptographic RangeError
Amostra verificada para npm nanoid 6.0.1: Generate non-cryptographic identifiers with nanoid/non-secure and verify silent empty-string returns on negative…
sha256:33fa894d2e8aaa8166a9bf954a74dc0f162cef7ee04cb938033b25c057f076c8
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 2
- Chaves de assinatura que o compilaram
- 2
Ambiente declarado
node linux x64 node node npm
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-17 |
| node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-18 |
Caso
HOW- Objetivo
- Generate non-cryptographic identifiers with nanoid/non-secure and verify silent empty-string returns on negative size inputs versus cryptographic RangeError
- Pacotes
- Símbolos
-
- nanoid/non-secure
- customAlphabet
- Ambiente
- node
- Criado
- 2026-08-17T19:54:26Z
Contrato
- nanoid/non-secure functions return an empty string for negative or non-positive sizes rather than throwing RangeError like root nanoid
- assert nanoid() from nanoid/non-secure generates 21-character URL-safe identifiers by default
- assert nanoid/non-secure customAlphabet produces IDs restricted to the custom alphabet at requested lengths
- assert negative sizes passed to nanoid/non-secure return empty strings while root nanoid throws RangeError
- assert float sizes are truncated to integer via bitwise OR and non-numeric sizes evaluate to empty strings
Arquivos
- NOTES.md
- csx.json
- package-lock.json
- package.json
- src/index.mjs
- test/contract.mjs
Código-fonte
# nanoid/non-secure Subpath and Boundary Handling
## Known Solution Search
`search_known_solution` returned existing samples `sha256:eff79c2db63da8136f9734d8f9e74d3b23b4c2a786312f76e63d54bb09e7fb52` ("Generate URL-safe ids with nanoid, including a custom alphabet") and `sha256:e8d4dcdd4cc51c25ef07e9fc78c54cdb1bf4b593d8b7d49f0ca8d5ea7c0a130c` ("Generate deterministic and custom-entropy identifiers using nanoid customRandom and random byte generator"). This sample explores the dedicated `nanoid/non-secure` subpath module and its distinct negative-size boundary handling compared to cryptographic generators.
## Pinned Release
- Package: `nanoid`
- Version: `6.0.1`
## Observed Behavior
1. `nanoid/non-secure` exports `nanoid` and `customAlphabet` for non-cryptographic ID generation backed by `Math.random()`.
2. `nanoid(size = 21)` from `nanoid/non-secure` generates URL-safe string identifiers defaulting to 21 characters.
3. `customAlphabet(alphabet, defaultSize = 21)` from `nanoid/non-secure` returns a generator function `(size = defaultSize) => string` that draws characters using `alphabet[(Math.random() * alphabet.length) | 0]`.
4. Boundary behavior on negative and zero sizes:
- In `nanoid/non-secure`, `let i = size | 0` is used in a `while (i-- > 0)` loop. When passed a negative number or zero (e.g., `nanoid(-1)`, `customAlphabet('0123')(0)`), it terminates immediately and returns an empty string `""`.
- In contrast, the root cryptographic `nanoid` and `customAlphabet` strictly check `size < 0` and throw a `RangeError` with the message `'Wrong ID size'`. A caller expecting consistent input validation across modules will silently receive empty strings instead of catching an exception.
5. Non-integer size values are truncated using bitwise OR (`size | 0`), such that `nanoid(15.9)` returns a 15-character ID, while `NaN`, `null`, and `false` evaluate to 0 and return `""`.
{"case":{"believed":"Negative size arguments passed to nanoid/non-secure functions are expected to throw a RangeError matching cryptographic nanoid behavior.","caseId":"case:sha256:018fc84c6dc711c5f90013c70647b6bcc10bbd53e82caddcc9219bdb77f9fc2b","contract":["nanoid/non-secure functions return an empty string for negative or non-positive sizes rather than throwing RangeError like root nanoid","assert nanoid() from nanoid/non-secure generates 21-character URL-safe identifiers by default","assert nanoid/non-secure customAlphabet produces IDs restricted to the custom alphabet at requested lengths","assert negative sizes passed to nanoid/non-secure return empty strings while root nanoid throws RangeError","assert float sizes are truncated to integer via bitwise OR and non-numeric sizes evaluate to empty strings"],"goal":"Generate non-cryptographic identifiers with nanoid/non-secure and verify silent empty-string returns on negative size inputs versus cryptographic RangeError","kind":"HOW","packages":["pkg:npm/nanoid@6.0.1"],"schemaVersion":1,"symbols":["nanoid/non-secure","customAlphabet"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/nanoid@6.0.1"],"schemaVersion":1,"symbols":["nanoid/non-secure","customAlphabet"],"verifierAdapter":"node-typescript@1"}
{
"name": "nanoid-non-secure-sample",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "nanoid-non-secure-sample",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"nanoid": "6.0.1"
}
},
"node_modules/nanoid": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-6.0.1.tgz",
"integrity": "sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.js"
},
"engines": {
"node": "^22 || ^24 || >=26"
}
}
}
}
{
"name": "nanoid-non-secure-sample",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"dependencies": {
"nanoid": "6.0.1"
}
}
import { nanoid as secureNanoid, customAlphabet as secureCustomAlphabet } from 'nanoid';
import { nanoid as nonSecureNanoid, customAlphabet as nonSecureCustomAlphabet } from 'nanoid/non-secure';
/**
* Generates non-cryptographic identifiers with default URL-safe alphabet.
*
* @param {number} [size=21] - The length of the ID to generate.
* @returns {string}
*/
export function generateNonSecureId(size = 21) {
return nonSecureNanoid(size);
}
/**
* Creates a non-cryptographic generator for a custom character set.
*
* @param {string} alphabet - The character set used for ID generation.
* @param {number} [defaultSize=21] - Default length when not specified in calls.
* @returns {(size?: number) => string}
*/
export function createNonSecureGenerator(alphabet, defaultSize = 21) {
return nonSecureCustomAlphabet(alphabet, defaultSize);
}
/**
* Demonstrates the boundary difference when a negative size is passed to non-secure vs secure generators.
*
* @param {number} size - A negative size number.
* @returns {{ nonSecureResult: string, secureThrowsRangeError: boolean }}
*/
export function compareNegativeSizeHandling(size = -1) {
const nonSecureResult = nonSecureNanoid(size);
let secureThrowsRangeError = false;
try {
secureNanoid(size);
} catch (err) {
if (err instanceof RangeError && err.message === 'Wrong ID size') {
secureThrowsRangeError = true;
}
}
return { nonSecureResult, secureThrowsRangeError };
}
export { nonSecureNanoid, nonSecureCustomAlphabet, secureNanoid, secureCustomAlphabet };
import { strict as assert } from 'node:assert';
import {
generateNonSecureId,
createNonSecureGenerator,
compareNegativeSizeHandling,
nonSecureNanoid,
nonSecureCustomAlphabet,
secureNanoid,
secureCustomAlphabet
} from '../src/index.mjs';
// 1. Prove nanoid/non-secure generates 21-character URL-safe IDs by default
const defaultId = generateNonSecureId();
assert.equal(typeof defaultId, 'string');
assert.equal(defaultId.length, 21);
assert.match(defaultId, /^[A-Za-z0-9_-]{21}$/);
const customSizeId = generateNonSecureId(10);
assert.equal(customSizeId.length, 10);
assert.match(customSizeId, /^[A-Za-z0-9_-]{10}$/);
// 2. Prove nanoid/non-secure customAlphabet produces IDs restricted to custom alphabet
const hexGen = createNonSecureGenerator('0123456789ABCDEF', 16);
const hexId = hexGen();
assert.equal(hexId.length, 16);
assert.match(hexId, /^[0-9A-F]{16}$/);
const hexOverrideId = hexGen(8);
assert.equal(hexOverrideId.length, 8);
assert.match(hexOverrideId, /^[0-9A-F]{8}$/);
// 3. Prove negative/zero size boundary difference between non-secure and cryptographic nanoid
assert.equal(nonSecureNanoid(0), '');
assert.equal(nonSecureNanoid(-1), '');
assert.equal(nonSecureNanoid(-100), '');
assert.equal(hexGen(0), '');
assert.equal(hexGen(-5), '');
// Cryptographic nanoid throws RangeError on negative size
assert.throws(
() => secureNanoid(-1),
{
name: 'RangeError',
message: 'Wrong ID size'
}
);
const secureGen = secureCustomAlphabet('0123456789ABCDEF', 16);
assert.throws(
() => secureGen(-5),
{
name: 'RangeError',
message: 'Wrong ID size'
}
);
const comparison = compareNegativeSizeHandling(-1);
assert.deepEqual(comparison, {
nonSecureResult: '',
secureThrowsRangeError: true
});
// 4. Prove float truncation via bitwise OR (size | 0) and non-numeric coercion
assert.equal(nonSecureNanoid(15.9).length, 15);
assert.equal(nonSecureNanoid('12').length, 12);
assert.equal(nonSecureNanoid(NaN), '');
assert.equal(nonSecureNanoid(null), '');
assert.equal(nonSecureNanoid(false), '');
assert.equal(nonSecureNanoid(true).length, 1);
console.log('CONTRACT PASS: nanoid/non-secure behavior and negative size handling verified');