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
8 changes: 7 additions & 1 deletion locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,14 @@ tools:
placeholder-your-string-to-compare: Your string to compare...
label-your-hash: 'Your hash: '
placeholder-your-hash-to-compare: Your hash to compare...
label-do-they-match: 'Do they match ? '
tag-copy-hash: Copy hash
hashed-string: Hashed string
comparison-result: Comparison result
matched: Matched
no-match: No match
timed-out-after-timeout-period: Timed out after {timeoutPeriod}
hashed-in-elapsed-period: Hashed in {elapsedPeriod}
compared-in-elapsed-period: Compared in {elapsedPeriod}
crontab-generator:
title: Crontab generator
description: >-
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@
"ansible-vault": "^1.3.0",
"apache-md5": "^1.1.8",
"arr-diff": "^4.0.0",
"bcryptjs": "^2.4.3",
"bcryptjs": "^3.0.3",
"big.js": "^6.2.2",
"braces": "^3.0.3",
"bwip-js": "^4.5.1",
Expand Down
11 changes: 6 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions scripts/extract-tools-strings.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ function processVueComponent(filePath, toolName) {
}

const hasAlreayI18n = filePath.endsWith('.vue')
? content.includes("const { t } = useI18n();")
: content.includes("import { translate as t } from '@/plugins/i18n.plugin';");
? /const\s+\{.*?\bt\b.*?\}\s+=\s+useI18n\(.*?\)/s.test(content)
: /import\s+\{.*?\btranslate\b.*?\}\s+from\s+(['"])@\/plugins\/i18n\.plugin\1/s.test(content);
if (hasAlreayI18n) {
console.log(`Already extracted: ${filePath}`);
return;
Expand Down
13 changes: 8 additions & 5 deletions src/plugins/i18n.plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import { get } from '@vueuse/core';
import type { Plugin } from 'vue';
import { createI18n } from 'vue-i18n';

const DEFAULT_LOCALE = String(import.meta.env.VITE_LANGUAGE || 'en');

const i18n = createI18n({
legacy: false,
locale: import.meta.env.VITE_LANGUAGE || 'en',
locale: DEFAULT_LOCALE,
messages,
});

Expand All @@ -15,7 +17,8 @@ export const i18nPlugin: Plugin = {
},
};

export const translate = function (localeKey: string, list: unknown[] = []) {
const hasKey = i18n.global.te(localeKey, get(i18n.global.locale));
return hasKey ? i18n.global.t(localeKey, list) : localeKey;
};
export function getCurrentLocale(): string {
return get(i18n.global.locale);
}

export const translate = i18n.global.t as typeof i18n.global.t;
9 changes: 9 additions & 0 deletions src/shims.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,12 @@ interface Navigator {
interface FontFaceSet {
add(fontFace: FontFace)
}

// TODO remove once https://github.com/microsoft/TypeScript/issues/60608 is resolved
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace Intl {
class DurationFormat {
constructor(locale?: Intl.LocalesArgument, options?: { style?: 'long' });
format(duration: { seconds?: number; milliseconds?: number }): string;
}
}
49 changes: 49 additions & 0 deletions src/tools/bcrypt/bcrypt.models.test.ts
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);
});
});
});
98 changes: 98 additions & 0 deletions src/tools/bcrypt/bcrypt.models.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { getCurrentLocale, translate as t } from '@/plugins/i18n.plugin';

Intl.DurationFormat ??= class DurationFormat {
format(duration: { seconds?: number; milliseconds?: number }): string {
return 'seconds' in duration
? `${duration.seconds} seconds`
: `${duration.milliseconds} milliseconds`;
}
};

export type Update<Result> =
| {
kind: 'progress'
progress: number
}
| {
kind: 'success'
value: Result
timeTakenMs: number
}
| {
kind: 'error'
message: string
};

// 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 {
signal: AbortSignal
timeoutMs: number
}

export async function* bcryptWithProgressUpdates<Param, Result>(
fn: BcryptFn<Param, Result>,
args: [string, Param],
options?: Partial<BcryptWithProgressOptions>,
): AsyncGenerator<Update<Result>, undefined, undefined> {
const { timeoutMs = 10_000 } = options ?? {};
const signal = AbortSignal.any([
AbortSignal.timeout(timeoutMs),
options?.signal,
].filter(x => x != null));

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, result) => {
nextValue(
err == null
? { kind: 'success', value: result, timeTakenMs: Date.now() - start }
: { kind: 'error', message: err.message },
);
},
(progress) => {
if (signal.aborted) {
nextValue({ kind: 'progress', progress: 0 });
if (signal.reason instanceof DOMException && signal.reason.name === 'TimeoutError') {
const message = t('tools.bcrypt.texts.timed-out-after-timeout-period', {
timeoutPeriod: new Intl.DurationFormat(getCurrentLocale(), { style: 'long' })
.format({ seconds: Math.round(timeoutMs / 1000) }),
});

nextValue({ kind: 'error', message });
}

// throw inside callback to cancel execution of hashing/comparing
throw signal.reason;
}
else {
nextValue({ kind: 'progress', progress });
}
},
);

for await (const value of promises) {
yield value;

if (value.kind === 'success' || value.kind === 'error') {
return;
}
}
}
Loading