mandat 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.
Files changed (70) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +293 -3
  3. package/dist/approvals/approvals.d.ts +136 -0
  4. package/dist/approvals/approvals.js +262 -0
  5. package/dist/bridge.d.ts +38 -0
  6. package/dist/bridge.js +117 -0
  7. package/dist/cli/args.d.ts +9 -0
  8. package/dist/cli/args.js +39 -0
  9. package/dist/cli/bin.d.ts +2 -0
  10. package/dist/cli/bin.js +3 -0
  11. package/dist/cli/main.d.ts +1 -0
  12. package/dist/cli/main.js +649 -0
  13. package/dist/cli/templates.d.ts +91 -0
  14. package/dist/cli/templates.js +57 -0
  15. package/dist/client.d.ts +54 -0
  16. package/dist/client.js +88 -0
  17. package/dist/controlplane/config.d.ts +48 -0
  18. package/dist/controlplane/config.js +33 -0
  19. package/dist/controlplane/console/.claude-flow/neural/patterns.json +402 -0
  20. package/dist/controlplane/console/.claude-flow/neural/stats.json +6 -0
  21. package/dist/controlplane/console/.claude-flow/policy/ledger-anchors.json +3 -0
  22. package/dist/controlplane/console/.claude-flow/policy/state.json +54 -0
  23. package/dist/controlplane/console/app.css +93 -0
  24. package/dist/controlplane/console/app.js +330 -0
  25. package/dist/controlplane/console/index.html +70 -0
  26. package/dist/controlplane/server.d.ts +17 -0
  27. package/dist/controlplane/server.js +427 -0
  28. package/dist/guard/guard.d.ts +154 -0
  29. package/dist/guard/guard.js +290 -0
  30. package/dist/guard/pinning.d.ts +46 -0
  31. package/dist/guard/pinning.js +49 -0
  32. package/dist/guard/remote.d.ts +78 -0
  33. package/dist/guard/remote.js +185 -0
  34. package/dist/index.d.ts +43 -0
  35. package/dist/index.js +67 -0
  36. package/dist/ledger/export.d.ts +27 -0
  37. package/dist/ledger/export.js +169 -0
  38. package/dist/ledger/ledger.d.ts +117 -0
  39. package/dist/ledger/ledger.js +139 -0
  40. package/dist/ledger/redact.d.ts +13 -0
  41. package/dist/ledger/redact.js +73 -0
  42. package/dist/ledger/report.d.ts +71 -0
  43. package/dist/ledger/report.js +128 -0
  44. package/dist/mcp/protect.d.ts +8 -0
  45. package/dist/mcp/protect.js +68 -0
  46. package/dist/mcp/server.d.ts +49 -0
  47. package/dist/mcp/server.js +211 -0
  48. package/dist/oidc.d.ts +52 -0
  49. package/dist/oidc.js +194 -0
  50. package/dist/policy/engine.d.ts +135 -0
  51. package/dist/policy/engine.js +243 -0
  52. package/dist/policy/expr.d.ts +56 -0
  53. package/dist/policy/expr.js +506 -0
  54. package/dist/scan/findings.d.ts +32 -0
  55. package/dist/scan/findings.js +105 -0
  56. package/dist/scan/remote.d.ts +7 -0
  57. package/dist/scan/remote.js +225 -0
  58. package/dist/scan/static.d.ts +15 -0
  59. package/dist/scan/static.js +245 -0
  60. package/dist/store.d.ts +14 -0
  61. package/dist/store.js +40 -0
  62. package/dist/sts/jwt.d.ts +64 -0
  63. package/dist/sts/jwt.js +168 -0
  64. package/dist/sts/revocation.d.ts +38 -0
  65. package/dist/sts/revocation.js +52 -0
  66. package/dist/sts/sts.d.ts +83 -0
  67. package/dist/sts/sts.js +239 -0
  68. package/dist/util.d.ts +28 -0
  69. package/dist/util.js +137 -0
  70. package/package.json +47 -4
package/LICENSE ADDED
@@ -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.
package/README.md CHANGED
@@ -1,3 +1,293 @@
1
- # Temporary Holding Version
2
-
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.
1
+ # Mandat
2
+
3
+ **Authorization, delegation and audit for AI agent actions — MCP first.**
4
+
5
+ Mandat answers three questions about every tool call an AI agent makes:
6
+
7
+ 1. **May it?** A policy is checked on *every* call, including its arguments (`refund ≤ €50 → auto · €50–500 → ask a human · > €500 → deny`).
8
+ 2. **On whose behalf?** Agents get short-lived, single-task tokens that carry the whole delegation chain: `human → agent → sub-agent` (RFC 8693 `act` and RFC 9396 `authorization_details`).
9
+ 3. **What happened?** One tamper-evident Action Record per call (hash chain), exportable to a SIEM (OCSF, OpenTelemetry), with a DPO/auditor report.
10
+
11
+ It also ships a **scanner** that checks MCP servers and client configs for the auth and supply-chain mistakes found in most public MCP servers.
12
+
13
+ This repo is the **MVP** (PRD phase 0–3 months, plus the core of delegation from phase 3–6). The spec it implements is in [`specs/rpd.md`](specs/rpd.md).
14
+
15
+ > Zero runtime dependencies. The npm package ships compiled JavaScript (Node ≥ 20). For development, Node ≥ 23.6 runs the TypeScript sources directly.
16
+
17
+ ---
18
+
19
+ ## 60-second demo
20
+
21
+ ```bash
22
+ node examples/demo.ts # full scenario, then exit
23
+ node examples/demo.ts --keep # …and keep the console running at the printed URL
24
+ ```
25
+
26
+ The demo starts a control plane and a protected "Acme Support" MCP server, then plays out this story:
27
+
28
+ | Step | What happens | Mandat feature |
29
+ |---|---|---|
30
+ | Scan | `mandat scan` finds the protected server clean; an anonymous request gets `401` + `resource_metadata` | Scanner, PRM (RFC 9728) |
31
+ | Delegate | Maria signs in. `support-bot` exchanges her token for a 5-minute token that covers only 4 tools | STS, RFC 8693 + RAR |
32
+ | €20 refund | Allowed automatically | PDP on arguments |
33
+ | €120 refund | The agent waits while "Alice" approves, then the call runs | Human approval bound to this exact call |
34
+ | €900 refund | Denied by the `refund-limit` rule | Deny overrides |
35
+ | `delete_customer` | Denied: the tool is outside the task's delegated capability | Capability in token |
36
+ | Prompt injection | After `read_inbox`, e-mail to `archive@exfil.test` is blocked; internal mail still works | Session taint ("lethal trifecta") |
37
+ | Sub-agent | `billing-bot` receives a narrower mandate (refund ≤ €30) with a nested `act` chain | Delegation can only narrow |
38
+ | Kill switch | `support-bot` and every token it delegated stop working in < 1 s; new tokens are refused | Revocation |
39
+ | Audit | The chain verifies. Editing one past record ("€900" → "€9") is detected | Hash-chained ledger |
40
+
41
+ ---
42
+
43
+ ## Quick start (your own setup)
44
+
45
+ ```bash
46
+ mandat init # config, starter policy + tests, keys (.mandat/credentials.json)
47
+ mandat policy test # 7/7 starter decision tests
48
+ mandat serve # control plane + console on http://127.0.0.1:7400/console
49
+
50
+ mandat agents add support-bot --tools "lookup_*,refund,send_email,read_inbox" \
51
+ --resources http://127.0.0.1:7401/mcp --versions 1.4.0 # prints the client secret once
52
+ node examples/refund-server/server.ts # protected MCP server on :7401
53
+ ```
54
+
55
+ (`mandat` is `node bin/mandat.ts`. Run `npm link` once to get the short name.)
56
+
57
+ Then, as an agent:
58
+
59
+ ```bash
60
+ TOKEN=$(mandat token --agent support-bot --secret <secret> --user user:maria --resource http://127.0.0.1:7401/mcp --version 1.4.0)
61
+ curl -s http://127.0.0.1:7401/mcp -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
62
+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"refund","arguments":{"order_id":"A-1002","amount":150,"currency":"EUR"}}}'
63
+ mandat approvals list # in another terminal
64
+ mandat approvals approve apr_… # the waiting call completes
65
+ mandat revoke --agent support-bot --reason "incident 42"
66
+ mandat ledger verify && mandat ledger report --retention 365
67
+ ```
68
+
69
+ ### Protecting your MCP server
70
+
71
+ With the official TypeScript SDK:
72
+
73
+ ```ts
74
+ import { createGuard, protect } from "mandat";
75
+
76
+ const guard = await createGuard({
77
+ resource: "https://mcp.example.com/mcp", // token audience
78
+ controlPlane: process.env.MANDAT_URL!,
79
+ apiKey: process.env.MANDAT_SERVICE_KEY!, // role: service
80
+ pinning: { lockfile: "mandat.lock.json", mode: "block" },
81
+ });
82
+ const server = protect(new McpServer({ name: "billing", version: "1.0.0" }), guard); // every registerTool is guarded
83
+ app.get("/.well-known/oauth-protected-resource/mcp", (_q, r) => r.json(guard.protectedResourceMetadata()));
84
+ app.use("/mcp", requireBearerAuth({ verifier: guard.sdkTokenVerifier({ InvalidTokenError }) }));
85
+ ```
86
+
87
+ Without dependencies, use the built-in server: `new McpHttpServer({ name, version, guard, tools }).listen(7401)` (see [`examples/refund-server`](examples/refund-server)).
88
+
89
+ On the agent side, use `exchangeToken()` and `McpHttpClient` from `mandat`.
90
+
91
+ ---
92
+
93
+ ## Connecting real agents (Claude Code, Codex, Cursor, Claude Desktop)
94
+
95
+ These clients start a browser login when an MCP server answers `401`. Mandat's control plane only does token exchange, not that login flow, so connect them through **`mandat bridge`**. The bridge is a local stdio MCP server: it acts as a registered agent, exchanges the user's identity for 5-minute task tokens, and gets a new one before the old one expires.
96
+
97
+ ```bash
98
+ mandat agents add claude-code --tools "lookup_*,refund,read_inbox,send_email,delete_*" --resources http://127.0.0.1:7401/mcp
99
+ # → copy the client_secret
100
+ ```
101
+
102
+ **Claude Code**
103
+
104
+ ```bash
105
+ claude mcp add acme -e MANDAT_AGENT_SECRET=<secret> -- \
106
+ node D:/Projects/Mandat1/bin/mandat.ts bridge --url http://127.0.0.1:7401/mcp \
107
+ --mandat http://127.0.0.1:7400 --agent claude-code --user user:maria --email maria@acme.example
108
+ ```
109
+
110
+ Equivalent `.mcp.json`:
111
+
112
+ ```json
113
+ { "mcpServers": { "acme": { "command": "node",
114
+ "args": ["D:/Projects/Mandat1/bin/mandat.ts", "bridge", "--url", "http://127.0.0.1:7401/mcp", "--mandat", "http://127.0.0.1:7400",
115
+ "--agent", "claude-code", "--user", "user:maria", "--email", "maria@acme.example"],
116
+ "env": { "MANDAT_AGENT_SECRET": "<secret>" } } } }
117
+ ```
118
+
119
+ **Codex** (`~/.codex/config.toml`)
120
+
121
+ ```toml
122
+ [mcp_servers.acme]
123
+ command = "node"
124
+ args = ["D:/Projects/Mandat1/bin/mandat.ts", "bridge", "--url", "http://127.0.0.1:7401/mcp", "--mandat", "http://127.0.0.1:7400",
125
+ "--agent", "codex", "--user", "user:maria", "--email", "maria@acme.example"]
126
+ env = { MANDAT_AGENT_SECRET = "<secret>" }
127
+
128
+ # Codex has its own approval gate for MCP tools that aren't read-only. Pass these tools through
129
+ # so that Mandat's policy decides (allow / deny / human approval):
130
+ [mcp_servers.acme.tools.refund]
131
+ approval_mode = "approve"
132
+ [mcp_servers.acme.tools.send_email]
133
+ approval_mode = "approve"
134
+ [mcp_servers.acme.tools.read_inbox]
135
+ approval_mode = "approve"
136
+ [mcp_servers.acme.tools.delete_customer]
137
+ approval_mode = "approve"
138
+ ```
139
+
140
+ **Notes**
141
+
142
+ - **Approvals.** A call that needs approval blocks for up to `approvalWaitMs` (15 s in the example server) while a human approves in the console, Slack or `mandat approvals approve <id>`. If nobody answers in time, the agent gets "approval required (request apr_…). Retry the same call once it is approved", and the approval is honoured when the agent retries the identical call.
143
+ - **Real users.** `--user` uses the dev IdP. With a real IdP, put the user's token in `MANDAT_SUBJECT_TOKEN` and configure `trustedIssuers`.
144
+ - **Narrower tasks.** Add `--tools a,b` to give a session less than everything the agent is allowed.
145
+ - **Tested with:** Claude Code 2.1.302 and codex-cli 0.166.0. Both attributed every call in the ledger; Mandat denied over-limit refunds, blocked exfiltration after a prompt injection, and held mid-size refunds and deletes for human approval.
146
+
147
+ ---
148
+
149
+ ## Real users with Auth0 (or any OIDC provider)
150
+
151
+ By default, `mandat init` turns on a dev IdP: anyone can claim to be any user. To have agents act for **real, signed-in people**, connect your identity provider. Auth0 is shown here; Okta, Entra ID and Keycloak work the same way, because Mandat only relies on standard OIDC discovery, JWKS and PKCE.
152
+
153
+ **1. Create an Auth0 application** (Dashboard → Applications → *Create Application*)
154
+
155
+ - **Type:** *Native*. It's a CLI, so there's no client secret; PKCE protects the login instead.
156
+ - **Settings → Allowed Callback URLs:** `http://127.0.0.1:8765/callback`
157
+ - **Settings → Advanced → Grant Types:** *Authorization Code* and *Refresh Token* (both on by default for Native apps).
158
+ - Copy the **Domain** and **Client ID**. You need at least one user (User Management → Users) or a social connection.
159
+
160
+ **2. Trust it on the control plane**, then restart `mandat serve`:
161
+
162
+ ```bash
163
+ mandat idp add --issuer https://YOUR_DOMAIN/ --client-id YOUR_CLIENT_ID --disable-dev-idp
164
+ # Auth0 Organizations: add --tenant-claim org_id
165
+ ```
166
+
167
+ **3. Sign in once** (this opens your browser):
168
+
169
+ ```bash
170
+ mandat login --issuer https://YOUR_DOMAIN/ --client-id YOUR_CLIENT_ID
171
+ mandat login status
172
+ ```
173
+
174
+ The session is stored in `~/.mandat/session.json` (mode 0600) and refreshed automatically when Auth0 issues a refresh token. `login status` tells you whether it did.
175
+
176
+ **4. Let your agent act for you:** in the bridge command, replace `--user …` with `--login`:
177
+
178
+ ```bash
179
+ claude mcp add acme -e MANDAT_AGENT_SECRET=<secret> -- \
180
+ node D:/Projects/Mandat1/bin/mandat.ts bridge --url http://127.0.0.1:7401/mcp --mandat http://127.0.0.1:7400 --agent claude-code --login
181
+ ```
182
+
183
+ Every call is now attributed to the Auth0 user, for example `principal.sub = "auth0|…"`, with their e-mail and `org_id` as tenant. That identity is what policies, approvals and the ledger see. The STS accepts only ID tokens issued by the trusted tenant **to that client ID**, so tokens issued to your other Auth0 apps are rejected.
184
+
185
+ ---
186
+
187
+ ## Architecture
188
+
189
+ ```
190
+ Human (IdP: Okta/Entra/Auth0/Keycloak via JWKS; dev IdP for local use)
191
+ │ ID / access token
192
+ ▼
193
+ Agent ──RFC 8693 (sub=user, act=agent) + RAR──▶ Mandat STS ──▶ 5-min task token (aud = one MCP server)
194
+ │
195
+ ▼ MCP (Streamable HTTP)
196
+ MCP server + Mandat Guard (PEP + in-process PDP) ◀── policy (ETag poll, offline snapshot) ── Control plane
197
+ │ allow / deny / require_approval ───────── approvals API ──▶ Slack · webhook · console · CLI
198
+ │ revocations (2 s poll) ◀──────────────────────────────────── kill switch
199
+ │ Action Records (async, batched, at-least-once, deduped) ──▶ hash-chained ledger ──▶ OCSF / OTLP
200
+ ▼
201
+ Downstream services (the user's token is never forwarded)
202
+ ```
203
+
204
+ | Path | What lives there |
205
+ |---|---|
206
+ | `src/policy/` | Expression language (CEL subset, no `eval`) and the PDP (deny-overrides, fail-closed on errors) |
207
+ | `src/sts/` | JWT/JWKS (ES256/RS256/PS256/EdDSA, no `none`/HMAC), token exchange, revocation model |
208
+ | `src/guard/` | Guard (PEP), tool pinning, remote clients for the control plane |
209
+ | `src/mcp/` | Zero-dep MCP HTTP server with Guard, and the `protect()` adapter for the official SDK |
210
+ | `src/approvals/` | Approval service, Slack (Block Kit + signed interactions), signed webhooks |
211
+ | `src/ledger/` | Hash chain, PII redaction, OCSF/OTel export, OTLP exporter, compliance report |
212
+ | `src/scan/` | Remote scanner and config/source scanner; text/JSON/SARIF/HTML output |
213
+ | `src/controlplane/` | HTTP control plane and web console |
214
+ | `src/cli/` | `mandat` CLI |
215
+
216
+ ### Decision semantics
217
+
218
+ - **Deny overrides.** Any matching `deny` wins. Otherwise any `require_approval` wins. Otherwise `allow` (obligations are merged). Otherwise the policy `default` applies, which is `deny`. Rule order doesn't matter.
219
+ - **Errors fail closed.** If a condition can't be evaluated (type error, missing data), it counts as a match for `deny`/`require_approval` rules and as no match for `allow` rules.
220
+ - **Capability first.** A call outside the token's `authorization_details` (tool, location, argument limits) is denied before any rule runs.
221
+ - **Taint.** A tool marked `taints: true` (e-mail, web, tickets) marks the session. Rules can then check `session.tainted`.
222
+ - **Approvals.** Each approval is bound to `sha256(user, agent, tool, server, args)` and can be used once. Self-approval is refused, `approvers: 2` means four-eyes, and a timeout means deny.
223
+ - **Fail modes.** If revocations can't be refreshed for 15 s, `financial`/`destructive` tools fail closed. Policy keeps working from the last snapshot.
224
+ - **Shadow mode** (`mode: "shadow"`) records the decision but never blocks. Use it to roll out new policies.
225
+
226
+ ### Policy language
227
+
228
+ ```jsonc
229
+ {
230
+ "version": 1,
231
+ "default": "deny",
232
+ "tools": { "refund": { "risk": "financial" }, "read_inbox": { "risk": "read", "taints": true },
233
+ "send_email": { "risk": "external_comm", "redact": ["body"] } },
234
+ "rules": [
235
+ { "id": "refund-approval", "tool": "refund", "when": "args.amount > 50 && args.amount <= 500",
236
+ "effect": "require_approval", "approval": { "approvers": 1, "timeout": "15m", "channels": ["slack"] } },
237
+ { "id": "no-exfil", "tool": "send_email",
238
+ "when": "session.tainted && !args.to.all(r, r.endsWith('@example.com'))", "effect": "deny" }
239
+ ]
240
+ }
241
+ ```
242
+
243
+ - **Context:** `principal.{sub,tenant,email,scope}`, `agent.{id,version,prompt_hash}`, `actor_chain[]`, `tool.{name,server,risk}`, `args.*`, `session.{tainted,taint_sources,calls}`, `task.{id,authorization_details}`, `env.{hour_utc,weekday_utc}`.
244
+ - **Operators:** `== != < <= > >= in && || ! ?: + - * / %`.
245
+ - **Functions:** `size has int double string lower upper abs min max`.
246
+ - **Methods:** `startsWith endsWith contains matches size lower upper trim keys`.
247
+ - **Macros:** `all exists filter`.
248
+ - **Effects:** `allow`, `deny`, `require_approval`, `allow_with_obligations` (obligations: `redact` fields, `annotate` tags).
249
+
250
+ Tooling: `mandat policy check|test|eval` and `mandat bench`. On this machine the PDP measures p50 ≈ 14 µs and p99 ≈ 70 µs (the PRD targets are 0.5 ms and 5 ms).
251
+
252
+ ---
253
+
254
+ ## PRD coverage
255
+
256
+ | PRD item | MVP status |
257
+ |---|---|
258
+ | **US-1** `mandat scan <url>`: auth on `tools/list`, invalid token, PRM, PKCE S256/`plain`, DCR vs CIMD, `iss` (RFC 9207), CORS, transport, tool poisoning, opt-in redirect-URI probe (`--active`); fixes include code | ✅ |
259
+ | Static scan of client configs (unpinned `npx`/`uvx`, known-malicious versions, typosquats, shell/stdio commands, `curl\|sh`, plaintext secrets, static bearer tokens, `0.0.0.0`, broad filesystem roots, privileged Docker) and server source (eval, shell exec, token passthrough); JSON/SARIF/HTML output; GitHub Action | ✅ |
260
+ | **US-2** `protect(server)` for the TS SDK | ✅ (duck-typed adapter, tested against an SDK-shaped fake; not yet run against the real SDK or MCP Inspector) · Python ❌ |
261
+ | **US-3** Argument policies with p99 < 5 ms; approval in Slack with context | ✅ (Slack: Block Kit message + signed interactivity endpoint `/slack/interactions`) |
262
+ | **US-4** Single-task token via RFC 8693 with `sub` = user, `act` = agent, RAR, 5 min | ✅ for Mandat-protected MCP servers · downstream tokens for Stripe/CRM ❌ |
263
+ | **US-5** ID-JAG / Okta XAA | ❌ |
264
+ | Real IdP users (PRD Must: Auth0, Okta, Entra, Keycloak) | ✅ OIDC login with PKCE (`mandat login`), `mandat idp add`, ID-token exchange. Covered by tests against an Auth0-like fake IdP |
265
+ | **US-6** OCSF event with the delegation chain | ✅ export via `/api/ledger/export`; OTLP push of spans (`ledger.otlp`) · direct SIEM connectors (Splunk HEC and others) ❌ |
266
+ | **US-7** Revocation by agent, version, user, task, tenant or token in ≤ 10 s | ✅ < 1 s in tests; issuance blocked until lifted |
267
+ | **US-8** DPO report from the hash chain, retention check | ✅ `mandat ledger report`, console |
268
+ | **US-9** Tool description/schema drift | ✅ server-side lockfile (warn/block) and client-side `mandat pin --check` |
269
+ | Attribution model, local ledger, shadow mode, taint, policy tests | ✅ |
270
+ | Control plane: agents registry, roles (admin / approver / auditor / service), policy change log, console | ✅ |
271
+ | Cloud Free, hosted multi-tenant ledger, CIBA, Teams, Transaction Tokens, SPIFFE, Gateway, other language SDKs | ❌ out of MVP scope |
272
+
273
+ ## Security notes and known limitations
274
+
275
+ - **Dev IdP.** `devIdp: true` (the `mandat init` default) lets anyone mint user tokens on `/dev/login`. Disable it with `mandat idp add … --disable-dev-idp` before any real use.
276
+ - **Approver identity.** Approvers still authenticate with API keys (console/CLI) or Slack, not through the IdP, so self-approval is only detected when the approver id matches the user's `sub` or e-mail.
277
+ - **Storage.** The control plane keeps state in JSON files under `dataDir` (single process, no HA). The `JsonCollection` interface is the seam for a database.
278
+ - **Ledger.** The ledger is tamper-*evident*, not tamper-*proof*: someone with write access could rewrite the whole chain. For that threat, anchor the head hash externally (WORM storage, a transparency log, or an eIDAS timestamp; see open question 8). Records are ordered by `seq`, which is arrival order; `ts` is event time.
279
+ - **Auth failures** (bad or revoked token → `401`) are returned to the caller but not yet written to the ledger.
280
+ - **Slack identity.** Slack approvers are recorded as `slack:<username>`. They are not yet mapped to IdP identities, so the self-approval check covers only the API, console and CLI.
281
+ - **MCP server scope.** The built-in MCP server implements the JSON response mode of Streamable HTTP (no SSE stream, no server→client requests).
282
+ - **OWASP mappings.** Mappings to OWASP Agentic (ASI) and MCP Top 10 are best effort.
283
+
284
+ ## Development
285
+
286
+ ```bash
287
+ npm test # 46 tests: expression language, PDP, STS, guard, approvals, ledger, scanner, end-to-end over HTTP
288
+ npm run typecheck # tsc --strict (dev dependency only)
289
+ npm run build # dist/ (plain JS + .d.ts) for the npm package; Node >= 20
290
+ npm run demo
291
+ ```
292
+
293
+ License: Apache-2.0.
@@ -0,0 +1,136 @@
1
+ import type { LedgerSink } from "../ledger/ledger.ts";
2
+ import type { Risk } from "../policy/engine.ts";
3
+ export type ApprovalStatus = "pending" | "approved" | "denied" | "expired";
4
+ export interface ApprovalContext {
5
+ tool: string;
6
+ server?: string | null;
7
+ risk?: Risk | null;
8
+ /** Already redacted. */
9
+ args: unknown;
10
+ principal: {
11
+ sub: string;
12
+ tenant?: string | null;
13
+ email?: string | null;
14
+ };
15
+ agent: {
16
+ id: string;
17
+ version?: string | null;
18
+ };
19
+ actor_chain?: string[];
20
+ task_id?: string | null;
21
+ rule: string;
22
+ reasons: string[];
23
+ session_tainted?: boolean;
24
+ }
25
+ export interface ApprovalRequest {
26
+ id: string;
27
+ binding: string;
28
+ status: ApprovalStatus;
29
+ required: number;
30
+ created_at: string;
31
+ expires_at: string;
32
+ decided_at: string | null;
33
+ consumed_at: string | null;
34
+ votes: Array<{
35
+ by: string;
36
+ decision: "approve" | "deny";
37
+ at: string;
38
+ via: string;
39
+ comment?: string;
40
+ }>;
41
+ channels: string[];
42
+ context: ApprovalContext;
43
+ }
44
+ export interface NewApproval {
45
+ binding: string;
46
+ required: number;
47
+ timeoutMs: number;
48
+ channels: string[];
49
+ context: ApprovalContext;
50
+ }
51
+ export declare function approvalBinding(p: {
52
+ sub: string;
53
+ agent: string;
54
+ tool: string;
55
+ server?: string | null;
56
+ args: unknown;
57
+ }): string;
58
+ export interface Notifier {
59
+ name: string;
60
+ notify(req: ApprovalRequest): Promise<void>;
61
+ /** Called after a decision so channels can update their message. */
62
+ decided?(req: ApprovalRequest): Promise<void>;
63
+ }
64
+ export declare class ApprovalError extends Error {
65
+ status: number;
66
+ constructor(status: number, message: string);
67
+ }
68
+ export declare class ApprovalService {
69
+ private store;
70
+ private events;
71
+ private notifiers;
72
+ private ledger?;
73
+ private sweeper;
74
+ constructor(opts: {
75
+ path: string | null;
76
+ notifiers?: Notifier[];
77
+ ledger?: LedgerSink;
78
+ });
79
+ close(): void;
80
+ get(id: string): ApprovalRequest | undefined;
81
+ list(status?: ApprovalStatus): ApprovalRequest[];
82
+ /** Creates a request, or returns the live one with the same binding (pending, or approved and unused). */
83
+ create(n: NewApproval): Promise<ApprovalRequest>;
84
+ decide(id: string, vote: {
85
+ by: string;
86
+ decision: "approve" | "deny";
87
+ via: string;
88
+ comment?: string;
89
+ }): ApprovalRequest;
90
+ /** Marks an approved request as used. Returns false if it was already used (replay). */
91
+ consume(id: string): boolean;
92
+ /** Resolves when the request leaves `pending` or after `timeoutMs` (returning the current state). */
93
+ wait(id: string, timeoutMs: number): Promise<ApprovalRequest | undefined>;
94
+ private expireDue;
95
+ private finalised;
96
+ }
97
+ /** Generic signed webhook: POST JSON, `X-Mandat-Signature: sha256=<hmac(timestamp + "." + body)>`. */
98
+ export declare class WebhookNotifier implements Notifier {
99
+ name: string;
100
+ private url;
101
+ private secret;
102
+ private consoleUrl;
103
+ constructor(opts: {
104
+ url: string;
105
+ secret: string;
106
+ consoleUrl: string;
107
+ name?: string;
108
+ });
109
+ notify(req: ApprovalRequest): Promise<void>;
110
+ decided(req: ApprovalRequest): Promise<void>;
111
+ private post;
112
+ }
113
+ /** Slack via an app's Incoming Webhook; buttons are handled by `handleSlackInteraction`. */
114
+ export declare class SlackNotifier implements Notifier {
115
+ name: string;
116
+ private webhookUrl;
117
+ private consoleUrl;
118
+ constructor(opts: {
119
+ webhookUrl: string;
120
+ consoleUrl: string;
121
+ });
122
+ notify(req: ApprovalRequest): Promise<void>;
123
+ }
124
+ export declare function slackBlocks(req: ApprovalRequest, consoleUrl: string): unknown[];
125
+ /** Verifies Slack's request signature (v0 HMAC-SHA256, 5 minute replay window). */
126
+ export declare function verifySlackSignature(rawBody: string, timestamp: string | undefined, signature: string | undefined, signingSecret: string): boolean;
127
+ export declare function handleSlackInteraction(service: ApprovalService, rawBody: string, consoleUrl: string): {
128
+ replace_original: boolean;
129
+ blocks?: unknown[];
130
+ text: string;
131
+ };
132
+ /** Dev channel: prints a hint to the control plane's stdout. */
133
+ export declare class ConsoleLogNotifier implements Notifier {
134
+ name: string;
135
+ notify(req: ApprovalRequest): Promise<void>;
136
+ }