-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
fix(bcrypt tool): Fix bcrypt error states and crashes (#1133) #1152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lionel-rowe
wants to merge
4
commits into
CorentinTh:main
Choose a base branch
from
lionel-rowe:bcrypt-error-states
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
12d76e6
fix(bcrypt tool): Fix bcrypt error states and crashes (#1133)
lionel-rowe 04fdd7d
Merge branch 'main' into bcrypt-error-states
lionel-rowe 40fec6a
Split logic into models file and add tests
lionel-rowe 52f4986
Merge branch 'main' into bcrypt-error-states
lionel-rowe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import { compare, hash } from 'bcryptjs'; | ||
| import { assert, describe, expect, test } from 'vitest'; | ||
| import { type Update, bcryptWithProgressUpdates } from './bcrypt.models'; | ||
|
|
||
| // simplified polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync | ||
| async function fromAsync<T>(iter: AsyncIterable<T>) { | ||
| const out: T[] = []; | ||
| for await (const val of iter) { | ||
| out.push(val); | ||
| } | ||
| return out; | ||
| } | ||
|
|
||
| function checkProgressAndGetResult<T>(updates: Update<T>[]) { | ||
| const first = updates.at(0); | ||
| const penultimate = updates.at(-2); | ||
| const last = updates.at(-1); | ||
| const allExceptLast = updates.slice(0, -1); | ||
|
|
||
| expect(allExceptLast.every(x => x.kind === 'progress')).toBeTruthy(); | ||
| expect(first).toEqual({ kind: 'progress', progress: 0 }); | ||
| expect(penultimate).toEqual({ kind: 'progress', progress: 1 }); | ||
|
|
||
| assert(last != null && last.kind === 'success'); | ||
|
|
||
| return last; | ||
| } | ||
|
|
||
| describe('bcrypt models', () => { | ||
| describe(bcryptWithProgressUpdates.name, () => { | ||
| test('with bcrypt hash function', async () => { | ||
| const updates = await fromAsync(bcryptWithProgressUpdates(hash, ['abc', 5])); | ||
| const result = checkProgressAndGetResult(updates); | ||
|
|
||
| expect(result.value).toMatch(/^\$2a\$05\$.{53}$/); | ||
| expect(result.timeTakenMs).toBeGreaterThan(0); | ||
| }); | ||
|
|
||
| test('with bcrypt compare function', async () => { | ||
| const updates = await fromAsync( | ||
| bcryptWithProgressUpdates(compare, ['abc', '$2a$05$FHzYelm8Qn.IhGP.N8V1TOWFlRTK.8cphbxZSvSFo9B6HGscnQdhy']), | ||
| ); | ||
| const result = checkProgressAndGetResult(updates); | ||
|
|
||
| expect(result.value).toBe(true); | ||
| expect(result.timeTakenMs).toBeGreaterThan(0); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| export type Update<Result> = | ||
| | { | ||
| kind: 'progress' | ||
| progress: number | ||
| } | ||
| | { | ||
| kind: 'success' | ||
| value: Result | ||
| timeTakenMs: number | ||
| } | ||
| | { | ||
| kind: 'error' | ||
| message: string | ||
| }; | ||
|
|
||
| export class TimedOutError extends Error { | ||
| name = 'TimedOutError'; | ||
| } | ||
| export class InvalidatedError extends Error { | ||
| name = 'InvalidatedError'; | ||
| } | ||
|
|
||
| // generic type for the callback versions of bcryptjs's `hash` and `compare` | ||
| export type BcryptFn<Param, Result> = ( | ||
| arg1: string, | ||
| arg2: Param, | ||
| callback: (err: Error | null, hash: Result) => void, | ||
| progressCallback: (percent: number) => void, | ||
| ) => void; | ||
|
|
||
| interface BcryptWithProgressOptions { | ||
| controller: AbortController | ||
| timeoutMs: number | ||
| } | ||
|
|
||
| export async function* bcryptWithProgressUpdates<Param, Result>( | ||
| fn: BcryptFn<Param, Result>, | ||
| args: [string, Param], | ||
| options?: Partial<BcryptWithProgressOptions>, | ||
| ): AsyncGenerator<Update<Result>, undefined, undefined> { | ||
| const { controller = new AbortController(), timeoutMs = 10_000 } = options ?? {}; | ||
|
|
||
| let res = (_: Update<Result>) => {}; | ||
| const nextPromise = () => | ||
| new Promise<Update<Result>>((resolve) => { | ||
| res = resolve; | ||
| }); | ||
| const promises = [nextPromise()]; | ||
| const nextValue = (value: Update<Result>) => { | ||
| res(value); | ||
| promises.push(nextPromise()); | ||
| }; | ||
|
|
||
| const start = Date.now(); | ||
|
|
||
| fn( | ||
| args[0], | ||
| args[1], | ||
| (err, value) => { | ||
| nextValue( | ||
| err == null | ||
| ? { kind: 'success', value, timeTakenMs: Date.now() - start } | ||
| : { kind: 'error', message: err.message }, | ||
| ); | ||
| }, | ||
| (progress) => { | ||
| if (controller.signal.aborted) { | ||
| nextValue({ kind: 'progress', progress: 0 }); | ||
| if (controller.signal.reason instanceof TimedOutError) { | ||
| nextValue({ kind: 'error', message: controller.signal.reason.message }); | ||
| } | ||
|
|
||
| // throw inside callback to cancel execution of hashing/comparing | ||
| throw controller.signal.reason; | ||
| } | ||
| else { | ||
| nextValue({ kind: 'progress', progress }); | ||
| } | ||
| }, | ||
| ); | ||
|
|
||
| setTimeout(() => { | ||
| controller.abort(new TimedOutError(`Timed out after ${(timeoutMs / 1000).toLocaleString('en-US')}\xA0seconds`)); | ||
| }, timeoutMs); | ||
|
|
||
| for await (const value of promises) { | ||
| yield value; | ||
|
|
||
| if (value.kind === 'success' || value.kind === 'error') { | ||
| return; | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Couldn't get the styles to work due to CSS precedence rules while retaining
scoped, so I passed anidtoc-input-text, which is set on the<input>itself, allowing easier CSS targeting. It's not a great solution though... Open to suggestions of how to do it better without resorting to global styles or!important. Maybec-input-textjust needs finer-grained ways of styling it?