prepublic 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.1.0] - 2026-11-30
8
+
9
+ ### Added
10
+ - Read-only, hardened scan of a local Git repository: secrets in tracked files, secrets and sensitive files in history, sensitive and unignored files, personal paths, internal markers and network references, author emails, `.gitignore` gaps, README, license, community files, tests and CI.
11
+ - Optional Gitleaks integration with redaction and merged results.
12
+ - Self-contained HTML report designed as a clearance record: verdict, check gauge, exposure ledger with one mark per finding, master-detail findings with redacted evidence, checklist and coverage tabs, light and dark themes, keyboard navigation, linkable view state, embedded IBM Plex fonts and a strict hash-based CSP. Markdown and JSON output.
13
+ - CLI with `--demo`, `--fail-on` for CI, `.prepublic.json` suppressions and inline `prepublic:allow`.
14
+ - Synthetic example repositories and a test suite covering detection, read-only behaviour, hostile repository config, report sanitization and the CLI.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Prepublic contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,165 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="docs/logo-dark.svg">
4
+ <img src="docs/logo-light.svg" alt="Prepublic" width="236" height="48">
5
+ </picture>
6
+ </p>
2
7
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
8
+ <p align="center"><strong>Know what you expose before you make a repository public.</strong></p>
9
+
10
+ Prepublic reviews a local Git repository the way a careful colleague would before it goes public: leaked credentials in the files <em>and</em> in the history, sensitive files, personal paths and emails, repository hygiene, documentation and licensing. It runs offline, never modifies the repository, and hands you one clearance record with a verdict, every finding, how to fix it and an honest account of what it could not check.
11
+
12
+ ![The Prepublic clearance record for a repository that is not ready to publish: verdict, check gauge, exposure ledger with one mark per finding, and a finding with redacted evidence](docs/screenshots/report-light.png)
13
+
14
+ ## Try it in ten seconds
15
+
16
+ ```sh
17
+ npx prepublic --demo
18
+ ```
19
+
20
+ `--demo` builds a throwaway repository full of fake credentials and personal paths, scans it, opens the report and deletes the repository again. Nothing leaves your machine.
21
+
22
+ - **Local-first:** no telemetry, no accounts, no API keys, no network requests. Zero runtime dependencies: Node.js 20+ and Git.
23
+ - **Read-only and hardened:** Git runs with repository-configurable command hooks disabled, so even a hostile `.git/config` cannot execute code during a scan.
24
+ - **Safe to share:** raw secret values never reach a report. Personal paths, user names and emails are masked.
25
+ - **Built on established tooling:** if [Gitleaks](https://github.com/gitleaks/gitleaks) is installed, Prepublic runs it as a second engine and merges the results.
26
+
27
+ ## Quick start
28
+
29
+ ```sh
30
+ npx prepublic path/to/your-repo # run without installing
31
+ npm install -g prepublic # or install the `prepublic` command
32
+ ```
33
+
34
+ From source: `git clone https://github.com/egemenozen1/prepublic.git`, then `node bin/prepublic.js path/to/your-repo`.
35
+
36
+ The scan prints a summary and opens the report in your browser. Reports go to your system temp folder, never into the scanned repository unless you pass `--out`.
37
+
38
+ ```sh
39
+ prepublic --demo # leaky-service: blocked by secrets and history exposure
40
+ prepublic --demo almost-ready # needs review: license and personal-data issues
41
+ prepublic --demo release-ready # passes every automated check
42
+ ```
43
+
44
+ ## What it checks
45
+
46
+ | Area | Examples |
47
+ |---|---|
48
+ | **Secrets in files** | AWS, GitHub, GitLab, Slack, Stripe, Google, OpenAI, Anthropic, npm, PyPI, SendGrid, Azure, Telegram tokens; private key blocks; JWTs; database and URL credentials; hard-coded `password = "…"` assignments (entropy-checked, placeholders ignored) |
49
+ | **Git history** | Secrets that were removed but remain in old commits on any local ref; sensitive files that were deleted but are still retrievable; large blobs; non-noreply author emails that will become public |
50
+ | **Sensitive files** | `.env`, private keys and keystores, cloud credential files, Terraform state, HAR captures, database dumps, shell history, registry configs with auth tokens; sensitive files that are untracked *and* not ignored |
51
+ | **Personal & internal data** | Absolute home-directory paths (your OS user name), confidentiality notices, private IPs and internal hostnames |
52
+ | **Repository hygiene** | `.gitignore` gaps for your stack (verified with `git check-ignore`, including patterns that only your *global* config ignores), committed `node_modules`, logs, OS and IDE clutter, oversized files, symlinks pointing outside the repo, tokens in submodule or remote URLs |
53
+ | **Docs & licensing** | README presence, substance and broken relative links; license presence, recognition, unfilled `[year]`/`[fullname]` placeholders, and mismatches with `package.json`, `pyproject.toml` or `Cargo.toml`; CONTRIBUTING, SECURITY, tests, CI |
54
+
55
+ Every finding explains **why it matters**, **what to do** (including copy-ready commands such as `git rm --cached` or `git filter-repo`), its locations, and redacted evidence.
56
+
57
+ ## The report
58
+
59
+ A Prepublic report reads like a clearance record: who and what was inspected, a verdict, and the evidence behind it.
60
+
61
+ | Dark theme: review required | On a phone |
62
+ |---|---|
63
+ | ![A repository that needs review, in the dark theme](docs/screenshots/report-dark.png) | ![The report on a phone](docs/screenshots/report-mobile.png) |
64
+
65
+ - **A verdict you can act on:** *Not ready to publish* (any critical or high finding), *Review before publishing* (medium) or *No blockers detected*. Never "safe".
66
+ - **Exposure ledger:** one mark per finding, by category and severity. Select a mark to open that finding, a category or a severity to filter.
67
+ - **Findings with everything needed to fix them:** evidence with secrets replaced by solid redaction marks, numbered fix steps, copy-ready commands, exact paths, lines and commits. List and detail side by side on desktop, inline on phones.
68
+ - **Publication checklist:** the automated checks plus the steps no scanner can take for you: rotating exposed credentials, reviewing issues, wikis and CI logs, confirming you have the right to publish.
69
+ - **Coverage and limitations:** what was scanned, what was skipped, and why.
70
+ - **Made for working through findings:** keyboard navigation (`/` to search, arrows or `j`/`k`), a reviewed state kept only in your browser, light and dark themes, links that keep the current view.
71
+ - **Exports:** sanitized Markdown, JSON, or print to PDF. The HTML is one self-contained file: fonts embedded, a strict hash-based Content Security Policy, no external resources.
72
+
73
+ | Nothing to fix | Publication checklist |
74
+ |---|---|
75
+ | ![A repository with no blockers: every category clear](docs/screenshots/report-clear.png) | ![The checklist: automated checks and manual steps](docs/screenshots/report-checklist.png) |
76
+
77
+ ## Usage
78
+
79
+ ```text
80
+ prepublic [path] [options]
81
+
82
+ -o, --out <file> Write the report to <file>; format follows the extension (.html, .md, .json)
83
+ -f, --format <fmt> html (default), md or json
84
+ --stdout Print the md/json report to stdout
85
+ --no-open Do not open the HTML report in your browser
86
+ --no-history Skip Git history checks
87
+ --no-snippets Leave redacted evidence lines out of the report
88
+ --gitleaks <mode> auto (default: use if installed), off, or require
89
+ --gitleaks-path <bin> Path to a gitleaks executable
90
+ --max-file-mb <n> Skip content checks for files larger than n MB (default 2)
91
+ --max-history-mb <n> Stop the history content scan after n MB of patches (default 512)
92
+ --fail-on <severity> Exit 1 if a finding is at or above: critical, high, medium, low, info
93
+ --demo [name] Scan a generated synthetic repository: leaky-service (default), almost-ready, release-ready
94
+ ```
95
+
96
+ Exit codes: `0` scan completed, `1` `--fail-on` threshold reached, `2` usage or repository error.
97
+
98
+ ### In CI
99
+
100
+ ```yaml
101
+ - uses: actions/checkout@v4
102
+ with: { fetch-depth: 0 } # full history, so history checks are meaningful
103
+ - run: npx --yes prepublic@0.1.0 . --no-open --format md --out prepublic.md --fail-on high
104
+ ```
105
+
106
+ ### Gitleaks integration
107
+
108
+ With `--gitleaks auto` (default) Prepublic runs `gitleaks git --redact` when the binary is on your `PATH`. Prepublic never downloads Gitleaks. Its report is written to a private temp directory that is deleted immediately, and Prepublic keeps only rule, file, line and commit. Matches that overlap a built-in finding are shown as *confirmed by Gitleaks*. Use `--gitleaks require` to fail when it cannot run.
109
+
110
+ ### Configuration and false positives
111
+
112
+ Add a `prepublic:allow` comment to a line to skip all line-level checks for it (`gitleaks:allow` also silences Prepublic's secret rules). For broader exclusions, add `.prepublic.json` to the repository root:
113
+
114
+ ```json
115
+ {
116
+ "ignorePaths": ["test/fixtures/**", "docs/examples/*.env"],
117
+ "ignoreRules": ["internal-network", "junk/*"]
118
+ }
119
+ ```
120
+
121
+ Suppressed paths and findings are counted in the report, so exclusions stay visible.
122
+
123
+ ## Security and privacy model
124
+
125
+ - **Read-only.** Prepublic only runs read-only Git commands with `GIT_OPTIONAL_LOCKS=0`, so it does not even refresh the index. The test suite verifies that every file in the repository, including `.git`, is byte-for-byte unchanged after a scan.
126
+ - **Hardened against hostile repositories.** Git is invoked with `core.fsmonitor=false`, `--no-textconv`, `--no-ext-diff`, a fixed pager and `protocol.allow=never`. The tests include a repository whose config tries to execute commands through fsmonitor, textconv and the pager. Without hardening, plain `git ls-files` and `git log -p` run those commands.
127
+ - **No raw secrets in output.** Detectors keep values in memory only. Reports show a public format prefix and the length (`ghp_•••••••• (40 chars)`), evidence lines are redacted, and a final pass re-redacts every string in the report. The absolute repository path is replaced with `<repo>`.
128
+ - **No network.** Prepublic makes no network requests. The HTML report loads nothing external.
129
+
130
+ See [SECURITY.md](SECURITY.md) to report a vulnerability.
131
+
132
+ ## Limitations
133
+
134
+ Prepublic reduces risk; it cannot prove that a repository is safe to publish.
135
+
136
+ - Detection is pattern-based. Unknown token formats and encoded, split or low-entropy secrets can be missed, and some findings will be false positives. Installing Gitleaks broadens coverage.
137
+ - Only tracked files (their working-tree versions) and history on **local** refs are inspected. Fetch all branches first. Remote-only branches, pull requests, issues, wikis, releases, CI logs, packages and container images are out of scope.
138
+ - Changes introduced only in merge commits are not content-scanned. Binary files and files over the size limit are only checked by name and size.
139
+ - If a credential was ever committed, assume it is compromised and rotate it. Rewriting history does not reach existing clones, forks or caches.
140
+
141
+ ## How Prepublic compares
142
+
143
+ Prepublic is a *pre-publication* tool. It does not try to replace established scanners; it combines their concerns into one local decision before the first push to a public remote.
144
+
145
+ | Tool | Focus | Where Prepublic differs |
146
+ |---|---|---|
147
+ | Gitleaks, TruffleHog, detect-secrets | Deep secret detection | Prepublic integrates Gitleaks and adds files, personal data, hygiene, docs and licensing, plus a readiness verdict and a shareable report |
148
+ | GitHub secret scanning and push protection | Secrets, server-side | Runs after code reaches GitHub; Prepublic runs before anything leaves your machine, on any host |
149
+ | Repolinter, community-profile checks | Required files and metadata | No secret, history or personal-data checks |
150
+ | OpenSSF Scorecard | Security posture of public GitHub projects | Assumes the project is already public |
151
+
152
+ ## Development
153
+
154
+ ```sh
155
+ npm test # node:test suite: detectors, scans of the synthetic repos, read-only and hardening checks, report sanitization, CLI
156
+ npm run examples # generate the synthetic example repositories into examples/
157
+ npm run scan:self # scan this repository with Prepublic
158
+ npm run screenshots # regenerate docs/screenshots with a local headless Chrome or Edge
159
+ ```
160
+
161
+ The example repositories are generated at runtime from a seeded generator ([scripts/make-examples.mjs](scripts/make-examples.mjs)), so no secret-shaped strings are ever committed to this repository. See [CONTRIBUTING.md](CONTRIBUTING.md).
162
+
163
+ ## License
164
+
165
+ [MIT](LICENSE). The report embeds IBM Plex Sans and IBM Plex Mono, licensed under the SIL Open Font License 1.1 ([notice](src/report/fonts/OFL.txt)).
package/SECURITY.md ADDED
@@ -0,0 +1,18 @@
1
+ # Security policy
2
+
3
+ Prepublic handles sensitive material by design, so we take reports seriously.
4
+
5
+ ## Reporting a vulnerability
6
+
7
+ Please **do not open a public issue**. Use GitHub's private vulnerability reporting ("Report a vulnerability" on the Security tab of this repository). Include steps to reproduce and the affected version. You can expect an acknowledgement within a few days.
8
+
9
+ ## In scope
10
+
11
+ - A raw secret value, an unmasked personal path or an unmasked email reaching any report format (HTML, Markdown, JSON, terminal).
12
+ - A scan writing to the scanned repository, or executing code configured by the scanned repository.
13
+ - Script injection or external resource loading in the HTML report.
14
+ - Gitleaks report files left on disk after a scan.
15
+
16
+ ## Out of scope
17
+
18
+ - Secrets that Prepublic fails to *detect*. That is a detection gap; please open a regular issue with a synthetic example (never a real credential).
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ const [major] = process.versions.node.split('.').map(Number);
5
+ if (major < 20) {
6
+ process.stderr.write(`prepublic: Node.js 20 or newer is required (found ${process.versions.node}).\n`);
7
+ process.exit(2);
8
+ }
9
+
10
+ main(process.argv.slice(2)).then((code) => {
11
+ process.exitCode = code;
12
+ });
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "prepublic",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Know what you expose before you make a Git repository public: a local, read-only clearance check for secrets, history, personal data, hygiene and licensing, with a sanitized report.",
5
+ "homepage": "https://github.com/egemenozen1/prepublic#readme",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/egemenozen1/prepublic.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/egemenozen1/prepublic/issues"
12
+ },
13
+ "type": "module",
14
+ "bin": {
15
+ "prepublic": "bin/prepublic.js"
16
+ },
17
+ "exports": {
18
+ ".": "./src/index.js"
19
+ },
20
+ "files": [
21
+ "bin/",
22
+ "src/",
23
+ "scripts/make-examples.mjs",
24
+ "README.md",
25
+ "LICENSE",
26
+ "CHANGELOG.md",
27
+ "SECURITY.md"
28
+ ],
29
+ "scripts": {
30
+ "test": "node --test",
31
+ "examples": "node scripts/make-examples.mjs examples",
32
+ "scan:self": "node bin/prepublic.js . --no-open --format md --out .prepublic/self-scan.md --fail-on medium",
33
+ "screenshots": "node scripts/screenshots.mjs"
34
+ },
35
+ "engines": {
36
+ "node": ">=20"
37
+ },
38
+ "keywords": [
39
+ "git",
40
+ "secrets",
41
+ "open-source",
42
+ "release",
43
+ "security",
44
+ "gitleaks",
45
+ "audit",
46
+ "cli",
47
+ "pre-publication",
48
+ "open-source-release",
49
+ "privacy"
50
+ ],
51
+ "license": "MIT"
52
+ }
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env node
2
+ // Generates synthetic example repositories for demos and tests.
3
+ //
4
+ // Every "secret" below is fake and generated at runtime from a seeded PRNG.
5
+ // Token prefixes are split in the source on purpose so this file never
6
+ // contains a string that a secret scanner (or GitHub push protection) would
7
+ // flag. Usage: node scripts/make-examples.mjs <target-dir>
8
+
9
+ import { mkdirSync, writeFileSync, rmSync, existsSync, mkdtempSync } from 'node:fs';
10
+ import { join, resolve, dirname } from 'node:path';
11
+ import { tmpdir } from 'node:os';
12
+ import { execFileSync } from 'node:child_process';
13
+ import { fileURLToPath } from 'node:url';
14
+
15
+ function rng(seed) {
16
+ let s = seed >>> 0;
17
+ return () => {
18
+ s = (s + 0x6d2b79f5) >>> 0;
19
+ let t = s;
20
+ t = Math.imul(t ^ (t >>> 15), t | 1);
21
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
22
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
23
+ };
24
+ }
25
+ const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
26
+ const UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
27
+
28
+ /** Build fake credentials. Same seed → same values. */
29
+ export function fakeSecrets(seed = 42) {
30
+ const r = rng(seed);
31
+ const pick = (alphabet, n) => Array.from({ length: n }, () => alphabet[Math.floor(r() * alphabet.length)]).join('');
32
+ return {
33
+ awsKeyId: ['AK', 'IA'].join('') + pick(UPPER, 16),
34
+ awsSecret: pick(ALNUM + '/+', 40),
35
+ githubToken: ['gh', 'p_'].join('') + pick(ALNUM, 36),
36
+ githubTokenOld: ['gh', 'p_'].join('') + pick(ALNUM, 36),
37
+ stripeLive: ['sk', '_li', 've_'].join('') + pick(ALNUM, 28),
38
+ slackToken: ['xo', 'xb-'].join('') + pick('0123456789', 12) + '-' + pick('0123456789', 13) + '-' + pick(ALNUM, 24),
39
+ googleKey: ['AI', 'za'].join('') + pick(ALNUM + '_-', 35),
40
+ dbPassword: pick(ALNUM, 18),
41
+ npmToken: ['np', 'm_'].join('') + pick(ALNUM, 36),
42
+ apiSecret: pick(ALNUM, 32),
43
+ keyBody: Array.from({ length: 6 }, () => pick(ALNUM + '+/', 64)),
44
+ };
45
+ }
46
+
47
+ const MIT = (holder) => `MIT License
48
+
49
+ Copyright (c) 2026 ${holder}
50
+
51
+ Permission is hereby granted, free of charge, to any person obtaining a copy
52
+ of this software and associated documentation files (the "Software"), to deal
53
+ in the Software without restriction, including without limitation the rights
54
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
55
+ copies of the Software, and to permit persons to whom the Software is
56
+ furnished to do so, subject to the following conditions:
57
+
58
+ The above copyright notice and this permission notice shall be included in all
59
+ copies or substantial portions of the Software.
60
+
61
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
62
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
63
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
64
+ `;
65
+
66
+ function makeGit(dir, emptyHooks) {
67
+ let tick = 0;
68
+ return (args, { email = '1001+demo@users.noreply.github.com', name = 'Demo Author' } = {}) => {
69
+ tick++;
70
+ const date = `2026-01-${String(1 + tick).padStart(2, '0')}T10:00:00Z`;
71
+ return execFileSync('git', [
72
+ '-c', `core.hooksPath=${emptyHooks}`, '-c', 'commit.gpgsign=false', '-c', 'core.autocrlf=false',
73
+ '-c', `user.name=${name}`, '-c', `user.email=${email}`, '-c', 'init.defaultBranch=main', ...args,
74
+ ], { cwd: dir, env: { ...process.env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date, GIT_CONFIG_NOSYSTEM: '1' }, stdio: ['ignore', 'pipe', 'pipe'] }).toString();
75
+ };
76
+ }
77
+
78
+ function writeFiles(dir, files) {
79
+ for (const [p, content] of Object.entries(files)) {
80
+ const abs = join(dir, p);
81
+ mkdirSync(dirname(abs), { recursive: true });
82
+ writeFileSync(abs, content);
83
+ }
84
+ }
85
+
86
+ function commitAll(g, message, who) {
87
+ g(['add', '-A']);
88
+ g(['commit', '--no-verify', '-q', '-m', message], who);
89
+ }
90
+
91
+ /** A service that is clearly not ready: secrets, sensitive files, history leaks. */
92
+ function leakyService(dir, s, g) {
93
+ const who = { email: 'jordan.doe@corp.example', name: 'Jordan Doe' };
94
+ writeFiles(dir, {
95
+ 'package.json': JSON.stringify({ name: 'leaky-service', version: '0.3.0', license: 'MIT', scripts: { start: 'node src/server.js' } }, null, 2),
96
+ 'README.md': '# leaky-service\n\nInternal billing worker.\n',
97
+ '.gitignore': 'node_modules/\n',
98
+ 'src/server.js': `const config = require('./config');\nconsole.log('listening', config.port);\n`,
99
+ 'secrets.json': JSON.stringify({ github: s.githubTokenOld }, null, 2),
100
+ });
101
+ commitAll(g, 'Initial import', who);
102
+
103
+ // Remove the secrets file: it stays in history.
104
+ rmSync(join(dir, 'secrets.json'));
105
+ writeFiles(dir, {
106
+ 'src/config.js': [
107
+ 'module.exports = {',
108
+ ' port: 8080,',
109
+ ` aws: { accessKeyId: '${s.awsKeyId}', secretAccessKey: '${s.awsSecret}' },`,
110
+ ` stripeKey: '${s.stripeLive}',`,
111
+ ` database: 'postgres://billing:${s.dbPassword}@db.prod.corp.example:5432/billing',`,
112
+ ` logDir: 'C:\\\\Users\\\\jordan.doe\\\\projects\\\\billing\\\\logs',`,
113
+ '};',
114
+ '',
115
+ ].join('\n'),
116
+ '.env': `SLACK_TOKEN=${s.slackToken}\nGOOGLE_MAPS_KEY=${s.googleKey}\nAPI_SECRET="${s.apiSecret}"\n`,
117
+ 'deploy/id_rsa': ['-----BEGIN OPENSSH PRIVATE KEY-----', ...s.keyBody, '-----END OPENSSH PRIVATE KEY-----', ''].join('\n'),
118
+ 'deploy/notes.md': '# Deploy notes\n\nCONFIDENTIAL - internal use only.\n\nSSH to 10.20.30.40 as deploy, see /home/jordan/keys/ for the key.\n',
119
+ 'logs/debug.log': 'GET /health 200\nGET /api/invoices 500 (stack in /Users/jordan/dev/billing/src/server.js:14)\n',
120
+ '.DS_Store': Buffer.from([0, 0, 0, 1, 66, 117, 100, 49]),
121
+ });
122
+ commitAll(g, 'Add config and deploy notes', who);
123
+
124
+ // A token that was committed and later replaced: history-only exposure.
125
+ writeFiles(dir, { 'scripts/publish.sh': `#!/bin/sh\nNPM_TOKEN=${s.npmToken} npm publish\n` });
126
+ commitAll(g, 'Add publish script', who);
127
+ writeFiles(dir, { 'scripts/publish.sh': '#!/bin/sh\n# NPM_TOKEN comes from the CI secret store\nnpm publish\n' });
128
+ commitAll(g, 'Read npm token from environment', who);
129
+ }
130
+
131
+ /** A library that is close: some docs/licensing gaps and personal data. */
132
+ function almostReady(dir, s, g) {
133
+ const who = { email: 'sam.lee@example.org', name: 'Sam Lee' };
134
+ writeFiles(dir, {
135
+ 'pyproject.toml': '[project]\nname = "almost-ready"\nversion = "1.0.0"\nlicense = "Apache-2.0"\n',
136
+ 'README.md': '# almost-ready\n\nA tiny library that formats durations for humans.\n\n## Install\n\n```\npip install almost-ready\n```\n\n## Usage\n\n```python\nfrom almost_ready import humanize\nhumanize(3600) # "1 hour"\n```\n\n![Screenshot](docs/screenshot.png)\n\nSee the [changelog](CHANGELOG.md) for details. This README is intentionally a little longer so that the length heuristic is satisfied in the example repository.\n',
137
+ 'LICENSE': MIT('[fullname]').replace('2026', '[year]'),
138
+ '.gitignore': '__pycache__/\n*.pyc\n.env\n',
139
+ 'almost_ready/__init__.py': 'def humanize(seconds):\n return f"{seconds // 3600} hour"\n',
140
+ 'tests/test_humanize.py': 'from almost_ready import humanize\n\n\ndef test_hour():\n assert humanize(3600) == "1 hour"\n',
141
+ 'docs/dev.md': '# Development\n\nRun `pytest` from /Users/samlee/code/almost-ready/ before sending a pull request.\n',
142
+ 'docs/example-config.yml': '# Example only\napi_key: "your_api_key_here"\npassword: "changeme"\n',
143
+ });
144
+ commitAll(g, 'First release', who);
145
+ }
146
+
147
+ /** A project that passes every automated check. */
148
+ function releaseReady(dir, s, g) {
149
+ writeFiles(dir, {
150
+ 'package.json': JSON.stringify({ name: 'release-ready', version: '1.0.0', license: 'MIT', type: 'module', scripts: { test: 'node --test' } }, null, 2),
151
+ 'README.md': '# release-ready\n\nA small, well-documented utility that slugifies strings.\n\n## Installation\n\n```sh\nnpm install release-ready\n```\n\n## Usage\n\n```js\nimport { slugify } from "release-ready";\nslugify("Hello World"); // "hello-world"\n```\n\n## Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md). Security issues: see [SECURITY.md](SECURITY.md).\n\n## License\n\nMIT, see [LICENSE](LICENSE).\n',
152
+ 'LICENSE': MIT('Release Ready Contributors'),
153
+ 'CONTRIBUTING.md': '# Contributing\n\n1. Fork and clone.\n2. Run `npm test`.\n3. Open a pull request.\n',
154
+ 'SECURITY.md': '# Security policy\n\nPlease report vulnerabilities privately through GitHub security advisories.\n',
155
+ 'CODE_OF_CONDUCT.md': '# Code of conduct\n\nBe kind. We follow the Contributor Covenant 2.1.\n',
156
+ 'CHANGELOG.md': '# Changelog\n\n## 1.0.0\n\n- First release.\n',
157
+ '.gitignore': 'node_modules/\n.env\n.env.*\n!.env.example\n*.log\n.DS_Store\ncoverage/\n',
158
+ '.env.example': 'API_KEY=\n',
159
+ '.github/workflows/ci.yml': 'name: CI\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-node@v4\n - run: npm test\n',
160
+ 'src/index.js': 'export function slugify(s) {\n return s.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");\n}\n',
161
+ 'spec/slugify.spec.mjs': 'import { test } from "node:test";\nimport assert from "node:assert";\nimport { slugify } from "../src/index.js";\n\ntest("slugify", () => assert.equal(slugify("Hello World"), "hello-world"));\n',
162
+ });
163
+ commitAll(g, 'Release 1.0.0');
164
+ }
165
+
166
+ export const EXAMPLES = { 'leaky-service': leakyService, 'almost-ready': almostReady, 'release-ready': releaseReady };
167
+
168
+ /**
169
+ * Create the example repositories under `target`. Existing example folders are
170
+ * replaced. Returns { [name]: absolutePath }.
171
+ */
172
+ export function createExamples(target, { seed = 42, only } = {}) {
173
+ const root = resolve(target);
174
+ mkdirSync(root, { recursive: true });
175
+ const emptyHooks = mkdtempSync(join(tmpdir(), 'prepublic-hooks-'));
176
+ const secrets = fakeSecrets(seed);
177
+ const out = {};
178
+ try {
179
+ for (const [name, build] of Object.entries(EXAMPLES)) {
180
+ if (only && !only.includes(name)) continue;
181
+ const dir = join(root, name);
182
+ if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
183
+ mkdirSync(dir, { recursive: true });
184
+ const g = makeGit(dir, emptyHooks);
185
+ g(['init', '-q']);
186
+ build(dir, secrets, g);
187
+ out[name] = dir;
188
+ }
189
+ } finally {
190
+ rmSync(emptyHooks, { recursive: true, force: true });
191
+ }
192
+ return out;
193
+ }
194
+
195
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
196
+ const target = process.argv[2] || 'examples';
197
+ const made = createExamples(target);
198
+ for (const [name, dir] of Object.entries(made)) process.stdout.write(`created ${name}: ${dir}\n`);
199
+ process.stdout.write('\nTry: npx prepublic examples/leaky-service\n');
200
+ }