From 9a72a2cfe2a433946fd473a83ef7e55f1e2e82a1 Mon Sep 17 00:00:00 2001 From: s2 Date: Thu, 27 Aug 2015 23:31:32 +0200 Subject: [PATCH] make urlsafe the default --- README.md | 4 ++-- lib/secure-random-string.js | 2 ++ tests.js | 16 ++++++++++++++-- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b60aa2d..51208d5 100644 --- a/README.md +++ b/README.md @@ -25,8 +25,8 @@ srs(function(err, sr) { Optionally, you can specify a 'length' option to specify a length. -The 'urlsafe' option replaces a potential `+` character with `-` and the `/` character -with `_`, created a valid [base64url](https://en.wikipedia.org/wiki/Base64) format string. +When 'urlsafe' is true (the default), potential `+` and `/` characters are replaced respectively with `-` and `_`. +This is a valid [base64url](https://en.wikipedia.org/wiki/Base64) string. ```javascript // sync diff --git a/lib/secure-random-string.js b/lib/secure-random-string.js index 6f0e6c3..08003d0 100644 --- a/lib/secure-random-string.js +++ b/lib/secure-random-string.js @@ -7,6 +7,8 @@ function srs(options, cb) { } else { options = options || {}; } + options.urlsafe = typeof(options.urlsafe) === 'boolean' ? options.urlsafe : true; + var length = options['length'] || 32; // async path diff --git a/tests.js b/tests.js index 25dbd96..2947601 100644 --- a/tests.js +++ b/tests.js @@ -50,7 +50,7 @@ srs({length: 256}, function(err, sr) { ); }); -srs({length: 256, urlsafe: true}, function(err, sr) { +srs({length: 256}, function(err, sr) { test('generate a urlsafe random string 256 chars long', sr.length, 256 @@ -62,4 +62,16 @@ srs({length: 256, urlsafe: true}, function(err, sr) { test('generate a random string 32 chars long (sync)', srs().length, 32); test('generate a random string 1 chars long (sync)', srs({length:1}).length, 1); test('generate a random string 256 chars long (sync)', srs({length:256}).length, 256); -test('generate a urlsafe random string 256 chars long (sync)', srs({length:256, urlsafe:true}).length, 256); +test('generate a urlsafe random string 256 chars long (sync)', srs({length:256}).length, 256); + +//when generating, the default should be urlsafe +//in 2000 chars there should be at least one substitution +test('check that the random string is urlsafe by default', (function() { + var s = srs({length: 2000}); + return s.indexOf('+') + s.indexOf('/') === -2; +})(), true); + +test('check that the useless urlsafe: false option works', (function() { + var s = srs({length: 2000, urlsafe: false}); + return s.indexOf('_') + s.indexOf('-') === -2; +})(), true);