secondkey 0.2.0__tar.gz

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.
Files changed (44) hide show
  1. secondkey-0.2.0/LICENSE +202 -0
  2. secondkey-0.2.0/PKG-INFO +208 -0
  3. secondkey-0.2.0/README.md +186 -0
  4. secondkey-0.2.0/pyproject.toml +39 -0
  5. secondkey-0.2.0/setup.cfg +4 -0
  6. secondkey-0.2.0/src/secondkey/__init__.py +3 -0
  7. secondkey-0.2.0/src/secondkey/__main__.py +3 -0
  8. secondkey-0.2.0/src/secondkey/audit.py +98 -0
  9. secondkey-0.2.0/src/secondkey/classify.py +616 -0
  10. secondkey-0.2.0/src/secondkey/cli.py +651 -0
  11. secondkey-0.2.0/src/secondkey/default_policy.yaml +85 -0
  12. secondkey-0.2.0/src/secondkey/gate.py +192 -0
  13. secondkey-0.2.0/src/secondkey/hooks/__init__.py +0 -0
  14. secondkey-0.2.0/src/secondkey/hooks/claude_code.py +67 -0
  15. secondkey-0.2.0/src/secondkey/hooks/cursor.py +77 -0
  16. secondkey-0.2.0/src/secondkey/notify.py +36 -0
  17. secondkey-0.2.0/src/secondkey/policy.py +165 -0
  18. secondkey-0.2.0/src/secondkey/proxy.py +244 -0
  19. secondkey-0.2.0/src/secondkey/snapshots/__init__.py +155 -0
  20. secondkey-0.2.0/src/secondkey/snapshots/aws.py +109 -0
  21. secondkey-0.2.0/src/secondkey/snapshots/base.py +48 -0
  22. secondkey-0.2.0/src/secondkey/snapshots/docker.py +70 -0
  23. secondkey-0.2.0/src/secondkey/snapshots/files.py +108 -0
  24. secondkey-0.2.0/src/secondkey/snapshots/git.py +216 -0
  25. secondkey-0.2.0/src/secondkey/snapshots/k8s.py +97 -0
  26. secondkey-0.2.0/src/secondkey/snapshots/mysql.py +104 -0
  27. secondkey-0.2.0/src/secondkey/snapshots/postgres.py +388 -0
  28. secondkey-0.2.0/src/secondkey/snapshots/terraform.py +74 -0
  29. secondkey-0.2.0/src/secondkey/sql.py +142 -0
  30. secondkey-0.2.0/src/secondkey/store.py +211 -0
  31. secondkey-0.2.0/src/secondkey/util.py +108 -0
  32. secondkey-0.2.0/src/secondkey.egg-info/PKG-INFO +208 -0
  33. secondkey-0.2.0/src/secondkey.egg-info/SOURCES.txt +42 -0
  34. secondkey-0.2.0/src/secondkey.egg-info/dependency_links.txt +1 -0
  35. secondkey-0.2.0/src/secondkey.egg-info/entry_points.txt +2 -0
  36. secondkey-0.2.0/src/secondkey.egg-info/requires.txt +5 -0
  37. secondkey-0.2.0/src/secondkey.egg-info/top_level.txt +1 -0
  38. secondkey-0.2.0/tests/test_classify.py +132 -0
  39. secondkey-0.2.0/tests/test_gate_flow.py +169 -0
  40. secondkey-0.2.0/tests/test_git_snapshots.py +73 -0
  41. secondkey-0.2.0/tests/test_k8s_terraform.py +83 -0
  42. secondkey-0.2.0/tests/test_policy_audit.py +77 -0
  43. secondkey-0.2.0/tests/test_postgres.py +235 -0
  44. secondkey-0.2.0/tests/test_v02_features.py +346 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,208 @@
1
+ Metadata-Version: 2.4
2
+ Name: secondkey
3
+ Version: 0.2.0
4
+ Summary: The second key for every AI agent action: approve, snapshot and undo destructive commands.
5
+ Author: Abhishek
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Abhishek-dev18/SecondKey
8
+ Keywords: ai-agents,claude-code,mcp,safety,change-control,undo,devops
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Environment :: Console
12
+ Classifier: Topic :: Security
13
+ Classifier: Topic :: System :: Systems Administration
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: PyYAML>=6.0
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=7; extra == "dev"
20
+ Requires-Dist: pg8000>=1.30; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ <p align="center">
24
+ <img src="assets/logo-wordmark.svg" alt="SecondKey" width="260">
25
+ </p>
26
+
27
+ <p align="center"><b>Agents hold the first key. You hold the second.</b></p>
28
+
29
+ SecondKey is a change-control gate for AI agents. It sits between Claude Code (or any agent that runs shell commands) and your infrastructure:
30
+
31
+ - **Safe commands pass straight through.** Reads, tests and plans run with no delay.
32
+ - **Destructive commands stop at the gate.** `DROP TABLE`, `DELETE`, `rm -rf`, `git push --force`, `terraform destroy`, `kubectl delete` and more are held until a human approves.
33
+ - **A restore point is taken right before an approved command runs.** If the approval was a mistake, `secondkey undo` puts things back.
34
+ - **Secrets are never read.** `.env`, cloud credentials, SSH keys and `curl | sh` are denied by policy.
35
+ - **Everything is logged** in a hash-chained audit log, so tampering is detectable.
36
+
37
+ > Status: v0.2, early. Works with Claude Code and Cursor (hooks), any Postgres client via the proxy, and anything else via `secondkey exec`.
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pipx install git+https://github.com/Abhishek-dev18/SecondKey
43
+ cd your-project
44
+ secondkey init # writes .secondkey/policy.yaml and adds the Claude Code hook
45
+ secondkey doctor # checks hooks, tools and state
46
+ ```
47
+
48
+ `init --agent cursor` adds the Cursor hooks (repeat `--agent` for both). `init --scope user` installs for every project instead. Try it end to end with [docs/try-it-with-claude-code.md](docs/try-it-with-claude-code.md). Requires Python 3.9+. For Postgres snapshots, `psql`, `pg_dump` and `pg_restore` must be on your PATH (same major version as your server or newer).
49
+
50
+ ## What it looks like
51
+
52
+ The agent tries something destructive:
53
+
54
+ ```
55
+ psql $PROD_DB -c "DROP TABLE users CASCADE;"
56
+ ```
57
+
58
+ Claude Code is told:
59
+
60
+ ```
61
+ SecondKey held this command for human approval (request req_880c0e).
62
+ Why: sql.drop → ask. Impact: users: 5,000 rows.
63
+ A restore point will be taken right before it runs, so it can be undone.
64
+ Ask the user to review it and run `secondkey approve req_880c0e` ...
65
+ ```
66
+
67
+ You look and decide:
68
+
69
+ ```console
70
+ $ secondkey pending
71
+ req_880c0e pending 12s ago claude-code /home/riya/shop
72
+ psql $PROD_DB -c "DROP TABLE users CASCADE;"
73
+ why: sql.drop → ask
74
+ impact: users: 5,000 rows
75
+
76
+ $ secondkey approve req_880c0e
77
+ approved req_880c0e by riya. The agent can now retry the exact same command (valid 15 min).
78
+ ```
79
+
80
+ The agent retries, SecondKey dumps `users` (plus the foreign keys on other tables that `CASCADE` will remove), and the command runs. If that was a mistake:
81
+
82
+ ```console
83
+ $ secondkey undo req_880c0e
84
+ snap_453a77 postgres users (5,000 rows)
85
+ will: users: recreate the table with 5,000 rows, indexes and constraints
86
+ will: re-add foreign key orders_user_id_fkey on orders if it's missing
87
+ will: re-add foreign key carts_user_id_fkey on carts if it's missing
88
+ Restore? [y/N] y
89
+ ✓ tables recreated from the snapshot: users
90
+ ✓ foreign key orders_user_id_fkey on orders re-added
91
+ ✓ foreign key carts_user_id_fkey on carts re-added
92
+ ✓ verified users: 5,000 rows
93
+ ```
94
+
95
+ ## Commands
96
+
97
+ | Command | What it does |
98
+ |---|---|
99
+ | `secondkey init` | Write a policy and install the Claude Code `PreToolUse` hook (merges with your existing settings) |
100
+ | `secondkey check "<cmd>"` | Show how a command is classified and what the policy decides, with its impact. Runs nothing |
101
+ | `secondkey pending` | List held commands (`--all` for history) |
102
+ | `secondkey approve <req>` | Turn the second key. Valid once, for the exact same command, for 15 minutes |
103
+ | `secondkey deny <req>` | Reject. The agent is told not to retry |
104
+ | `secondkey snapshots` | List restore points |
105
+ | `secondkey undo <snap or req>` | Restore. Shows what it will do and asks first (`--yes`, `--dry-run`, `--mode`) |
106
+ | `secondkey log` | Audit log. `--verify` checks the hash chain |
107
+ | `secondkey policy` | Show the effective policy |
108
+ | `secondkey exec -- <cmd>` | Run a command through the gate, for agents without hook support. Waits up to 5 min for approval |
109
+ | `secondkey proxy --upstream host:5432` | Postgres proxy: gates every query from scripts, ORMs and migrations, not just shell commands |
110
+ | `secondkey prune` | Delete old restore points (also runs automatically once a day; the newest is always kept) |
111
+ | `secondkey doctor` | Check hooks, tools, policy, audit chain and snapshot storage |
112
+
113
+ ## How it works
114
+
115
+ ```
116
+ agent proposes a command
117
+ → classify shell/SQL/tool call → actions like sql.drop, git.force_push, secrets.read
118
+ → policy first matching rule: allow / ask / deny (a && b gets the strictest)
119
+ → deny blocked, agent told not to work around it
120
+ → allow runs (some rules, like single-file rm, take a quiet snapshot first)
121
+ → ask held as a request; Slack ping if configured
122
+ human approves → agent retries → snapshot → runs
123
+ → audit every decision appended to a hash-chained log
124
+ ```
125
+
126
+ SecondKey never widens what Claude Code allows on its own: for allowed commands it returns no decision, so Claude Code's normal permission rules still apply. If SecondKey itself errors, the hook answers `ask` (Claude Code) or `deny` (Cursor) rather than crashing, because a crashing hook would let the command run.
127
+
128
+ **The agent can't hold the second key.** A built-in guard, which no policy can turn off, denies an agent that tries to run `secondkey approve`/`deny`/`undo`/`prune`, touch `~/.secondkey/`, or change `.secondkey/policy.yaml`, `.claude/settings*.json` or `.cursor/hooks.json`. Commands are stored and logged with passwords and tokens masked, and the state directory is private to your user.
129
+
130
+ ### What can be undone
131
+
132
+ | Target | Snapshot | Undo |
133
+ |---|---|---|
134
+ | **Postgres** `DROP`, `TRUNCATE`, `DELETE`, `UPDATE`, `ALTER` via `psql` | `pg_dump` of the affected tables, row counts, foreign keys on other tables that point at them | Dropped tables are recreated with indexes, constraints and sequences, and foreign keys are re-added. For tables that still exist, saved rows are put back by primary key and rows written since are kept (`--mode exact` removes them). Verified inside the transaction; if anything fails, nothing changes |
135
+ | **Files** `rm`, `rm -rf` | tar.gz of the paths | Put back; refuses to overwrite paths that exist again unless `--force` |
136
+ | **Git** force push, delete remote branch, `reset --hard`, `checkout -- .`, `clean`, `branch -D`, stash drop | Commits pinned under `refs/secondkey/…`, uncommitted changes saved with `git stash create`, untracked files archived | Force-push the old commit back, reset and re-apply changes, recreate branches, restore files. Your current changes are saved first |
137
+ | **Migrations** `prisma migrate reset`, `alembic downgrade`, `rails db:drop`, `manage.py flush` and more | Whole-database `pg_dump` when a Postgres `DATABASE_URL` is set | The whole database restored in one transaction |
138
+ | **Neon** (any of the above, `postgres_strategy: neon`) | Just the timestamp: no copy, works for any size | `neon branches restore <branch> ^self@<time>`; the current state is kept as a branch |
139
+ | **MySQL / MariaDB** `mysql -e "DROP/DELETE/…"` | `mysqldump` of the affected tables | Replayed, row counts verified |
140
+ | **AWS** `ec2 delete-volume`, `rds delete-db-instance`, `s3 rm/rb` | EBS snapshot, RDS manual snapshot, or S3 objects downloaded | New volume from the snapshot, instance restored, objects uploaded back |
141
+ | **Docker** `volume rm`, `volume prune`, `system prune --volumes` | Volume contents tarred through a throwaway container | Volume recreated and unpacked |
142
+ | **Kubernetes** `kubectl delete` | `kubectl get -o yaml`, cleaned of server fields | `kubectl apply`. Data in deleted volumes is not restored |
143
+ | **Terraform** `destroy`, `apply`, `state rm/mv` | `terraform state pull` and the config's git commit | State surgery: state pushed back. Destroy: explains how to recreate from the saved config. Cloud resources can't be un-destroyed, and SecondKey won't pretend otherwise |
144
+
145
+ **Cannot be undone, so they're denied or held without a snapshot:** emails, payments and webhooks; `DROP DATABASE`; cloud deletes (`aws … delete`, `terminate-instances`); `docker system prune`; anything that reads secrets.
146
+
147
+ Blast radius is shown before you approve: row counts per table, and for `DELETE`/`UPDATE … WHERE` how many rows match (estimated in a read-only transaction).
148
+
149
+ ## Policy
150
+
151
+ `secondkey init` writes `.secondkey/policy.yaml`. Rules are checked top to bottom and the first match wins:
152
+
153
+ ```yaml
154
+ rules:
155
+ - match: ["secrets.*", "shell.pipe_to_shell", "sql.drop_database"]
156
+ action: deny
157
+ - match: ["sql.drop", "sql.delete", "sql.truncate", "git.force_push", "tf.destroy", "k8s.delete"]
158
+ action: ask # snapshot: true is the default for ask
159
+ - match: ["fs.delete"] # rm of single files
160
+ action: allow
161
+ snapshot: true # run, but keep a restore point
162
+ default: allow
163
+
164
+ approval:
165
+ via: secondkey # or "agent": snapshot, then let Claude Code's own prompt ask you
166
+ wait_seconds: 0 # how long the hook waits for an approval before replying "held"
167
+ ttl_minutes: 15
168
+ require_snapshot: true
169
+
170
+ notify:
171
+ slack_webhook: "${SECONDKEY_SLACK_WEBHOOK}"
172
+ ```
173
+
174
+ Run `secondkey check "<command>"` to see the category of any command. Policy lookup order: `$SECONDKEY_POLICY`, `.secondkey/policy.yaml` in the project (searching upward to the git root), `~/.secondkey/policy.yaml`, then the built-in default.
175
+
176
+ State (approvals, snapshots, audit log) lives in `~/.secondkey/` (override with `SECONDKEY_HOME`).
177
+
178
+ ## Known limits (v0.2)
179
+
180
+ - Hooks see the commands an agent runs. For Postgres, run `secondkey proxy` so scripts and ORMs are gated too. Other databases and APIs called from agent-written code aren't covered, so give agents scoped credentials.
181
+ - An agent could still write a script that edits SecondKey's files directly; the guard covers tool calls and shell commands, not arbitrary code. Running agents as a separate OS user closes this.
182
+ - MCP tools are gated by name; their effects can't be snapshotted automatically.
183
+ - Approvals happen in the CLI, or Slack (notification only for now; buttons come with the hosted version).
184
+ - Snapshots are local. Dumps over `postgres_max_dump_mb` (2 GB) and file snapshots over 500 MB are refused and reported as unprotected; use the Neon strategy for big Postgres databases.
185
+ - Tested on Linux. macOS should work; Windows is untested.
186
+
187
+ More recipes: [docs/policy-cookbook.md](docs/policy-cookbook.md).
188
+
189
+ ## Development
190
+
191
+ ```bash
192
+ pip install -e ".[dev]"
193
+ pytest -q # unit + git + files + stubbed k8s/terraform/aws/docker/mysql
194
+ SECONDKEY_TEST_PG='postgresql://postgres:postgres@localhost:5432/postgres' pytest -q # + real Postgres and the proxy
195
+ ```
196
+
197
+ Releases: push a tag like `v0.2.0` and `.github/workflows/release.yml` publishes to PyPI (needs a one-time trusted-publisher setup on pypi.org, described in the workflow file). Licensed under Apache-2.0.
198
+
199
+ ## This repo
200
+
201
+ | Path | What it is |
202
+ |---|---|
203
+ | `src/secondkey/` | The CLI (`classify.py`, `policy.py`, `gate.py`, `snapshots/`, `hooks/`, `proxy.py`) |
204
+ | `docs/` | Policy cookbook and a 5-minute Claude Code walkthrough |
205
+ | `tests/` | Test suite |
206
+ | `index.html`, `assets/` | Landing page (live demo of the gate) and logo files |
207
+
208
+ The landing page is a single static file. Enable GitHub Pages for the `main` branch to publish it.
@@ -0,0 +1,186 @@
1
+ <p align="center">
2
+ <img src="assets/logo-wordmark.svg" alt="SecondKey" width="260">
3
+ </p>
4
+
5
+ <p align="center"><b>Agents hold the first key. You hold the second.</b></p>
6
+
7
+ SecondKey is a change-control gate for AI agents. It sits between Claude Code (or any agent that runs shell commands) and your infrastructure:
8
+
9
+ - **Safe commands pass straight through.** Reads, tests and plans run with no delay.
10
+ - **Destructive commands stop at the gate.** `DROP TABLE`, `DELETE`, `rm -rf`, `git push --force`, `terraform destroy`, `kubectl delete` and more are held until a human approves.
11
+ - **A restore point is taken right before an approved command runs.** If the approval was a mistake, `secondkey undo` puts things back.
12
+ - **Secrets are never read.** `.env`, cloud credentials, SSH keys and `curl | sh` are denied by policy.
13
+ - **Everything is logged** in a hash-chained audit log, so tampering is detectable.
14
+
15
+ > Status: v0.2, early. Works with Claude Code and Cursor (hooks), any Postgres client via the proxy, and anything else via `secondkey exec`.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pipx install git+https://github.com/Abhishek-dev18/SecondKey
21
+ cd your-project
22
+ secondkey init # writes .secondkey/policy.yaml and adds the Claude Code hook
23
+ secondkey doctor # checks hooks, tools and state
24
+ ```
25
+
26
+ `init --agent cursor` adds the Cursor hooks (repeat `--agent` for both). `init --scope user` installs for every project instead. Try it end to end with [docs/try-it-with-claude-code.md](docs/try-it-with-claude-code.md). Requires Python 3.9+. For Postgres snapshots, `psql`, `pg_dump` and `pg_restore` must be on your PATH (same major version as your server or newer).
27
+
28
+ ## What it looks like
29
+
30
+ The agent tries something destructive:
31
+
32
+ ```
33
+ psql $PROD_DB -c "DROP TABLE users CASCADE;"
34
+ ```
35
+
36
+ Claude Code is told:
37
+
38
+ ```
39
+ SecondKey held this command for human approval (request req_880c0e).
40
+ Why: sql.drop → ask. Impact: users: 5,000 rows.
41
+ A restore point will be taken right before it runs, so it can be undone.
42
+ Ask the user to review it and run `secondkey approve req_880c0e` ...
43
+ ```
44
+
45
+ You look and decide:
46
+
47
+ ```console
48
+ $ secondkey pending
49
+ req_880c0e pending 12s ago claude-code /home/riya/shop
50
+ psql $PROD_DB -c "DROP TABLE users CASCADE;"
51
+ why: sql.drop → ask
52
+ impact: users: 5,000 rows
53
+
54
+ $ secondkey approve req_880c0e
55
+ approved req_880c0e by riya. The agent can now retry the exact same command (valid 15 min).
56
+ ```
57
+
58
+ The agent retries, SecondKey dumps `users` (plus the foreign keys on other tables that `CASCADE` will remove), and the command runs. If that was a mistake:
59
+
60
+ ```console
61
+ $ secondkey undo req_880c0e
62
+ snap_453a77 postgres users (5,000 rows)
63
+ will: users: recreate the table with 5,000 rows, indexes and constraints
64
+ will: re-add foreign key orders_user_id_fkey on orders if it's missing
65
+ will: re-add foreign key carts_user_id_fkey on carts if it's missing
66
+ Restore? [y/N] y
67
+ ✓ tables recreated from the snapshot: users
68
+ ✓ foreign key orders_user_id_fkey on orders re-added
69
+ ✓ foreign key carts_user_id_fkey on carts re-added
70
+ ✓ verified users: 5,000 rows
71
+ ```
72
+
73
+ ## Commands
74
+
75
+ | Command | What it does |
76
+ |---|---|
77
+ | `secondkey init` | Write a policy and install the Claude Code `PreToolUse` hook (merges with your existing settings) |
78
+ | `secondkey check "<cmd>"` | Show how a command is classified and what the policy decides, with its impact. Runs nothing |
79
+ | `secondkey pending` | List held commands (`--all` for history) |
80
+ | `secondkey approve <req>` | Turn the second key. Valid once, for the exact same command, for 15 minutes |
81
+ | `secondkey deny <req>` | Reject. The agent is told not to retry |
82
+ | `secondkey snapshots` | List restore points |
83
+ | `secondkey undo <snap or req>` | Restore. Shows what it will do and asks first (`--yes`, `--dry-run`, `--mode`) |
84
+ | `secondkey log` | Audit log. `--verify` checks the hash chain |
85
+ | `secondkey policy` | Show the effective policy |
86
+ | `secondkey exec -- <cmd>` | Run a command through the gate, for agents without hook support. Waits up to 5 min for approval |
87
+ | `secondkey proxy --upstream host:5432` | Postgres proxy: gates every query from scripts, ORMs and migrations, not just shell commands |
88
+ | `secondkey prune` | Delete old restore points (also runs automatically once a day; the newest is always kept) |
89
+ | `secondkey doctor` | Check hooks, tools, policy, audit chain and snapshot storage |
90
+
91
+ ## How it works
92
+
93
+ ```
94
+ agent proposes a command
95
+ → classify shell/SQL/tool call → actions like sql.drop, git.force_push, secrets.read
96
+ → policy first matching rule: allow / ask / deny (a && b gets the strictest)
97
+ → deny blocked, agent told not to work around it
98
+ → allow runs (some rules, like single-file rm, take a quiet snapshot first)
99
+ → ask held as a request; Slack ping if configured
100
+ human approves → agent retries → snapshot → runs
101
+ → audit every decision appended to a hash-chained log
102
+ ```
103
+
104
+ SecondKey never widens what Claude Code allows on its own: for allowed commands it returns no decision, so Claude Code's normal permission rules still apply. If SecondKey itself errors, the hook answers `ask` (Claude Code) or `deny` (Cursor) rather than crashing, because a crashing hook would let the command run.
105
+
106
+ **The agent can't hold the second key.** A built-in guard, which no policy can turn off, denies an agent that tries to run `secondkey approve`/`deny`/`undo`/`prune`, touch `~/.secondkey/`, or change `.secondkey/policy.yaml`, `.claude/settings*.json` or `.cursor/hooks.json`. Commands are stored and logged with passwords and tokens masked, and the state directory is private to your user.
107
+
108
+ ### What can be undone
109
+
110
+ | Target | Snapshot | Undo |
111
+ |---|---|---|
112
+ | **Postgres** `DROP`, `TRUNCATE`, `DELETE`, `UPDATE`, `ALTER` via `psql` | `pg_dump` of the affected tables, row counts, foreign keys on other tables that point at them | Dropped tables are recreated with indexes, constraints and sequences, and foreign keys are re-added. For tables that still exist, saved rows are put back by primary key and rows written since are kept (`--mode exact` removes them). Verified inside the transaction; if anything fails, nothing changes |
113
+ | **Files** `rm`, `rm -rf` | tar.gz of the paths | Put back; refuses to overwrite paths that exist again unless `--force` |
114
+ | **Git** force push, delete remote branch, `reset --hard`, `checkout -- .`, `clean`, `branch -D`, stash drop | Commits pinned under `refs/secondkey/…`, uncommitted changes saved with `git stash create`, untracked files archived | Force-push the old commit back, reset and re-apply changes, recreate branches, restore files. Your current changes are saved first |
115
+ | **Migrations** `prisma migrate reset`, `alembic downgrade`, `rails db:drop`, `manage.py flush` and more | Whole-database `pg_dump` when a Postgres `DATABASE_URL` is set | The whole database restored in one transaction |
116
+ | **Neon** (any of the above, `postgres_strategy: neon`) | Just the timestamp: no copy, works for any size | `neon branches restore <branch> ^self@<time>`; the current state is kept as a branch |
117
+ | **MySQL / MariaDB** `mysql -e "DROP/DELETE/…"` | `mysqldump` of the affected tables | Replayed, row counts verified |
118
+ | **AWS** `ec2 delete-volume`, `rds delete-db-instance`, `s3 rm/rb` | EBS snapshot, RDS manual snapshot, or S3 objects downloaded | New volume from the snapshot, instance restored, objects uploaded back |
119
+ | **Docker** `volume rm`, `volume prune`, `system prune --volumes` | Volume contents tarred through a throwaway container | Volume recreated and unpacked |
120
+ | **Kubernetes** `kubectl delete` | `kubectl get -o yaml`, cleaned of server fields | `kubectl apply`. Data in deleted volumes is not restored |
121
+ | **Terraform** `destroy`, `apply`, `state rm/mv` | `terraform state pull` and the config's git commit | State surgery: state pushed back. Destroy: explains how to recreate from the saved config. Cloud resources can't be un-destroyed, and SecondKey won't pretend otherwise |
122
+
123
+ **Cannot be undone, so they're denied or held without a snapshot:** emails, payments and webhooks; `DROP DATABASE`; cloud deletes (`aws … delete`, `terminate-instances`); `docker system prune`; anything that reads secrets.
124
+
125
+ Blast radius is shown before you approve: row counts per table, and for `DELETE`/`UPDATE … WHERE` how many rows match (estimated in a read-only transaction).
126
+
127
+ ## Policy
128
+
129
+ `secondkey init` writes `.secondkey/policy.yaml`. Rules are checked top to bottom and the first match wins:
130
+
131
+ ```yaml
132
+ rules:
133
+ - match: ["secrets.*", "shell.pipe_to_shell", "sql.drop_database"]
134
+ action: deny
135
+ - match: ["sql.drop", "sql.delete", "sql.truncate", "git.force_push", "tf.destroy", "k8s.delete"]
136
+ action: ask # snapshot: true is the default for ask
137
+ - match: ["fs.delete"] # rm of single files
138
+ action: allow
139
+ snapshot: true # run, but keep a restore point
140
+ default: allow
141
+
142
+ approval:
143
+ via: secondkey # or "agent": snapshot, then let Claude Code's own prompt ask you
144
+ wait_seconds: 0 # how long the hook waits for an approval before replying "held"
145
+ ttl_minutes: 15
146
+ require_snapshot: true
147
+
148
+ notify:
149
+ slack_webhook: "${SECONDKEY_SLACK_WEBHOOK}"
150
+ ```
151
+
152
+ Run `secondkey check "<command>"` to see the category of any command. Policy lookup order: `$SECONDKEY_POLICY`, `.secondkey/policy.yaml` in the project (searching upward to the git root), `~/.secondkey/policy.yaml`, then the built-in default.
153
+
154
+ State (approvals, snapshots, audit log) lives in `~/.secondkey/` (override with `SECONDKEY_HOME`).
155
+
156
+ ## Known limits (v0.2)
157
+
158
+ - Hooks see the commands an agent runs. For Postgres, run `secondkey proxy` so scripts and ORMs are gated too. Other databases and APIs called from agent-written code aren't covered, so give agents scoped credentials.
159
+ - An agent could still write a script that edits SecondKey's files directly; the guard covers tool calls and shell commands, not arbitrary code. Running agents as a separate OS user closes this.
160
+ - MCP tools are gated by name; their effects can't be snapshotted automatically.
161
+ - Approvals happen in the CLI, or Slack (notification only for now; buttons come with the hosted version).
162
+ - Snapshots are local. Dumps over `postgres_max_dump_mb` (2 GB) and file snapshots over 500 MB are refused and reported as unprotected; use the Neon strategy for big Postgres databases.
163
+ - Tested on Linux. macOS should work; Windows is untested.
164
+
165
+ More recipes: [docs/policy-cookbook.md](docs/policy-cookbook.md).
166
+
167
+ ## Development
168
+
169
+ ```bash
170
+ pip install -e ".[dev]"
171
+ pytest -q # unit + git + files + stubbed k8s/terraform/aws/docker/mysql
172
+ SECONDKEY_TEST_PG='postgresql://postgres:postgres@localhost:5432/postgres' pytest -q # + real Postgres and the proxy
173
+ ```
174
+
175
+ Releases: push a tag like `v0.2.0` and `.github/workflows/release.yml` publishes to PyPI (needs a one-time trusted-publisher setup on pypi.org, described in the workflow file). Licensed under Apache-2.0.
176
+
177
+ ## This repo
178
+
179
+ | Path | What it is |
180
+ |---|---|
181
+ | `src/secondkey/` | The CLI (`classify.py`, `policy.py`, `gate.py`, `snapshots/`, `hooks/`, `proxy.py`) |
182
+ | `docs/` | Policy cookbook and a 5-minute Claude Code walkthrough |
183
+ | `tests/` | Test suite |
184
+ | `index.html`, `assets/` | Landing page (live demo of the gate) and logo files |
185
+
186
+ The landing page is a single static file. Enable GitHub Pages for the `main` branch to publish it.
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "secondkey"
7
+ version = "0.2.0"
8
+ description = "The second key for every AI agent action: approve, snapshot and undo destructive commands."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "Abhishek" }]
13
+ dependencies = ["PyYAML>=6.0"]
14
+ keywords = ["ai-agents", "claude-code", "mcp", "safety", "change-control", "undo", "devops"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Environment :: Console",
19
+ "Topic :: Security",
20
+ "Topic :: System :: Systems Administration",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ dev = ["pytest>=7", "pg8000>=1.30"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/Abhishek-dev18/SecondKey"
28
+
29
+ [project.scripts]
30
+ secondkey = "secondkey.cli:main"
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+
35
+ [tool.setuptools.package-data]
36
+ secondkey = ["default_policy.yaml"]
37
+
38
+ [tool.pytest.ini_options]
39
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """SecondKey: the second key for every AI agent action."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())