agent-spend-gate 0.7.2__py3-none-any.whl

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.
@@ -0,0 +1,195 @@
1
+ Metadata-Version: 2.5
2
+ Name: agent-spend-gate
3
+ Version: 0.7.2
4
+ Summary: A human-in-the-loop spending gate for AI agents on macOS - no Touch ID or password approval, no paid API call.
5
+ Project-URL: Homepage, https://github.com/yuyauchuncn-dot/agent-spend-gate
6
+ Project-URL: Issues, https://github.com/yuyauchuncn-dot/agent-spend-gate/issues
7
+ Author: Derek Yu
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: ai-agents,human-in-the-loop,macos,safety,spending,touch-id
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: MacOS X
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Security
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: pyobjc-framework-localauthentication>=13; sys_platform == 'darwin'
22
+ Provides-Extra: dev
23
+ Requires-Dist: build; extra == 'dev'
24
+ Requires-Dist: pytest>=8; extra == 'dev'
25
+ Requires-Dist: twine; extra == 'dev'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # agent-spend-gate
29
+
30
+ **Your AI agent is about to spend money. This makes it ask you first.**
31
+
32
+ > **Adopting this in an existing repo?** [`skill/`](skill/) scans for paid API calls, asks once which vendors should stay behind a prompt, and wraps the call sites. One fingerprint for the whole policy. [Read the case study](docs/CASE-STUDY.md) — 215 apparent call sites turned out to be 3 real ones.
33
+
34
+ One line before the paid call. A dialog says who gets paid and how much. Then macOS asks for your fingerprint or password. If either step fails, the call never happens.
35
+
36
+ ```
37
+ ┌─ Spending approval ─────────────────────┐
38
+ │ openai/gpt-4o requests 2.00 CNY for: │
39
+ │ summarise 10 documents │
40
+ │ Quantity: 10 calls │
41
+ │ │
42
+ │ [ Cancel ] [ Approve ] │
43
+ └─────────────────────────────────────────┘
44
+ ↓ you click Approve
45
+ ┌─ macOS ─────────────────────────────────┐
46
+ │ 🔒 Touch ID │
47
+ │ Approve spending 2.00 CNY to openai │
48
+ └─────────────────────────────────────────┘
49
+ ↓ fingerprint accepted
50
+ the API call runs
51
+ ```
52
+
53
+ ## Install
54
+
55
+ ```bash
56
+ pip install agent-spend-gate
57
+ ```
58
+
59
+ macOS only, Python 3.11+. On any other platform the gate **refuses** — it does not silently skip the check.
60
+
61
+ ## The one thing you have to do
62
+
63
+ Put `require_approval` in front of every billable call.
64
+
65
+ ```python
66
+ from spend_gate import require_approval
67
+
68
+ require_approval(amount=2.0, currency="CNY",
69
+ vendor="openai/gpt-4o",
70
+ purpose="summarise 10 documents",
71
+ quantity="10 calls")
72
+
73
+ # Only reached after a human approved. Now spend.
74
+ client.chat.completions.create(...)
75
+ ```
76
+
77
+ If you do not wrap a call, that call is not protected. The gate is opt-in per call site — there is no interception layer, and nothing fails loudly when you miss one. **That is the single most important thing to understand about this library.**
78
+
79
+ ## Three ways to spend, pick one
80
+
81
+ | Situation | Use | Prompts |
82
+ |---|---|---|
83
+ | You know the price | `require_approval(amount=...)` | one per call |
84
+ | A job whose total you don't know | `open_envelope(max_amount=...)` | one per job, then charges run inside it |
85
+ | Many calls, small amounts | auto-approve policy | none, until a ceiling is hit |
86
+
87
+ ### Envelope: when the total isn't known upfront
88
+
89
+ ```python
90
+ from spend_gate import open_envelope
91
+
92
+ with open_envelope(max_amount=10.0, vendor="openai",
93
+ purpose="nightly summarisation", ttl_hours=24) as env:
94
+ for doc in docs:
95
+ rid = env.reserve(0.50) # hold capacity first
96
+ cost = call_api(doc) # actual cost, known only afterwards
97
+ env.settle(rid, cost) # charge what it really cost
98
+ ```
99
+
100
+ One approval for "up to 10 CNY". Charges inside it do not prompt. It stops accepting charges when the cap or the 24 hours runs out. If you already know the price, `env.spend(0.05)` is the shortcut.
101
+
102
+ ### Ceilings: what a day, week or month may cost
103
+
104
+ ```bash
105
+ spend-gate policy set --daily-limit 20 --weekly-limit 80 --monthly-limit 200
106
+ ```
107
+
108
+ These apply to **all** spending, regardless of envelopes. Opening ten envelopes does not get around them.
109
+
110
+ When a charge would cross one, the dialog changes and tells you by how much:
111
+
112
+ ```
113
+ Budget limit reached
114
+ openai/gpt-4o requests 5.00 CNY for: batch job
115
+
116
+ This would exceed your daily limit:
117
+ daily: 18.00 + 5.00 = 23.00 > 20.00
118
+
119
+ [ Cancel ] [ Just this once ] [ Allow for this day ]
120
+ ```
121
+
122
+ "Allow for this day" writes a waiver until the period ends, so a long job keeps running instead of prompting at every file.
123
+
124
+ ### Per-vendor limits and whitelist
125
+
126
+ ```bash
127
+ spend-gate policy set --vendor dashscope --vendor-daily-limit 5 --vendor-trusted
128
+ ```
129
+
130
+ `--vendor` is a prefix; longest match wins, so `dashscope/wanx2.1-t2i` is covered by `dashscope`.
131
+
132
+ **Trusted** means: skip the dialog for this vendor *while it stays inside its own and the global ceilings*. It removes the interruption, not the limit. Exceed any ceiling and you are asked again.
133
+
134
+ ## What it does and does not protect
135
+
136
+ **Protects:** an agent or script running as you deciding to spend on its own. Both gates need a human action, and every attempt is recorded.
137
+
138
+ **Does not protect:** anyone who can edit this library (including an agent that can edit its own code), set `SPEND_GATE_BYPASS=1`, or obtain root. A call site you forgot to wrap is unprotected too.
139
+
140
+ This is a seatbelt, not a safe. Read [SECURITY.md](SECURITY.md) before trusting it with real money.
141
+
142
+ ## Every attempt is recorded
143
+
144
+ Two files under `~/.spend-gate/`:
145
+
146
+ - `audit.jsonl` — each approval decision: amount, vendor, purpose, method, result
147
+ - `ledger.jsonl` — each money movement, hash-chained. `spend-gate verify` detects edited or deleted rows and checks the head against a Keychain checkpoint.
148
+
149
+ ```bash
150
+ spend-gate verify # ledger chain + envelope reconciliation
151
+ spend-gate audit # recent decisions
152
+ ```
153
+
154
+ ## Commands
155
+
156
+ ```bash
157
+ spend-gate doctor # can this machine enforce approval?
158
+ spend-gate approve --amount 0.01 --vendor demo --purpose "smoke test"
159
+ spend-gate verify
160
+ spend-gate audit --tail 20
161
+ spend-gate policy show
162
+ spend-gate policy set --auto-under 0.05 --daily-limit 20
163
+ spend-gate policy set --vendor openai --vendor-daily-limit 20 --vendor-trusted
164
+ spend-gate policy load policy.json # batch, one fingerprint for all
165
+ ```
166
+
167
+ ## Environment variables
168
+
169
+ | Variable | Purpose |
170
+ |---|---|
171
+ | `SPEND_GATE_HOME` | Override `~/.spend-gate` |
172
+ | `SPEND_GATE_LEDGER_PATH` | Override the ledger path |
173
+ | `SPEND_GATE_AUDIT_PATH` | Override the audit path |
174
+ | `SPEND_GATE_NO_KEYCHAIN=1` | Run without a Keychain; anchor checks report as skipped |
175
+ | `SPEND_GATE_BYPASS=1` | **Skips both gates.** Tests only. Every use is logged as `bypassed`. |
176
+
177
+ ## Languages
178
+
179
+ Dialog, limit warning and Touch ID prompt follow the macOS UI language: English, Simplified Chinese, Traditional Chinese, Japanese, Korean, German, French, Spanish. Cantonese maps to Traditional Chinese; anything else falls back to English. Adding a language is a copy of `en.json` — a test fails if keys are missing.
180
+
181
+ ## Wrapping an existing codebase
182
+
183
+ The skill lives in [`skill/`](skill/) and ships with this repository — no separate install.
184
+
185
+ ```bash
186
+ python3 skill/scan_paid_calls.py /path/to/repo # what actually costs money
187
+ ```
188
+
189
+ Then point your agent at [`skill/SKILL.md`](skill/SKILL.md). It asks four questions, writes the policy, applies it in one authenticated call, and wraps the call sites. It also requires the agent to list what it did **not** wrap and why.
190
+
191
+ Why it is bundled rather than a separate repository: the skill depends on this CLI's flags, so the two must version together, and the files are small enough that a second repo would only add a way for them to drift.
192
+
193
+ ## License
194
+
195
+ Apache-2.0.
@@ -0,0 +1,23 @@
1
+ spend_gate/__init__.py,sha256=PAiEyvS6iNSvMji9c5MyISpmzs010QNg66gqx4s00uA,693
2
+ spend_gate/audit.py,sha256=Ze7CsZT4imGZ2s5EnSdPuKLen3s819HiwqrxnXNnvlI,1244
3
+ spend_gate/auth.py,sha256=I8E1zIu7JnT3Ytdo1dJeVm-pb98c5n1LanE9pAW8M0c,3954
4
+ spend_gate/budget.py,sha256=oVO2uhmq6_hGwEK4m3V4aL_YCMy_ZoJaAOTI6OMaLE8,13332
5
+ spend_gate/cli.py,sha256=OuDS4DaIbksFSb0LCczextXVrIwuYoG2lsifS6RMQQM,8319
6
+ spend_gate/gate.py,sha256=IIuyjt8j2-oJvN5Ab5cvnqHKHI-auG98nK4b5oDtREI,9857
7
+ spend_gate/i18n.py,sha256=2A-rIx2VDN3X0MK3KXaqMdbyfNbYDL0XK6Exhm30qlg,3133
8
+ spend_gate/keychain.py,sha256=Z5c7OpGVFI4d67QYHYv2r455hKBVn9EQZAIlmMKrpA0,2762
9
+ spend_gate/ledger.py,sha256=b29YmdiXh_bLFncuDXOp62zrSz-1CHElgAA8AoJUljE,3924
10
+ spend_gate/policy.py,sha256=LjMLYUiKnlQaUonkJpp4jYnMlnG9nEX95tIKwcKu7jc,9234
11
+ spend_gate/locales/de.json,sha256=MIEjPHDk63heef6UntfJYTtbYHb2OIHAEPyWjC47_7k,1693
12
+ spend_gate/locales/en.json,sha256=hWK3MuhsLOw2RxjYteifatLrpe5X7Akh2Z2qHtrngB0,1548
13
+ spend_gate/locales/es.json,sha256=-SmU-ToJo-KxnvyxGiF2z1zQaPkXSHVeKE-OXype0QQ,1650
14
+ spend_gate/locales/fr.json,sha256=GjZmSQ8CACRsMxNGpZlLXOsFIhXY1ld4r20qDyNbTfs,1715
15
+ spend_gate/locales/ja.json,sha256=hk2HQq2epGRa0Om73mSFARFp5FwzjtndDlFGs4oahvg,1865
16
+ spend_gate/locales/ko.json,sha256=bRlMd5eh6hwMxXjsGk9scHZQsKbyZBoq8W_NalnBruk,1751
17
+ spend_gate/locales/zh-Hans.json,sha256=24oLzxOMJxHDg59wyifNSSTCQPIlV2mYCaazWDCzWH0,1532
18
+ spend_gate/locales/zh-Hant.json,sha256=KdwBjnjXVomi6_HrA9VTK0r48tb5mm0_c3WlGLDJl80,1532
19
+ agent_spend_gate-0.7.2.dist-info/METADATA,sha256=mO9KBID4to-cHBges2Oryd9bRbVm4jqJwTP-W5Lhzxs,8340
20
+ agent_spend_gate-0.7.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
21
+ agent_spend_gate-0.7.2.dist-info/entry_points.txt,sha256=ml0HwSK0zG1MfuA5IZuysN2aAaVb7du50mFL5llHv_o,51
22
+ agent_spend_gate-0.7.2.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
23
+ agent_spend_gate-0.7.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ spend-gate = spend_gate.cli:main
@@ -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.
spend_gate/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ # -*- coding: utf-8 -*-
2
+ """agent-spend-gate —— macOS 上给 AI agent 花钱加一道人肉闸门。
3
+
4
+ from spend_gate import require_approval
5
+
6
+ require_approval(amount=2.0, currency="CNY",
7
+ vendor="openai/gpt-4o", purpose="summarise 10 files")
8
+
9
+ 没有 Touch ID 或密码,这行代码不会返回。
10
+ """
11
+ from .gate import Approval, SpendNotApproved, require_approval
12
+ from .budget import BudgetExceeded, Envelope, open_envelope, verify_ledger
13
+ from . import auth, budget, i18n
14
+
15
+ __all__ = ["require_approval", "Approval", "SpendNotApproved", "BudgetExceeded",
16
+ "Envelope", "open_envelope", "verify_ledger", "auth", "budget", "i18n"]
17
+ __version__ = "0.7.2"
spend_gate/audit.py ADDED
@@ -0,0 +1,38 @@
1
+ # -*- coding: utf-8 -*-
2
+ """审计日志:每次审批尝试都留一条,append-only。
3
+
4
+ 路径默认 ~/.spend-gate/audit.jsonl,可用 SPEND_GATE_AUDIT_PATH 覆盖。
5
+ 写不进去不能在「已批准」路径上静默——那会出现花了钱却没记录。
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import socket
12
+ from datetime import datetime, timezone
13
+
14
+ ENV_PATH = "SPEND_GATE_AUDIT_PATH"
15
+ DEFAULT = "~/.spend-gate/audit.jsonl"
16
+
17
+
18
+ class AuditWriteError(RuntimeError):
19
+ pass
20
+
21
+
22
+ def audit_path() -> str:
23
+ return os.path.expanduser(os.environ.get(ENV_PATH) or DEFAULT)
24
+
25
+
26
+ def record(entry: dict, strict: bool = True) -> None:
27
+ """追加一条。strict=True 时写失败抛异常(批准路径必须用)。"""
28
+ entry = dict(entry)
29
+ entry.setdefault("ts", datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds"))
30
+ entry.setdefault("host", socket.gethostname())
31
+ path = audit_path()
32
+ try:
33
+ os.makedirs(os.path.dirname(path), exist_ok=True)
34
+ with open(path, "a", encoding="utf-8") as f:
35
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
36
+ except Exception as e:
37
+ if strict:
38
+ raise AuditWriteError(f"cannot write audit log: {e}") from e
spend_gate/auth.py ADDED
@@ -0,0 +1,105 @@
1
+ # -*- coding: utf-8 -*-
2
+ """macOS 身份验证后端。
3
+
4
+ 两道闸的第二道:调 LocalAuthentication 让系统弹 Touch ID / 密码面板。
5
+ 用 PyObjC 直调,不编译任何东西,也就没有架构和 Gatekeeper 的问题。
6
+
7
+ 为什么不用 `osascript ... with administrator privileges`:
8
+ 那条路走的是 Authorization Services,认证面板只给密码框,不会弹指纹。
9
+ 改 /etc/pam.d/sudo 加 pam_tid 对这条路径无效——它不是 sudo。
10
+
11
+ 为什么用 LAPolicyDeviceOwnerAuthentication 而不是 WithBiometrics:
12
+ 前者在指纹失败/被锁定后自动回落到密码,一个 API 覆盖两种方式;
13
+ 后者只认生物识别,锁定后还要调用方自己处理回落。
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+ import threading
19
+ import time
20
+ from dataclasses import dataclass
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class AuthResult:
25
+ ok: bool
26
+ method: str # "biometric" | "password" | "unknown"
27
+ reason: str = "" # 失败原因码:cancelled / unavailable / timeout / error
28
+
29
+
30
+ def backend_available() -> tuple[bool, str]:
31
+ """检查当前环境能否弹系统认证。不触发 UI。"""
32
+ if sys.platform != "darwin":
33
+ return False, "not macOS"
34
+ try:
35
+ from LocalAuthentication import LAContext, LAPolicyDeviceOwnerAuthentication
36
+ except Exception as e: # pyobjc 没装
37
+ return False, f"pyobjc unavailable: {e}"
38
+ try:
39
+ ctx = LAContext.new()
40
+ ok, err = ctx.canEvaluatePolicy_error_(LAPolicyDeviceOwnerAuthentication, None)
41
+ if not ok:
42
+ return False, f"policy unavailable: {err}"
43
+ return True, "ok"
44
+ except Exception as e:
45
+ return False, f"probe failed: {e}"
46
+
47
+
48
+ def authenticate(reason: str, timeout: float = 300.0) -> AuthResult:
49
+ """弹出系统认证面板。阻塞直到用户操作、超时或出错。
50
+
51
+ 任何异常都按失败处理(fail-closed)。调用方拿到 ok=False 必须停止。
52
+ """
53
+ if sys.platform != "darwin":
54
+ return AuthResult(False, "unknown", "unavailable")
55
+ try:
56
+ from LocalAuthentication import LAContext, LAPolicyDeviceOwnerAuthentication
57
+ except Exception:
58
+ return AuthResult(False, "unknown", "unavailable")
59
+
60
+ ctx = LAContext.new()
61
+ try:
62
+ ok, err = ctx.canEvaluatePolicy_error_(LAPolicyDeviceOwnerAuthentication, None)
63
+ except Exception:
64
+ # PyObjC 在这里抛异常时,调用方只 catch SpendNotApproved 会意外崩溃。
65
+ return AuthResult(False, "unknown", "unavailable")
66
+ if not ok:
67
+ return AuthResult(False, "unknown", "unavailable")
68
+
69
+ done = threading.Event()
70
+ box: dict = {"ok": False, "err": None}
71
+
72
+ def reply(success, error):
73
+ box["ok"] = bool(success)
74
+ box["err"] = error
75
+ done.set()
76
+
77
+ t0 = time.monotonic()
78
+ try:
79
+ ctx.evaluatePolicy_localizedReason_reply_(
80
+ LAPolicyDeviceOwnerAuthentication, reason, reply)
81
+ except Exception:
82
+ return AuthResult(False, "unknown", "error")
83
+
84
+ if not done.wait(timeout):
85
+ # 超时就作废这次上下文,别让面板留着等一个已经放弃的调用。
86
+ try:
87
+ ctx.invalidate()
88
+ except Exception:
89
+ pass
90
+ return AuthResult(False, "unknown", "timeout")
91
+
92
+ if box["ok"]:
93
+ # LocalAuthentication 不告诉我们用户按了指纹还是输了密码。
94
+ # 有生物识别硬件时大概率是指纹,但 API 层面无法确认,照实标 unknown。
95
+ return AuthResult(True, "unknown")
96
+
97
+ err = box["err"]
98
+ code = getattr(err, "code", None)
99
+ # LAError: -2 userCancel, -3 userFallback, -4 systemCancel, -1 appCancel,
100
+ # -8 biometryLockout, -9 biometryNotEnrolled, -6 biometryNotAvailable
101
+ if code in (-1, -2, -4):
102
+ return AuthResult(False, "unknown", "cancelled")
103
+ if code in (-6, -9):
104
+ return AuthResult(False, "unknown", "unavailable")
105
+ return AuthResult(False, "unknown", "error")