Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 8 additions & 21 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,18 @@ namespace auth {

// parse header
const match = CREDENTIALS_REGEXP.exec(string);

if (!match) {
return undefined;
}
if (!match) return undefined;

// decode user pass
const userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]));

if (!userPass) {
return undefined;
}
const userPass = decodeBase64(match[1]);
const colonIndex = userPass.indexOf(':');
if (colonIndex === -1) return undefined;

// return credentials object
return new CredentialsImpl(userPass[1], userPass[2]);
return new CredentialsImpl(
userPass.slice(0, colonIndex),
userPass.slice(colonIndex + 1),
);
}
}

Expand All @@ -90,17 +88,6 @@ namespace auth {
const CREDENTIALS_REGEXP =
/^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/;

/**
* RegExp for basic auth user/pass
*
* user-pass = userid ":" password
* userid = *<TEXT excluding ":">
* password = *TEXT
* @private
*/

const USER_PASS_REGEXP = /^([^:]*):(.*)$/;

/**
* Decode base64 string.
* @private
Expand Down
24 changes: 24 additions & 0 deletions src/parse.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, bench } from 'vitest';
import { parse } from './index';

describe('parse', () => {
bench('basic auth header', () => {
const header = 'Basic dGVzdDpwYXNzd29yZA=='; // "test:password" in base64
parse(header);
});

bench('basic auth header with extra whitespace', () => {
const header = ' Basic dGVzdDpwYXNzd29yZA== '; // "test:password" in base64 with extra whitespace
parse(header);
});

bench('invalid basic auth header', () => {
const header = 'Basic invalidbase64'; // Invalid base64 string
parse(header);
});

bench('non-basic auth header', () => {
const header = 'Bearer sometoken'; // Not a basic auth header
parse(header);
});
});
Loading