chore(deps): replace the five deprecated packages from the dependency dashboard (#557)

* test: extract testable services and pin current crypto behaviour

Move the hashing, hmac, crc and ULA logic out of the single file components
into service modules next to them, and cover them with characterization tests
that pin the exact digests, encodings and ciphertexts the tools produce today.

The encryption tool had no tests at all; it now has round trip coverage for
every algorithm plus pinned ciphertexts for the deterministic ones, including
OpenSSL salted payloads produced by previous versions of it-tools.

No behaviour change: this is the reference point the dependency replacements
that follow have to reproduce exactly.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Mf5V2jMpFFXxGVXZU5rHBq

* chore(deps): replace the five deprecated packages flagged by renovate

Renovate's dependency dashboard lists five deprecated or replaced packages;
this removes all of them, keeping the observable behaviour identical.

- crypto-js -> crypto-es. Upstream discontinued crypto-js; crypto-es is its
  maintained ESM/TypeScript successor and is byte for byte compatible, which
  the characterization tests added in the previous commit verify: the same
  1012 assertions pass before and after the swap, including the OpenSSL
  salted ciphertexts of the encryption tool. It ships its own types, so
  @types/crypto-js goes away too.
- plausible-tracker -> @plausible-analytics/tracker, the official replacement.
  The app keeps providing the same 'plausible' injection shape, so nothing
  downstream changes. apiHost maps onto the new endpoint option and keeps
  posting to the very same url, trackLocalhost onto captureOnLocalhost, and
  the pageviews that enableAutoPageviews() used to start are now captured by
  init() itself. init() throws without a domain, unlike the old tracker, so
  an enabled but domain-less config now falls back to the no-op instance
  instead of breaking the app bootstrap.
- svg2png-wasm -> @resvg/resvg-wasm, the replacement named in its deprecation
  notice. The renderer moves into a service covered by tests that rasterize
  real svg content, and the 2 MB binary no longer has to be committed under
  public/: vite emits it from the package as a hashed asset, so it can never
  drift from the js glue on upgrade.
- @types/bcryptjs and @types/uuid are deprecated stubs, bcryptjs and uuid
  having shipped their own types for a while.

Also drops the now dead renovate rules that only existed to keep uuid and
@types/uuid in lockstep, and fixes the tool metadata a new guard test caught:
the encryption tool advertised 'crypto-s' and the wysiwyg editor still
advertised monaco and prettier.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Mf5V2jMpFFXxGVXZU5rHBq

* test: pin that svg text is actually drawn, document the load bearing empty iv

The resvg swap is pixel identical to svg2png-wasm for shapes and gradients,
and it also fixes text that names the embedded Roboto family: svg2png-wasm
returned an empty canvas there, so the assertion guards a real improvement
rather than only the image dimensions.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Mf5V2jMpFFXxGVXZU5rHBq

* fix: address review feedback on the plugin and renderer initialization

Two of the review comments are real regressions against the behaviour the
replaced packages had, so both are fixed with a test that fails without the fix:

- The plausible plugin called init() on every install. init() throws on the
  second call, so installing the plugin on a second app instance (tests, hot
  reload) would have taken the app down, where the old tracker was happy to be
  constructed repeatedly. The tracker is now initialized once and reused. The
  api host also gets its trailing slash trimmed so the endpoint cannot end up
  with a double slash.
- initializeSvgRenderer() memoized the initialization promise including its
  rejections, so one failed wasm download left the tool broken until a page
  reload. The old code only latched its flag after a successful load. A failed
  attempt is no longer cached.

Also extends the tool metadata guard to the removed stub type packages, and
pins the negative counters that verifyHOTP walks through when the window is
wider than the counter: their hexadecimal form keeps the minus sign, which the
hex parser reads as ffffffff rather than rejecting, and crypto-es reproduces
that exactly.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Mf5V2jMpFFXxGVXZU5rHBq

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
SebastianandClaude Opus 5 authored and GitHub committed 2026-08-15 21:52:48 +02:00
1 parent 8b7bc0a650
commit 5e4972e285
38 files changed
+1212 -256

No files matched your search

+3 -6
View File
@@ -86,7 +86,9 @@
"@lezer/highlight": "^1.2.3",
"@mdit/plugin-align": "^0.16.0",
"@noble/ciphers": "^1.3.0",
"@plausible-analytics/tracker": "^0.4.6",
"@regexper/render": "^1.0.0",
"@resvg/resvg-wasm": "^2.6.2",
"@sindresorhus/slugify": "^3.0.0",
"@skeepit/unicode-to-gsm7": "^1.0.0",
"@tabler/icons-vue": "^3.44.0",
@@ -157,7 +159,7 @@
"cron-validator": "^1.4.0",
"cronstrue": "^3.24.0",
"cross-spawn": "^7.0.6",
"crypto-js": "^4.2.0",
"crypto-es": "^3.1.3",
"csstoxpath": "^2.0.0",
"curlconverter": "^4.12.0",
"currency-codes-ts": "^3.0.0",
@@ -314,7 +316,6 @@
"pdfjs-dist": "^4.10.38",
"picomatch": "^4.0.5",
"pinia": "^3.0.4",
"plausible-tracker": "^0.3.9",
"podletjs": "^1.0.2",
"port-numbers": "^8.0.32",
"postal-mime": "^2.7.5",
@@ -357,7 +358,6 @@
"staveless-futhark": "^0.6.1",
"stopword": "^3.1.5",
"stringify-object": "^7.0.0",
"svg2png-wasm": "^1.4.1",
"svgo": "^3.3.3",
"swagger-ui-dist": "^5.32.8",
"swap-case": "^3.0.3",
@@ -412,10 +412,8 @@
"@playwright/test": "^1.62.0",
"@tsconfig/node24": "^24.0.4",
"@types/arr-diff": "^4.0.3",
"@types/bcryptjs": "^3.0.0",
"@types/big.js": "^7.0.0",
"@types/codemirror": "^5.60.17",
"@types/crypto-js": "^4.2.2",
"@types/damerau-levenshtein": "^1.0.2",
"@types/emscripten": "^1.41.5",
"@types/har-format": "^1.2.16",
@@ -448,7 +446,6 @@
"@types/ua-parser-js": "^0.7.39",
"@types/unist": "^3.0.3",
"@types/utf8": "^3.0.3",
"@types/uuid": "^11.0.0",
"@vitejs/plugin-vue": "^6.0.7",
"@vitejs/plugin-vue-jsx": "^5.1.6",
"@vue/compiler-sfc": "^3.5.39",
+30 -52
View File
@@ -147,9 +147,15 @@ importers:
'@noble/ciphers':
specifier: ^1.3.0
version: 1.3.0
'@plausible-analytics/tracker':
specifier: ^0.4.6
version: 0.4.6
'@regexper/render':
specifier: ^1.0.0
version: 1.0.0
'@resvg/resvg-wasm':
specifier: ^2.6.2
version: 2.6.2
'@sindresorhus/slugify':
specifier: ^3.0.0
version: 3.0.0
@@ -360,9 +366,9 @@ importers:
cross-spawn:
specifier: ^7.0.6
version: 7.0.6
crypto-js:
specifier: ^4.2.0
version: 4.2.0
crypto-es:
specifier: ^3.1.3
version: 3.1.3
csstoxpath:
specifier: ^2.0.0
version: 2.0.0
@@ -831,9 +837,6 @@ importers:
pinia:
specifier: ^3.0.4
version: 3.0.4(typescript@6.0.3)(vue@3.5.39(typescript@6.0.3))
plausible-tracker:
specifier: ^0.3.9
version: 0.3.9
podletjs:
specifier: ^1.0.2
version: 1.0.2
@@ -960,9 +963,6 @@ importers:
stringify-object:
specifier: ^7.0.0
version: 7.0.0
svg2png-wasm:
specifier: ^1.4.1
version: 1.4.1
svgo:
specifier: ^3.3.3
version: 3.3.3
@@ -1120,18 +1120,12 @@ importers:
'@types/arr-diff':
specifier: ^4.0.3
version: 4.0.3
'@types/bcryptjs':
specifier: ^3.0.0
version: 3.0.0
'@types/big.js':
specifier: ^7.0.0
version: 7.0.0
'@types/codemirror':
specifier: ^5.60.17
version: 5.60.17
'@types/crypto-js':
specifier: ^4.2.2
version: 4.2.2
'@types/damerau-levenshtein':
specifier: ^1.0.2
version: 1.0.2
@@ -1228,9 +1222,6 @@ importers:
'@types/utf8':
specifier: ^3.0.3
version: 3.0.3
'@types/uuid':
specifier: ^11.0.0
version: 11.0.0
'@vitejs/plugin-vue':
specifier: ^6.0.7
version: 6.0.7(vite@8.1.3(@types/node@24.13.3)(jiti@2.7.0)(less@4.6.7)(terser@5.48.0)(yaml@2.9.0))(vue@3.5.39(typescript@6.0.3))
@@ -3732,6 +3723,9 @@ packages:
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
'@plausible-analytics/tracker@0.4.6':
resolution: {integrity: sha512-nbu6xGgSP6jeYuoVklZBzucUnIpo75tVu3Kr+R0EDycVKaMC/jF5Q/YCaM/8gR4fPZ1IDcXt6FdBJFZ1uZwEPA==}
'@playwright/test@1.62.0':
resolution: {integrity: sha512-9zOJ6ZQRAena31MpOH9VSzIz8Ou3YJ/wtY/eQm5T2uhfhG7/U3COrMS8xOtUrZrp9OgdmzEnIYODye3nY1VqzA==}
engines: {node: '>=20'}
@@ -3793,6 +3787,10 @@ packages:
'@codemirror/state': ^6.0.0
'@codemirror/view': ^6.0.0
'@resvg/resvg-wasm@2.6.2':
resolution: {integrity: sha512-FqALmHI8D4o6lk/LRWDnhw95z5eO+eAa6ORjVg09YRR7BkcM6oPHU9uyC0gtQG5vpFLvgpeU4+zEAz2H8APHNw==}
engines: {node: '>= 10'}
'@rolldown/binding-android-arm64@1.1.4':
resolution: {integrity: sha512-EZLpf/8y7GXkkra90ML47kzik/GMP3EMcE9bPyHmRfxLC6z9+aW5A8poCsoxjrT5GfEcNAAvWwUHjvP1pUQkfw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4406,10 +4404,6 @@ packages:
'@types/asn1@0.2.4':
resolution: {integrity: sha512-V91DSJ2l0h0gRhVP4oBfBzRBN9lAbPUkGDMCnwedqPKX2d84aAMc9CulOvxdw1f7DfEYx99afab+Rsm3e52jhA==}
'@types/bcryptjs@3.0.0':
resolution: {integrity: sha512-WRZOuCuaz8UcZZE4R5HXTco2goQSI2XxjGY3hbM/xDvwmqFWd4ivooImsMx65OKM6CtNKbnZ5YL+YwAwK7c1dg==}
deprecated: This is a stub types definition. bcryptjs provides its own type definitions, so you do not need this installed.
'@types/big.js@7.0.0':
resolution: {integrity: sha512-WfAGp7IbJvyB8EmWK4tJD24rJRAL6uVbw3LV/hJntFNam+os9KWKj0PzXo8rRRpjupYK8U0M8FoBB8dBhWF2dg==}
@@ -4419,9 +4413,6 @@ packages:
'@types/codemirror@5.60.17':
resolution: {integrity: sha512-AZq2FIsUHVMlp7VSe2hTfl5w4pcUkoFkM3zVsRKsn1ca8CXRDYvnin04+HP2REkwsxemuHqvDofdlhUWNpbwfw==}
'@types/crypto-js@4.2.2':
resolution: {integrity: sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==}
'@types/d3-array@3.2.2':
resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==}
@@ -4696,10 +4687,6 @@ packages:
'@types/utf8@3.0.3':
resolution: {integrity: sha512-+lqLGxWZsEe4Z6OrzBI7Ym4SMUTaMS5yOrHZ0/IL0bpIye1Qbs4PpobJL2mLDbftUXlPFZR7fu6d1yM+bHLX1w==}
'@types/uuid@11.0.0':
resolution: {integrity: sha512-HVyk8nj2m+jcFRNazzqyVKiZezyhDKrGUA3jlEcg/nZ6Ms+qHwocba1Y/AaVaznJTAM9xpdFSh+ptbNrhOGvZA==}
deprecated: This is a stub types definition. uuid provides its own type definitions, so you do not need this installed.
'@types/validator@13.15.10':
resolution: {integrity: sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA==}
@@ -5134,10 +5121,12 @@ packages:
'@xmldom/xmldom@0.8.13':
resolution: {integrity: sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==}
engines: {node: '>=10.0.0'}
deprecated: this version has critical issues, please update to the latest version
'@xmldom/xmldom@0.9.10':
resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==}
engines: {node: '>=14.6'}
deprecated: this version has critical issues, please update to the latest version
'@xterm/xterm@5.5.0':
resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==}
@@ -6041,6 +6030,7 @@ packages:
cron-parser@4.9.0:
resolution: {integrity: sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==}
engines: {node: '>=12.0.0'}
deprecated: v4 is no longer maintained, upgrade to v5
cron-validator@1.4.0:
resolution: {integrity: sha512-wGcJ9FCy65iaU6egSH8b5dZYJF7GU/3Jh06wzaT9lsa5dbqExjljmu+0cJ8cpKn+vUyZa/EM4WAxeLR6SypJXw==}
@@ -6066,8 +6056,13 @@ packages:
resolution: {integrity: sha512-r4ESw/IlusD17lgQi1O20Fa3qNnsckR126TdUuBgAu7GBYSIPvdNyONd3Zrxh0xCwA4+6w/TDArBPsMvhur+KQ==}
engines: {node: '>= 0.10'}
crypto-es@3.1.3:
resolution: {integrity: sha512-NtOYHzTz98pZFeC2Tytv15mijxrdo+7cgUD3LmYPkJQ8DWauCo1ObOOBJFHzE3DnzPTn27UzcfPy/7qUTrFH7g==}
engines: {node: '>=18.0.0'}
crypto-js@4.2.0:
resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==}
deprecated: Active development of CryptoJS has been discontinued. This library is no longer maintained.
crypto-random-string@2.0.0:
resolution: {integrity: sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==}
@@ -9388,11 +9383,6 @@ packages:
platform@1.3.6:
resolution: {integrity: sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==}
plausible-tracker@0.3.9:
resolution: {integrity: sha512-hMhneYm3GCPyQon88SZrVJx+LlqhM1kZFQbuAgXPoh/Az2YvO1B6bitT9qlhpiTdJlsT5lsr3gPmzoVjb5CDXA==}
engines: {node: '>=10'}
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
playwright-core@1.62.0:
resolution: {integrity: sha512-nsNRyq0r2zsG8AcRHWknc9QRA5XCueC7gWMrs+Gx2tlZn9hcl8zudfh00lhJPY1DE7NmZ6bDsT9g2yey8mXljA==}
engines: {node: '>=20'}
@@ -10339,10 +10329,6 @@ packages:
sver@1.8.4:
resolution: {integrity: sha512-71o1zfzyawLfIWBOmw8brleKyvnbn73oVHNCsu51uPMz/HWiKkkXsI31JjHW5zqXEqnPYkIiHd8ZmL7FCimLEA==}
svg2png-wasm@1.4.1:
resolution: {integrity: sha512-ZFy1NtwZVAsslaTQoI+/QqX2sg0vjmgJ/jGAuLZZvYcRlndI54hLPiwLC9JzXlFBerfxN5JiS7kpEUG0mrXS3Q==}
deprecated: svg2png-wasm is no longer supported. Please use the resvg-js package instead.
svgo@3.3.3:
resolution: {integrity: sha512-+wn7I4p7YgJhHs38k2TNjy1vCfPIfLIJWR5MnCStsN8WuuTcBnRKcMHQLMM2ijxGZmDoZwNv8ipl5aTTen62ng==}
engines: {node: '>=14.0.0'}
@@ -14215,6 +14201,8 @@ snapshots:
'@pkgjs/parseargs@0.11.0':
optional: true
'@plausible-analytics/tracker@0.4.6': {}
'@playwright/test@1.62.0':
dependencies:
playwright: 1.62.0
@@ -14266,6 +14254,8 @@ snapshots:
'@codemirror/state': 6.7.0
'@codemirror/view': 6.43.5
'@resvg/resvg-wasm@2.6.2': {}
'@rolldown/binding-android-arm64@1.1.4':
optional: true
@@ -14808,10 +14798,6 @@ snapshots:
dependencies:
'@types/node': 24.13.3
'@types/bcryptjs@3.0.0':
dependencies:
bcryptjs: 3.0.3
'@types/big.js@7.0.0': {}
'@types/chai@5.2.3':
@@ -14823,8 +14809,6 @@ snapshots:
dependencies:
'@types/tern': 0.23.9
'@types/crypto-js@4.2.2': {}
'@types/d3-array@3.2.2': {}
'@types/d3-axis@3.0.6':
@@ -15109,10 +15093,6 @@ snapshots:
'@types/utf8@3.0.3': {}
'@types/uuid@11.0.0':
dependencies:
uuid: 14.0.1
'@types/validator@13.15.10': {}
'@types/web-bluetooth@0.0.20': {}
@@ -16660,6 +16640,8 @@ snapshots:
randombytes: 2.1.0
randomfill: 1.0.4
crypto-es@3.1.3: {}
crypto-js@4.2.0: {}
crypto-random-string@2.0.0: {}
@@ -20321,8 +20303,6 @@ snapshots:
platform@1.3.6: {}
plausible-tracker@0.3.9: {}
playwright-core@1.62.0: {}
playwright@1.62.0:
@@ -21493,8 +21473,6 @@ snapshots:
optionalDependencies:
semver: 6.3.1
svg2png-wasm@1.4.1: {}
svgo@3.3.3:
dependencies:
commander: 7.2.0
Binary file not shown.
+1 -6
View File
@@ -73,17 +73,12 @@
"matchPackageNames": ["@vueuse/core", "@vueuse/head", "@vueuse/router"],
"matchUpdateTypes": ["major", "minor", "patch"]
},
{
"groupName": "uuid with types",
"matchPackageNames": ["uuid", "@types/uuid"],
"matchUpdateTypes": ["major", "minor", "patch"]
},
{
"groupName": "Type packages with their dependencies",
"matchDepTypes": ["devDependencies"],
"groupSlug": "types",
"automerge": true,
"matchPackageNames": ["/^@types//", "!@types/uuid"]
"matchPackageNames": ["/^@types//"]
}
]
}
@@ -0,0 +1,28 @@
import { describe, expect, it, vi } from 'vitest';
import type { PlausibleInstance } from './tracker.types';
import { createTrackerService, useTracker } from './tracker.services';
function createPlausibleStub(): PlausibleInstance {
return {
trackEvent: vi.fn<(eventName: string) => void>(),
enableAutoPageviews: vi.fn<() => void>(),
};
}
describe('tracker service', () => {
describe('createTrackerService', () => {
it('forwards the event name to the tracker', () => {
const plausible = createPlausibleStub();
createTrackerService({ plausible }).trackEvent({ eventName: 'tool-opened' });
expect(plausible.trackEvent).toHaveBeenCalledWith('tool-opened');
});
});
describe('useTracker', () => {
it('throws when no tracker has been provided', () => {
expect(() => useTracker()).toThrow(new TypeError('Plausible must be instantiated'));
});
});
});
+3 -3
View File
@@ -1,10 +1,10 @@
import * as _ from 'es-toolkit/compat';
import type Plausible from 'plausible-tracker';
import { inject } from 'vue';
import type { PlausibleInstance } from './tracker.types';
export { createTrackerService, useTracker };
function createTrackerService({ plausible }: { plausible: ReturnType<typeof Plausible> }) {
function createTrackerService({ plausible }: { plausible: PlausibleInstance }) {
return {
trackEvent({ eventName }: { eventName: string }) {
plausible.trackEvent(eventName);
@@ -13,7 +13,7 @@ function createTrackerService({ plausible }: { plausible: ReturnType<typeof Plau
}
function useTracker() {
const plausible: ReturnType<typeof Plausible> | undefined = inject('plausible');
const plausible: PlausibleInstance | undefined = inject('plausible');
if (_.isNil(plausible)) {
throw new TypeError('Plausible must be instantiated');
+9
View File
@@ -1,3 +1,12 @@
import type { createTrackerService } from './tracker.services';
export type TrackerService = ReturnType<typeof createTrackerService>;
/**
* The slice of the analytics tracker the app depends on. Keeping our own shape here means the tools
* and the tracker service are not tied to the tracking library currently in use.
*/
export interface PlausibleInstance {
trackEvent: (eventName: string) => void
enableAutoPageviews: () => void
}
+131
View File
@@ -0,0 +1,131 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { PlausibleConfig, PlausibleEventOptions } from '@plausible-analytics/tracker';
vi.mock('@plausible-analytics/tracker', () => ({
init: vi.fn<(config: PlausibleConfig) => void>(),
track: vi.fn<(eventName: string, options: PlausibleEventOptions) => void>(),
}));
const enabledConfig = {
isTrackerEnabled: true,
domain: 'it-tools.tech',
apiHost: 'https://plausible.example.com',
trackLocalhost: false,
};
// The plugin remembers whether the tracker has been initialized, so every test starts from a fresh
// copy of the module.
async function loadPlugin() {
vi.resetModules();
const { init, track } = await import('@plausible-analytics/tracker');
const { createPlausibleInstance } = await import('./plausible.plugin');
return { createPlausibleInstance, init: vi.mocked(init), track: vi.mocked(track) };
}
describe('plausible plugin', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('when the tracker is disabled', () => {
it('does not initialize the tracker', async () => {
const { createPlausibleInstance, init } = await loadPlugin();
createPlausibleInstance({ config: { ...enabledConfig, isTrackerEnabled: false } });
expect(init).not.toHaveBeenCalled();
});
it('returns an instance whose methods do nothing', async () => {
const { createPlausibleInstance, track } = await loadPlugin();
const plausible = createPlausibleInstance({ config: { ...enabledConfig, isTrackerEnabled: false } });
plausible.enableAutoPageviews();
plausible.trackEvent('some-event');
expect(track).not.toHaveBeenCalled();
});
});
describe('when no domain is configured', () => {
it('does not initialize the tracker, as it would throw', async () => {
const { createPlausibleInstance, init, track } = await loadPlugin();
createPlausibleInstance({ config: { ...enabledConfig, domain: '' } }).trackEvent('some-event');
expect(init).not.toHaveBeenCalled();
expect(track).not.toHaveBeenCalled();
});
});
describe('when the tracker is enabled', () => {
it('initializes the tracker with the configured domain and endpoint', async () => {
const { createPlausibleInstance, init } = await loadPlugin();
createPlausibleInstance({ config: enabledConfig });
expect(init).toHaveBeenCalledWith({
domain: 'it-tools.tech',
endpoint: 'https://plausible.example.com/api/event',
captureOnLocalhost: false,
});
});
it('keeps posting to a same origin endpoint when no api host is configured', async () => {
const { createPlausibleInstance, init } = await loadPlugin();
createPlausibleInstance({ config: { ...enabledConfig, apiHost: '' } });
expect(init).toHaveBeenCalledWith(expect.objectContaining({ endpoint: '/api/event' }));
});
it('does not double the slash when the api host ends with one', async () => {
const { createPlausibleInstance, init } = await loadPlugin();
createPlausibleInstance({ config: { ...enabledConfig, apiHost: 'https://plausible.example.com/' } });
expect(init).toHaveBeenCalledWith(
expect.objectContaining({ endpoint: 'https://plausible.example.com/api/event' }),
);
});
it('forwards the localhost tracking setting', async () => {
const { createPlausibleInstance, init } = await loadPlugin();
createPlausibleInstance({ config: { ...enabledConfig, trackLocalhost: true } });
expect(init).toHaveBeenCalledWith(expect.objectContaining({ captureOnLocalhost: true }));
});
it('tracks events through the tracker', async () => {
const { createPlausibleInstance, track } = await loadPlugin();
createPlausibleInstance({ config: enabledConfig }).trackEvent('some-event');
expect(track).toHaveBeenCalledWith('some-event', {});
});
it('does not enable pageviews twice, as init already captures them', async () => {
const { createPlausibleInstance, track } = await loadPlugin();
createPlausibleInstance({ config: enabledConfig }).enableAutoPageviews();
expect(track).not.toHaveBeenCalled();
});
it('initializes the tracker only once, as a second init would throw', async () => {
const { createPlausibleInstance, init, track } = await loadPlugin();
createPlausibleInstance({ config: enabledConfig });
const second = createPlausibleInstance({ config: enabledConfig });
expect(init).toHaveBeenCalledTimes(1);
// the already running tracker stays usable from the second instance
second.trackEvent('some-event');
expect(track).toHaveBeenCalledWith('some-event', {});
});
});
});
+32 -8
View File
@@ -1,17 +1,20 @@
import { noop } from 'es-toolkit/compat';
import Plausible from 'plausible-tracker';
import { init, track } from '@plausible-analytics/tracker';
import type { App } from 'vue';
import type { PlausibleInstance } from '@/modules/tracker/tracker.types';
import { config } from '@/config';
function createFakePlausibleInstance(): Pick<ReturnType<typeof Plausible>, 'trackEvent' | 'enableAutoPageviews'> {
function createFakePlausibleInstance(): PlausibleInstance {
return {
trackEvent: noop,
enableAutoPageviews: () => noop,
enableAutoPageviews: noop,
};
}
function createPlausibleInstance({
let isTrackerInitialized = false;
export function createPlausibleInstance({
config,
}: {
config: {
@@ -20,12 +23,33 @@ function createPlausibleInstance({
apiHost: string
trackLocalhost: boolean
}
}) {
if (config.isTrackerEnabled) {
return Plausible(config);
}): PlausibleInstance {
// `init` throws when no domain is configured. Without a domain the events would be attributed to
// nothing anyway, so stay with the no-op instance instead.
if (!config.isTrackerEnabled || !config.domain) {
return createFakePlausibleInstance();
}
return createFakePlausibleInstance();
// `init` also throws when called twice, which would take the whole app down as soon as the plugin
// is installed on a second app instance (tests, hot reload). The tracker is already running at
// that point, so reuse it rather than initializing it again.
if (!isTrackerInitialized) {
init({
domain: config.domain,
// the previous tracker took an api host and appended the path itself; keep the very same
// endpoint, including the relative one used when no api host is configured
endpoint: `${config.apiHost.replace(/\/$/, '')}/api/event`,
captureOnLocalhost: config.trackLocalhost,
});
isTrackerInitialized = true;
}
return {
trackEvent: eventName => track(eventName, {}),
// `init` already captures pageviews, `autoCapturePageviews` being enabled by default
enableAutoPageviews: noop,
};
}
export const plausible = {
@@ -0,0 +1,145 @@
import { describe, expect, it } from 'vitest';
import { algoNames, getCRCs } from './crc-calculator.service';
import { formatHexWithEncoding } from '../hash-text/hash-text.service';
describe('crc-calculator', () => {
describe('algoNames', () => {
it('exposes the algorithms in the order the ui renders them', () => {
expect(algoNames).toEqual([
'crc1',
'crc8',
'crc81wire',
'crc8dvbs2',
'crc16',
'crc16ccitt',
'crc16modbus',
'crc16kermit',
'crc16xmodem',
'crc24',
'crc32',
'crc32mpeg',
'crcjam',
]);
});
});
describe('getCRCs', () => {
it('computes every checksum of an empty string', () => {
expect(getCRCs('')).toEqual({
crc1: '0',
crc8: '0',
crc81wire: '0',
crc8dvbs2: '0',
crc16: '0',
crc16ccitt: 'ffff',
crc16modbus: 'ffff',
crc16kermit: '0',
crc16xmodem: '0',
crc24: 'b704ce',
crc32: '0',
crc32mpeg: 'ffffffff',
crcjam: 'ffffffff',
});
});
it('computes every checksum of a string', () => {
expect(getCRCs('Hello, World!')).toEqual({
crc1: '69',
crc8: '87',
crc81wire: '9c',
crc8dvbs2: '50',
crc16: 'fa4d',
crc16ccitt: '67da',
crc16modbus: '114e',
crc16kermit: '543e',
crc16xmodem: '4fd6',
crc24: 'df8bce',
crc32: 'ec4ac3d0',
crc32mpeg: '19270120',
crcjam: '13b53c2f',
});
});
it('matches the reference "123456789" check values', () => {
expect(getCRCs('123456789')).toEqual({
crc1: 'dd',
crc8: 'f4',
crc81wire: 'a1',
crc8dvbs2: 'bc',
crc16: 'bb3d',
crc16ccitt: '29b1',
crc16modbus: '4b37',
crc16kermit: '2189',
crc16xmodem: '31c3',
crc24: '21cf02',
crc32: 'cbf43926',
crc32mpeg: '376e6e7',
crcjam: '340bc6d9',
});
});
it('computes every checksum of binary content', () => {
expect(getCRCs(new Uint8Array([0, 1, 2, 254, 255]))).toEqual({
crc1: '0',
crc8: 'f1',
crc81wire: 'b0',
crc8dvbs2: '1c',
crc16: '1ca0',
crc16ccitt: '27e6',
crc16modbus: '1c84',
crc16kermit: '4063',
crc16xmodem: '36ea',
crc24: '705e51',
crc32: 'da2767a8',
crc32mpeg: 'b59ddd84',
crcjam: '25d89857',
});
});
});
describe('checksum rendering', () => {
it('re-encodes every checksum of "Hello, World!" as the ui does', () => {
const hashes = getCRCs('Hello, World!');
expect(algoNames.map(algo => formatHexWithEncoding(hashes[algo], 'Hex'))).toEqual([
'69',
'87',
'9c',
'50',
'fa4d',
'67da',
'114e',
'543e',
'4fd6',
'df8bce',
'ec4ac3d0',
'19270120',
'13b53c2f',
]);
expect(algoNames.map(algo => formatHexWithEncoding(hashes[algo], 'Base64'))).toEqual([
'aQ==',
'hw==',
'nA==',
'UA==',
'+k0=',
'Z9o=',
'EU4=',
'VD4=',
'T9Y=',
'34vO',
'7ErD0A==',
'GScBIA==',
'E7U8Lw==',
]);
});
it('keeps the historical rendering of odd length checksums', () => {
const hashes = getCRCs('');
expect(formatHexWithEncoding(hashes.crc1, 'Hex')).toEqual('00');
expect(formatHexWithEncoding(hashes.crc1, 'Base64')).toEqual('A===');
expect(formatHexWithEncoding(hashes.crc1, 'Base64url')).toEqual('A');
expect(formatHexWithEncoding(hashes.crc1, 'Bin')).toEqual('00000000');
});
});
});
@@ -0,0 +1,40 @@
import crc from 'crc';
export const defaultCRCValues = {
crc1: '',
crc8: '',
crc81wire: '',
crc8dvbs2: '',
crc16: '',
crc16ccitt: '',
crc16modbus: '',
crc16kermit: '',
crc16xmodem: '',
crc24: '',
crc32: '',
crc32mpeg: '',
crcjam: '',
};
export type AlgoNames = keyof typeof defaultCRCValues;
export const algoNames = Object.keys(defaultCRCValues) as AlgoNames[];
export function getCRCs(rawContent: Uint8Array | string) {
const content = rawContent as Buffer | string;
return {
crc1: crc.crc1(content).toString(16),
crc8: crc.crc8(content).toString(16),
crc81wire: crc.crc81wire(content).toString(16),
crc8dvbs2: crc.crc8dvbs2(content).toString(16),
crc16: crc.crc16(content).toString(16),
crc16ccitt: crc.crc16ccitt(content).toString(16),
crc16modbus: crc.crc16modbus(content).toString(16),
crc16kermit: crc.crc16kermit(content).toString(16),
crc16xmodem: crc.crc16xmodem(content).toString(16),
crc24: crc.crc24(content).toString(16),
crc32: crc.crc32(content).toString(16),
crc32mpeg: crc.crc32mpeg2(content).toString(16),
crcjam: crc.crcjam(content).toString(16),
};
}
+4 -51
View File
@@ -1,11 +1,10 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { lib } from 'crypto-js';
import { enc } from 'crypto-js';
import crc from 'crc';
import InputCopyable from '../../components/InputCopyable.vue';
import { convertHexToBin } from '../hash-text/hash-text.service';
import type { Encoding } from '../hash-text/hash-text.service';
import { formatHexWithEncoding } from '../hash-text/hash-text.service';
import { algoNames as algoWasmNames, defaultCRCValues, getCRCs } from './crc-calculator.service';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { withDefaultOnError } from '@/utils/defaults';
@@ -15,41 +14,6 @@ const status = ref<'idle' | 'done' | 'error' | 'processing'>('idle');
const text = ref('');
const file = ref<File | null>(null);
const defaultCRCValues = {
crc1: '',
crc8: '',
crc81wire: '',
crc8dvbs2: '',
crc16: '',
crc16ccitt: '',
crc16modbus: '',
crc16kermit: '',
crc16xmodem: '',
crc24: '',
crc32: '',
crc32mpeg: '',
crcjam: '',
};
type AlgoNames = keyof typeof defaultCRCValues;
function getCRCs(rawContent: Uint8Array | string) {
const content = rawContent as Buffer | string;
return {
crc1: crc.crc1(content).toString(16),
crc8: crc.crc8(content).toString(16),
crc81wire: crc.crc81wire(content).toString(16),
crc8dvbs2: crc.crc8dvbs2(content).toString(16),
crc16: crc.crc16(content).toString(16),
crc16ccitt: crc.crc16ccitt(content).toString(16),
crc16modbus: crc.crc16modbus(content).toString(16),
crc16kermit: crc.crc16kermit(content).toString(16),
crc16xmodem: crc.crc16xmodem(content).toString(16),
crc24: crc.crc24(content).toString(16),
crc32: crc.crc32(content).toString(16),
crc32mpeg: crc.crc32mpeg2(content).toString(16),
crcjam: crc.crcjam(content).toString(16),
};
}
const hashes = ref(defaultCRCValues);
async function onUpload(uploadedFile: File) {
status.value = 'processing';
@@ -66,23 +30,12 @@ async function onUpload(uploadedFile: File) {
}
}
const algoWasmNames = Object.keys(defaultCRCValues) as AlgoNames[];
type Encoding = keyof typeof enc | 'Bin';
const encoding = useQueryParamOrStorage<Encoding>({
defaultValue: 'Hex',
storageName: 'hash-text:encoding',
name: 'encoding',
});
function formatWithEncoding(words: lib.WordArray, encoding: Encoding) {
if (encoding === 'Bin') {
return convertHexToBin(words.toString(enc.Hex));
}
return words.toString(enc[encoding]);
}
const CRCValues = computed(() =>
withDefaultOnError(() => {
const encodingValue = encoding.value;
@@ -90,7 +43,7 @@ const CRCValues = computed(() =>
const ret = defaultCRCValues;
for (const algo of algoWasmNames) {
ret[algo] = formatWithEncoding(enc.Hex.parse(hashesValue[algo]), encodingValue);
ret[algo] = formatHexWithEncoding(hashesValue[algo], encodingValue);
}
return ret;
}, defaultCRCValues),
@@ -0,0 +1,152 @@
import { describe, expect, it } from 'vitest';
import { algos } from './encryption.service';
const message = 'Lorem ipsum dolor sit amet';
// 32 bytes, so that every algorithm accepts it: the aes variants take 16/24/32 bytes and the
// salsa/chacha variants require exactly 32.
const hexKey = '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f';
const textKey = 'my secret key 16my secret key 16';
const algoNames = Object.keys(algos) as (keyof typeof algos)[];
// AES-KW only wraps key material: its input must be a multiple of 8 bytes, so arbitrary text is rejected.
const algoNamesAcceptingText = algoNames.filter(algo => algo !== 'AES-KW');
describe('encryption', () => {
describe('algos', () => {
it('exposes the algorithms in the order the ui renders them', () => {
expect(algoNames).toEqual([
'TripleDES',
'Rabbit',
'RC4',
'AES-GCM',
'AES-SIV',
'AES-CTR',
'AES-CFB',
'AES-CBC',
'AES-ECB',
'AES-KW',
'AES-KWP',
'Salsa-XSalsa20poly1305',
'Chacha-Chacha20poly1305',
'Chacha-XChacha20poly1305',
'Salsa-Salsa20',
'Salsa-XSalsa20',
'Chacha-Chacha20',
'Chacha-XChacha20',
'Chacha-Chacha8',
'Chacha-Chacha12 ',
]);
});
});
describe('round trip', () => {
it.each(algoNamesAcceptingText)('%s encrypts and decrypts back with an hexadecimal key', (algo) => {
expect(algos[algo].decrypt(algos[algo].encrypt(message, hexKey, 'Hex'), hexKey, 'Hex')).toEqual(message);
});
it.each(algoNamesAcceptingText)('%s encrypts and decrypts back with a plain text key', (algo) => {
expect(algos[algo].decrypt(algos[algo].encrypt(message, textKey, 'Text'), textKey, 'Text')).toEqual(message);
});
// AES-KWP pads its input to a multiple of 8 bytes but still requires at least one byte.
it.each(algoNamesAcceptingText.filter(algo => algo !== 'AES-KWP'))(
'%s round trips an empty message',
(algo) => {
expect(algos[algo].decrypt(algos[algo].encrypt('', hexKey, 'Hex'), hexKey, 'Hex')).toEqual('');
},
);
it('AES-KWP rejects an empty message', () => {
expect(() => algos['AES-KWP'].encrypt('', hexKey, 'Hex')).toThrow('invalid plaintext length');
});
it.each(algoNamesAcceptingText)('%s round trips non-ascii content', (algo) => {
const unicode = 'héllo € 日本 🔐';
expect(algos[algo].decrypt(algos[algo].encrypt(unicode, hexKey, 'Hex'), hexKey, 'Hex')).toEqual(unicode);
});
it('AES-KW only accepts inputs whose length is a multiple of 8 bytes', () => {
expect(() => algos['AES-KW'].encrypt(message, hexKey, 'Hex')).toThrow();
expect(algos['AES-KW'].decrypt(algos['AES-KW'].encrypt('0123456789abcdef', hexKey, 'Hex'), hexKey, 'Hex')).toEqual(
'0123456789abcdef',
);
});
});
// These pin the exact ciphertexts the tool has always produced, so that anything encrypted with a
// previous version of it-tools can still be decrypted.
describe('legacy ciphertexts', () => {
it.each<[keyof typeof algos, string, string]>([
['TripleDES', '000102030405060708090a0b0c0d0e0f1011121314151617', 'U0hH7zp0yBXvfPYdKWdndZZkjfT9PmU/44Ked0J30Aw='],
['TripleDES', '00112233445566778899aabbccddeeff', '8jBStRvbRaOH+fBhicWLyqV6X1AaOpCkHv2ZYLNQADQ='],
['RC4', '000102030405060708090a0b0c0d0e0f1011121314151617', 'ZvyH7eY06NnEk/i8gGFhLM6N+y6Mf5ng+2I='],
['RC4', '00112233445566778899aabbccddeeff', 'yTTeMv8HCPWLLNQb8SoR+3vl4DnVN+pDBdU='],
['Rabbit', '000102030405060708090a0b0c0d0e0f1011121314151617', '5JiU/gRgzv1gHzE1LnoVPdTEUDEtw2NNjxw='],
['Rabbit', '00112233445566778899aabbccddeeff', 'RwdmiqzmfNyS7k/7VpCqdzE0UGdrF1F+k2o='],
])('%s with the hexadecimal key %s', (algo, key, expected) => {
expect(algos[algo].encrypt(message, key, 'Hex')).toEqual(expected);
expect(algos[algo].decrypt(expected, key, 'Hex')).toEqual(message);
});
it.each<[keyof typeof algos, string]>([
['TripleDES', 'U0hH7zp0yBXvfPYdKWdndZZkjfT9PmU/44Ked0J30Aw='],
['Rabbit', '5JiU/gRgzv1gHzE1LnoVPdTEUDEtw2NNjxw='],
['RC4', 'XEuDrMePwE0FSfOgbFoF/L6pUx2n7sXQA44='],
['AES-ECB', 'HT97lv4ramN0LrSKNLdEZXsMl3FnpUBzbnmb13zQ22M='],
['AES-KWP', 'oE0hxSLq5a1mPX1W8Rx33aXY8GwFeYnJcFt7k1xAhHhdJxs/EOyaJg=='],
])('%s is deterministic with the 32 byte hexadecimal key', (algo, expected) => {
expect(algos[algo].encrypt(message, hexKey, 'Hex')).toEqual(expected);
expect(algos[algo].decrypt(expected, hexKey, 'Hex')).toEqual(message);
});
it.each<[keyof typeof algos, string]>([
['TripleDES', 'U2FsdGVkX18x0ZcSvWVAPwBWufCZWGvkKEL4SC7VHCduC1hmGS6wgMRECvJlNjOo'],
['RC4', 'U2FsdGVkX18Qr/9zZ+1Xm/kGxEoD/GHWU+VbphyZxc1YPHMVVIU2WRal'],
['Rabbit', 'U2FsdGVkX1+PUswpDnaEQuYjAnWIrgOE54cwBGKSii7JDaEOltR01Uwc'],
])('%s decrypts an openssl salted ciphertext produced with a passphrase', (algo, ciphertext) => {
expect(algos[algo].decrypt(ciphertext, 'my secret key 16', 'Text')).toEqual(message);
});
});
describe('passphrase based ciphers', () => {
it.each<keyof typeof algos>(['TripleDES', 'Rabbit', 'RC4'])(
'%s salts every encryption, so the same input yields a different ciphertext',
(algo) => {
const first = algos[algo].encrypt(message, 'my secret key 16', 'Text');
const second = algos[algo].encrypt(message, 'my secret key 16', 'Text');
expect(first).not.toEqual(second);
// base64 of the "Salted__" openssl header
expect(first.startsWith('U2FsdGVkX1')).toBe(true);
expect(algos[algo].decrypt(first, 'my secret key 16', 'Text')).toEqual(message);
expect(algos[algo].decrypt(second, 'my secret key 16', 'Text')).toEqual(message);
},
);
});
describe('wrong keys', () => {
it('does not return the clear text when decrypting with another key', () => {
const ciphertext = algos.RC4.encrypt(message, hexKey, 'Hex');
// the plain bytes decoded with the wrong key are not valid utf-8, which the ui surfaces as an error
expect(() => algos.RC4.decrypt(ciphertext, 'f'.repeat(64), 'Hex')).toThrow('Malformed UTF-8 data');
});
it('does not return the clear text when an authenticated cipher is given another key', () => {
const ciphertext = algos['AES-GCM'].encrypt(message, hexKey, 'Hex');
expect(() => algos['AES-GCM'].decrypt(ciphertext, 'f'.repeat(64), 'Hex')).toThrow();
});
it('rejects a key that is not valid hexadecimal for the noble ciphers', () => {
expect(() => algos['AES-GCM'].encrypt(message, 'not-hex', 'Hex')).toThrow();
});
it('rejects a 3DES key that is too short', () => {
expect(() => algos.TripleDES.encrypt(message, 'aabb', 'Hex')).toThrow();
});
});
});
+13 -9
View File
@@ -1,22 +1,26 @@
import { Buffer } from 'node:buffer';
import { RC4, Rabbit, TripleDES, enc } from 'crypto-js';
import { Hex, RC4, Rabbit, TripleDES, Utf8 } from 'crypto-es';
import { managedNonce, randomBytes } from '@noble/ciphers/webcrypto';
import { aeskw, aeskwp, cbc, cfb, ctr, ecb, gcm, siv } from '@noble/ciphers/aes';
import { salsa20, xsalsa20, xsalsa20poly1305 } from '@noble/ciphers/salsa';
import { chacha12, chacha20, chacha20poly1305, chacha8, xchacha20, xchacha20poly1305 } from '@noble/ciphers/chacha';
import { bytesToUtf8, hexToBytes, utf8ToBytes } from '@noble/ciphers/utils';
function getCryptoJSKey(key: string, keyEncoding: KeyEncoding) {
return keyEncoding === 'Text' ? key : enc.Hex.parse(key);
function getCryptoESKey(key: string, keyEncoding: KeyEncoding) {
return keyEncoding === 'Text' ? key : Hex.parse(key);
}
function getNobleKey(key: string, keyEncoding: KeyEncoding) {
return keyEncoding === 'Text' ? utf8ToBytes(key) : hexToBytes(key);
}
function getCryptoJSCipher(cipher: any) {
// The empty iv is load bearing, not leftover scaffolding: it is what makes the block ciphers run
// with an all zero iv, which is how every ciphertext this tool has produced so far was built.
// Dropping it makes TripleDES throw and changes the Rabbit keystream, so old ciphertexts would no
// longer decrypt.
function getCryptoESCipher(cipher: any) {
return {
encrypt: (value: string, key: string, keyEncoding: KeyEncoding) => cipher.encrypt(value, getCryptoJSKey(key, keyEncoding), { iv: enc.Hex.parse('') }).toString(),
decrypt: (value: string, key: string, keyEncoding: KeyEncoding) => cipher.decrypt(value, getCryptoJSKey(key, keyEncoding), { iv: enc.Hex.parse('') }).toString(enc.Utf8),
encrypt: (value: string, key: string, keyEncoding: KeyEncoding) => cipher.encrypt(value, getCryptoESKey(key, keyEncoding), { iv: Hex.parse('') }).toString(),
decrypt: (value: string, key: string, keyEncoding: KeyEncoding) => cipher.decrypt(value, getCryptoESKey(key, keyEncoding), { iv: Hex.parse('') }).toString(Utf8),
};
}
function getNobleCipher(algo: any, nonceType: 'auto' | 'none' | 'manual' = 'auto', nonceSize: number = 0) {
@@ -49,9 +53,9 @@ function getNobleCipher(algo: any, nonceType: 'auto' | 'none' | 'manual' = 'auto
}
export const algos = {
'TripleDES': getCryptoJSCipher(TripleDES),
'Rabbit': getCryptoJSCipher(Rabbit),
'RC4': getCryptoJSCipher(RC4),
'TripleDES': getCryptoESCipher(TripleDES),
'Rabbit': getCryptoESCipher(Rabbit),
'RC4': getCryptoESCipher(RC4),
'AES-GCM': getNobleCipher(gcm),
'AES-SIV': getNobleCipher(siv),
'AES-CTR': getNobleCipher(ctr),
+1 -1
View File
@@ -9,6 +9,6 @@ export const tool = defineTool({
component: () => import('./encryption.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Lock')),
redirectFrom: ['/cypher'],
npmPackages: ['crypto-s'],
npmPackages: ['crypto-es', '@noble/ciphers'],
category: 'Crypto',
});
+3 -14
View File
@@ -24,12 +24,11 @@ import {
// createXXHash3, //(seedLow: number, seedHigh: number): Promise<IHasher>
// createXXHash128, //(seedLow: number, seedHigh: number): Promise<IHasher>
} from 'hash-wasm';
import type { lib } from 'crypto-js';
import { enc } from 'crypto-js';
import type { IHasher } from 'hash-wasm/dist/lib/WASMInterface';
import InputCopyable from '../../components/InputCopyable.vue';
import { convertHexToBin } from '../hash-text/hash-text.service';
import type { Encoding } from '../hash-text/hash-text.service';
import { formatHexWithEncoding } from '../hash-text/hash-text.service';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { withDefaultOnError } from '@/utils/defaults';
@@ -140,22 +139,12 @@ async function onUpload(uploadedFile: File) {
}
}
type Encoding = keyof typeof enc | 'Bin';
const encoding = useQueryParamOrStorage<Encoding>({
defaultValue: 'Hex',
storageName: 'hash-text:encoding',
name: 'encoding',
});
function formatWithEncoding(words: lib.WordArray, encoding: Encoding) {
if (encoding === 'Bin') {
return convertHexToBin(words.toString(enc.Hex));
}
return words.toString(enc[encoding]);
}
const hashWasmValues = computed(() =>
withDefaultOnError(() => {
const encodingValue = encoding.value;
@@ -163,7 +152,7 @@ const hashWasmValues = computed(() =>
const ret = defaultHashWasmValues;
for (const algo of algoWasmNames) {
ret[algo] = formatWithEncoding(enc.Hex.parse(hashesValue[algo]), encodingValue);
ret[algo] = formatHexWithEncoding(hashesValue[algo], encodingValue);
}
return ret;
}, defaultHashWasmValues),
+102 -1
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import { convertHexToBin } from './hash-text.service';
import type { AlgoNames, Encoding } from './hash-text.service';
import { algoNames, convertHexToBin, formatHexWithEncoding, hashText } from './hash-text.service';
describe('hash text', () => {
describe('convertHexToBin', () => {
@@ -12,4 +13,104 @@ describe('hash text', () => {
);
});
});
describe('algoNames', () => {
it('exposes the algorithms in the order the ui renders them', () => {
expect(algoNames).toEqual(['MD5', 'SHA1', 'SHA256', 'SHA224', 'SHA512', 'SHA384', 'SHA3', 'RIPEMD160']);
});
});
describe('hashText', () => {
it.each<[AlgoNames, string]>([
['MD5', '65a8e27d8879283831b664bd8b7f0ad4'],
['SHA1', '0a0a9f2a6772942557ab5355d76af442f8f65e01'],
['SHA256', 'dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f'],
['SHA224', '72a23dfa411ba6fde01dbfabf3b00a709c93ebf273dc29e2d8b261ff'],
[
'SHA512',
'374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6cc69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387',
],
['SHA384', '5485cc9b3365b4305dfb4e8337e0a598a574f8242bf17289e0dd6c20a3cd44a089de16ab4ab308f63e44b1170eb5f515'],
[
'SHA3',
'eda765576c84c600ed7f5d97510e92703b61f5215def2a161037fd9dd1f5b6ed4f86ce46073c0e3f34b52de0289e9c618798fff9dd4b1bfe035bdb8645fc6e37',
],
['RIPEMD160', '527a6a4b9a6da75607546842e0e00105350b1aaf'],
])('hashes "Hello, World!" with %s', (algo, expected) => {
expect(hashText(algo, 'Hello, World!', 'Hex')).toEqual(expected);
});
it.each<[AlgoNames, string]>([
['MD5', 'd41d8cd98f00b204e9800998ecf8427e'],
['SHA1', 'da39a3ee5e6b4b0d3255bfef95601890afd80709'],
['SHA256', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'],
['SHA224', 'd14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f'],
[
'SHA512',
'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e',
],
['SHA384', '38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b'],
[
'SHA3',
'0eab42de4c3ceb9235fc91acffe746b29c29a8c366b7c60e4e67c466f36a4304c00fa9caf9d87976ba469bcbe06713b435f091ef2769fb160cdab33d3670680e',
],
['RIPEMD160', '9c1185a5c5e9fc54612808977ee8f548b2258d31'],
])('hashes the empty string with %s', (algo, expected) => {
expect(hashText(algo, '', 'Hex')).toEqual(expected);
});
it('hashes non-ascii text as utf-8', () => {
expect(hashText('MD5', 'héllo € 日本', 'Hex')).toEqual('7e7be0494c46bf5b05c19a5d30286957');
});
it('renders the digest in every supported encoding', () => {
expect(hashText('SHA256', 'abc', 'Hex')).toEqual(
'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
);
expect(hashText('SHA256', 'abc', 'Base64')).toEqual('ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=');
expect(hashText('SHA256', 'abc', 'Base64url')).toEqual('ungWv48Bz-pBQUDeXa4iI7ADYaOWF3qctBD_YfIAFa0');
expect(hashText('SHA256', 'abc', 'Bin')).toEqual(
'1011101001111000000101101011111110001111000000011100111111101010010000010100000101000000110111100101110110101110001000100010001110110000000000110110000110100011100101100001011101111010100111001011010000010000111111110110000111110010000000000001010110101101',
);
});
});
describe('formatHexWithEncoding', () => {
// The 'Base64'/'Base64url' columns keep the historical behaviour for odd-length digests (as produced by
// the crc tool): the trailing half-byte is zeroed before base64 encoding, while 'Hex' keeps it.
it.each<[string, string, string, string, string]>([
['', '', '', '', ''],
['5', '00000101', '05', 'A===', 'A'],
['a', '00001010', '0a', 'A===', 'A'],
['abc', '1010101100001100', 'ab0c', 'qw==', 'qw'],
['deadbeef', '11011110101011011011111011101111', 'deadbeef', '3q2+7w==', '3q2-7w'],
['ffffffff', '11111111111111111111111111111111', 'ffffffff', '/////w==', '_____w'],
['0f0f0f0f0f', '0000111100001111000011110000111100001111', '0f0f0f0f0f', 'Dw8PDw8=', 'Dw8PDw8'],
[
'900150983cd24fb0d6963f7d28e17f72',
'10010000000000010101000010011000001111001101001001001111101100001101011010010110001111110111110100101000111000010111111101110010',
'900150983cd24fb0d6963f7d28e17f72',
'kAFQmDzST7DWlj99KOF/cg==',
'kAFQmDzST7DWlj99KOF_cg',
],
])('re-encodes the digest %s', (hex, bin, hexOut, base64, base64url) => {
expect(formatHexWithEncoding(hex, 'Bin')).toEqual(bin);
expect(formatHexWithEncoding(hex, 'Hex')).toEqual(hexOut);
expect(formatHexWithEncoding(hex, 'Base64')).toEqual(base64);
expect(formatHexWithEncoding(hex, 'Base64url')).toEqual(base64url);
});
it('does not mutate its input across successive encodings', () => {
const encodings: Encoding[] = ['Hex', 'Base64', 'Hex', 'Base64url', 'Bin', 'Hex'];
expect(encodings.map(encoding => formatHexWithEncoding('deadbeef', encoding))).toEqual([
'deadbeef',
'3q2+7w==',
'deadbeef',
'3q2-7w',
'11011110101011011011111011101111',
'deadbeef',
]);
});
});
});
+65
View File
@@ -1,3 +1,51 @@
import type { WordArray } from 'crypto-es';
import {
Base64,
Base64url,
Hex,
Latin1,
MD5,
RIPEMD160,
SHA1,
SHA3,
SHA224,
SHA256,
SHA384,
SHA512,
Utf8,
Utf16,
Utf16BE,
Utf16LE,
} from 'crypto-es';
export const encodings = {
Hex,
Latin1,
Utf8,
Utf16BE,
Utf16,
Utf16LE,
Base64,
Base64url,
};
export type Encoding = keyof typeof encodings | 'Bin';
export const algos = {
MD5,
SHA1,
SHA256,
SHA224,
SHA512,
SHA384,
SHA3,
RIPEMD160,
} as const;
export type AlgoNames = keyof typeof algos;
export const algoNames = Object.keys(algos) as AlgoNames[];
export function convertHexToBin(hex: string) {
return hex
.trim()
@@ -5,3 +53,20 @@ export function convertHexToBin(hex: string) {
.map(byte => Number.parseInt(byte, 16).toString(2).padStart(4, '0'))
.join('');
}
export function formatWithEncoding(words: WordArray, encoding: Encoding) {
if (encoding === 'Bin') {
return convertHexToBin(words.toString(encodings.Hex));
}
return words.toString(encodings[encoding]);
}
// Re-encodes an already computed hexadecimal digest, as produced by the wasm hashers and the crc library.
export function formatHexWithEncoding(hex: string, encoding: Encoding) {
return formatWithEncoding(encodings.Hex.parse(hex), encoding);
}
export function hashText(algo: AlgoNames, value: string, encoding: Encoding) {
return formatWithEncoding(algos[algo](value), encoding);
}
+4 -30
View File
@@ -1,7 +1,5 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { lib } from 'crypto-js';
import { MD5, RIPEMD160, SHA1, SHA224, SHA256, SHA3, SHA384, SHA512, enc } from 'crypto-js';
import {
adler32,
@@ -24,26 +22,12 @@ import {
} from 'hash-wasm';
import InputCopyable from '../../components/InputCopyable.vue';
import { convertHexToBin } from './hash-text.service';
import type { Encoding } from './hash-text.service';
import { algoNames, formatHexWithEncoding, hashText } from './hash-text.service';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const { t } = useI18n();
const algos = {
MD5,
SHA1,
SHA256,
SHA224,
SHA512,
SHA384,
SHA3,
RIPEMD160,
} as const;
type AlgoNames = keyof typeof algos;
type Encoding = keyof typeof enc | 'Bin';
const algoNames = Object.keys(algos) as AlgoNames[];
const algosWasm = {
adler32,
crc32,
@@ -65,16 +49,6 @@ const algoWasmNames = Object.keys(algosWasm) as AlgoWasmNames[];
const encoding = useQueryParamOrStorage<Encoding>({ defaultValue: 'Hex', storageName: 'hash-text:encoding', name: 'encoding' });
const clearText = ref('');
function formatWithEncoding(words: lib.WordArray, encoding: Encoding) {
if (encoding === 'Bin') {
return convertHexToBin(words.toString(enc.Hex));
}
return words.toString(enc[encoding]);
}
const hashText = (algo: AlgoNames, value: string) => formatWithEncoding(algos[algo](value), encoding.value);
const defaultHashWasmValues = {
adler32: '',
crc32: '',
@@ -94,7 +68,7 @@ const hashWasmValues = computedAsync(async () => {
const clearTextValue = clearText.value;
const ret = defaultHashWasmValues;
for (const algo of algoWasmNames) {
ret[algo] = formatWithEncoding(enc.Hex.parse(await algosWasm[algo](clearTextValue)), encodingValue);
ret[algo] = formatHexWithEncoding(await algosWasm[algo](clearTextValue), encodingValue);
}
return ret;
}, defaultHashWasmValues);
@@ -190,7 +164,7 @@ const hashWasmPBKDF2 = computedAsync(async () => {
<n-input-group-label style="flex: 0 0 120px">
{{ algo }}
</n-input-group-label>
<InputCopyable :value="hashText(algo, clearText)" readonly />
<InputCopyable :value="hashText(algo, clearText, encoding)" readonly />
</n-input-group>
</div>
@@ -0,0 +1,89 @@
import { describe, expect, it } from 'vitest';
import type { AlgoNames } from './hmac-generator.service';
import { algos, computeHmac } from './hmac-generator.service';
const plainText = 'The quick brown fox';
const secret = 'secret-key';
describe('hmac-generator', () => {
describe('algos', () => {
it('exposes the hash functions in the order the ui renders them', () => {
expect(Object.keys(algos)).toEqual(['MD5', 'RIPEMD160', 'SHA1', 'SHA3', 'SHA224', 'SHA256', 'SHA384', 'SHA512']);
});
});
describe('computeHmac', () => {
it.each<[AlgoNames, string]>([
['MD5', 'fd9d5bf7eba2cee3bf0eefb3d35427a2'],
['RIPEMD160', '991ff9d8ec73656a80b39bd84311ce5c63c27f75'],
['SHA1', 'a1227cb668d79ba40f687f384e525074b477397c'],
[
'SHA3',
'6bce2a56a578b542ab0e2858b44b25f158155c4ecb7b380a902c6792d74bff54f360193977e02e0b53b810085ddb68716a0540b9e1fff24cd8019213fda08e1d',
],
['SHA224', '3a3b5ff96301a710558afcb3a54368dbf3c11cb441428f805880a337'],
['SHA256', 'fb8626bea6af7aca505231f3fa99c27995e34bf32128625aac73ac2a67d8b409'],
['SHA384', '52d4b58187ef42c054ecd867b4fbea503901ab4554d67cc89fac6e8d59dbd8b0f636b40a3a02fec8c2f316bf30c34030'],
[
'SHA512',
'8de43db68a03ce898fb535d3a8d199281e96368ec8ab755b49c12b1b718cf4228e9ab00b45de3b9175efa39759ff640d2b31490fb803ee5b924b1eca679b7a97',
],
])('computes an %s hmac with a plain text key', (hashFunction, expected) => {
expect(computeHmac({ plainText, secret, hashFunction, keyEncoding: 'Text', encoding: 'Hex' })).toEqual(expected);
});
it('computes an hmac with an hexadecimal key', () => {
expect(
computeHmac({ plainText, secret: '00ff10ab', hashFunction: 'SHA256', keyEncoding: 'Hex', encoding: 'Hex' }),
).toEqual('31136fb961306fb90091e9ba85cbfb862b1ecaa62ab831e67540d346f3d39ca7');
});
it('treats a plain text key and its hexadecimal representation as different keys', () => {
const asText = computeHmac({
plainText,
secret: '00ff10ab',
hashFunction: 'SHA256',
keyEncoding: 'Text',
encoding: 'Hex',
});
const asHex = computeHmac({
plainText,
secret: '00ff10ab',
hashFunction: 'SHA256',
keyEncoding: 'Hex',
encoding: 'Hex',
});
expect(asText).not.toEqual(asHex);
});
it('renders the hmac in every supported encoding', () => {
const args = { plainText, secret, hashFunction: 'SHA256', keyEncoding: 'Text' } as const;
expect(computeHmac({ ...args, encoding: 'Hex' })).toEqual(
'fb8626bea6af7aca505231f3fa99c27995e34bf32128625aac73ac2a67d8b409',
);
expect(computeHmac({ ...args, encoding: 'Base64' })).toEqual(
'+4YmvqavespQUjHz+pnCeZXjS/MhKGJarHOsKmfYtAk=',
);
expect(computeHmac({ ...args, encoding: 'Base64url' })).toEqual(
'-4YmvqavespQUjHz-pnCeZXjS_MhKGJarHOsKmfYtAk',
);
expect(computeHmac({ ...args, encoding: 'Bin' })).toEqual(
'1111101110000110001001101011111010100110101011110111101011001010010100000101001000110001111100111111101010011001110000100111100110010101111000110100101111110011001000010010100001100010010110101010110001110011101011000010101001100111110110001011010000001001',
);
});
it('handles an empty message and an empty key', () => {
expect(
computeHmac({ plainText: '', secret: '', hashFunction: 'SHA256', keyEncoding: 'Text', encoding: 'Hex' }),
).toEqual('b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad');
});
it('handles an odd length hexadecimal key', () => {
expect(
computeHmac({ plainText: 'msg', secret: 'abc', hashFunction: 'SHA256', keyEncoding: 'Hex', encoding: 'Hex' }),
).toEqual('d89e19442aad8643ea8ef0e93f5e60b0f1ca3445357b77080ff844adb08e21b7');
});
});
});
@@ -0,0 +1,46 @@
import {
Hex,
HmacMD5,
HmacRIPEMD160,
HmacSHA1,
HmacSHA3,
HmacSHA224,
HmacSHA256,
HmacSHA384,
HmacSHA512,
} from 'crypto-es';
import type { Encoding } from '../hash-text/hash-text.service';
import { formatWithEncoding } from '../hash-text/hash-text.service';
export const algos = {
MD5: HmacMD5,
RIPEMD160: HmacRIPEMD160,
SHA1: HmacSHA1,
SHA3: HmacSHA3,
SHA224: HmacSHA224,
SHA256: HmacSHA256,
SHA384: HmacSHA384,
SHA512: HmacSHA512,
} as const;
export type AlgoNames = keyof typeof algos;
export type KeyEncoding = 'Text' | 'Hex';
export function computeHmac({
plainText,
secret,
hashFunction,
keyEncoding,
encoding,
}: {
plainText: string
secret: string
hashFunction: AlgoNames
keyEncoding: KeyEncoding
encoding: Encoding
}) {
// normalize secret according to the key encoding
const key = keyEncoding === 'Text' ? secret : Hex.parse(secret);
return formatWithEncoding(algos[hashFunction](plainText, key), encoding);
}
+13 -40
View File
@@ -1,54 +1,27 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { lib } from 'crypto-js';
import {
HmacMD5,
HmacRIPEMD160,
HmacSHA1,
HmacSHA224,
HmacSHA256,
HmacSHA3,
HmacSHA384,
HmacSHA512,
enc,
} from 'crypto-js';
import { convertHexToBin } from '../hash-text/hash-text.service';
import type { Encoding } from '../hash-text/hash-text.service';
import type { AlgoNames, KeyEncoding } from './hmac-generator.service';
import { algos, computeHmac } from './hmac-generator.service';
import { useCopy } from '@/composable/copy';
const { t } = useI18n();
const algos = {
MD5: HmacMD5,
RIPEMD160: HmacRIPEMD160,
SHA1: HmacSHA1,
SHA3: HmacSHA3,
SHA224: HmacSHA224,
SHA256: HmacSHA256,
SHA384: HmacSHA384,
SHA512: HmacSHA512,
} as const;
type Encoding = keyof typeof enc | 'Bin';
type KeyEncoding = 'Text' | 'Hex';
function formatWithEncoding(words: lib.WordArray, encoding: Encoding) {
if (encoding === 'Bin') {
return convertHexToBin(words.toString(enc.Hex));
}
return words.toString(enc[encoding]);
}
const plainText = ref('');
const secret = ref('');
const hashFunction = ref<keyof typeof algos>('SHA256');
const hashFunction = ref<AlgoNames>('SHA256');
const encoding = ref<Encoding>('Hex');
const keyEncoding = ref<KeyEncoding>('Text');
const hmac = computed(() => {
// normalize secret according to the key encoding
const key = keyEncoding.value === 'Text' ? secret.value : enc.Hex.parse(secret.value);
return formatWithEncoding(algos[hashFunction.value](plainText.value, key), encoding.value);
});
const hmac = computed(() =>
computeHmac({
plainText: plainText.value,
secret: secret.value,
hashFunction: hashFunction.value,
keyEncoding: keyEncoding.value,
encoding: encoding.value,
}),
);
const { copy } = useCopy({ source: hmac });
</script>
+1 -1
View File
@@ -8,6 +8,6 @@ export const tool = defineTool({
keywords: ['hmac', 'generator', 'MD5', 'SHA1', 'SHA256', 'SHA224', 'SHA512', 'SHA384', 'SHA3', 'RIPEMD160'],
component: () => import('./hmac-generator.vue'),
icon: defineAsyncComponent(() => import('@vicons/material/es/ShortTextRound')),
npmPackages: ['crypto-js'],
npmPackages: ['crypto-es'],
category: 'Crypto',
});
+1 -1
View File
@@ -8,6 +8,6 @@ export const tool = defineTool({
keywords: ['html', 'wysiwyg', 'editor', 'p', 'ul', 'ol', 'converter', 'live'],
component: () => import('./html-wysiwyg-editor.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Edit')),
npmPackages: ['monaco', 'prettier'],
npmPackages: ['@tiptap/vue-3', 'htmlfy'],
category: 'Web',
});
@@ -0,0 +1,80 @@
import { beforeAll, describe, expect, it } from 'vitest';
// the repo aliases `node:fs` to an empty stub, so the binary is inlined by vite instead of read from disk
import wasmDataUrl from '@resvg/resvg-wasm/index_bg.wasm?url&inline';
import { convertSvgToPng, initializeSvgRenderer } from './image-converter.service';
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="50"><rect width="100" height="50" fill="#18a058"/></svg>';
function readPngSize(png: Uint8Array) {
const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
// width and height are the first two fields of the IHDR chunk, which always comes first
return { width: view.getUint32(16), height: view.getUint32(20) };
}
function isPng(bytes: Uint8Array) {
return [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A].every((byte, index) => bytes[index] === byte);
}
describe('image-converter', () => {
const loadWasm = async () => new Uint8Array(await (await fetch(wasmDataUrl)).arrayBuffer());
let firstAttemptError: unknown;
beforeAll(async () => {
// a failed download must not be memoized: this first attempt fails, and the next one still has
// to initialize the renderer for the rest of the suite
await initializeSvgRenderer(() => Promise.reject(new Error('network is down'))).catch((error) => {
firstAttemptError = error;
});
await initializeSvgRenderer(loadWasm);
});
describe('convertSvgToPng', () => {
it('rasterizes an svg to a png', async () => {
const png = await convertSvgToPng({ svg, scale: 1 });
expect(isPng(png)).toBe(true);
expect(readPngSize(png)).toEqual({ width: 100, height: 50 });
});
it('scales the output', async () => {
expect(readPngSize(await convertSvgToPng({ svg, scale: 2 }))).toEqual({ width: 200, height: 100 });
expect(readPngSize(await convertSvgToPng({ svg, scale: 4 }))).toEqual({ width: 400, height: 200 });
expect(readPngSize(await convertSvgToPng({ svg, scale: 0.5 }))).toEqual({ width: 50, height: 25 });
});
it.each<[string, string]>([
['the default family', '<text x="10" y="30" font-size="20">it-tools</text>'],
['an explicit roboto family', '<text x="10" y="30" font-size="20" font-family="Roboto">it-tools</text>'],
])('draws text using %s', async (_, text) => {
const canvas = (content: string) =>
`<svg xmlns="http://www.w3.org/2000/svg" width="200" height="50">${content}</svg>`;
const blank = await convertSvgToPng({ svg: canvas(''), scale: 1 });
const png = await convertSvgToPng({ svg: canvas(text), scale: 1 });
expect(isPng(png)).toBe(true);
expect(readPngSize(png)).toEqual({ width: 200, height: 50 });
// something was actually drawn: svg2png-wasm used to return an empty canvas for the second case
expect(png).not.toEqual(blank);
});
it('rejects content that is not an svg', async () => {
await expect(convertSvgToPng({ svg: 'not an svg at all', scale: 1 })).rejects.toThrow();
});
});
describe('initializeSvgRenderer', () => {
it('surfaces a failed download without memoizing it', () => {
// the whole suite renders fine afterwards, which is what proves the retry actually happened
expect(firstAttemptError).toEqual(new Error('network is down'));
});
it('only initializes the wasm module once, as a second call would throw', async () => {
await expect(initializeSvgRenderer(() => {
throw new Error('should not be called again');
})).resolves.toBeUndefined();
});
});
});
@@ -0,0 +1,56 @@
import type { InitInput } from '@resvg/resvg-wasm';
import { Resvg, initWasm } from '@resvg/resvg-wasm';
import { Base64 } from 'js-base64';
import { normal as robotoBase64 } from 'roboto-base64';
import resvgWasmUrl from '@resvg/resvg-wasm/index_bg.wasm?url';
type WasmLoader = () => Promise<InitInput> | InitInput;
const defaultWasmLoader: WasmLoader = () => fetch(resvgWasmUrl);
let initialization: Promise<void> | undefined;
/**
* `initWasm` throws when called more than once, so the very first call wins and every later one
* awaits it. The loader is injectable so tests can feed the binary without going through the network.
*/
export function initializeSvgRenderer(loadWasm: WasmLoader = defaultWasmLoader) {
initialization ??= Promise.resolve(loadWasm())
.then(input => initWasm(input))
.catch((error) => {
// a failed download must not be memoized, otherwise a single network hiccup would leave the
// tool broken until the page is reloaded
initialization = undefined;
throw error;
});
return initialization;
}
export async function convertSvgToPng({ svg, scale }: { svg: string; scale: number }) {
await initializeSvgRenderer();
const renderer = new Resvg(svg, {
fitTo: { mode: 'zoom', value: scale },
// Roboto is the only font embedded in the app, so it also has to be the fallback family:
// resvg defaults to a family that is not loaded, which would drop every text node.
font: {
fontBuffers: [Base64.toUint8Array(robotoBase64)],
defaultFontFamily: 'Roboto',
},
});
try {
const rendered = renderer.render();
try {
return rendered.asPng();
}
finally {
rendered.free();
}
}
finally {
renderer.free();
}
}
+3 -13
View File
@@ -14,8 +14,7 @@ import {
encodeTiff,
} from 'image-in-browser';
import { arrayBufferToWebP } from 'webp-converter-browser';
import { createSvg2png, initialize } from 'svg2png-wasm';
import { normal as robotoBase64 } from 'roboto-base64';
import { convertSvgToPng } from './image-converter.service';
import { useDownloadFileFromBase64 } from '@/composable/downloadBase64';
import { useQueryParamOrStorage } from '@/composable/queryParams';
@@ -88,8 +87,6 @@ const outputFormatHasQuality = computed(() => {
return outputFormat.value === 'jpg';
});
const svgWasmLoaded = ref(false);
async function onFilesUploaded(uploadedFiles: File[]) {
for (const file of uploadedFiles) {
await onFileUploaded(file);
@@ -109,17 +106,10 @@ async function onFileUploaded(uploadedFile: File) {
base64OutputFile.value = `data:image/webp;base64,${Base64.fromUint8Array(new Uint8Array(await encodedImage.arrayBuffer()))}`;
} else {
if (uploadedFile.type === 'image/svg+xml') {
if (!svgWasmLoaded.value) {
await initialize(fetch('/svg2png_wasm_bg.wasm'));
svgWasmLoaded.value = true;
}
const svg2png = createSvg2png({
fonts: [Base64.toUint8Array(robotoBase64)],
});
fileBuffer = (await svg2png(await readAsText(uploadedFile), {
fileBuffer = (await convertSvgToPng({
svg: await readAsText(uploadedFile),
scale: svgScale.value,
})) as Uint8Array<ArrayBuffer>;
svg2png.dispose();
}
const decodedImage = decodeImage({
data: fileBuffer,
+1 -1
View File
@@ -9,6 +9,6 @@ export const tool = defineTool({
component: () => import('./ipv6-ula-generator.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/BuildingFactory')),
createdAt: new Date('2023-04-09'),
npmPackages: ['crypto-js'],
npmPackages: ['crypto-es'],
category: 'Network',
});
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest';
import { generateUlaBlocks, generateUlaPrefix } from './ipv6-ula-generator.service';
describe('ipv6-ula-generator', () => {
describe('generateUlaPrefix', () => {
it.each<[number, string, string]>([
[0, '20:37:06:12:34:56', 'fda8:5b32:b6f9'],
[1700000000000, '20:37:06:12:34:56', 'fdb7:29eb:4229'],
[1234567890, 'aa:bb:cc:dd:ee:ff', 'fd0c:d4a8:7e9a'],
])('derives the prefix from timestamp %s and mac %s', (timestamp, macAddress, expected) => {
expect(generateUlaPrefix({ macAddress, timestamp })).toEqual(expected);
});
it('always starts with the fd00::/8 locally assigned prefix', () => {
for (let timestamp = 0; timestamp < 50; timestamp++) {
expect(generateUlaPrefix({ macAddress: '20:37:06:12:34:56', timestamp })).toMatch(
/^fd[0-9a-f]{2}:[0-9a-f]{4}:[0-9a-f]{4}$/,
);
}
});
it('is stable for a given timestamp and mac address', () => {
const args = { macAddress: '20:37:06:12:34:56', timestamp: 42 };
expect(generateUlaPrefix(args)).toEqual(generateUlaPrefix(args));
});
it('changes when the timestamp or the mac address changes', () => {
expect(generateUlaPrefix({ macAddress: '20:37:06:12:34:56', timestamp: 1 })).not.toEqual(
generateUlaPrefix({ macAddress: '20:37:06:12:34:56', timestamp: 2 }),
);
expect(generateUlaPrefix({ macAddress: '20:37:06:12:34:56', timestamp: 1 })).not.toEqual(
generateUlaPrefix({ macAddress: '20:37:06:12:34:57', timestamp: 1 }),
);
});
});
describe('generateUlaBlocks', () => {
it('builds the ula and its routable blocks', () => {
expect(generateUlaBlocks({ macAddress: '20:37:06:12:34:56', timestamp: 1700000000000 })).toEqual({
ula: 'fdb7:29eb:4229::/48',
firstRoutableBlock: 'fdb7:29eb:4229:0::/64',
lastRoutableBlock: 'fdb7:29eb:4229:ffff::/64',
});
});
});
});
@@ -0,0 +1,20 @@
import { SHA1 } from 'crypto-es';
// RFC 4193 §3.2.2: sha1 of the current timestamp concatenated with the mac address, keeping the lowest 40 bits.
export function generateUlaPrefix({ macAddress, timestamp }: { macAddress: string; timestamp: number }) {
const hex40bit = SHA1(timestamp + macAddress)
.toString()
.substring(30);
return `fd${hex40bit.substring(0, 2)}:${hex40bit.substring(2, 6)}:${hex40bit.substring(6)}`;
}
export function generateUlaBlocks({ macAddress, timestamp }: { macAddress: string; timestamp: number }) {
const ula = generateUlaPrefix({ macAddress, timestamp });
return {
ula: `${ula}::/48`,
firstRoutableBlock: `${ula}:0::/64`,
lastRoutableBlock: `${ula}:ffff::/64`,
};
}
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { SHA1 } from 'crypto-js';
import { generateUlaBlocks } from './ipv6-ula-generator.service';
import InputCopyable from '@/components/InputCopyable.vue';
import { macAddressValidation } from '@/utils/macAddress';
import { useQueryParam } from '@/composable/queryParams';
@@ -9,25 +9,23 @@ const { t } = useI18n();
const macAddress = useQueryParam({ tool: 'ipv6-ula-gen', name: 'mac', defaultValue: '20:37:06:12:34:56' });
const calculatedSections = computed(() => {
const timestamp = new Date().getTime();
const hex40bit = SHA1(timestamp + macAddress.value)
.toString()
.substring(30);
const ula = `fd${hex40bit.substring(0, 2)}:${hex40bit.substring(2, 6)}:${hex40bit.substring(6)}`;
const { ula, firstRoutableBlock, lastRoutableBlock } = generateUlaBlocks({
macAddress: macAddress.value,
timestamp: new Date().getTime(),
});
return [
{
label: t('tools.ipv6-ula-generator.texts.label-ipv6-ula'),
value: `${ula}::/48`,
value: ula,
},
{
label: t('tools.ipv6-ula-generator.texts.label-first-routable-block'),
value: `${ula}:0::/64`,
value: firstRoutableBlock,
},
{
label: t('tools.ipv6-ula-generator.texts.label-last-routable-block'),
value: `${ula}:ffff::/64`,
value: lastRoutableBlock,
},
];
});
@@ -24,6 +24,6 @@ export const tool = defineTool({
],
component: () => import('./otp-code-generator-and-validator.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/DeviceMobile')),
npmPackages: ['crypto-js'],
npmPackages: ['crypto-es'],
category: 'Generators',
});
@@ -62,6 +62,20 @@ describe('otp functions', () => {
expect(verifyHOTP({ token, key, counter: 5, window: 2 })).to.eql(false);
expect(verifyHOTP({ token, key, counter: 5, window: 5 })).to.eql(true);
});
// A window wider than the counter walks into negative counters, whose hexadecimal representation
// keeps the minus sign ('00000000000000-1'). The hex parser reads that as ffffffff rather than
// rejecting it, so these codes are stable rather than random, and validating around counter 0
// must not throw.
it('handles the negative counters a window around zero walks through', () => {
const key = 'JBSWY3DPEHPK3PXP';
expect(generateHOTP({ key, counter: -1 })).to.eql('681584');
expect(generateHOTP({ key, counter: -2 })).to.eql('072586');
expect(verifyHOTP({ token: '681584', key, counter: 0, window: 1 })).to.eql(true);
expect(verifyHOTP({ token: '282760', key, counter: 0, window: 3 })).to.eql(true);
expect(verifyHOTP({ token: 'INVALID', key, counter: 0, window: 3 })).to.eql(false);
});
});
describe('generateTOTP', () => {
@@ -1,4 +1,4 @@
import { HmacSHA1, enc } from 'crypto-js';
import { Hex, HmacSHA1 } from 'crypto-es';
import { createToken } from '../token-generator/token-generator.service';
export {
@@ -18,7 +18,7 @@ function hexToBytes(hex: string) {
}
function computeHMACSha1(message: string, key: string) {
return HmacSHA1(enc.Hex.parse(message), enc.Hex.parse(base32toHex(key))).toString(enc.Hex);
return HmacSHA1(Hex.parse(message), Hex.parse(base32toHex(key))).toString(Hex);
}
function base32toHex(base32: string) {
+1 -1
View File
@@ -1,4 +1,4 @@
import { MD5 } from 'crypto-js';
import { MD5 } from 'crypto-es';
import { translate as t } from '@/plugins/i18n.plugin';
export { getAuthHeaderCheckResult };
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest';
import packageJson from '../../package.json';
import { tools, toolsByCategory } from './index';
const declaredDependencies = {
...packageJson.dependencies,
...packageJson.devDependencies,
} as Record<string, string>;
describe('tools metadata', () => {
it('registers the tools of every category', () => {
expect(toolsByCategory.length).toBeGreaterThan(0);
expect(tools.length).toBeGreaterThan(0);
});
describe('npmPackages', () => {
// The tool pages advertise the libraries they are built on. A dependency that gets replaced has
// to be renamed here too, otherwise the ui links to a package the app no longer uses.
const declarations = tools.flatMap(tool =>
(tool.npmPackages ?? []).map(npmPackage => ({ tool: tool.name, npmPackage })),
);
it('only references packages the app actually depends on', () => {
const unknown = declarations
.filter(({ npmPackage }) => !npmPackage.includes('://'))
.filter(({ npmPackage }) => declaredDependencies[npmPackage] === undefined);
expect(unknown).toEqual([]);
});
it('does not reference the packages that were replaced', () => {
const replaced = [
'crypto-js',
'@types/crypto-js',
'plausible-tracker',
'svg2png-wasm',
'@types/bcryptjs',
'@types/uuid',
];
expect(declarations.filter(({ npmPackage }) => replaced.includes(npmPackage))).toEqual([]);
});
});
});
@@ -10,4 +10,19 @@ describe('wpa-psk-generator', () => {
});
expect(generateWpaPskRawKey('test', 'test')?.psk).toHaveLength(256 / 8 * 2);
});
it.each<[string, string, string]>([
['MyNetwork', 'SuperSecret123', '667d7ea7ef34fd9468f4a5ca7ff69cb8bdc05980dee5ba784dfc70e65f70f51a'],
['', '', '5c622913020b8e2ddd9a58552396ccebd10eb57121a346f127d13c9006434cc0'],
])('derives the psk of ssid "%s" with passphrase "%s"', (ssid, passphrase, psk) => {
expect(generateWpaPskRawKey(ssid, passphrase)).to.deep.eq({ ssid, passphrase, psk });
});
it('uses the ssid as the salt, so swapping ssid and passphrase changes the psk', () => {
expect(generateWpaPskRawKey('alice', 'bob').psk).not.toEqual(generateWpaPskRawKey('bob', 'alice').psk);
});
it('is deterministic', () => {
expect(generateWpaPskRawKey('ssid', 'passphrase').psk).toEqual(generateWpaPskRawKey('ssid', 'passphrase').psk);
});
});
@@ -1,12 +1,11 @@
import CryptoJS from 'crypto-js';
import pbkdf2 from 'crypto-js/pbkdf2';
import { Hex, PBKDF2, SHA1Algo } from 'crypto-es';
export function generateWpaPskRawKey(ssid: string, passphrase: string) {
const psk = pbkdf2(passphrase, ssid, {
const psk = PBKDF2(passphrase, ssid, {
keySize: 256 / 32,
iterations: 4096,
hasher: CryptoJS.algo.SHA1,
}).toString(CryptoJS.enc.Hex);
hasher: SHA1Algo,
}).toString(Hex);
return {
ssid,
passphrase,