Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f61d001ab | ||
|
|
e4aa85a503 |
@@ -0,0 +1,39 @@
|
||||
name: Verify
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: verify-${{ gitea.repository }}-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
CI: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
- name: Select declared npm version
|
||||
run: npm install --global npm@11.17.0
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Audit runtime dependencies
|
||||
run: npm audit --omit=dev --audit-level=moderate
|
||||
- name: Check, test, and build
|
||||
run: npm run check
|
||||
- name: Install browser engines
|
||||
run: npx playwright install --with-deps chromium firefox webkit
|
||||
- name: Browser tests
|
||||
run: npm run test:browser
|
||||
@@ -1,5 +1,17 @@
|
||||
# Changelog
|
||||
|
||||
## 0.2.0 - 2026-09-02
|
||||
|
||||
- Added exact weighted sampling without replacement and versioned executable seeded recipes.
|
||||
- Added a bounded, domain-separated WebCrypto commit–reveal ceremony and verifier.
|
||||
|
||||
## 0.1.1 - 2026-09-01
|
||||
|
||||
- Removed the external randomness-service client and its network permission; Random Tools is now entirely local-only.
|
||||
- Replaced the remote workspace with bounded local coin, card, sequence, calendar-date, decimal-fraction and spherical-coordinate draws.
|
||||
- Added weekday and no-replacement date controls, recipe metadata and expanded cross-browser coverage.
|
||||
- Hardened identifier and inclusive-integer bounds, added normalized custom-list identity, and limited screen-reader announcements to concise result status.
|
||||
|
||||
## 0.1.0 - 2026-09-01
|
||||
|
||||
- Added the initial local-first Random Tools workbench.
|
||||
|
||||
@@ -4,15 +4,19 @@ Generate secure or reproducible random values locally in the browser.
|
||||
|
||||
Random Tools is a standalone local-first application in the [add·ideas Toolbox](https://git.add-ideas.de/lotobo/toolbox-portal). Inputs are processed in the browser and are not uploaded.
|
||||
|
||||
## Version 0.1 scope
|
||||
## Current scope
|
||||
|
||||
- Unbiased local WebCrypto integers and strings plus normal-distribution samples
|
||||
- Explicitly non-cryptographic, seeded deterministic generation with reproduction metadata
|
||||
- Dice expressions, sampling without replacement, Fisher–Yates shuffling and passphrases
|
||||
- Exact weighted sampling without replacement from bounded quoted CSV input
|
||||
- Versioned executable seeded recipes for integers, strings, equal-weight samples and weighted samples
|
||||
- WebCrypto commit–reveal ceremonies with domain-separated commitments, 256-bit private nonces, canonical participant ordering and fail-closed verification
|
||||
- UUIDv4, UUIDv7 and random ULID generation
|
||||
- Optional RANDOM.ORG integer requests only after per-session consent
|
||||
- Local draws for coin flips, shuffled card deals and unique integer sequences
|
||||
- Random calendar dates with weekday and uniqueness controls, exact decimal fractions, and equal-area spherical coordinates
|
||||
|
||||
Secure local generation never falls back to the seeded or remote source. Deterministic results are reproducible but not suitable for secrets. The RANDOM.ORG workspace is the sole network-capable feature: it is not the default, requires an explicit consent checkbox, omits credentials/referrer and may still be unavailable because of browser CORS policy. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) and [docs/PRIVACY-SECURITY.md](docs/PRIVACY-SECURITY.md).
|
||||
All functionality runs locally. Secure generation never falls back to the seeded source, and deterministic results/recipes are reproducible but not suitable for secrets. Recipes can embed list values, so review them before sharing. Recipes for custom passphrases identify the normalized list by count and SHA-256 but do not embed it, so reproduction requires the same custom input. A commit–reveal result proves only that the supplied reveals match the supplied commitments; participants must publish every commitment before any reveal through a channel of their choice. The browser CSPRNG is not physical entropy, and no operation is presented as certified for regulated drawings or gambling. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) and [docs/PRIVACY-SECURITY.md](docs/PRIVACY-SECURITY.md).
|
||||
|
||||
## Development
|
||||
|
||||
@@ -26,7 +30,7 @@ npm run test:browser
|
||||
|
||||
## Release
|
||||
|
||||
`npm run release:artifact` creates a deterministic `release/rand-tools-0.1.0.zip` and checksum sidecar.
|
||||
`npm run release:artifact` creates a deterministic `release/rand-tools-0.2.0.zip` and checksum sidecar.
|
||||
|
||||
## Licence
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Corresponding source
|
||||
|
||||
The corresponding source for Random Tools 0.1.0 is available at:
|
||||
The corresponding source for Random Tools 0.2.0 is available at:
|
||||
|
||||
https://git.add-ideas.de/lotobo/rand-tools/src/tag/v0.1.0
|
||||
https://git.add-ideas.de/lotobo/rand-tools/src/tag/v0.2.0
|
||||
|
||||
Build with Node.js 22, npm 11, `npm ci`, and `npm run release:artifact`.
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
# Third-party notices
|
||||
|
||||
Random Tools 0.1.0 directly depends on these runtime packages:
|
||||
Random Tools 0.1.1 directly depends on these runtime packages:
|
||||
|
||||
| Package | Pinned version | Declared licence |
|
||||
| -------------------------------- | -------------: | ---------------- |
|
||||
| `@add-ideas/toolbox-contract` | 0.2.3 | Apache-2.0 |
|
||||
| `@add-ideas/toolbox-helpers` | 0.1.0 | GPL-3.0-or-later |
|
||||
| `@add-ideas/toolbox-shell-react` | 0.2.3 | Apache-2.0 |
|
||||
| `@add-ideas/toolbox-contract` | 0.3.0 | Apache-2.0 |
|
||||
| `@add-ideas/toolbox-helpers` | 0.2.0 | GPL-3.0-or-later |
|
||||
| `@add-ideas/toolbox-shell-react` | 0.3.0 | Apache-2.0 |
|
||||
| `react` | 19.2.8 | MIT |
|
||||
| `react-dom` | 19.2.8 | MIT |
|
||||
|
||||
The optional RANDOM.ORG feature calls a public HTTP API after explicit user consent; it does not embed or redistribute RANDOM.ORG code or data. Use of that service remains subject to its operator's terms and availability.
|
||||
|
||||
This table covers direct production dependencies, not transitive packages or development tooling. During a release build, the exact non-development dependency tree and discovered licence texts are generated from the lockfile into `LICENSES/npm-runtime-licenses.txt` and included in the release ZIP. Copyright and licence terms remain with their respective authors.
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
Random Tools is a static React/Vite application wrapped in the shared Toolbox shell. `random/source.ts` exposes one common interface over two deliberately distinct local sources: browser WebCrypto with rejection-sampled integers, and the versioned `toolbox-helpers` xoshiro128** seeded generator. Secure mode never falls back to deterministic mode.
|
||||
|
||||
`random/generators.ts` builds bounded numbers, strings, identifiers, dice, samples, shuffles, passphrases and normal samples on that interface. Each successful local result includes source identity, parameters and deterministic state where applicable. Operations are synchronous and bounded, so version 0.1 creates no worker.
|
||||
`random/generators.ts` builds bounded numbers, strings, identifiers, dice, samples, shuffles, passphrases and normal samples on that interface. `random/draws.ts` adds local binary coin flips, standard playing-card deals, shuffled inclusive integer sequences, Gregorian calendar-date sampling, exact decimal-digit fractions and equal-area points on a spherical surface model. Date sampling can filter weekdays and use a partial Fisher–Yates mapping for selection without replacement; it does not allocate every date in a large range.
|
||||
|
||||
`random/remote.ts` is a separate, explicitly selected RANDOM.ORG integer client. Requests are validated, serialised, credentialless, no-referrer, no-store and subject to a 120-second abort timeout; responses are checked against the requested count/range. This is the only runtime network path and the production CSP permits only that origin in addition to self.
|
||||
`random/weighted.ts` parses bounded two-column quoted CSV and ranks each item by an exponential-race key, yielding an exact weighted sample without replacement. `random/recipes.ts` validates a 2 MiB, schema-versioned executable recipe and runs it only through the deterministic source; every algorithm then applies its normal count/list/alphabet bounds. Recipe output includes the generator identity and state after execution.
|
||||
|
||||
`random/ceremony.ts` creates 32-byte WebCrypto reveal nonces. A SHA-256 commitment is domain-separated and binds the normalized ceremony ID, participant name and canonical unpadded Base64url nonce. Finalization validates every commitment, rejects duplicate/missing/changed entries, sorts normalized participant names by a locale-independent code-unit order, and hashes the complete verified reveal set under a separate final-seed domain. It cannot enforce the social publication order.
|
||||
|
||||
Each successful result includes source identity, parameters and deterministic state where applicable. Most operations are synchronous and bounded; custom word-list identity and ceremony hashes use the asynchronous browser Web Crypto digest API without a worker. Custom lists are trimmed, emptied lines are dropped and uniqueness is checked once before both selection and metadata are derived. Weighted input is capped at 100,000 items/4,000,000 UTF-16 units; recipes and ceremony documents at 2 MiB; ceremonies at 1,000 participants. The application contains no third-party network client; its CSP limits connections to its own origin for loading the local application shell.
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# Privacy and security
|
||||
|
||||
Local WebCrypto is the default. It stays in the browser, has no remote fallback, and is the only mode intended for secrets. Seeded xoshiro128** output is reproducible and explicitly non-cryptographic; anyone with the seed/state/recipe can reproduce or predict it. The entropy estimate for a passphrase is a simple uniform-choice model, not a password-strength audit.
|
||||
Local Web Crypto is the default. It stays in the browser, has no network or seeded fallback, and is the only mode intended for secrets. Seeded xoshiro128** output is reproducible and explicitly non-cryptographic; anyone with the seed/state/recipe can reproduce or predict it. The entropy estimate for a passphrase is a simple uniform-choice model, not a password-strength audit.
|
||||
|
||||
The RANDOM.ORG workspace is an opt-in exception to local processing. Only after checking consent and pressing the request button does the browser send the requested count and range to `https://www.random.org`; RANDOM.ORG and network intermediaries can observe the request and the user's IP address. Credentials and referrer are omitted. Browser CORS policy or service limits may prevent the request. No other operation substitutes this source automatically.
|
||||
There is no third-party request path, telemetry, analytics, account, geolocation lookup or persistence. Coordinates are generated as mathematical samples and are not derived from the device location. Results, seeds, recipe contents and ceremony nonces remain in page memory unless copied or downloaded. Executable sample recipes embed their input lists; a custom passphrase recipe instead contains the normalized list count and a versioned SHA-256 identity, not the list contents. The same normalized passphrase input is therefore still required for reproduction.
|
||||
|
||||
Counts, ranges, alphabets, list sizes and generated byte counts have explicit limits before large allocations. Results and seeds remain in page memory unless copied or downloaded. The app has no telemetry, analytics, account or persistence and is not certified for regulated drawings or gambling.
|
||||
Commit–reveal is a coordination primitive, not an audited drawing service. Keep each nonce private until every commitment is independently published, preserve that publication record, and reject missing participants. The verifier proves correspondence between the document's commitments/reveals and derives an order-independent seed; it cannot prove publication timing, participant identity or freedom from collusion. Use that final seed in the deterministic generator and preserve the exact executable recipe for reproducibility.
|
||||
|
||||
Counts, ranges, alphabets, list sizes and generated byte counts have explicit limits before large allocations. Web Crypto is a browser-provided CSPRNG, not a physical randomness source. The app is not certified for regulated drawings or gambling.
|
||||
|
||||
Generated
+22
-23
@@ -1,22 +1,22 @@
|
||||
{
|
||||
"name": "rand-tools",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "rand-tools",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@add-ideas/toolbox-contract": "0.2.3",
|
||||
"@add-ideas/toolbox-helpers": "0.1.0",
|
||||
"@add-ideas/toolbox-shell-react": "0.2.3",
|
||||
"@add-ideas/toolbox-contract": "0.3.0",
|
||||
"@add-ideas/toolbox-helpers": "0.2.0",
|
||||
"@add-ideas/toolbox-shell-react": "0.3.0",
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@add-ideas/toolbox-testkit": "0.2.3",
|
||||
"@add-ideas/toolbox-testkit": "0.3.0",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@playwright/test": "1.62.1",
|
||||
"@testing-library/jest-dom": "6.9.1",
|
||||
@@ -42,24 +42,24 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@add-ideas/toolbox-contract": {
|
||||
"version": "0.2.3",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://git.add-ideas.de/api/packages/lotobo/npm/%40add-ideas%2Ftoolbox-contract/-/0.3.0/toolbox-contract-0.3.0.tgz",
|
||||
"integrity": "sha512-dKrK7BjOFwqJaBfJuhKxZKIld4sH0AKjEn6a0yLnbdMUFY+fFv4VSLGV2tNSBD016gumc2iNqOjUj/ld7x4rtA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@add-ideas/toolbox-helpers": {
|
||||
"version": "0.1.0",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://git.add-ideas.de/api/packages/lotobo/npm/%40add-ideas%2Ftoolbox-helpers/-/0.2.0/toolbox-helpers-0.2.0.tgz",
|
||||
"integrity": "sha512-SdOqkw+P+3J3fa5iVkzb5P15rVepB001GNV21Oh8w0CZcVL+YRltgD/s+MVcTyrNijWQf3E5vtQON/3N2LLyKg==",
|
||||
"license": "GPL-3.0-or-later"
|
||||
},
|
||||
"node_modules/@add-ideas/toolbox-shell-react": {
|
||||
"version": "0.2.3",
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://git.add-ideas.de/api/packages/lotobo/npm/%40add-ideas%2Ftoolbox-shell-react/-/0.3.0/toolbox-shell-react-0.3.0.tgz",
|
||||
"integrity": "sha512-74p6JzAOG0YCAKdlc1hLofV4ZIko7vb448S75cIiM88PKm93EHl5VD7g8YVyfM56Ui97UY9dmy+Whiq4sGzpsg==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@add-ideas/toolbox-contract": "0.2.3"
|
||||
"@add-ideas/toolbox-contract": "0.3.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18 <20",
|
||||
@@ -67,17 +67,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@add-ideas/toolbox-testkit": {
|
||||
"version": "0.2.3",
|
||||
"version": "0.3.0",
|
||||
"resolved": "https://git.add-ideas.de/api/packages/lotobo/npm/%40add-ideas%2Ftoolbox-testkit/-/0.3.0/toolbox-testkit-0.3.0.tgz",
|
||||
"integrity": "sha512-4Fk+oSvZFspOMIXr8Xy040nhAaBsIQAzsGyXWSpjn3+k3yBKq7nB1r5zCHhsXzfdLzvPDAx2KcmSNOhM330D9w==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@add-ideas/toolbox-contract": "0.2.3"
|
||||
"@add-ideas/toolbox-contract": "0.3.0"
|
||||
},
|
||||
"bin": {
|
||||
"toolbox-check": "dist/cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/@adobe/css-tools": {
|
||||
|
||||
+5
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "rand-tools",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"description": "Generate secure or reproducible random values locally in the browser.",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"author": "Albrecht Degering",
|
||||
@@ -39,14 +39,14 @@
|
||||
"release:artifact": "npm run check && npm run test:browser && npm run package:release -- --force"
|
||||
},
|
||||
"dependencies": {
|
||||
"@add-ideas/toolbox-contract": "0.2.3",
|
||||
"@add-ideas/toolbox-helpers": "0.1.0",
|
||||
"@add-ideas/toolbox-shell-react": "0.2.3",
|
||||
"@add-ideas/toolbox-contract": "0.3.0",
|
||||
"@add-ideas/toolbox-helpers": "0.2.0",
|
||||
"@add-ideas/toolbox-shell-react": "0.3.0",
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@add-ideas/toolbox-testkit": "0.2.3",
|
||||
"@add-ideas/toolbox-testkit": "0.3.0",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@playwright/test": "1.62.1",
|
||||
"@testing-library/jest-dom": "6.9.1",
|
||||
|
||||
+20
-2
@@ -15,7 +15,25 @@ export default defineConfig({
|
||||
timeout: 180_000,
|
||||
},
|
||||
projects: [
|
||||
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
|
||||
{ name: "firefox", use: { ...devices["Desktop Firefox"] } },
|
||||
{
|
||||
name: "chromium",
|
||||
testIgnore: /responsive\.spec\.ts/,
|
||||
use: { ...devices["Desktop Chrome"] },
|
||||
},
|
||||
{
|
||||
name: "firefox",
|
||||
testIgnore: /responsive\.spec\.ts/,
|
||||
use: { ...devices["Desktop Firefox"] },
|
||||
},
|
||||
{
|
||||
name: "webkit",
|
||||
testIgnore: /responsive\.spec\.ts/,
|
||||
use: { ...devices["Desktop Safari"] },
|
||||
},
|
||||
{
|
||||
name: "mobile-chromium",
|
||||
testMatch: /responsive\.spec\.ts/,
|
||||
use: { ...devices["Pixel 5"] },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
# Changelog
|
||||
|
||||
## 0.2.0 - 2026-09-02
|
||||
|
||||
- Added exact weighted sampling without replacement and versioned executable seeded recipes.
|
||||
- Added a bounded, domain-separated WebCrypto commit–reveal ceremony and verifier.
|
||||
|
||||
## 0.1.1 - 2026-09-01
|
||||
|
||||
- Removed the external randomness-service client and its network permission; Random Tools is now entirely local-only.
|
||||
- Replaced the remote workspace with bounded local coin, card, sequence, calendar-date, decimal-fraction and spherical-coordinate draws.
|
||||
- Added weekday and no-replacement date controls, recipe metadata and expanded cross-browser coverage.
|
||||
- Hardened identifier and inclusive-integer bounds, added normalized custom-list identity, and limited screen-reader announcements to concise result status.
|
||||
|
||||
## 0.1.0 - 2026-09-01
|
||||
|
||||
- Added the initial local-first Random Tools workbench.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
==============================================================================
|
||||
@add-ideas/toolbox-contract@0.2.3
|
||||
@add-ideas/toolbox-contract@0.3.0
|
||||
Declared licence: Apache-2.0
|
||||
==============================================================================
|
||||
--- LICENSE ---
|
||||
@@ -198,7 +198,7 @@ Declared licence: Apache-2.0
|
||||
|
||||
|
||||
==============================================================================
|
||||
@add-ideas/toolbox-helpers@0.1.0
|
||||
@add-ideas/toolbox-helpers@0.2.0
|
||||
Declared licence: GPL-3.0-or-later
|
||||
==============================================================================
|
||||
--- LICENSE ---
|
||||
@@ -879,7 +879,7 @@ Public License instead of this License. But first, please read
|
||||
|
||||
|
||||
==============================================================================
|
||||
@add-ideas/toolbox-shell-react@0.2.3
|
||||
@add-ideas/toolbox-shell-react@0.3.0
|
||||
Declared licence: Apache-2.0
|
||||
==============================================================================
|
||||
--- LICENSE ---
|
||||
|
||||
+8
-4
@@ -4,15 +4,19 @@ Generate secure or reproducible random values locally in the browser.
|
||||
|
||||
Random Tools is a standalone local-first application in the [add·ideas Toolbox](https://git.add-ideas.de/lotobo/toolbox-portal). Inputs are processed in the browser and are not uploaded.
|
||||
|
||||
## Version 0.1 scope
|
||||
## Current scope
|
||||
|
||||
- Unbiased local WebCrypto integers and strings plus normal-distribution samples
|
||||
- Explicitly non-cryptographic, seeded deterministic generation with reproduction metadata
|
||||
- Dice expressions, sampling without replacement, Fisher–Yates shuffling and passphrases
|
||||
- Exact weighted sampling without replacement from bounded quoted CSV input
|
||||
- Versioned executable seeded recipes for integers, strings, equal-weight samples and weighted samples
|
||||
- WebCrypto commit–reveal ceremonies with domain-separated commitments, 256-bit private nonces, canonical participant ordering and fail-closed verification
|
||||
- UUIDv4, UUIDv7 and random ULID generation
|
||||
- Optional RANDOM.ORG integer requests only after per-session consent
|
||||
- Local draws for coin flips, shuffled card deals and unique integer sequences
|
||||
- Random calendar dates with weekday and uniqueness controls, exact decimal fractions, and equal-area spherical coordinates
|
||||
|
||||
Secure local generation never falls back to the seeded or remote source. Deterministic results are reproducible but not suitable for secrets. The RANDOM.ORG workspace is the sole network-capable feature: it is not the default, requires an explicit consent checkbox, omits credentials/referrer and may still be unavailable because of browser CORS policy. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) and [docs/PRIVACY-SECURITY.md](docs/PRIVACY-SECURITY.md).
|
||||
All functionality runs locally. Secure generation never falls back to the seeded source, and deterministic results/recipes are reproducible but not suitable for secrets. Recipes can embed list values, so review them before sharing. Recipes for custom passphrases identify the normalized list by count and SHA-256 but do not embed it, so reproduction requires the same custom input. A commit–reveal result proves only that the supplied reveals match the supplied commitments; participants must publish every commitment before any reveal through a channel of their choice. The browser CSPRNG is not physical entropy, and no operation is presented as certified for regulated drawings or gambling. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) and [docs/PRIVACY-SECURITY.md](docs/PRIVACY-SECURITY.md).
|
||||
|
||||
## Development
|
||||
|
||||
@@ -26,7 +30,7 @@ npm run test:browser
|
||||
|
||||
## Release
|
||||
|
||||
`npm run release:artifact` creates a deterministic `release/rand-tools-0.1.0.zip` and checksum sidecar.
|
||||
`npm run release:artifact` creates a deterministic `release/rand-tools-0.2.0.zip` and checksum sidecar.
|
||||
|
||||
## Licence
|
||||
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
# Corresponding source
|
||||
|
||||
The corresponding source for Random Tools 0.1.0 is available at:
|
||||
The corresponding source for Random Tools 0.2.0 is available at:
|
||||
|
||||
https://git.add-ideas.de/lotobo/rand-tools/src/tag/v0.1.0
|
||||
https://git.add-ideas.de/lotobo/rand-tools/src/tag/v0.2.0
|
||||
|
||||
Build with Node.js 22, npm 11, `npm ci`, and `npm run release:artifact`.
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
# Third-party notices
|
||||
|
||||
Random Tools 0.1.0 directly depends on these runtime packages:
|
||||
Random Tools 0.1.1 directly depends on these runtime packages:
|
||||
|
||||
| Package | Pinned version | Declared licence |
|
||||
| -------------------------------- | -------------: | ---------------- |
|
||||
| `@add-ideas/toolbox-contract` | 0.2.3 | Apache-2.0 |
|
||||
| `@add-ideas/toolbox-helpers` | 0.1.0 | GPL-3.0-or-later |
|
||||
| `@add-ideas/toolbox-shell-react` | 0.2.3 | Apache-2.0 |
|
||||
| `@add-ideas/toolbox-contract` | 0.3.0 | Apache-2.0 |
|
||||
| `@add-ideas/toolbox-helpers` | 0.2.0 | GPL-3.0-or-later |
|
||||
| `@add-ideas/toolbox-shell-react` | 0.3.0 | Apache-2.0 |
|
||||
| `react` | 19.2.8 | MIT |
|
||||
| `react-dom` | 19.2.8 | MIT |
|
||||
|
||||
The optional RANDOM.ORG feature calls a public HTTP API after explicit user consent; it does not embed or redistribute RANDOM.ORG code or data. Use of that service remains subject to its operator's terms and availability.
|
||||
|
||||
This table covers direct production dependencies, not transitive packages or development tooling. During a release build, the exact non-development dependency tree and discovered licence texts are generated from the lockfile into `LICENSES/npm-runtime-licenses.txt` and included in the release ZIP. Copyright and licence terms remain with their respective authors.
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
Random Tools is a static React/Vite application wrapped in the shared Toolbox shell. `random/source.ts` exposes one common interface over two deliberately distinct local sources: browser WebCrypto with rejection-sampled integers, and the versioned `toolbox-helpers` xoshiro128** seeded generator. Secure mode never falls back to deterministic mode.
|
||||
|
||||
`random/generators.ts` builds bounded numbers, strings, identifiers, dice, samples, shuffles, passphrases and normal samples on that interface. Each successful local result includes source identity, parameters and deterministic state where applicable. Operations are synchronous and bounded, so version 0.1 creates no worker.
|
||||
`random/generators.ts` builds bounded numbers, strings, identifiers, dice, samples, shuffles, passphrases and normal samples on that interface. `random/draws.ts` adds local binary coin flips, standard playing-card deals, shuffled inclusive integer sequences, Gregorian calendar-date sampling, exact decimal-digit fractions and equal-area points on a spherical surface model. Date sampling can filter weekdays and use a partial Fisher–Yates mapping for selection without replacement; it does not allocate every date in a large range.
|
||||
|
||||
`random/remote.ts` is a separate, explicitly selected RANDOM.ORG integer client. Requests are validated, serialised, credentialless, no-referrer, no-store and subject to a 120-second abort timeout; responses are checked against the requested count/range. This is the only runtime network path and the production CSP permits only that origin in addition to self.
|
||||
`random/weighted.ts` parses bounded two-column quoted CSV and ranks each item by an exponential-race key, yielding an exact weighted sample without replacement. `random/recipes.ts` validates a 2 MiB, schema-versioned executable recipe and runs it only through the deterministic source; every algorithm then applies its normal count/list/alphabet bounds. Recipe output includes the generator identity and state after execution.
|
||||
|
||||
`random/ceremony.ts` creates 32-byte WebCrypto reveal nonces. A SHA-256 commitment is domain-separated and binds the normalized ceremony ID, participant name and canonical unpadded Base64url nonce. Finalization validates every commitment, rejects duplicate/missing/changed entries, sorts normalized participant names by a locale-independent code-unit order, and hashes the complete verified reveal set under a separate final-seed domain. It cannot enforce the social publication order.
|
||||
|
||||
Each successful result includes source identity, parameters and deterministic state where applicable. Most operations are synchronous and bounded; custom word-list identity and ceremony hashes use the asynchronous browser Web Crypto digest API without a worker. Custom lists are trimmed, emptied lines are dropped and uniqueness is checked once before both selection and metadata are derived. Weighted input is capped at 100,000 items/4,000,000 UTF-16 units; recipes and ceremony documents at 2 MiB; ceremonies at 1,000 participants. The application contains no third-party network client; its CSP limits connections to its own origin for loading the local application shell.
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# Privacy and security
|
||||
|
||||
Local WebCrypto is the default. It stays in the browser, has no remote fallback, and is the only mode intended for secrets. Seeded xoshiro128** output is reproducible and explicitly non-cryptographic; anyone with the seed/state/recipe can reproduce or predict it. The entropy estimate for a passphrase is a simple uniform-choice model, not a password-strength audit.
|
||||
Local Web Crypto is the default. It stays in the browser, has no network or seeded fallback, and is the only mode intended for secrets. Seeded xoshiro128** output is reproducible and explicitly non-cryptographic; anyone with the seed/state/recipe can reproduce or predict it. The entropy estimate for a passphrase is a simple uniform-choice model, not a password-strength audit.
|
||||
|
||||
The RANDOM.ORG workspace is an opt-in exception to local processing. Only after checking consent and pressing the request button does the browser send the requested count and range to `https://www.random.org`; RANDOM.ORG and network intermediaries can observe the request and the user's IP address. Credentials and referrer are omitted. Browser CORS policy or service limits may prevent the request. No other operation substitutes this source automatically.
|
||||
There is no third-party request path, telemetry, analytics, account, geolocation lookup or persistence. Coordinates are generated as mathematical samples and are not derived from the device location. Results, seeds, recipe contents and ceremony nonces remain in page memory unless copied or downloaded. Executable sample recipes embed their input lists; a custom passphrase recipe instead contains the normalized list count and a versioned SHA-256 identity, not the list contents. The same normalized passphrase input is therefore still required for reproduction.
|
||||
|
||||
Counts, ranges, alphabets, list sizes and generated byte counts have explicit limits before large allocations. Results and seeds remain in page memory unless copied or downloaded. The app has no telemetry, analytics, account or persistence and is not certified for regulated drawings or gambling.
|
||||
Commit–reveal is a coordination primitive, not an audited drawing service. Keep each nonce private until every commitment is independently published, preserve that publication record, and reject missing participants. The verifier proves correspondence between the document's commitments/reveals and derives an order-independent seed; it cannot prove publication timing, participant identity or freedom from collusion. Use that final seed in the deterministic generator and preserve the exact executable recipe for reproducibility.
|
||||
|
||||
Counts, ranges, alphabets, list sizes and generated byte counts have explicit limits before large allocations. Web Crypto is a browser-provided CSPRNG, not a physical randomness source. The app is not certified for regulated drawings or gambling.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
const CACHE_PREFIX = "rand-tools-shell-";
|
||||
const CACHE_NAME = CACHE_PREFIX + "0.1.0";
|
||||
const CACHE_NAME = CACHE_PREFIX + "0.2.0";
|
||||
const CORE = ["./", "./manifest.webmanifest", "./favicon.svg"];
|
||||
self.addEventListener("install", (event) => {
|
||||
event.waitUntil(
|
||||
|
||||
+27
-4
@@ -3,12 +3,22 @@
|
||||
"schemaVersion": 1,
|
||||
"id": "de.add-ideas.rand-tools",
|
||||
"name": "Random Tools",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"description": "Generate secure or reproducible random values locally in the browser.",
|
||||
"entry": "./",
|
||||
"icon": "./favicon.svg",
|
||||
"categories": ["random", "developer", "productivity"],
|
||||
"tags": ["random", "uuid", "ulid", "dice", "shuffle", "sample"],
|
||||
"tags": [
|
||||
"random",
|
||||
"uuid",
|
||||
"ulid",
|
||||
"dice",
|
||||
"shuffle",
|
||||
"sample",
|
||||
"cards",
|
||||
"dates",
|
||||
"coordinates"
|
||||
],
|
||||
"integration": {
|
||||
"contextVersion": 1,
|
||||
"launchModes": ["navigate", "new-tab"],
|
||||
@@ -21,11 +31,24 @@
|
||||
"crossOriginIsolated": false,
|
||||
"topLevelContext": false
|
||||
},
|
||||
"io": {
|
||||
"accepts": [
|
||||
{ "mediaType": "text/csv", "extensions": [".csv"] },
|
||||
{ "mediaType": "application/json", "extensions": [".json"] },
|
||||
{ "mediaType": "text/plain", "extensions": [".txt"] }
|
||||
],
|
||||
"produces": [
|
||||
{ "mediaType": "application/json", "extensions": [".json"] },
|
||||
{ "mediaType": "text/csv", "extensions": [".csv"] },
|
||||
{ "mediaType": "text/plain", "extensions": [".txt"] }
|
||||
]
|
||||
},
|
||||
"capabilities": { "required": ["secure-random"], "optional": [] },
|
||||
"privacy": {
|
||||
"processing": "mixed",
|
||||
"processing": "local",
|
||||
"fileUploads": false,
|
||||
"telemetry": false,
|
||||
"label": "Local generation is the default; RANDOM.ORG is contacted only after explicit opt-in."
|
||||
"label": "All generation runs locally; the application makes no third-party requests."
|
||||
},
|
||||
"source": {
|
||||
"repository": "https://git.add-ideas.de/lotobo/rand-tools",
|
||||
|
||||
@@ -24,7 +24,7 @@ const types = new Map([
|
||||
]);
|
||||
const headers = {
|
||||
"Content-Security-Policy":
|
||||
"default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self' https://www.random.org; worker-src 'self' blob:; manifest-src 'self'",
|
||||
"default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; worker-src 'self' blob:; manifest-src 'self'",
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
"Cross-Origin-Resource-Policy": "same-origin",
|
||||
"Permissions-Policy":
|
||||
|
||||
@@ -35,9 +35,9 @@ export function HelpDialog({
|
||||
Generate secure or reproducible random values locally in the browser.
|
||||
</p>
|
||||
<p>
|
||||
Local WebCrypto and seeded generation stay in this browser. RANDOM.ORG
|
||||
is contacted only from its separate workspace after explicit consent;
|
||||
local sources never fall back to it. Inputs and responses are bounded.
|
||||
Web Crypto and seeded generation stay in this browser. The application
|
||||
has no third-party network path, and local sources never fall back to
|
||||
one another. Inputs and outputs are bounded.
|
||||
</p>
|
||||
</dialog>
|
||||
);
|
||||
|
||||
+706
-155
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,227 @@
|
||||
import {
|
||||
base64UrlToBytes,
|
||||
bytesToBase64Url,
|
||||
secureRandomBytes,
|
||||
} from "@add-ideas/toolbox-helpers";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const MAX_PARTICIPANTS = 1_000;
|
||||
const MAX_DOCUMENT = 2 * 1024 * 1024;
|
||||
|
||||
export interface CeremonyCommitment {
|
||||
ceremonyId: string;
|
||||
participant: string;
|
||||
commitment: string;
|
||||
}
|
||||
|
||||
export interface CeremonyReveal extends CeremonyCommitment {
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
export interface CeremonyDocument {
|
||||
schemaVersion: 1;
|
||||
ceremonyId: string;
|
||||
participants: CeremonyReveal[];
|
||||
}
|
||||
|
||||
export interface CeremonyResult {
|
||||
valid: boolean;
|
||||
seed?: string;
|
||||
verified: number;
|
||||
errors: string[];
|
||||
canonicalParticipants: string[];
|
||||
}
|
||||
|
||||
function text(value: string, name: string): string {
|
||||
const normalized = value.normalize("NFC").trim();
|
||||
if (
|
||||
!normalized ||
|
||||
normalized.length > 200 ||
|
||||
[...normalized].some((character) => {
|
||||
const code = character.codePointAt(0)!;
|
||||
return code <= 31 || code === 127;
|
||||
})
|
||||
)
|
||||
throw new Error(`${name} must contain 1–200 printable characters.`);
|
||||
return normalized;
|
||||
}
|
||||
|
||||
async function hash(value: string): Promise<string> {
|
||||
return bytesToBase64Url(
|
||||
new Uint8Array(
|
||||
await crypto.subtle.digest("SHA-256", encoder.encode(value)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function canonicalCommitInput(
|
||||
ceremonyId: string,
|
||||
participant: string,
|
||||
nonce: string,
|
||||
): string {
|
||||
return JSON.stringify([
|
||||
"add-ideas-rand-tools-commit-v1",
|
||||
ceremonyId,
|
||||
participant,
|
||||
nonce,
|
||||
]);
|
||||
}
|
||||
|
||||
function canonicalDigest(value: string, name: string): string {
|
||||
const bytes = base64UrlToBytes(value, { maxOutputBytes: 32 });
|
||||
if (bytes.length !== 32 || bytesToBase64Url(bytes) !== value)
|
||||
throw new Error(
|
||||
`${name} must be canonical unpadded Base64url for exactly 32 bytes.`,
|
||||
);
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function commitmentForReveal(
|
||||
ceremonyIdInput: string,
|
||||
participantInput: string,
|
||||
nonce: string,
|
||||
): Promise<CeremonyCommitment> {
|
||||
const ceremonyId = text(ceremonyIdInput, "Ceremony ID");
|
||||
const participant = text(participantInput, "Participant");
|
||||
canonicalDigest(nonce, "Reveal nonce");
|
||||
return {
|
||||
ceremonyId,
|
||||
participant,
|
||||
commitment: await hash(
|
||||
canonicalCommitInput(ceremonyId, participant, nonce),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createCeremonyReveal(
|
||||
ceremonyId: string,
|
||||
participant: string,
|
||||
): Promise<CeremonyReveal> {
|
||||
const nonce = bytesToBase64Url(secureRandomBytes(32, crypto, 32));
|
||||
return {
|
||||
...(await commitmentForReveal(ceremonyId, participant, nonce)),
|
||||
nonce,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseCeremonyDocument(source: string): CeremonyDocument {
|
||||
if (source.length > MAX_DOCUMENT)
|
||||
throw new Error("Ceremony document exceeds the 2 MiB limit.");
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(source);
|
||||
} catch {
|
||||
throw new Error("Ceremony document is not valid JSON.");
|
||||
}
|
||||
if (!value || typeof value !== "object" || Array.isArray(value))
|
||||
throw new Error("Ceremony document must be an object.");
|
||||
const candidate = value as Partial<CeremonyDocument>;
|
||||
if (candidate.schemaVersion !== 1 || !Array.isArray(candidate.participants))
|
||||
throw new Error(
|
||||
"Expected ceremony schemaVersion 1 and a participants array.",
|
||||
);
|
||||
if (
|
||||
candidate.participants.length < 1 ||
|
||||
candidate.participants.length > MAX_PARTICIPANTS
|
||||
)
|
||||
throw new Error(
|
||||
`Ceremony must contain 1–${MAX_PARTICIPANTS} participants.`,
|
||||
);
|
||||
const ceremonyId = text(candidate.ceremonyId ?? "", "Ceremony ID");
|
||||
const participants = candidate.participants.map((item, index) => {
|
||||
if (!item || typeof item !== "object")
|
||||
throw new Error(`Participant ${index + 1} is not an object.`);
|
||||
const entry = item as Partial<CeremonyReveal>;
|
||||
if (
|
||||
typeof entry.participant !== "string" ||
|
||||
typeof entry.commitment !== "string" ||
|
||||
typeof entry.nonce !== "string"
|
||||
)
|
||||
throw new Error(
|
||||
`Participant ${index + 1} has incomplete commitment/reveal fields.`,
|
||||
);
|
||||
const entryCeremonyId =
|
||||
entry.ceremonyId === undefined
|
||||
? ceremonyId
|
||||
: typeof entry.ceremonyId === "string"
|
||||
? text(entry.ceremonyId, `Participant ${index + 1} ceremony ID`)
|
||||
: (() => {
|
||||
throw new Error(
|
||||
`Participant ${index + 1} ceremony ID must be a string.`,
|
||||
);
|
||||
})();
|
||||
return {
|
||||
ceremonyId: entryCeremonyId,
|
||||
participant: text(entry.participant, `Participant ${index + 1}`),
|
||||
commitment: entry.commitment,
|
||||
nonce: entry.nonce,
|
||||
};
|
||||
});
|
||||
return { schemaVersion: 1, ceremonyId, participants };
|
||||
}
|
||||
|
||||
export async function finalizeCeremony(
|
||||
document: CeremonyDocument,
|
||||
): Promise<CeremonyResult> {
|
||||
if (
|
||||
document.participants.length < 1 ||
|
||||
document.participants.length > MAX_PARTICIPANTS
|
||||
)
|
||||
throw new Error(
|
||||
`Ceremony must contain 1–${MAX_PARTICIPANTS} participants.`,
|
||||
);
|
||||
const ceremonyId = text(document.ceremonyId, "Ceremony ID");
|
||||
const errors: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
const verified: CeremonyReveal[] = [];
|
||||
for (const [index, entry] of document.participants.entries()) {
|
||||
try {
|
||||
if (entry.ceremonyId !== ceremonyId)
|
||||
throw new Error("ceremony ID differs from the document");
|
||||
canonicalDigest(entry.commitment, "Commitment");
|
||||
const expected = await commitmentForReveal(
|
||||
ceremonyId,
|
||||
entry.participant,
|
||||
entry.nonce,
|
||||
);
|
||||
if (seen.has(expected.participant))
|
||||
throw new Error("participant name is duplicated");
|
||||
seen.add(expected.participant);
|
||||
if (expected.commitment !== entry.commitment)
|
||||
throw new Error("reveal does not match the published commitment");
|
||||
verified.push({ ...entry, participant: expected.participant });
|
||||
} catch (error) {
|
||||
errors.push(
|
||||
`Participant ${index + 1}: ${error instanceof Error ? error.message : "verification failed"}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const canonical = verified.sort((left, right) =>
|
||||
left.participant < right.participant
|
||||
? -1
|
||||
: left.participant > right.participant
|
||||
? 1
|
||||
: 0,
|
||||
);
|
||||
if (errors.length > 0)
|
||||
return {
|
||||
valid: false,
|
||||
verified: verified.length,
|
||||
errors,
|
||||
canonicalParticipants: canonical.map((entry) => entry.participant),
|
||||
};
|
||||
const seed = await hash(
|
||||
JSON.stringify([
|
||||
"add-ideas-rand-tools-final-seed-v1",
|
||||
ceremonyId,
|
||||
canonical.map((entry) => [entry.participant, entry.nonce]),
|
||||
]),
|
||||
);
|
||||
return {
|
||||
valid: true,
|
||||
seed,
|
||||
verified: canonical.length,
|
||||
errors: [],
|
||||
canonicalParticipants: canonical.map((entry) => entry.participant),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import type { RandomSource } from "./source";
|
||||
|
||||
const MAX_RESULTS = 100_000;
|
||||
const DAY_MILLISECONDS = 86_400_000;
|
||||
const RANKS = [
|
||||
"A",
|
||||
"2",
|
||||
"3",
|
||||
"4",
|
||||
"5",
|
||||
"6",
|
||||
"7",
|
||||
"8",
|
||||
"9",
|
||||
"10",
|
||||
"J",
|
||||
"Q",
|
||||
"K",
|
||||
] as const;
|
||||
const SUITS = ["spades", "hearts", "diamonds", "clubs"] as const;
|
||||
const SUIT_SYMBOLS: Record<(typeof SUITS)[number], string> = {
|
||||
spades: "♠",
|
||||
hearts: "♥",
|
||||
diamonds: "♦",
|
||||
clubs: "♣",
|
||||
};
|
||||
|
||||
function validateCount(count: number, label = "Count"): void {
|
||||
if (!Number.isSafeInteger(count) || count < 1 || count > MAX_RESULTS)
|
||||
throw new Error(
|
||||
`${label} must be 1–${MAX_RESULTS.toLocaleString("en-US")}.`,
|
||||
);
|
||||
}
|
||||
|
||||
export function coinFlips(
|
||||
source: RandomSource,
|
||||
count: number,
|
||||
): Array<"Heads" | "Tails"> {
|
||||
validateCount(count, "Flip count");
|
||||
return Array.from({ length: count }, () =>
|
||||
source.integer(0, 2) === 0 ? "Heads" : "Tails",
|
||||
);
|
||||
}
|
||||
|
||||
export function dealCards(
|
||||
source: RandomSource,
|
||||
deckCount: number,
|
||||
cardCount: number,
|
||||
): string[] {
|
||||
if (!Number.isSafeInteger(deckCount) || deckCount < 1 || deckCount > 8)
|
||||
throw new Error("Deck count must be 1–8.");
|
||||
if (
|
||||
!Number.isSafeInteger(cardCount) ||
|
||||
cardCount < 1 ||
|
||||
cardCount > deckCount * 52
|
||||
)
|
||||
throw new Error(`Cards to deal must be 1–${deckCount * 52}.`);
|
||||
|
||||
const deck = Array.from({ length: deckCount }, (_, deckIndex) =>
|
||||
SUITS.flatMap((suit) =>
|
||||
RANKS.map(
|
||||
(rank) =>
|
||||
`${rank}${SUIT_SYMBOLS[suit]}${deckCount > 1 ? ` (deck ${deckIndex + 1})` : ""}`,
|
||||
),
|
||||
),
|
||||
).flat();
|
||||
return source.shuffle(deck).slice(0, cardCount);
|
||||
}
|
||||
|
||||
export function integerSequence(
|
||||
source: RandomSource,
|
||||
minimum: number,
|
||||
maximumInclusive: number,
|
||||
): number[] {
|
||||
if (
|
||||
!Number.isSafeInteger(minimum) ||
|
||||
!Number.isSafeInteger(maximumInclusive) ||
|
||||
maximumInclusive < minimum
|
||||
)
|
||||
throw new Error("Sequence bounds must be ordered safe integers.");
|
||||
const length = maximumInclusive - minimum + 1;
|
||||
if (!Number.isSafeInteger(length) || length < 1 || length > MAX_RESULTS)
|
||||
throw new Error("A sequence may contain 1–100,000 integers.");
|
||||
return source.shuffle(Array.from({ length }, (_, index) => minimum + index));
|
||||
}
|
||||
|
||||
function dateToDay(value: string): number {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/u.exec(value);
|
||||
if (!match) throw new Error("Dates must use the YYYY-MM-DD format.");
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
if (year < 1 || month < 1 || month > 12 || day < 1 || day > 31)
|
||||
throw new Error("Date is outside the supported calendar range.");
|
||||
const date = new Date(0);
|
||||
date.setUTCHours(0, 0, 0, 0);
|
||||
date.setUTCFullYear(year, month - 1, day);
|
||||
if (
|
||||
date.getUTCFullYear() !== year ||
|
||||
date.getUTCMonth() !== month - 1 ||
|
||||
date.getUTCDate() !== day
|
||||
)
|
||||
throw new Error("Date is not a valid Gregorian calendar date.");
|
||||
return Math.floor(date.getTime() / DAY_MILLISECONDS);
|
||||
}
|
||||
|
||||
function dayToDate(dayIndex: number): string {
|
||||
const date = new Date(dayIndex * DAY_MILLISECONDS);
|
||||
return [
|
||||
String(date.getUTCFullYear()).padStart(4, "0"),
|
||||
String(date.getUTCMonth() + 1).padStart(2, "0"),
|
||||
String(date.getUTCDate()).padStart(2, "0"),
|
||||
].join("-");
|
||||
}
|
||||
|
||||
function weekdayForDay(dayIndex: number): number {
|
||||
// 1970-01-01 (day zero) was Thursday (4 in the Sunday-first convention).
|
||||
return (((dayIndex + 4) % 7) + 7) % 7;
|
||||
}
|
||||
|
||||
function allowedDayCount(
|
||||
first: number,
|
||||
last: number,
|
||||
weekdays: ReadonlySet<number>,
|
||||
): number {
|
||||
const days = last - first + 1;
|
||||
const fullWeeks = Math.floor(days / 7);
|
||||
let count = fullWeeks * weekdays.size;
|
||||
for (let offset = fullWeeks * 7; offset < days; offset += 1)
|
||||
if (weekdays.has(weekdayForDay(first + offset))) count += 1;
|
||||
return count;
|
||||
}
|
||||
|
||||
function dayAtAllowedIndex(
|
||||
first: number,
|
||||
index: number,
|
||||
weekdays: ReadonlySet<number>,
|
||||
): number {
|
||||
const fullWeeks = Math.floor(index / weekdays.size);
|
||||
let remainder = index % weekdays.size;
|
||||
const weekStart = first + fullWeeks * 7;
|
||||
for (let offset = 0; offset < 7; offset += 1) {
|
||||
if (!weekdays.has(weekdayForDay(weekStart + offset))) continue;
|
||||
if (remainder === 0) return weekStart + offset;
|
||||
remainder -= 1;
|
||||
}
|
||||
throw new Error("Could not map the selected calendar day.");
|
||||
}
|
||||
|
||||
function sampleIndices(
|
||||
source: RandomSource,
|
||||
population: number,
|
||||
count: number,
|
||||
): number[] {
|
||||
const swaps = new Map<number, number>();
|
||||
const values: number[] = [];
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const selected = source.integer(index, population);
|
||||
values.push(swaps.get(selected) ?? selected);
|
||||
swaps.set(selected, swaps.get(index) ?? index);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
export interface RandomDateOptions {
|
||||
weekdays?: readonly number[];
|
||||
withoutReplacement?: boolean;
|
||||
}
|
||||
|
||||
export function randomDates(
|
||||
source: RandomSource,
|
||||
count: number,
|
||||
start: string,
|
||||
end: string,
|
||||
options: RandomDateOptions = {},
|
||||
): string[] {
|
||||
validateCount(count, "Date count");
|
||||
const first = dateToDay(start);
|
||||
const last = dateToDay(end);
|
||||
if (last < first) throw new Error("End date must not precede start date.");
|
||||
const weekdays = new Set(options.weekdays ?? [0, 1, 2, 3, 4, 5, 6]);
|
||||
if (
|
||||
weekdays.size < 1 ||
|
||||
[...weekdays].some(
|
||||
(weekday) => !Number.isSafeInteger(weekday) || weekday < 0 || weekday > 6,
|
||||
)
|
||||
)
|
||||
throw new Error("Select at least one valid weekday.");
|
||||
const available = allowedDayCount(first, last, weekdays);
|
||||
if (available < 1)
|
||||
throw new Error("The range contains no dates on the selected weekdays.");
|
||||
if (options.withoutReplacement && count > available)
|
||||
throw new Error(
|
||||
`Unique date count cannot exceed the ${available.toLocaleString("en-US")} matching dates.`,
|
||||
);
|
||||
const indices = options.withoutReplacement
|
||||
? sampleIndices(source, available, count)
|
||||
: Array.from({ length: count }, () => source.integer(0, available));
|
||||
return indices.map((index) =>
|
||||
dayToDate(dayAtAllowedIndex(first, index, weekdays)),
|
||||
);
|
||||
}
|
||||
|
||||
export function decimalFractions(
|
||||
source: RandomSource,
|
||||
count: number,
|
||||
decimalPlaces: number,
|
||||
): string[] {
|
||||
validateCount(count, "Fraction count");
|
||||
if (
|
||||
!Number.isSafeInteger(decimalPlaces) ||
|
||||
decimalPlaces < 1 ||
|
||||
decimalPlaces > 64
|
||||
)
|
||||
throw new Error("Decimal places must be 1–64.");
|
||||
if (count * decimalPlaces > 4_000_000)
|
||||
throw new Error("Requested decimal output exceeds 4,000,000 digits.");
|
||||
return Array.from({ length: count }, () => {
|
||||
const digits = Array.from({ length: decimalPlaces }, () =>
|
||||
String(source.integer(0, 10)),
|
||||
).join("");
|
||||
return `0.${digits}`;
|
||||
});
|
||||
}
|
||||
|
||||
export interface Coordinate {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
}
|
||||
|
||||
export function randomCoordinates(
|
||||
source: RandomSource,
|
||||
count: number,
|
||||
decimalPlaces: number,
|
||||
): Coordinate[] {
|
||||
validateCount(count, "Coordinate count");
|
||||
if (
|
||||
!Number.isSafeInteger(decimalPlaces) ||
|
||||
decimalPlaces < 0 ||
|
||||
decimalPlaces > 10
|
||||
)
|
||||
throw new Error("Coordinate decimal places must be 0–10.");
|
||||
const round = (value: number) => {
|
||||
const rounded = Number(value.toFixed(decimalPlaces));
|
||||
return Object.is(rounded, -0) ? 0 : rounded;
|
||||
};
|
||||
return Array.from({ length: count }, () => ({
|
||||
// asin(2u - 1) makes equal-area latitude bands on a spherical model.
|
||||
latitude: round((Math.asin(2 * source.float() - 1) * 180) / Math.PI),
|
||||
longitude: round(source.float() * 360 - 180),
|
||||
}));
|
||||
}
|
||||
+81
-22
@@ -133,11 +133,16 @@ export function randomIntegers(
|
||||
if (
|
||||
!Number.isSafeInteger(minimum) ||
|
||||
!Number.isSafeInteger(maximumInclusive) ||
|
||||
maximumInclusive < minimum ||
|
||||
maximumInclusive - minimum >= 2 ** 32
|
||||
maximumInclusive < minimum
|
||||
)
|
||||
throw new Error("Integer bounds must be safe, ordered integers.");
|
||||
if (maximumInclusive === Number.MAX_SAFE_INTEGER)
|
||||
throw new Error(
|
||||
"Integer bounds must be safe, ordered, and span fewer than 2³² values.",
|
||||
"Maximum inclusive must be less than Number.MAX_SAFE_INTEGER so its exclusive bound is exactly representable.",
|
||||
);
|
||||
if (maximumInclusive - minimum >= 2 ** 32)
|
||||
throw new Error(
|
||||
"The inclusive integer range must contain at most 2³² values.",
|
||||
);
|
||||
return Array.from({ length: count }, () =>
|
||||
source.integer(minimum, maximumInclusive + 1),
|
||||
@@ -211,6 +216,25 @@ export function ulid(source: RandomSource, now = Date.now()): string {
|
||||
return left + right;
|
||||
}
|
||||
|
||||
export type IdentifierKind = "uuid4" | "uuid7" | "ulid";
|
||||
|
||||
export function randomIdentifiers(
|
||||
source: RandomSource,
|
||||
count: number,
|
||||
kind: IdentifierKind,
|
||||
now = Date.now(),
|
||||
): string[] {
|
||||
if (!Number.isSafeInteger(count) || count < 1 || count > 100_000)
|
||||
throw new Error("Identifier count must be a safe integer from 1–100,000.");
|
||||
return Array.from({ length: count }, () =>
|
||||
kind === "uuid4"
|
||||
? uuidV4(source)
|
||||
: kind === "uuid7"
|
||||
? uuidV7(source, now)
|
||||
: ulid(source, now),
|
||||
);
|
||||
}
|
||||
|
||||
export interface DiceResult {
|
||||
expression: string;
|
||||
rolls: number[];
|
||||
@@ -249,30 +273,65 @@ export function rollDice(source: RandomSource, expression: string): DiceResult {
|
||||
};
|
||||
}
|
||||
|
||||
export interface NormalizedWordList {
|
||||
readonly words: readonly string[];
|
||||
readonly canonical: string;
|
||||
readonly normalization: "trim-lines-drop-empty-preserve-order-v1";
|
||||
}
|
||||
|
||||
export function normalizeWordList(
|
||||
input: string | readonly string[],
|
||||
): NormalizedWordList {
|
||||
if (typeof input === "string" && input.length > 4_000_000)
|
||||
throw new Error("Custom word-list input exceeds 4,000,000 UTF-16 units.");
|
||||
const words = typeof input === "string" ? input.split(/\r\n?|\n/u) : input;
|
||||
if (words.length > 100_000 || words.some((word) => word.length > 10_000))
|
||||
throw new Error(
|
||||
"Word lists are limited to 100,000 entries and 10,000 UTF-16 units per entry.",
|
||||
);
|
||||
const normalized = words.map((word) => word.trim()).filter(Boolean);
|
||||
const uniqueCount = new Set(normalized).size;
|
||||
if (uniqueCount < 2 || uniqueCount !== normalized.length)
|
||||
throw new Error(
|
||||
"Word list must contain at least two unique non-empty entries after trimming.",
|
||||
);
|
||||
return {
|
||||
words: normalized,
|
||||
canonical: normalized.join("\n"),
|
||||
normalization: "trim-lines-drop-empty-preserve-order-v1",
|
||||
};
|
||||
}
|
||||
|
||||
export function passphraseWithWordList(
|
||||
source: RandomSource,
|
||||
count: number,
|
||||
wordList: NormalizedWordList,
|
||||
separator = "-",
|
||||
): { value: string; entropy: number; listSize: number } {
|
||||
if (!Number.isSafeInteger(count) || count < 1 || count > 100)
|
||||
throw new Error("Passphrase word count must be 1–100.");
|
||||
return {
|
||||
value: Array.from(
|
||||
{ length: count },
|
||||
() => wordList.words[source.integer(0, wordList.words.length)]!,
|
||||
).join(separator),
|
||||
entropy: count * Math.log2(wordList.words.length),
|
||||
listSize: wordList.words.length,
|
||||
};
|
||||
}
|
||||
|
||||
export function passphrase(
|
||||
source: RandomSource,
|
||||
count: number,
|
||||
words: readonly string[] = DEFAULT_WORDS,
|
||||
separator = "-",
|
||||
): { value: string; entropy: number } {
|
||||
if (words.length > 100_000 || words.some((word) => word.length > 10_000))
|
||||
throw new Error(
|
||||
"Word lists are limited to 100,000 entries and 10,000 UTF-16 units per entry.",
|
||||
);
|
||||
const clean = words.map((word) => word.trim()).filter(Boolean);
|
||||
if (!Number.isSafeInteger(count) || count < 1 || count > 100)
|
||||
throw new Error("Passphrase word count must be 1–100.");
|
||||
if (new Set(clean).size < 2 || new Set(clean).size !== clean.length)
|
||||
throw new Error(
|
||||
"Word list must contain at least two unique non-empty entries.",
|
||||
);
|
||||
return {
|
||||
value: Array.from(
|
||||
{ length: count },
|
||||
() => clean[source.integer(0, clean.length)]!,
|
||||
).join(separator),
|
||||
entropy: count * Math.log2(clean.length),
|
||||
};
|
||||
): { value: string; entropy: number; listSize: number } {
|
||||
return passphraseWithWordList(
|
||||
source,
|
||||
count,
|
||||
normalizeWordList(words),
|
||||
separator,
|
||||
);
|
||||
}
|
||||
|
||||
export function normalValues(
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { randomIntegers, randomString, sampleValues } from "./generators";
|
||||
import { randomSource } from "./source";
|
||||
import {
|
||||
weightedSampleWithoutReplacement,
|
||||
type WeightedItem,
|
||||
} from "./weighted";
|
||||
|
||||
const MAX_RECIPE = 2 * 1024 * 1024;
|
||||
|
||||
export type SeededRecipe =
|
||||
| {
|
||||
schemaVersion: 1;
|
||||
algorithm: "integers-v1";
|
||||
seed: string;
|
||||
parameters: { count: number; minimum: number; maximumInclusive: number };
|
||||
}
|
||||
| {
|
||||
schemaVersion: 1;
|
||||
algorithm: "string-v1";
|
||||
seed: string;
|
||||
parameters: { length: number; alphabet: string };
|
||||
}
|
||||
| {
|
||||
schemaVersion: 1;
|
||||
algorithm: "sample-v1";
|
||||
seed: string;
|
||||
parameters: { count: number; values: string[] };
|
||||
}
|
||||
| {
|
||||
schemaVersion: 1;
|
||||
algorithm: "weighted-sample-v1";
|
||||
seed: string;
|
||||
parameters: { count: number; items: WeightedItem[] };
|
||||
};
|
||||
|
||||
export interface RecipeRun {
|
||||
output: string[];
|
||||
identity: string;
|
||||
stateAfter: readonly number[];
|
||||
}
|
||||
|
||||
export function parseSeededRecipe(source: string): SeededRecipe {
|
||||
if (source.length > MAX_RECIPE)
|
||||
throw new Error("Recipe exceeds the 2 MiB limit.");
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(source);
|
||||
} catch {
|
||||
throw new Error("Recipe is not valid JSON.");
|
||||
}
|
||||
if (!value || typeof value !== "object" || Array.isArray(value))
|
||||
throw new Error("Recipe must be an object.");
|
||||
const candidate = value as Partial<SeededRecipe> & { parameters?: unknown };
|
||||
if (
|
||||
candidate.schemaVersion !== 1 ||
|
||||
typeof candidate.seed !== "string" ||
|
||||
!candidate.seed
|
||||
)
|
||||
throw new Error("Recipe requires schemaVersion 1 and a non-empty seed.");
|
||||
if (candidate.seed.length > 10_000)
|
||||
throw new Error("Recipe seed exceeds 10,000 UTF-16 units.");
|
||||
if (
|
||||
!candidate.parameters ||
|
||||
typeof candidate.parameters !== "object" ||
|
||||
Array.isArray(candidate.parameters)
|
||||
)
|
||||
throw new Error("Recipe parameters must be an object.");
|
||||
if (
|
||||
!["integers-v1", "string-v1", "sample-v1", "weighted-sample-v1"].includes(
|
||||
String(candidate.algorithm),
|
||||
)
|
||||
)
|
||||
throw new Error("Recipe algorithm is unsupported.");
|
||||
return candidate as SeededRecipe;
|
||||
}
|
||||
|
||||
export function runSeededRecipe(recipe: SeededRecipe): RecipeRun {
|
||||
const source = randomSource("deterministic", recipe.seed);
|
||||
let output: string[];
|
||||
switch (recipe.algorithm) {
|
||||
case "integers-v1":
|
||||
output = randomIntegers(
|
||||
source,
|
||||
recipe.parameters.count,
|
||||
recipe.parameters.minimum,
|
||||
recipe.parameters.maximumInclusive,
|
||||
).map(String);
|
||||
break;
|
||||
case "string-v1":
|
||||
output = [
|
||||
randomString(
|
||||
source,
|
||||
recipe.parameters.length,
|
||||
recipe.parameters.alphabet,
|
||||
),
|
||||
];
|
||||
break;
|
||||
case "sample-v1": {
|
||||
const { values, count } = recipe.parameters;
|
||||
if (
|
||||
!Array.isArray(values) ||
|
||||
values.length > 100_000 ||
|
||||
values.some(
|
||||
(value) => typeof value !== "string" || value.length > 100_000,
|
||||
)
|
||||
)
|
||||
throw new Error("Recipe sample values are invalid or exceed limits.");
|
||||
output = sampleValues(source, values, count);
|
||||
break;
|
||||
}
|
||||
case "weighted-sample-v1": {
|
||||
const { items, count } = recipe.parameters;
|
||||
if (!Array.isArray(items))
|
||||
throw new Error("Recipe weighted items must be an array.");
|
||||
output = weightedSampleWithoutReplacement(source, items, count).map(
|
||||
(item) => item.value,
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return {
|
||||
output,
|
||||
identity: source.identity,
|
||||
stateAfter: source.state?.() ?? [],
|
||||
};
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
export interface RemoteIntegerRequest {
|
||||
count: number;
|
||||
minimum: number;
|
||||
maximum: number;
|
||||
}
|
||||
|
||||
const ENDPOINT = "https://www.random.org/integers/";
|
||||
let lastRequest: Promise<unknown> = Promise.resolve();
|
||||
|
||||
export async function randomOrgIntegers(
|
||||
request: RemoteIntegerRequest,
|
||||
signal?: AbortSignal,
|
||||
): Promise<number[]> {
|
||||
if (
|
||||
!Number.isInteger(request.count) ||
|
||||
request.count < 1 ||
|
||||
request.count > 1_000
|
||||
)
|
||||
throw new Error("Remote count must be 1–1,000.");
|
||||
if (
|
||||
!Number.isSafeInteger(request.minimum) ||
|
||||
!Number.isSafeInteger(request.maximum) ||
|
||||
request.maximum < request.minimum ||
|
||||
request.minimum < -1_000_000_000 ||
|
||||
request.maximum > 1_000_000_000
|
||||
)
|
||||
throw new Error(
|
||||
"RANDOM.ORG bounds must be ordered integers from −1,000,000,000 to 1,000,000,000.",
|
||||
);
|
||||
const execute = async () => {
|
||||
const timeout = new AbortController();
|
||||
const timer = window.setTimeout(() => timeout.abort(), 120_000);
|
||||
const abort = () => timeout.abort();
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
try {
|
||||
const url = new URL(ENDPOINT);
|
||||
url.search = new URLSearchParams({
|
||||
num: String(request.count),
|
||||
min: String(request.minimum),
|
||||
max: String(request.maximum),
|
||||
col: "1",
|
||||
base: "10",
|
||||
format: "plain",
|
||||
rnd: "new",
|
||||
}).toString();
|
||||
const response = await fetch(url, {
|
||||
credentials: "omit",
|
||||
referrerPolicy: "no-referrer",
|
||||
cache: "no-store",
|
||||
signal: timeout.signal,
|
||||
});
|
||||
if (!response.ok)
|
||||
throw new Error(`RANDOM.ORG returned HTTP ${response.status}.`);
|
||||
const text = await response.text();
|
||||
const values = text.trim().split(/\s+/u).filter(Boolean).map(Number);
|
||||
if (
|
||||
values.length !== request.count ||
|
||||
values.some(
|
||||
(value) =>
|
||||
!Number.isSafeInteger(value) ||
|
||||
value < request.minimum ||
|
||||
value > request.maximum,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
"RANDOM.ORG response did not match the requested integer contract.",
|
||||
);
|
||||
return values;
|
||||
} finally {
|
||||
window.clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", abort);
|
||||
}
|
||||
};
|
||||
const queued = lastRequest.then(execute, execute);
|
||||
lastRequest = queued.catch(() => undefined);
|
||||
return queued;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { parseCsv } from "@add-ideas/toolbox-helpers";
|
||||
import type { RandomSource } from "./source";
|
||||
|
||||
const MAX_ITEMS = 100_000;
|
||||
const MAX_INPUT = 4_000_000;
|
||||
|
||||
export interface WeightedItem {
|
||||
value: string;
|
||||
weight: number;
|
||||
}
|
||||
|
||||
export interface WeightedSelection extends WeightedItem {
|
||||
inputIndex: number;
|
||||
}
|
||||
|
||||
export function parseWeightedItems(source: string): WeightedItem[] {
|
||||
if (source.length > MAX_INPUT)
|
||||
throw new Error("Weighted input exceeds 4,000,000 UTF-16 units.");
|
||||
const rows = parseCsv(source, {
|
||||
delimiter: ",",
|
||||
maxRows: MAX_ITEMS + 1,
|
||||
maxColumns: 2,
|
||||
maxFieldChars: 100_000,
|
||||
});
|
||||
const items: WeightedItem[] = [];
|
||||
for (const [index, row] of rows.entries()) {
|
||||
if (row.length === 1 && row[0]?.trim() === "") continue;
|
||||
if (row.length !== 2)
|
||||
throw new Error(`CSV row ${index + 1}: expected item and weight.`);
|
||||
const value = row[0] ?? "";
|
||||
const weightText = row[1]?.trim() ?? "";
|
||||
if (!value.trim())
|
||||
throw new Error(`CSV row ${index + 1}: item must not be empty.`);
|
||||
if (value.length > 100_000)
|
||||
throw new Error(
|
||||
`CSV row ${index + 1}: item exceeds 100,000 UTF-16 units.`,
|
||||
);
|
||||
if (!/^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/u.test(weightText))
|
||||
throw new Error(
|
||||
`CSV row ${index + 1}: weight must be a positive decimal number.`,
|
||||
);
|
||||
const weight = Number(weightText);
|
||||
if (!Number.isFinite(weight) || weight < 1e-12 || weight > 1e12)
|
||||
throw new Error(
|
||||
`CSV row ${index + 1}: weight must be between 1e-12 and 1e12.`,
|
||||
);
|
||||
items.push({ value, weight });
|
||||
}
|
||||
if (items.length === 0 || items.length > MAX_ITEMS)
|
||||
throw new Error(
|
||||
`Supply between 1 and ${MAX_ITEMS.toLocaleString()} weighted items.`,
|
||||
);
|
||||
return items;
|
||||
}
|
||||
|
||||
export function weightedSampleWithoutReplacement(
|
||||
source: RandomSource,
|
||||
items: readonly WeightedItem[],
|
||||
count: number,
|
||||
): WeightedSelection[] {
|
||||
if (items.length === 0 || items.length > MAX_ITEMS)
|
||||
throw new Error(
|
||||
`Supply between 1 and ${MAX_ITEMS.toLocaleString()} weighted items.`,
|
||||
);
|
||||
if (!Number.isSafeInteger(count) || count < 1 || count > items.length)
|
||||
throw new Error(
|
||||
"Sample count must be between 1 and the number of weighted items.",
|
||||
);
|
||||
const ranked = items.map((item, inputIndex) => {
|
||||
if (
|
||||
!item ||
|
||||
typeof item.value !== "string" ||
|
||||
typeof item.weight !== "number" ||
|
||||
!item.value.trim() ||
|
||||
item.value.length > 100_000 ||
|
||||
!Number.isFinite(item.weight) ||
|
||||
item.weight < 1e-12 ||
|
||||
item.weight > 1e12
|
||||
)
|
||||
throw new Error(`Weighted item ${inputIndex + 1} is invalid.`);
|
||||
// Exponential-race sampling: the smallest -ln(U)/weight keys form an
|
||||
// exact weighted sample without replacement. Avoid ln(0) explicitly.
|
||||
const uniform = Math.max(Number.MIN_VALUE, source.float());
|
||||
return {
|
||||
...item,
|
||||
inputIndex,
|
||||
rank: -Math.log(uniform) / item.weight,
|
||||
};
|
||||
});
|
||||
ranked.sort(
|
||||
(left, right) =>
|
||||
left.rank - right.rank || left.inputIndex - right.inputIndex,
|
||||
);
|
||||
return ranked.slice(0, count).map((item) => ({
|
||||
value: item.value,
|
||||
weight: item.weight,
|
||||
inputIndex: item.inputIndex,
|
||||
}));
|
||||
}
|
||||
+50
-1
@@ -15,6 +15,16 @@
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
html {
|
||||
min-width: 20rem;
|
||||
min-height: 100%;
|
||||
@@ -161,7 +171,7 @@ textarea {
|
||||
overflow-x: auto;
|
||||
padding-bottom: 0.2rem;
|
||||
}
|
||||
.workspace-tabs button[aria-selected="true"] {
|
||||
.workspace-tabs button[aria-pressed="true"] {
|
||||
border-color: var(--toolbox-accent);
|
||||
background: var(--toolbox-accent);
|
||||
color: var(--toolbox-accent-contrast);
|
||||
@@ -244,6 +254,31 @@ textarea {
|
||||
gap: 0.55rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.ceremony-stack,
|
||||
.ceremony-output {
|
||||
display: grid;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
.ceremony-output {
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
|
||||
padding: 0.8rem;
|
||||
border: 1px solid var(--toolbox-border);
|
||||
border-radius: 0.68rem;
|
||||
background: var(--toolbox-surface-soft);
|
||||
}
|
||||
.ceremony-output section {
|
||||
min-width: 0;
|
||||
}
|
||||
.ceremony-output pre {
|
||||
max-height: 18rem;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.seed-value {
|
||||
overflow-wrap: anywhere;
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
}
|
||||
.primary {
|
||||
border-color: var(--toolbox-accent);
|
||||
background: var(--toolbox-accent);
|
||||
@@ -259,6 +294,20 @@ textarea {
|
||||
width: auto;
|
||||
min-height: auto;
|
||||
}
|
||||
.weekday-options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(5.3rem, 1fr));
|
||||
gap: 0.55rem;
|
||||
margin: 0;
|
||||
padding: 0.75rem;
|
||||
border: 1px solid var(--toolbox-border);
|
||||
border-radius: 0.65rem;
|
||||
}
|
||||
.weekday-options legend {
|
||||
padding: 0 0.35rem;
|
||||
font-size: 0.76rem;
|
||||
font-weight: 750;
|
||||
}
|
||||
.result {
|
||||
display: grid;
|
||||
gap: 0.8rem;
|
||||
|
||||
@@ -3,12 +3,22 @@
|
||||
"schemaVersion": 1,
|
||||
"id": "de.add-ideas.rand-tools",
|
||||
"name": "Random Tools",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.0",
|
||||
"description": "Generate secure or reproducible random values locally in the browser.",
|
||||
"entry": "./",
|
||||
"icon": "./favicon.svg",
|
||||
"categories": ["random", "developer", "productivity"],
|
||||
"tags": ["random", "uuid", "ulid", "dice", "shuffle", "sample"],
|
||||
"tags": [
|
||||
"random",
|
||||
"uuid",
|
||||
"ulid",
|
||||
"dice",
|
||||
"shuffle",
|
||||
"sample",
|
||||
"cards",
|
||||
"dates",
|
||||
"coordinates"
|
||||
],
|
||||
"integration": {
|
||||
"contextVersion": 1,
|
||||
"launchModes": ["navigate", "new-tab"],
|
||||
@@ -21,11 +31,45 @@
|
||||
"crossOriginIsolated": false,
|
||||
"topLevelContext": false
|
||||
},
|
||||
"io": {
|
||||
"accepts": [
|
||||
{
|
||||
"mediaType": "text/csv",
|
||||
"extensions": [".csv"]
|
||||
},
|
||||
{
|
||||
"mediaType": "application/json",
|
||||
"extensions": [".json"]
|
||||
},
|
||||
{
|
||||
"mediaType": "text/plain",
|
||||
"extensions": [".txt"]
|
||||
}
|
||||
],
|
||||
"produces": [
|
||||
{
|
||||
"mediaType": "application/json",
|
||||
"extensions": [".json"]
|
||||
},
|
||||
{
|
||||
"mediaType": "text/csv",
|
||||
"extensions": [".csv"]
|
||||
},
|
||||
{
|
||||
"mediaType": "text/plain",
|
||||
"extensions": [".txt"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"capabilities": {
|
||||
"required": ["secure-random"],
|
||||
"optional": []
|
||||
},
|
||||
"privacy": {
|
||||
"processing": "mixed",
|
||||
"processing": "local",
|
||||
"fileUploads": false,
|
||||
"telemetry": false,
|
||||
"label": "Local generation is the default; RANDOM.ORG is contacted only after explicit opt-in."
|
||||
"label": "All generation runs locally; the application makes no third-party requests."
|
||||
},
|
||||
"source": {
|
||||
"repository": "https://git.add-ideas.de/lotobo/rand-tools",
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
export const APP_VERSION = "0.1.0";
|
||||
export const APP_VERSION = "0.2.0";
|
||||
|
||||
+137
-3
@@ -28,7 +28,7 @@ test("runs from a nested path without external requests", async ({ page }) => {
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test("repeats deterministic output without contacting the remote source", async ({
|
||||
test("repeats deterministic output without external requests", async ({
|
||||
page,
|
||||
}) => {
|
||||
const external = await localOnly(page);
|
||||
@@ -50,6 +50,137 @@ test("repeats deterministic output without contacting the remote source", async
|
||||
expect(external).toEqual([]);
|
||||
});
|
||||
|
||||
test("runs the local draw catalogue with recipe metadata", async ({ page }) => {
|
||||
const external = await localOnly(page);
|
||||
await page.goto("/deep/nested/rand/");
|
||||
await page.getByLabel("Random source").selectOption("deterministic");
|
||||
await page
|
||||
.getByRole("textbox", { name: "Seed", exact: true })
|
||||
.fill("draw-catalogue");
|
||||
await page.getByRole("button", { name: "Draws" }).click();
|
||||
|
||||
await page.getByLabel("Result count").fill("7");
|
||||
await page.getByRole("button", { name: "Generate draw" }).click();
|
||||
await expect(page.locator(".result > pre")).toContainText(/Heads|Tails/u);
|
||||
|
||||
await page.getByLabel("Draw type").selectOption("cards");
|
||||
await page.getByLabel("Cards to deal").fill("5");
|
||||
await page.getByRole("button", { name: "Generate draw" }).click();
|
||||
await expect(page.locator(".result > pre")).toContainText(/[♠♥♦♣]/u);
|
||||
|
||||
await page.getByLabel("Draw type").selectOption("sequence");
|
||||
await page.getByLabel("Sequence minimum").fill("5");
|
||||
await page.getByLabel("Sequence maximum (inclusive)").fill("8");
|
||||
await page.getByRole("button", { name: "Generate draw" }).click();
|
||||
const sequence = (await page.locator(".result > pre").textContent())
|
||||
?.trim()
|
||||
.split("\n")
|
||||
.map(Number)
|
||||
.sort((a, b) => a - b);
|
||||
expect(sequence).toEqual([5, 6, 7, 8]);
|
||||
|
||||
await page.getByLabel("Draw type").selectOption("dates");
|
||||
await page.getByLabel("Result count").fill("3");
|
||||
await page.getByLabel("Start date (inclusive)").fill("2026-01-01");
|
||||
await page.getByLabel("End date (inclusive)").fill("2026-01-31");
|
||||
await page.getByLabel("Do not repeat dates").check();
|
||||
await page.getByRole("button", { name: "Generate draw" }).click();
|
||||
await expect(page.locator(".result > pre")).toContainText(/2026-01-/u);
|
||||
|
||||
await page.getByLabel("Draw type").selectOption("decimals");
|
||||
await page.getByLabel("Result count").fill("2");
|
||||
await page.getByLabel("Decimal places").fill("4");
|
||||
await page.getByRole("button", { name: "Generate draw" }).click();
|
||||
await expect(page.locator(".result > pre")).toContainText(/0\.\d{4}/u);
|
||||
|
||||
await page.getByLabel("Draw type").selectOption("coordinates");
|
||||
await page.getByLabel("Result count").fill("2");
|
||||
await page.getByLabel("Coordinate decimal places").fill("4");
|
||||
await page.getByRole("button", { name: "Generate draw" }).click();
|
||||
await expect(page.locator(".result > pre")).toContainText(
|
||||
/-?\d+\.\d{4}, -?\d+\.\d{4}/u,
|
||||
);
|
||||
await expect(
|
||||
page.getByText(/mathematical samples on a spherical model/u),
|
||||
).toBeVisible();
|
||||
expect(external).toEqual([]);
|
||||
});
|
||||
|
||||
test("identifies normalized custom passphrase inputs without announcing output", async ({
|
||||
page,
|
||||
}) => {
|
||||
const external = await localOnly(page);
|
||||
await page.goto("/deep/nested/rand/");
|
||||
await page.getByLabel("Random source").selectOption("deterministic");
|
||||
await page
|
||||
.getByRole("textbox", { name: "Seed", exact: true })
|
||||
.fill("word-list-identity");
|
||||
await page.getByRole("button", { name: "Passphrases" }).click();
|
||||
await page
|
||||
.getByLabel(/Optional custom word list/u)
|
||||
.fill(" alpha \n\nbeta\n gamma ");
|
||||
await page.getByRole("button", { name: "Generate passphrase" }).click();
|
||||
|
||||
const result = page.locator(".result");
|
||||
await expect(result.getByRole("status")).toHaveText(
|
||||
/Result ready: Passphrase/u,
|
||||
);
|
||||
await expect(result).not.toHaveAttribute("aria-live");
|
||||
await result.getByText("Reproduction metadata").click();
|
||||
await expect(result.locator("details pre")).toContainText(
|
||||
/"normalizedCount": 3/u,
|
||||
);
|
||||
await expect(result.locator("details pre")).toContainText(
|
||||
/"sha256": "[0-9a-f]{64}"/u,
|
||||
);
|
||||
await expect(result.locator("details pre")).toContainText(
|
||||
/"customInputRequiredForReproduction": true/u,
|
||||
);
|
||||
expect(external).toEqual([]);
|
||||
});
|
||||
|
||||
test("runs weighted draws and a local commit–reveal ceremony", async ({
|
||||
page,
|
||||
}) => {
|
||||
const external = await localOnly(page);
|
||||
await page.goto("/deep/nested/rand/");
|
||||
await page.getByLabel("Random source").selectOption("deterministic");
|
||||
await page
|
||||
.getByRole("textbox", { name: "Seed", exact: true })
|
||||
.fill("weighted");
|
||||
await page.getByRole("button", { name: "Lists" }).click();
|
||||
await page.getByLabel("Sampling model").selectOption("weighted");
|
||||
await page
|
||||
.getByRole("textbox", { name: /CSV rows/u })
|
||||
.fill('"Alpha, Inc",10\nBeta,2\nGamma,1');
|
||||
await page.getByLabel(/Sample count/u).fill("2");
|
||||
await page.getByRole("button", { name: "Draw weighted sample" }).click();
|
||||
const weighted = (await page.locator(".result > pre").textContent())
|
||||
?.trim()
|
||||
.split("\n");
|
||||
expect(weighted).toHaveLength(2);
|
||||
expect(
|
||||
weighted?.every((value) => ["Alpha, Inc", "Beta", "Gamma"].includes(value)),
|
||||
).toBe(true);
|
||||
expect(new Set(weighted).size).toBe(2);
|
||||
|
||||
await page.getByRole("button", { name: "Commit–reveal" }).click();
|
||||
await page.getByRole("button", { name: /Generate commitment/u }).click();
|
||||
await expect(page.getByLabel("Public commitment")).toContainText(
|
||||
/"commitment": "[A-Za-z0-9_-]{43}"/u,
|
||||
);
|
||||
await expect(page.getByLabel("Private reveal")).toContainText(
|
||||
/"nonce": "[A-Za-z0-9_-]{43}"/u,
|
||||
);
|
||||
await page
|
||||
.getByRole("button", { name: "Use this reveal in verifier" })
|
||||
.click();
|
||||
await page.getByRole("button", { name: /Verify reveals/u }).click();
|
||||
await expect(page.getByText("1 reveals verified")).toBeVisible();
|
||||
await expect(page.getByText(/Final Base64url seed:/u)).toBeVisible();
|
||||
expect(external).toEqual([]);
|
||||
});
|
||||
|
||||
test("serves the release identity and hardened headers", async ({
|
||||
request,
|
||||
}) => {
|
||||
@@ -59,13 +190,16 @@ test("serves the release identity and hardened headers", async ({
|
||||
"default-src 'self'",
|
||||
);
|
||||
expect(index.headers()["content-security-policy"]).toContain(
|
||||
"connect-src 'self' https://www.random.org",
|
||||
"connect-src 'self'",
|
||||
);
|
||||
expect(index.headers()["content-security-policy"]).not.toMatch(
|
||||
/connect-src[^;]*https?:/u,
|
||||
);
|
||||
expect(await index.text()).not.toMatch(/\b(?:src|href)=["']\//u);
|
||||
const manifest = await request.get("/deep/nested/rand/toolbox-app.json");
|
||||
await expect(manifest.json()).resolves.toMatchObject({
|
||||
id: "de.add-ideas.rand-tools",
|
||||
version: "0.1.0",
|
||||
version: "0.2.0",
|
||||
entry: "./",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
test("keeps the primary workspace inside a narrow viewport", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto("/deep/nested/rand/");
|
||||
await expect(page.locator("main").first()).toBeVisible();
|
||||
await expect(
|
||||
page.locator("main .loading, main .workbench-loading"),
|
||||
).toHaveCount(0);
|
||||
|
||||
const widths = await page.evaluate(() => ({
|
||||
content: document.documentElement.scrollWidth,
|
||||
viewport: document.documentElement.clientWidth,
|
||||
}));
|
||||
expect(widths.viewport).toBeLessThanOrEqual(430);
|
||||
expect(widths.content).toBeLessThanOrEqual(widths.viewport + 1);
|
||||
});
|
||||
@@ -12,6 +12,8 @@ describe("Random Tools", () => {
|
||||
expect(
|
||||
await screen.findByRole("heading", { name: "Random Tools" }),
|
||||
).toBeVisible();
|
||||
expect(await screen.findByText("WebCrypto by default")).toBeVisible();
|
||||
expect(await screen.findByText("No network requests")).toBeVisible();
|
||||
expect(screen.getByRole("button", { name: "Draws" })).toBeVisible();
|
||||
expect(screen.queryByText(/RANDOM\.ORG/iu)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
normalizeWordList,
|
||||
passphrase,
|
||||
passphraseWithWordList,
|
||||
randomIdentifiers,
|
||||
randomIntegers,
|
||||
randomString,
|
||||
rollDice,
|
||||
@@ -8,7 +11,26 @@ import {
|
||||
uuidV4,
|
||||
uuidV7,
|
||||
} from "../../src/random/generators";
|
||||
import {
|
||||
coinFlips,
|
||||
dealCards,
|
||||
decimalFractions,
|
||||
integerSequence,
|
||||
randomCoordinates,
|
||||
randomDates,
|
||||
} from "../../src/random/draws";
|
||||
import { randomSource } from "../../src/random/source";
|
||||
import {
|
||||
commitmentForReveal,
|
||||
createCeremonyReveal,
|
||||
finalizeCeremony,
|
||||
parseCeremonyDocument,
|
||||
} from "../../src/random/ceremony";
|
||||
import { parseSeededRecipe, runSeededRecipe } from "../../src/random/recipes";
|
||||
import {
|
||||
parseWeightedItems,
|
||||
weightedSampleWithoutReplacement,
|
||||
} from "../../src/random/weighted";
|
||||
|
||||
describe("random generators", () => {
|
||||
it("repeats deterministic recipes", () =>
|
||||
@@ -28,6 +50,38 @@ describe("random generators", () => {
|
||||
expect(ulid(randomSource("deterministic", "id"), 0)).toMatch(
|
||||
/^[0-9A-HJKMNP-TV-Z]{26}$/u,
|
||||
));
|
||||
it("bounds identifier batches before allocating their output array", () => {
|
||||
const source = randomSource("deterministic", "identifier-bounds");
|
||||
expect(() => randomIdentifiers(source, 0, "uuid4", 0)).toThrow(
|
||||
/safe integer from 1–100,000/u,
|
||||
);
|
||||
expect(() => randomIdentifiers(source, 100_001, "uuid7", 0)).toThrow(
|
||||
/safe integer from 1–100,000/u,
|
||||
);
|
||||
expect(() => randomIdentifiers(source, Number.NaN, "ulid", 0)).toThrow(
|
||||
/safe integer from 1–100,000/u,
|
||||
);
|
||||
expect(randomIdentifiers(source, 2, "uuid4", 0)).toHaveLength(2);
|
||||
});
|
||||
it("rejects an inclusive MAX_SAFE_INTEGER bound before adding one", () => {
|
||||
const source = randomSource("deterministic", "integer-boundary");
|
||||
expect(() =>
|
||||
randomIntegers(
|
||||
source,
|
||||
1,
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
),
|
||||
).toThrow(/less than Number\.MAX_SAFE_INTEGER/u);
|
||||
expect(
|
||||
randomIntegers(
|
||||
source,
|
||||
1,
|
||||
Number.MAX_SAFE_INTEGER - 1,
|
||||
Number.MAX_SAFE_INTEGER - 1,
|
||||
),
|
||||
).toEqual([Number.MAX_SAFE_INTEGER - 1]);
|
||||
});
|
||||
it("rejects biased duplicate alphabets", () =>
|
||||
expect(() =>
|
||||
randomString(randomSource("deterministic", "x"), 3, "aab"),
|
||||
@@ -45,6 +99,21 @@ describe("random generators", () => {
|
||||
"four",
|
||||
]).entropy,
|
||||
).toBe(8));
|
||||
it("normalizes a custom word list once and reports its eligible count", () => {
|
||||
const words = normalizeWordList(" one \r\n\r\ntwo\n three ");
|
||||
expect(words).toMatchObject({
|
||||
words: ["one", "two", "three"],
|
||||
canonical: "one\ntwo\nthree",
|
||||
normalization: "trim-lines-drop-empty-preserve-order-v1",
|
||||
});
|
||||
expect(
|
||||
passphraseWithWordList(
|
||||
randomSource("deterministic", "normalized-words"),
|
||||
4,
|
||||
words,
|
||||
),
|
||||
).toMatchObject({ listSize: 3, entropy: 4 * Math.log2(3) });
|
||||
});
|
||||
it("bounds alphabet and word-list allocation before generation", () => {
|
||||
const source = randomSource("deterministic", "bounds");
|
||||
expect(() => randomString(source, 1, "ab".repeat(70_000))).toThrow(
|
||||
@@ -55,3 +124,215 @@ describe("random generators", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("local draws", () => {
|
||||
it("reproduces coin flips and reports only binary outcomes", () => {
|
||||
const first = coinFlips(randomSource("deterministic", "coins"), 50);
|
||||
const second = coinFlips(randomSource("deterministic", "coins"), 50);
|
||||
expect(first).toEqual(second);
|
||||
expect(first.every((value) => value === "Heads" || value === "Tails")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("deals every card from a standard deck without replacement", () => {
|
||||
const cards = dealCards(randomSource("deterministic", "cards"), 1, 52);
|
||||
expect(cards).toHaveLength(52);
|
||||
expect(new Set(cards).size).toBe(52);
|
||||
expect(
|
||||
cards.every((card) => /^(?:A|[2-9]|10|J|Q|K)[♠♥♦♣]$/u.test(card)),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("shuffles an inclusive integer range exactly once", () => {
|
||||
const values = integerSequence(
|
||||
randomSource("deterministic", "sequence"),
|
||||
-2,
|
||||
3,
|
||||
);
|
||||
expect(values).toHaveLength(6);
|
||||
expect([...values].sort((a, b) => a - b)).toEqual([-2, -1, 0, 1, 2, 3]);
|
||||
});
|
||||
|
||||
it("filters dates by weekday and can sample without replacement", () => {
|
||||
const values = randomDates(
|
||||
randomSource("deterministic", "dates"),
|
||||
4,
|
||||
"2024-02-01",
|
||||
"2024-02-29",
|
||||
{ weekdays: [1], withoutReplacement: true },
|
||||
);
|
||||
expect(values).toHaveLength(4);
|
||||
expect(new Set(values).size).toBe(4);
|
||||
expect(
|
||||
values.every((value) => new Date(`${value}T00:00:00Z`).getUTCDay() === 1),
|
||||
).toBe(true);
|
||||
expect(() =>
|
||||
randomDates(
|
||||
randomSource("deterministic", "bad-date"),
|
||||
1,
|
||||
"2023-02-29",
|
||||
"2023-03-01",
|
||||
),
|
||||
).toThrow(/valid Gregorian/u);
|
||||
});
|
||||
|
||||
it("generates exact-length decimal fractions with no binary formatting", () => {
|
||||
const values = decimalFractions(
|
||||
randomSource("deterministic", "fractions"),
|
||||
4,
|
||||
12,
|
||||
);
|
||||
expect(values).toHaveLength(4);
|
||||
expect(values.every((value) => /^0\.\d{12}$/u.test(value))).toBe(true);
|
||||
});
|
||||
|
||||
it("generates reproducible coordinates inside geographic bounds", () => {
|
||||
const first = randomCoordinates(
|
||||
randomSource("deterministic", "coordinates"),
|
||||
100,
|
||||
6,
|
||||
);
|
||||
const second = randomCoordinates(
|
||||
randomSource("deterministic", "coordinates"),
|
||||
100,
|
||||
6,
|
||||
);
|
||||
expect(first).toEqual(second);
|
||||
expect(
|
||||
first.every(
|
||||
({ latitude, longitude }) =>
|
||||
latitude >= -90 &&
|
||||
latitude <= 90 &&
|
||||
longitude >= -180 &&
|
||||
longitude <= 180,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects draw requests beyond their allocation bounds", () => {
|
||||
const source = randomSource("deterministic", "bounds");
|
||||
expect(() => coinFlips(source, 100_001)).toThrow(/100,000/u);
|
||||
expect(() => dealCards(source, 1, 53)).toThrow(/1–52/u);
|
||||
expect(() => integerSequence(source, 0, 100_000)).toThrow(/100,000/u);
|
||||
expect(() => decimalFractions(source, 100_000, 64)).toThrow(/4,000,000/u);
|
||||
expect(() => randomCoordinates(source, 1, 11)).toThrow(/0–10/u);
|
||||
});
|
||||
});
|
||||
|
||||
describe("weighted draws and recipes", () => {
|
||||
it("parses quoted CSV and samples entries without replacement", () => {
|
||||
const items = parseWeightedItems('"Alpha, Inc.",1\nBeta,10\nGamma,2');
|
||||
const first = weightedSampleWithoutReplacement(
|
||||
randomSource("deterministic", "weighted"),
|
||||
items,
|
||||
3,
|
||||
);
|
||||
const second = weightedSampleWithoutReplacement(
|
||||
randomSource("deterministic", "weighted"),
|
||||
items,
|
||||
3,
|
||||
);
|
||||
expect(first).toEqual(second);
|
||||
expect(new Set(first.map((item) => item.inputIndex)).size).toBe(3);
|
||||
expect(items[0]?.value).toBe("Alpha, Inc.");
|
||||
});
|
||||
|
||||
it("rejects invalid weights before drawing", () => {
|
||||
expect(() => parseWeightedItems("Alpha,0")).toThrow(/between/u);
|
||||
expect(() =>
|
||||
weightedSampleWithoutReplacement(
|
||||
randomSource("deterministic", "weighted"),
|
||||
[{ value: "Alpha", weight: Number.POSITIVE_INFINITY }],
|
||||
1,
|
||||
),
|
||||
).toThrow(/invalid/u);
|
||||
});
|
||||
|
||||
it("validates and exactly replays a versioned seeded recipe", () => {
|
||||
const source = JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
algorithm: "weighted-sample-v1",
|
||||
seed: "recipe-seed",
|
||||
parameters: {
|
||||
count: 2,
|
||||
items: [
|
||||
{ value: "one", weight: 1 },
|
||||
{ value: "two", weight: 4 },
|
||||
{ value: "three", weight: 2 },
|
||||
],
|
||||
},
|
||||
});
|
||||
const recipe = parseSeededRecipe(source);
|
||||
expect(runSeededRecipe(recipe)).toEqual(runSeededRecipe(recipe));
|
||||
expect(runSeededRecipe(recipe).output).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("commit–reveal ceremonies", () => {
|
||||
it("verifies commitments and derives an order-independent final seed", async () => {
|
||||
const alice = await createCeremonyReveal("draw-1", "Alice");
|
||||
const bob = await createCeremonyReveal("draw-1", "Bob");
|
||||
const first = await finalizeCeremony({
|
||||
schemaVersion: 1,
|
||||
ceremonyId: "draw-1",
|
||||
participants: [alice, bob],
|
||||
});
|
||||
const second = await finalizeCeremony({
|
||||
schemaVersion: 1,
|
||||
ceremonyId: "draw-1",
|
||||
participants: [bob, alice],
|
||||
});
|
||||
expect(first.valid).toBe(true);
|
||||
expect(first.seed).toMatch(/^[A-Za-z0-9_-]{43}$/u);
|
||||
expect(second.seed).toBe(first.seed);
|
||||
});
|
||||
|
||||
it("rejects a reveal changed after commitment", async () => {
|
||||
const entry = await createCeremonyReveal("draw-2", "Alice");
|
||||
const other = await createCeremonyReveal("draw-2", "Other");
|
||||
const result = await finalizeCeremony({
|
||||
schemaVersion: 1,
|
||||
ceremonyId: "draw-2",
|
||||
participants: [{ ...entry, nonce: other.nonce }],
|
||||
});
|
||||
expect(result).toMatchObject({ valid: false, verified: 0 });
|
||||
expect(result.errors.join(" ")).toMatch(/does not match/u);
|
||||
});
|
||||
|
||||
it("parses a bounded document and reproduces its commitment", async () => {
|
||||
const entry = await createCeremonyReveal("draw-3", "Alice");
|
||||
const parsed = parseCeremonyDocument(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
ceremonyId: "draw-3",
|
||||
participants: [entry],
|
||||
}),
|
||||
);
|
||||
await expect(
|
||||
commitmentForReveal("draw-3", "Alice", parsed.participants[0]!.nonce),
|
||||
).resolves.toMatchObject({ commitment: entry.commitment });
|
||||
});
|
||||
|
||||
it("retains per-reveal ceremony IDs and rejects malformed commitments", async () => {
|
||||
const entry = await createCeremonyReveal("draw-4", "Alice");
|
||||
const parsed = parseCeremonyDocument(
|
||||
JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
ceremonyId: "draw-4",
|
||||
participants: [{ ...entry, ceremonyId: "another-draw" }],
|
||||
}),
|
||||
);
|
||||
await expect(finalizeCeremony(parsed)).resolves.toMatchObject({
|
||||
valid: false,
|
||||
verified: 0,
|
||||
});
|
||||
await expect(
|
||||
finalizeCeremony({
|
||||
schemaVersion: 1,
|
||||
ceremonyId: "draw-4",
|
||||
participants: [{ ...entry, commitment: "not-base64url" }],
|
||||
}),
|
||||
).resolves.toMatchObject({ valid: false, verified: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user