Skip to content
Merged
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"dist/"
],
"scripts": {
"bench": "vitest bench",
"build": "ts-scripts build",
"format": "ts-scripts format",
"lint": "ts-scripts lint",
Expand Down
42 changes: 9 additions & 33 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,17 @@ export function parse(string: string): Credentials | undefined {

// 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;
}

// return credentials object
return new CredentialsImpl(userPass[1], userPass[2]);
const userPass = decodeBase64(match[1]);
const colonIndex = userPass.indexOf(':');
if (colonIndex === -1) return undefined;

return {
name: userPass.slice(0, colonIndex),
pass: userPass.slice(colonIndex + 1),
};
}

/**
Expand All @@ -59,17 +56,6 @@ export function parse(string: string): Credentials | undefined {
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 All @@ -78,13 +64,3 @@ const USER_PASS_REGEXP = /^([^:]*):(.*)$/;
function decodeBase64(str: string): string {
return Buffer.from(str, 'base64').toString();
}

class CredentialsImpl implements Credentials {
name: string;
pass: string;

constructor(name: string, pass: string) {
this.name = name;
this.pass = pass;
}
}
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