@entros/verify 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,14 +7,14 @@ It opens the Entros popup and checks the returned application policy result befo
7
7
 
8
8
  Source: [github.com/entros-protocol/entros-verify](https://github.com/entros-protocol/entros-verify) · Hosted by [entros.io](https://entros.io).
9
9
 
10
- This README describes the prepared `0.2.0` source release. npm still serves `0.1.1` as `latest`.
11
- Package publication and the compatible hosted popup release remain pending.
12
- Deploy an upgraded consumer after the compatible popup release completes.
10
+ Pin an exact version when you integrate the policy contract.
11
+ The package is published, and the hosted Entros popup supports this policy contract.
12
+ A self-hosted popup must implement the same contract before it can serve an upgraded consumer.
13
13
 
14
- After publication, install the prepared version with React 19:
14
+ Install with React 19:
15
15
 
16
16
  ```bash
17
- npm install @entros/verify@0.2.0
17
+ npm install @entros/verify
18
18
  ```
19
19
 
20
20
  ## Usage
@@ -26,7 +26,7 @@ import { EntrosVerify } from "@entros/verify";
26
26
  integratorKey="your-integrator-key"
27
27
  onVerified={(result) => showVerificationResult(result)}
28
28
  onError={(error) => showVerificationError(error.reason, error.policyReason)}
29
- />
29
+ />;
30
30
  ```
31
31
 
32
32
  Without `policy`, the component uses a one-day verification age, a 90-second evaluation age, and optional SAS issuance.
@@ -88,7 +88,7 @@ Required attestations must exist and remain valid through consumption.
88
88
  cluster="devnet"
89
89
  minTrustScore={200}
90
90
  popupWidth={480}
91
- popupHeight={720}
91
+ popupHeight={800}
92
92
  timeoutMs={9 * 60 * 1000}
93
93
  popupBlockedFallback={true}
94
94
  className="verification-button"
@@ -109,21 +109,21 @@ Use `style` for inline styles and children for custom button content.
109
109
  `onError` receives `reason` and an optional `policyReason`.
110
110
  Policy reasons describe application requirements or evidence availability. They do not expose private behavioral rejection signals.
111
111
 
112
- | Reason | Meaning |
113
- |---|---|
114
- | `wallet_rejected` | User denied wallet connection or signing |
112
+ | Reason | Meaning |
113
+ | ------------------- | --------------------------------------------------- |
114
+ | `wallet_rejected` | User denied wallet connection or signing |
115
115
  | `validation_failed` | Verification or the application policy did not pass |
116
- | `network_error` | The flow encountered a network failure |
117
- | `user_canceled` | User closed the popup before completion |
118
- | `origin_invalid` | The integrator origin failed the allowlist check |
119
- | `popup_blocked` | The browser blocked `window.open()` |
120
- | `timeout` | The popup exceeded `timeoutMs` |
121
- | `unknown` | The flow encountered an unclassified failure |
116
+ | `network_error` | The flow encountered a network failure |
117
+ | `user_canceled` | User closed the popup before completion |
118
+ | `origin_invalid` | The integrator origin failed the allowlist check |
119
+ | `popup_blocked` | The browser blocked `window.open()` |
120
+ | `timeout` | The popup exceeded `timeoutMs` |
121
+ | `unknown` | The flow encountered an unclassified failure |
122
122
 
123
123
  ## Settlement checks
124
124
 
125
125
  The React-free `@entros/verify/policy` subpath exports `normalizePolicyRequest`, `evaluatePolicy`, and strict wire guards.
126
- Pair the evaluator with `readIntegratorEvidence` from the prepared Pulse `4.10.0` release against your service's configured RPC connection.
126
+ Pair the evaluator with `readIntegratorEvidence` from Pulse `4.10.2` or later against your service's configured RPC connection.
127
127
  The evaluator accepts typed observations. It cannot authenticate observations supplied by a browser.
128
128
 
129
129
  For protected actions, your service owns the policy and authenticates the wallet's signature over a one-use action challenge.
@@ -131,6 +131,68 @@ Bind the challenge to the wallet, action parameters, audience, and expiry.
131
131
  Read current chain evidence before executing the action. Consume the challenge and execute the action in one atomic operation.
132
132
  An on-chain action must enforce its requirements within the action transaction.
133
133
 
134
+ Run the [protected-action example](examples/protected-action) to exercise signature checks, fresh policy evaluation, and one-use settlement with synthetic data.
135
+
136
+ ## Agent Operator Permit
137
+
138
+ The React-free `@entros/verify/agent-permit` subpath implements permit version 1 for agents in the 8004 agent registry on devnet.
139
+ A permit authorizes one action by one registered agent. The wallet that owns the agent signs it, and the agent's registered agent wallet presents it.
140
+
141
+ 1. Your service reads the agent with `readAgentState` from Pulse `4.12.0` or later.
142
+ 2. Your service calls `createAgentPermitRequest` and stores the rendered text under its nonce.
143
+ 3. The owner opens the request on the Entros signing page and signs it with the owning wallet.
144
+ 4. The agent signs `renderAgentPermitPresentation(permitId)` with its agent wallet and sends the settlement bundle.
145
+ 5. Your service runs `precheckAgentPermit`, reads agent state and operator evidence, and runs `evaluateAgentPermit`.
146
+ 6. On `allow`, your service consumes the nonce and executes the stored action in one atomic operation.
147
+
148
+ ```ts
149
+ import {
150
+ evaluateAgentPermit,
151
+ parseAgentPermitSettlement,
152
+ precheckAgentPermit,
153
+ } from "@entros/verify/agent-permit";
154
+
155
+ const bundle = parseAgentPermitSettlement(body);
156
+ const stored = bundle && pending.get(bundle.nonce);
157
+ if (!bundle || !stored) return reject("nonce_unavailable");
158
+
159
+ const signatures = {
160
+ operatorSignature: bundle.operatorSignature,
161
+ presentationSignature: bundle.presentationSignature,
162
+ };
163
+ const precheck = precheckAgentPermit({ request: stored, ...signatures, nowSeconds: now() });
164
+ if (!precheck.ok) return reject(precheck.reason);
165
+
166
+ const [agentState, operatorEvidence] = await Promise.all([
167
+ readAgentState({ agent: stored.agent, connection }),
168
+ readIntegratorEvidence({
169
+ walletPubkey: stored.operator,
170
+ transactionSignature: bundle.verifiedTransaction,
171
+ connection,
172
+ nowSeconds: now,
173
+ }),
174
+ ]);
175
+ const result = evaluateAgentPermit({
176
+ request: stored,
177
+ ...signatures,
178
+ agentState,
179
+ operatorEvidence,
180
+ nowSeconds: now(),
181
+ });
182
+ ```
183
+
184
+ The precheck covers expiry and both signatures, so an expired or forged permit costs your service no chain read.
185
+ Sample the clock again after the reads, because a permit can expire while they run.
186
+
187
+ - Settle only requests that your service stored. Never take request text, policy, or RPC settings from the agent.
188
+ - Execute the stored action at settlement. Do not return a reusable credential to the presenter.
189
+ - The owner is the wallet in the Metaplex Core asset. The registry's cached owner and the `entros:human-operator` metadata grant nothing.
190
+ - A transfer after the settlement read can still land before your action. An on-chain action must check ownership inside its transaction.
191
+
192
+ Run the [agent-permit example](examples/agent-permit) to exercise issuance, both signatures, transfer rejection, and one-use settlement with synthetic data.
193
+
194
+ A permit states current wallet control of a registered agent and the owner's Entros policy result. It does not establish legal ownership, population uniqueness, or hardware assurance.
195
+
134
196
  ## Migration from `0.1.1`
135
197
 
136
198
  Version `0.2.0` changes the callback contract:
@@ -0,0 +1,190 @@
1
+ import { PolicyRequest, PolicyEvidenceReadResult, PolicyResult } from './policy.mjs';
2
+
3
+ declare const AGENT_PERMIT_VERSION_LINE = "Entros-Agent-Permit-v1";
4
+ declare const AGENT_PERMIT_NOTICE_LINE = "Sign only to let this agent perform the action below. This is not a transaction.";
5
+ declare const AGENT_PERMIT_PRESENTATION_LINE = "Entros-Agent-Permit-Presentation-v1";
6
+ declare const AGENT_PERMIT_NETWORK: Readonly<{
7
+ readonly cluster: "devnet";
8
+ readonly genesisHash: "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG";
9
+ readonly entrosAnchorProgram: string;
10
+ readonly agentRegistryProgram: "8oo4J9tBB3Hna1jRQ3rWvJjojqM5DYTDJo5cejUuJy3C";
11
+ readonly agentCollection: "6CTyGPcn8dMwKEqgtvx2XCpkGUd7uqCVK6937RSM5bhA";
12
+ readonly coreProgram: "CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d";
13
+ }>;
14
+ declare const AGENT_PERMIT_LIMITS: Readonly<{
15
+ minLifetimeSeconds: 30;
16
+ maxLifetimeSeconds: 900;
17
+ clockSkewSeconds: 30;
18
+ maxAudienceLength: 200;
19
+ maxLabelLength: 96;
20
+ minTimeSeconds: 946684800;
21
+ maxTimeSeconds: 253402300799;
22
+ }>;
23
+ interface AgentPermitAction {
24
+ label: string;
25
+ /** Lowercase hex SHA-256 of the consumer's own action record. */
26
+ sha256: string;
27
+ }
28
+ interface AgentPermitRequest {
29
+ version: 1;
30
+ agent: string;
31
+ agentWallet: string;
32
+ operator: string;
33
+ audience: string;
34
+ action: AgentPermitAction;
35
+ policy: PolicyRequest;
36
+ cluster: "devnet";
37
+ genesisHash: string;
38
+ entrosAnchorProgram: string;
39
+ agentRegistryProgram: string;
40
+ agentCollection: string;
41
+ issuedAt: number;
42
+ expiresAt: number;
43
+ nonce: string;
44
+ }
45
+ interface CreateAgentPermitRequestInput {
46
+ agent: string;
47
+ agentWallet: string;
48
+ operator: string;
49
+ audience: string;
50
+ action: AgentPermitAction;
51
+ policy: PolicyRequest;
52
+ issuedAt: number;
53
+ lifetimeSeconds: number;
54
+ /** Omit to draw 32 random bytes from `crypto.getRandomValues`. */
55
+ nonce?: string;
56
+ }
57
+ type AgentWalletStatus = "bound" | "unbound" | "stale";
58
+ interface AgentStateEvidence {
59
+ cluster: "devnet";
60
+ genesisHash: string;
61
+ coreProgram: string;
62
+ agentRegistryProgram: string;
63
+ agentCollection: string;
64
+ agent: string;
65
+ agentAccount: string;
66
+ /** Owner field of the Metaplex Core asset. The only owner source. */
67
+ owner: string;
68
+ /** Registry cache. Informational, and the agent wallet counts only when it matches. */
69
+ cachedOwner: string;
70
+ agentWallet: string | null;
71
+ agentWalletStatus: AgentWalletStatus;
72
+ readContextSlot: number;
73
+ }
74
+ type AgentStateFailureReason = "invalid_request" | "wrong_cluster" | "agent_missing" | "agent_invalid" | "agent_unregistered" | "rpc_unavailable";
75
+ type AgentStateReadResult = {
76
+ status: "available";
77
+ evidence: AgentStateEvidence;
78
+ } | {
79
+ status: "invalid" | "unavailable";
80
+ reason: AgentStateFailureReason;
81
+ };
82
+ type AgentPermitReason = "accepted" | "invalid_permit" | "permit_expired" | "invalid_signature" | "invalid_presentation" | "wrong_cluster" | "agent_missing" | "agent_invalid" | "agent_unregistered" | "agent_unavailable" | "owner_changed" | "agent_wallet_stale" | "agent_wallet_unbound" | "agent_wallet_changed" | "score_below_minimum" | "verification_stale" | "attestation_required" | "invalid_evidence" | "state_unavailable";
83
+ type AgentPermitDenyReason = Exclude<AgentPermitReason, "accepted" | "agent_unavailable" | "state_unavailable">;
84
+ type AgentPermitPrecheck = {
85
+ ok: true;
86
+ request: AgentPermitRequest;
87
+ permitId: string;
88
+ } | {
89
+ ok: false;
90
+ reason: "invalid_permit" | "permit_expired" | "invalid_signature" | "invalid_presentation";
91
+ request: AgentPermitRequest | null;
92
+ permitId: string | null;
93
+ };
94
+ interface AgentPermitResultBase {
95
+ permitId: string | null;
96
+ request: AgentPermitRequest | null;
97
+ evaluatedAt: number;
98
+ expiresAt: number | null;
99
+ agentState: AgentStateEvidence | null;
100
+ policy: PolicyResult | null;
101
+ }
102
+ type AgentPermitResult = AgentPermitResultBase & ({
103
+ decision: "allow";
104
+ reason: "accepted";
105
+ } | {
106
+ decision: "deny";
107
+ reason: AgentPermitDenyReason;
108
+ } | {
109
+ decision: "unavailable";
110
+ reason: "agent_unavailable" | "state_unavailable";
111
+ });
112
+ interface AgentPermitSignatures {
113
+ operatorSignature: string;
114
+ presentationSignature: string;
115
+ }
116
+ interface AgentPermitEvaluationInput extends AgentPermitSignatures {
117
+ request: AgentPermitRequest;
118
+ agentState: AgentStateReadResult;
119
+ operatorEvidence: PolicyEvidenceReadResult;
120
+ nowSeconds: number;
121
+ }
122
+ interface AgentPermitApproval {
123
+ version: 1;
124
+ permitId: string;
125
+ operatorSignature: string;
126
+ verifiedTransaction: string;
127
+ }
128
+ interface AgentPermitSettlementBundle extends AgentPermitSignatures {
129
+ version: 1;
130
+ nonce: string;
131
+ verifiedTransaction: string;
132
+ }
133
+ declare class AgentPermitValidationError extends Error {
134
+ readonly field: string;
135
+ constructor(field: string);
136
+ }
137
+ /** Accepts only URLs that already equal their WHATWG `URL.href`. */
138
+ declare function isAgentPermitAudience(value: unknown): value is string;
139
+ /** Validates every field and returns a detached copy. Throws `AgentPermitValidationError`. */
140
+ declare function normalizeAgentPermitRequest(value: unknown): AgentPermitRequest;
141
+ /** Builds a permit request for the consumer to store and render. */
142
+ declare function createAgentPermitRequest(input: CreateAgentPermitRequestInput): AgentPermitRequest;
143
+ /** Renders the seventeen-line text that the operator signs. */
144
+ declare function renderAgentPermitMessage(request: AgentPermitRequest): string;
145
+ /** Parses a permit request and requires byte equality with its own rendering. */
146
+ declare function parseAgentPermitMessage(text: unknown): AgentPermitRequest;
147
+ /** Lowercase hex SHA-256 of the permit request text. */
148
+ declare function agentPermitId(request: AgentPermitRequest): string;
149
+ /** The two-line text that the agent wallet signs. */
150
+ declare function renderAgentPermitPresentation(permitId: string): string;
151
+ /** Checks the operator signature and the agent wallet presentation with strict rules. */
152
+ declare function verifyAgentPermitSignatures(request: AgentPermitRequest, signatures: {
153
+ operatorSignature: unknown;
154
+ presentationSignature: unknown;
155
+ }): {
156
+ operator: boolean;
157
+ presentation: boolean;
158
+ };
159
+ /**
160
+ * Runs every check that needs no chain read: request shape, clock, expiry and both signatures.
161
+ * Call it before reading chain state so an expired or forged permit costs no RPC request.
162
+ */
163
+ declare function precheckAgentPermit(input: {
164
+ request: unknown;
165
+ operatorSignature: unknown;
166
+ presentationSignature: unknown;
167
+ nowSeconds: number;
168
+ }): AgentPermitPrecheck;
169
+ /** Strict shape check for agent state from a trusted reader. */
170
+ declare function isAgentStateEvidence(value: unknown): value is AgentStateEvidence;
171
+ /**
172
+ * Evaluates a permit at settlement against agent state and operator evidence read after the
173
+ * precheck. Pass a clock value sampled after those reads complete.
174
+ */
175
+ declare function evaluateAgentPermit(input: AgentPermitEvaluationInput): AgentPermitResult;
176
+ /** Serializes the approval that the signing page hands to the agent. */
177
+ declare function encodeAgentPermitApproval(approval: Omit<AgentPermitApproval, "version">): string;
178
+ declare function parseAgentPermitApproval(input: unknown): AgentPermitApproval | null;
179
+ /** Serializes the bundle that the agent sends to the consumer. */
180
+ declare function encodeAgentPermitSettlement(bundle: Omit<AgentPermitSettlementBundle, "version">): string;
181
+ declare function parseAgentPermitSettlement(input: unknown): AgentPermitSettlementBundle | null;
182
+ /** URL fragment for the signing page, without the leading `#`. */
183
+ declare function encodeAgentPermitFragment(request: AgentPermitRequest): string;
184
+ /** Parses a `request=` fragment. Returns null for anything else. */
185
+ declare function parseAgentPermitFragment(fragment: string): {
186
+ request: AgentPermitRequest;
187
+ message: string;
188
+ } | null;
189
+
190
+ export { AGENT_PERMIT_LIMITS, AGENT_PERMIT_NETWORK, AGENT_PERMIT_NOTICE_LINE, AGENT_PERMIT_PRESENTATION_LINE, AGENT_PERMIT_VERSION_LINE, type AgentPermitAction, type AgentPermitApproval, type AgentPermitDenyReason, type AgentPermitEvaluationInput, type AgentPermitPrecheck, type AgentPermitReason, type AgentPermitRequest, type AgentPermitResult, type AgentPermitSettlementBundle, type AgentPermitSignatures, AgentPermitValidationError, type AgentStateEvidence, type AgentStateFailureReason, type AgentStateReadResult, type AgentWalletStatus, type CreateAgentPermitRequestInput, agentPermitId, createAgentPermitRequest, encodeAgentPermitApproval, encodeAgentPermitFragment, encodeAgentPermitSettlement, evaluateAgentPermit, isAgentPermitAudience, isAgentStateEvidence, normalizeAgentPermitRequest, parseAgentPermitApproval, parseAgentPermitFragment, parseAgentPermitMessage, parseAgentPermitSettlement, precheckAgentPermit, renderAgentPermitMessage, renderAgentPermitPresentation, verifyAgentPermitSignatures };
@@ -0,0 +1,190 @@
1
+ import { PolicyRequest, PolicyEvidenceReadResult, PolicyResult } from './policy.js';
2
+
3
+ declare const AGENT_PERMIT_VERSION_LINE = "Entros-Agent-Permit-v1";
4
+ declare const AGENT_PERMIT_NOTICE_LINE = "Sign only to let this agent perform the action below. This is not a transaction.";
5
+ declare const AGENT_PERMIT_PRESENTATION_LINE = "Entros-Agent-Permit-Presentation-v1";
6
+ declare const AGENT_PERMIT_NETWORK: Readonly<{
7
+ readonly cluster: "devnet";
8
+ readonly genesisHash: "EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG";
9
+ readonly entrosAnchorProgram: string;
10
+ readonly agentRegistryProgram: "8oo4J9tBB3Hna1jRQ3rWvJjojqM5DYTDJo5cejUuJy3C";
11
+ readonly agentCollection: "6CTyGPcn8dMwKEqgtvx2XCpkGUd7uqCVK6937RSM5bhA";
12
+ readonly coreProgram: "CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d";
13
+ }>;
14
+ declare const AGENT_PERMIT_LIMITS: Readonly<{
15
+ minLifetimeSeconds: 30;
16
+ maxLifetimeSeconds: 900;
17
+ clockSkewSeconds: 30;
18
+ maxAudienceLength: 200;
19
+ maxLabelLength: 96;
20
+ minTimeSeconds: 946684800;
21
+ maxTimeSeconds: 253402300799;
22
+ }>;
23
+ interface AgentPermitAction {
24
+ label: string;
25
+ /** Lowercase hex SHA-256 of the consumer's own action record. */
26
+ sha256: string;
27
+ }
28
+ interface AgentPermitRequest {
29
+ version: 1;
30
+ agent: string;
31
+ agentWallet: string;
32
+ operator: string;
33
+ audience: string;
34
+ action: AgentPermitAction;
35
+ policy: PolicyRequest;
36
+ cluster: "devnet";
37
+ genesisHash: string;
38
+ entrosAnchorProgram: string;
39
+ agentRegistryProgram: string;
40
+ agentCollection: string;
41
+ issuedAt: number;
42
+ expiresAt: number;
43
+ nonce: string;
44
+ }
45
+ interface CreateAgentPermitRequestInput {
46
+ agent: string;
47
+ agentWallet: string;
48
+ operator: string;
49
+ audience: string;
50
+ action: AgentPermitAction;
51
+ policy: PolicyRequest;
52
+ issuedAt: number;
53
+ lifetimeSeconds: number;
54
+ /** Omit to draw 32 random bytes from `crypto.getRandomValues`. */
55
+ nonce?: string;
56
+ }
57
+ type AgentWalletStatus = "bound" | "unbound" | "stale";
58
+ interface AgentStateEvidence {
59
+ cluster: "devnet";
60
+ genesisHash: string;
61
+ coreProgram: string;
62
+ agentRegistryProgram: string;
63
+ agentCollection: string;
64
+ agent: string;
65
+ agentAccount: string;
66
+ /** Owner field of the Metaplex Core asset. The only owner source. */
67
+ owner: string;
68
+ /** Registry cache. Informational, and the agent wallet counts only when it matches. */
69
+ cachedOwner: string;
70
+ agentWallet: string | null;
71
+ agentWalletStatus: AgentWalletStatus;
72
+ readContextSlot: number;
73
+ }
74
+ type AgentStateFailureReason = "invalid_request" | "wrong_cluster" | "agent_missing" | "agent_invalid" | "agent_unregistered" | "rpc_unavailable";
75
+ type AgentStateReadResult = {
76
+ status: "available";
77
+ evidence: AgentStateEvidence;
78
+ } | {
79
+ status: "invalid" | "unavailable";
80
+ reason: AgentStateFailureReason;
81
+ };
82
+ type AgentPermitReason = "accepted" | "invalid_permit" | "permit_expired" | "invalid_signature" | "invalid_presentation" | "wrong_cluster" | "agent_missing" | "agent_invalid" | "agent_unregistered" | "agent_unavailable" | "owner_changed" | "agent_wallet_stale" | "agent_wallet_unbound" | "agent_wallet_changed" | "score_below_minimum" | "verification_stale" | "attestation_required" | "invalid_evidence" | "state_unavailable";
83
+ type AgentPermitDenyReason = Exclude<AgentPermitReason, "accepted" | "agent_unavailable" | "state_unavailable">;
84
+ type AgentPermitPrecheck = {
85
+ ok: true;
86
+ request: AgentPermitRequest;
87
+ permitId: string;
88
+ } | {
89
+ ok: false;
90
+ reason: "invalid_permit" | "permit_expired" | "invalid_signature" | "invalid_presentation";
91
+ request: AgentPermitRequest | null;
92
+ permitId: string | null;
93
+ };
94
+ interface AgentPermitResultBase {
95
+ permitId: string | null;
96
+ request: AgentPermitRequest | null;
97
+ evaluatedAt: number;
98
+ expiresAt: number | null;
99
+ agentState: AgentStateEvidence | null;
100
+ policy: PolicyResult | null;
101
+ }
102
+ type AgentPermitResult = AgentPermitResultBase & ({
103
+ decision: "allow";
104
+ reason: "accepted";
105
+ } | {
106
+ decision: "deny";
107
+ reason: AgentPermitDenyReason;
108
+ } | {
109
+ decision: "unavailable";
110
+ reason: "agent_unavailable" | "state_unavailable";
111
+ });
112
+ interface AgentPermitSignatures {
113
+ operatorSignature: string;
114
+ presentationSignature: string;
115
+ }
116
+ interface AgentPermitEvaluationInput extends AgentPermitSignatures {
117
+ request: AgentPermitRequest;
118
+ agentState: AgentStateReadResult;
119
+ operatorEvidence: PolicyEvidenceReadResult;
120
+ nowSeconds: number;
121
+ }
122
+ interface AgentPermitApproval {
123
+ version: 1;
124
+ permitId: string;
125
+ operatorSignature: string;
126
+ verifiedTransaction: string;
127
+ }
128
+ interface AgentPermitSettlementBundle extends AgentPermitSignatures {
129
+ version: 1;
130
+ nonce: string;
131
+ verifiedTransaction: string;
132
+ }
133
+ declare class AgentPermitValidationError extends Error {
134
+ readonly field: string;
135
+ constructor(field: string);
136
+ }
137
+ /** Accepts only URLs that already equal their WHATWG `URL.href`. */
138
+ declare function isAgentPermitAudience(value: unknown): value is string;
139
+ /** Validates every field and returns a detached copy. Throws `AgentPermitValidationError`. */
140
+ declare function normalizeAgentPermitRequest(value: unknown): AgentPermitRequest;
141
+ /** Builds a permit request for the consumer to store and render. */
142
+ declare function createAgentPermitRequest(input: CreateAgentPermitRequestInput): AgentPermitRequest;
143
+ /** Renders the seventeen-line text that the operator signs. */
144
+ declare function renderAgentPermitMessage(request: AgentPermitRequest): string;
145
+ /** Parses a permit request and requires byte equality with its own rendering. */
146
+ declare function parseAgentPermitMessage(text: unknown): AgentPermitRequest;
147
+ /** Lowercase hex SHA-256 of the permit request text. */
148
+ declare function agentPermitId(request: AgentPermitRequest): string;
149
+ /** The two-line text that the agent wallet signs. */
150
+ declare function renderAgentPermitPresentation(permitId: string): string;
151
+ /** Checks the operator signature and the agent wallet presentation with strict rules. */
152
+ declare function verifyAgentPermitSignatures(request: AgentPermitRequest, signatures: {
153
+ operatorSignature: unknown;
154
+ presentationSignature: unknown;
155
+ }): {
156
+ operator: boolean;
157
+ presentation: boolean;
158
+ };
159
+ /**
160
+ * Runs every check that needs no chain read: request shape, clock, expiry and both signatures.
161
+ * Call it before reading chain state so an expired or forged permit costs no RPC request.
162
+ */
163
+ declare function precheckAgentPermit(input: {
164
+ request: unknown;
165
+ operatorSignature: unknown;
166
+ presentationSignature: unknown;
167
+ nowSeconds: number;
168
+ }): AgentPermitPrecheck;
169
+ /** Strict shape check for agent state from a trusted reader. */
170
+ declare function isAgentStateEvidence(value: unknown): value is AgentStateEvidence;
171
+ /**
172
+ * Evaluates a permit at settlement against agent state and operator evidence read after the
173
+ * precheck. Pass a clock value sampled after those reads complete.
174
+ */
175
+ declare function evaluateAgentPermit(input: AgentPermitEvaluationInput): AgentPermitResult;
176
+ /** Serializes the approval that the signing page hands to the agent. */
177
+ declare function encodeAgentPermitApproval(approval: Omit<AgentPermitApproval, "version">): string;
178
+ declare function parseAgentPermitApproval(input: unknown): AgentPermitApproval | null;
179
+ /** Serializes the bundle that the agent sends to the consumer. */
180
+ declare function encodeAgentPermitSettlement(bundle: Omit<AgentPermitSettlementBundle, "version">): string;
181
+ declare function parseAgentPermitSettlement(input: unknown): AgentPermitSettlementBundle | null;
182
+ /** URL fragment for the signing page, without the leading `#`. */
183
+ declare function encodeAgentPermitFragment(request: AgentPermitRequest): string;
184
+ /** Parses a `request=` fragment. Returns null for anything else. */
185
+ declare function parseAgentPermitFragment(fragment: string): {
186
+ request: AgentPermitRequest;
187
+ message: string;
188
+ } | null;
189
+
190
+ export { AGENT_PERMIT_LIMITS, AGENT_PERMIT_NETWORK, AGENT_PERMIT_NOTICE_LINE, AGENT_PERMIT_PRESENTATION_LINE, AGENT_PERMIT_VERSION_LINE, type AgentPermitAction, type AgentPermitApproval, type AgentPermitDenyReason, type AgentPermitEvaluationInput, type AgentPermitPrecheck, type AgentPermitReason, type AgentPermitRequest, type AgentPermitResult, type AgentPermitSettlementBundle, type AgentPermitSignatures, AgentPermitValidationError, type AgentStateEvidence, type AgentStateFailureReason, type AgentStateReadResult, type AgentWalletStatus, type CreateAgentPermitRequestInput, agentPermitId, createAgentPermitRequest, encodeAgentPermitApproval, encodeAgentPermitFragment, encodeAgentPermitSettlement, evaluateAgentPermit, isAgentPermitAudience, isAgentStateEvidence, normalizeAgentPermitRequest, parseAgentPermitApproval, parseAgentPermitFragment, parseAgentPermitMessage, parseAgentPermitSettlement, precheckAgentPermit, renderAgentPermitMessage, renderAgentPermitPresentation, verifyAgentPermitSignatures };
@@ -0,0 +1,4 @@
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);var agent_permit_exports={};__export(agent_permit_exports,{AGENT_PERMIT_LIMITS:()=>AGENT_PERMIT_LIMITS,AGENT_PERMIT_NETWORK:()=>AGENT_PERMIT_NETWORK,AGENT_PERMIT_NOTICE_LINE:()=>AGENT_PERMIT_NOTICE_LINE,AGENT_PERMIT_PRESENTATION_LINE:()=>AGENT_PERMIT_PRESENTATION_LINE,AGENT_PERMIT_VERSION_LINE:()=>AGENT_PERMIT_VERSION_LINE,AgentPermitValidationError:()=>AgentPermitValidationError,agentPermitId:()=>agentPermitId,createAgentPermitRequest:()=>createAgentPermitRequest,encodeAgentPermitApproval:()=>encodeAgentPermitApproval,encodeAgentPermitFragment:()=>encodeAgentPermitFragment,encodeAgentPermitSettlement:()=>encodeAgentPermitSettlement,evaluateAgentPermit:()=>evaluateAgentPermit,isAgentPermitAudience:()=>isAgentPermitAudience,isAgentStateEvidence:()=>isAgentStateEvidence,normalizeAgentPermitRequest:()=>normalizeAgentPermitRequest,parseAgentPermitApproval:()=>parseAgentPermitApproval,parseAgentPermitFragment:()=>parseAgentPermitFragment,parseAgentPermitMessage:()=>parseAgentPermitMessage,parseAgentPermitSettlement:()=>parseAgentPermitSettlement,precheckAgentPermit:()=>precheckAgentPermit,renderAgentPermitMessage:()=>renderAgentPermitMessage,renderAgentPermitPresentation:()=>renderAgentPermitPresentation,verifyAgentPermitSignatures:()=>verifyAgentPermitSignatures});module.exports=__toCommonJS(agent_permit_exports);var import_ed25519=require("@noble/curves/ed25519"),import_sha2=require("@noble/hashes/sha2");var ALPHABET="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Encode(bytes){let number=0n;for(let byte of bytes)number=number<<8n|BigInt(byte);let text="";for(;number>0n;)text=ALPHABET[Number(number%58n)]+text,number/=58n;let zeros=0;for(;zeros<bytes.length&&bytes[zeros]===0;)zeros++;return"1".repeat(zeros)+text}function base58Decode(text){if(text.length===0)return null;let number=0n;for(let character of text){let digit=ALPHABET.indexOf(character);if(digit<0)return null;number=number*58n+BigInt(digit)}let body=[];for(;number>0n;)body.unshift(Number(number&0xffn)),number>>=8n;let zeros=0;for(;zeros<text.length&&text[zeros]==="1";)zeros++;return Uint8Array.from([...new Array(zeros).fill(0),...body])}function canonicalKeyBytes(text){if(text.length<32||text.length>44)return null;let bytes=base58Decode(text);return!bytes||bytes.length!==32||base58Encode(bytes)!==text?null:bytes}var POLICY_NETWORK=Object.freeze({genesisHash:"EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG",programIds:Object.freeze({anchor:"GZYwTp2ozeuRA5Gof9vs4ya961aANcJBdUzB7LN6q4b2",verifier:"4F97jNoxQzT2qRbkWpW3ztC3Nz2TtKj3rnKG8ExgnrfV",registry:"6VBs3zr9KrfFPGd6j7aGBPQWwZa5tajVfA7HN6MMV9VW",sas:"22zoJMtdu4tQc2PzL74ZUT7FrwgB1Udec8DdW4yw4BdG",credential:"AMBtabCgRFwGLjoZ21Z2LhSKJ6c47NckxUkMogJ3Lpuw",schema:"5LNc7syFW7USPLveVLcNcjjY1xqS7QTXVjHZ7CQCbAMQ"})}),PolicyValidationError=class extends Error{constructor(reason){super(`Invalid verification policy: ${reason}`);this.reason=reason;this.name="PolicyValidationError"}};function record(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function exactKeys(value,keys){return Object.keys(value).length===keys.length&&keys.every(key=>Object.prototype.hasOwnProperty.call(value,key))}function integer(value,minimum=0,maximum=Number.MAX_SAFE_INTEGER){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=minimum&&value<=maximum}var REQUEST_KEYS=["id","version","minTrustScore","maxVerificationAgeSeconds","maxEvaluationAgeSeconds","requiredAssurance","uniquenessRequirement","requireAttestation","cluster"];function normalizePolicyRequest(input,legacyMinTrustScore){if(legacyMinTrustScore!==void 0&&!integer(legacyMinTrustScore,0,1e4))throw new PolicyValidationError("unsupported_policy");let value=input===void 0?{id:"entros-verify-default",version:1,minTrustScore:legacyMinTrustScore??0,maxVerificationAgeSeconds:86400,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",cluster:"devnet"}:input;if(!record(value)||Object.keys(value).some(key=>!REQUEST_KEYS.includes(key)))throw new PolicyValidationError("unsupported_policy");if(value.requiredAssurance!=="browser_unattested")throw new PolicyValidationError("unsupported_assurance");if(value.uniquenessRequirement!=="allow_unmeasured")throw new PolicyValidationError("unsupported_uniqueness");if(typeof value.id!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(value.id)||value.version!==1||!integer(value.minTrustScore,0,1e4)||!integer(value.maxVerificationAgeSeconds,1,31536e3)||!integer(value.maxEvaluationAgeSeconds===void 0?90:value.maxEvaluationAgeSeconds,1,90)||value.requireAttestation!==void 0&&typeof value.requireAttestation!="boolean"||value.cluster!=="devnet"||legacyMinTrustScore!==void 0&&value.minTrustScore!==legacyMinTrustScore)throw new PolicyValidationError("unsupported_policy");return{id:value.id,version:1,minTrustScore:value.minTrustScore,maxVerificationAgeSeconds:value.maxVerificationAgeSeconds,maxEvaluationAgeSeconds:value.maxEvaluationAgeSeconds??90,requiredAssurance:"browser_unattested",uniquenessRequirement:"allow_unmeasured",requireAttestation:value.requireAttestation===!0,cluster:"devnet"}}function encodePolicyRequest(request){return JSON.stringify(normalizePolicyRequest(request))}var BASE58="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function base58Bytes(value,expected){if(typeof value!="string"||value.length<1||value.length>expected*2)return!1;let number=0n;for(let character of value){let digit=BASE58.indexOf(character);if(digit<0)return!1;number=number*58n+BigInt(digit)}let bytes=0;for(;number>0n;)bytes++,number>>=8n;let zeros=0;for(;value[zeros]==="1";)zeros++;return bytes+zeros===expected}function commitment(value){return typeof value=="string"&&/^[0-9a-f]{64}$/.test(value)&&!/^0+$/.test(value)}function isPolicyAttestation(value){return record(value)?value.status==="present"?exactKeys(value,["status","address","readContextSlot","expiresAt"])&&base58Bytes(value.address,32)&&integer(value.readContextSlot)&&(value.expiresAt===null||integer(value.expiresAt,1)):exactKeys(value,["status"])&&["missing","invalid","unavailable"].includes(String(value.status)):!1}function isPolicyEvidence(value){if(!record(value)||!exactKeys(value,["cluster","genesisHash","programIds","assuranceTier","uniquenessStatus","readContextSlot","identity","transaction","attestation"])||value.cluster!=="devnet"||value.genesisHash!==POLICY_NETWORK.genesisHash||value.assuranceTier!=="browser_unattested"||value.uniquenessStatus!=="unmeasured"||!integer(value.readContextSlot))return!1;let programs=value.programIds;if(!record(programs)||!exactKeys(programs,Object.keys(POLICY_NETWORK.programIds))||Object.entries(POLICY_NETWORK.programIds).some(([key,id])=>programs[key]!==id))return!1;let identity=value.identity,transaction=value.transaction;return!record(identity)||!exactKeys(identity,["walletPubkey","identityPda","creationTimestamp","lastVerificationTimestamp","verificationCount","trustScore","currentCommitment","projectionVersion","lastResetTimestamp","lastRebaselineTimestamp","mint"])||!base58Bytes(identity.walletPubkey,32)||!base58Bytes(identity.identityPda,32)||!base58Bytes(identity.mint,32)||!integer(identity.creationTimestamp,1)||!integer(identity.lastVerificationTimestamp,identity.creationTimestamp)||!integer(identity.verificationCount,0,4294967295)||!integer(identity.trustScore,0,1e4)||!commitment(identity.currentCommitment)||!integer(identity.projectionVersion,0,2)||!integer(identity.lastResetTimestamp)||!integer(identity.lastRebaselineTimestamp)||!record(transaction)||!exactKeys(transaction,["signature","slot","blockTime","commitment","kind"])||!base58Bytes(transaction.signature,64)||!integer(transaction.slot)||!integer(transaction.blockTime,identity.creationTimestamp)||!commitment(transaction.commitment)||!["mint","update","rebaseline"].includes(String(transaction.kind))?!1:isPolicyAttestation(value.attestation)}function evaluatePolicy(request,observation,nowSeconds){let requirements=normalizePolicyRequest(request);if(!integer(nowSeconds,1)||nowSeconds>Number.MAX_SAFE_INTEGER-31536e3)throw new PolicyValidationError("invalid_evidence");let base={policyId:requirements.id,policyVersion:1,requirements,evaluatedAt:nowSeconds,expiresAt:nowSeconds,evidenceTimestamp:null,evaluatedAgeSeconds:null};if(record(observation)&&observation.status==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable",evidence:null};if(!record(observation)||observation.status!=="available"||!isPolicyEvidence(observation.evidence))return{...base,decision:"deny",reason:"invalid_evidence",evidence:null};let evidence=observation.evidence,{identity,transaction,attestation}=evidence,deny=reason=>({...base,decision:"deny",reason,evidence}),freshMint=transaction.kind==="mint"&&identity.verificationCount===0&&identity.trustScore===0&&identity.creationTimestamp===transaction.blockTime&&identity.lastVerificationTimestamp===transaction.blockTime&&identity.lastResetTimestamp===0&&identity.lastRebaselineTimestamp===0;return identity.verificationCount===0&&!freshMint||identity.currentCommitment!==transaction.commitment||identity.lastResetTimestamp>=transaction.blockTime||identity.lastResetTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>identity.lastVerificationTimestamp||identity.lastRebaselineTimestamp>transaction.blockTime||identity.lastVerificationTimestamp>nowSeconds||transaction.blockTime>nowSeconds||evidence.readContextSlot<transaction.slot||attestation.status==="invalid"||attestation.status==="present"&&(attestation.readContextSlot<transaction.slot||attestation.expiresAt!==null&&attestation.expiresAt<=nowSeconds)?deny("invalid_evidence"):(base.evidenceTimestamp=Math.min(identity.lastVerificationTimestamp,transaction.blockTime),base.evaluatedAgeSeconds=nowSeconds-base.evidenceTimestamp,base.expiresAt=Math.min(base.evidenceTimestamp+requirements.maxVerificationAgeSeconds,nowSeconds+requirements.maxEvaluationAgeSeconds),requirements.requireAttestation&&attestation.status==="present"&&attestation.expiresAt!==null&&(base.expiresAt=Math.min(base.expiresAt,attestation.expiresAt)),identity.trustScore<requirements.minTrustScore?deny("score_below_minimum"):nowSeconds>=base.expiresAt?deny("verification_stale"):requirements.requireAttestation&&attestation.status==="missing"?deny("attestation_required"):requirements.requireAttestation&&attestation.status==="unavailable"?{...base,decision:"unavailable",reason:"state_unavailable",evidence}:{...base,decision:"allow",reason:"accepted",evidence})}var AGENT_PERMIT_VERSION_LINE="Entros-Agent-Permit-v1",AGENT_PERMIT_NOTICE_LINE="Sign only to let this agent perform the action below. This is not a transaction.",AGENT_PERMIT_PRESENTATION_LINE="Entros-Agent-Permit-Presentation-v1",AGENT_PERMIT_NETWORK=Object.freeze({cluster:"devnet",genesisHash:POLICY_NETWORK.genesisHash,entrosAnchorProgram:POLICY_NETWORK.programIds.anchor,agentRegistryProgram:"8oo4J9tBB3Hna1jRQ3rWvJjojqM5DYTDJo5cejUuJy3C",agentCollection:"6CTyGPcn8dMwKEqgtvx2XCpkGUd7uqCVK6937RSM5bhA",coreProgram:"CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d"}),AGENT_PERMIT_LIMITS=Object.freeze({minLifetimeSeconds:30,maxLifetimeSeconds:900,clockSkewSeconds:30,maxAudienceLength:200,maxLabelLength:96,minTimeSeconds:946684800,maxTimeSeconds:253402300799}),AgentPermitValidationError=class extends Error{constructor(field){super(`Invalid agent permit: ${field}`);this.field=field;this.name="AgentPermitValidationError"}},FIELD_KEYS=["agent","agent_wallet","operator","audience","action","action_sha256","policy","cluster","genesis","entros_anchor","agent_registry","agent_collection","issued_at","expires_at","nonce"],REQUEST_KEYS2=["version","agent","agentWallet","operator","audience","action","policy","cluster","genesisHash","entrosAnchorProgram","agentRegistryProgram","agentCollection","issuedAt","expiresAt","nonce"],HEX64=/^[0-9a-f]{64}$/,HEX128=/^[0-9a-f]{128}$/,TIME=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/,LABEL="(?:[a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])",FINAL="(?:[a-z]|[a-z][a-z0-9-]{0,61}[a-z0-9])",PORT="(?::([1-9][0-9]{0,4}))?",PATH="(/(?:[A-Za-z0-9._~-]+(?:/[A-Za-z0-9._~-]+)*/?)?)",HTTPS_AUDIENCE=new RegExp(`^https://((?:${LABEL}\\.)+${FINAL})${PORT}${PATH}$`),LOOPBACK_AUDIENCE=new RegExp(`^http://(127\\.0\\.0\\.1)${PORT}${PATH}$`),MAX_POLICY_LENGTH=512,encoder=new TextEncoder;function record2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function exactKeys2(value,keys){return Object.keys(value).length===keys.length&&keys.every(key=>Object.prototype.hasOwnProperty.call(value,key))}function integer2(value,minimum,maximum){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=minimum&&value<=maximum}function hexToBytes(value){let bytes=new Uint8Array(value.length/2);for(let index=0;index<bytes.length;index++)bytes[index]=Number.parseInt(value.slice(index*2,index*2+2),16);return bytes}function bytesToHex(bytes){return Array.from(bytes,byte=>byte.toString(16).padStart(2,"0")).join("")}function printable(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<32||code>126)return!1}return!0}function digestHex(value){return typeof value=="string"&&HEX64.test(value)&&!/^0+$/.test(value)}function strictPublicKey(bytes){try{return!import_ed25519.ed25519.Point.fromBytes(bytes,!1).isSmallOrder()}catch{return!1}}function signingKey(value){if(typeof value!="string")return!1;let bytes=canonicalKeyBytes(value);return bytes!==null&&strictPublicKey(bytes)}function address(value){return typeof value=="string"&&canonicalKeyBytes(value)!==null}function isAgentPermitAudience(value){if(typeof value!="string"||value.length>AGENT_PERMIT_LIMITS.maxAudienceLength)return!1;let https=HTTPS_AUDIENCE.exec(value),match=https??LOOPBACK_AUDIENCE.exec(value);if(!match)return!1;let[,host,port,path]=match;if(host===void 0||path===void 0||host.split(".").some(label=>label.length>=4&&label[2]==="-"&&label[3]==="-"))return!1;if(port!==void 0){let number=Number(port);if(number>65535||number===(https?443:80))return!1}return path.split("/").every(segment=>segment!=="."&&segment!=="..")}function actionLabel(value){return typeof value=="string"&&value.length>=1&&value.length<=AGENT_PERMIT_LIMITS.maxLabelLength&&printable(value)&&value===value.trim()}function unixSeconds(value){return integer2(value,AGENT_PERMIT_LIMITS.minTimeSeconds,AGENT_PERMIT_LIMITS.maxTimeSeconds)}function formatTime(seconds){return new Date(seconds*1e3).toISOString().replace(".000Z","Z")}function parseTime(value){if(!TIME.test(value))return null;let milliseconds=Date.parse(value);if(!Number.isFinite(milliseconds)||milliseconds%1e3!==0)return null;let seconds=milliseconds/1e3;return unixSeconds(seconds)&&formatTime(seconds)===value?seconds:null}function policyRequest(value){try{let policy=normalizePolicyRequest(value);return encodePolicyRequest(policy)===JSON.stringify(value)?policy:null}catch{return null}}function normalizeAgentPermitRequest(value){if(!record2(value)||!exactKeys2(value,REQUEST_KEYS2))throw new AgentPermitValidationError("request");let{version,agent,agentWallet,operator,audience,action,issuedAt,expiresAt,nonce}=value;if(version!==1)throw new AgentPermitValidationError("version");if(!address(agent))throw new AgentPermitValidationError("agent");if(!signingKey(agentWallet))throw new AgentPermitValidationError("agentWallet");if(!signingKey(operator))throw new AgentPermitValidationError("operator");if(!isAgentPermitAudience(audience))throw new AgentPermitValidationError("audience");if(!record2(action)||!exactKeys2(action,["label","sha256"])||!actionLabel(action.label)||!digestHex(action.sha256))throw new AgentPermitValidationError("action");let policy=policyRequest(value.policy);if(!policy)throw new AgentPermitValidationError("policy");if(value.cluster!==AGENT_PERMIT_NETWORK.cluster||value.genesisHash!==AGENT_PERMIT_NETWORK.genesisHash||value.entrosAnchorProgram!==AGENT_PERMIT_NETWORK.entrosAnchorProgram||value.agentRegistryProgram!==AGENT_PERMIT_NETWORK.agentRegistryProgram||value.agentCollection!==AGENT_PERMIT_NETWORK.agentCollection)throw new AgentPermitValidationError("deployment");if(!unixSeconds(issuedAt)||!unixSeconds(expiresAt))throw new AgentPermitValidationError("time");let lifetime=expiresAt-issuedAt;if(lifetime<AGENT_PERMIT_LIMITS.minLifetimeSeconds||lifetime>AGENT_PERMIT_LIMITS.maxLifetimeSeconds)throw new AgentPermitValidationError("lifetime");if(!digestHex(nonce))throw new AgentPermitValidationError("nonce");return{version:1,agent,agentWallet,operator,audience,action:{label:action.label,sha256:action.sha256},policy,cluster:AGENT_PERMIT_NETWORK.cluster,genesisHash:AGENT_PERMIT_NETWORK.genesisHash,entrosAnchorProgram:AGENT_PERMIT_NETWORK.entrosAnchorProgram,agentRegistryProgram:AGENT_PERMIT_NETWORK.agentRegistryProgram,agentCollection:AGENT_PERMIT_NETWORK.agentCollection,issuedAt,expiresAt,nonce}}function randomNonce(){let cryptoApi=globalThis.crypto;if(!cryptoApi||typeof cryptoApi.getRandomValues!="function")throw new AgentPermitValidationError("nonce");let bytes=new Uint8Array(32);return cryptoApi.getRandomValues(bytes),bytesToHex(bytes)}function createAgentPermitRequest(input){if(!integer2(input.lifetimeSeconds,1,AGENT_PERMIT_LIMITS.maxLifetimeSeconds))throw new AgentPermitValidationError("lifetime");return normalizeAgentPermitRequest({version:1,agent:input.agent,agentWallet:input.agentWallet,operator:input.operator,audience:input.audience,action:{label:input.action.label,sha256:input.action.sha256},policy:normalizePolicyRequest(input.policy),cluster:AGENT_PERMIT_NETWORK.cluster,genesisHash:AGENT_PERMIT_NETWORK.genesisHash,entrosAnchorProgram:AGENT_PERMIT_NETWORK.entrosAnchorProgram,agentRegistryProgram:AGENT_PERMIT_NETWORK.agentRegistryProgram,agentCollection:AGENT_PERMIT_NETWORK.agentCollection,issuedAt:input.issuedAt,expiresAt:input.issuedAt+input.lifetimeSeconds,nonce:input.nonce??randomNonce()})}function renderNormalized(value){let fields=[value.agent,value.agentWallet,value.operator,value.audience,value.action.label,value.action.sha256,encodePolicyRequest(value.policy),value.cluster,value.genesisHash,value.entrosAnchorProgram,value.agentRegistryProgram,value.agentCollection,formatTime(value.issuedAt),formatTime(value.expiresAt),value.nonce];return[AGENT_PERMIT_VERSION_LINE,AGENT_PERMIT_NOTICE_LINE,...FIELD_KEYS.map((key,index)=>`${key}:${fields[index]}`)].join(`
2
+ `)}function permitIdOf(message){return bytesToHex((0,import_sha2.sha256)(encoder.encode(message)))}function renderAgentPermitMessage(request){return renderNormalized(normalizeAgentPermitRequest(request))}function parseAgentPermitMessage(text){if(typeof text!="string"||text.length>4096)throw new AgentPermitValidationError("message");for(let index=0;index<text.length;index++){let code=text.charCodeAt(index);if(code!==10&&(code<32||code>126))throw new AgentPermitValidationError("message")}let lines=text.split(`
3
+ `);if(lines.length!==FIELD_KEYS.length+2||lines[0]!==AGENT_PERMIT_VERSION_LINE||lines[1]!==AGENT_PERMIT_NOTICE_LINE)throw new AgentPermitValidationError("message");let values=new Map;FIELD_KEYS.forEach((key,index)=>{let line=lines[index+2]??"";if(!line.startsWith(`${key}:`))throw new AgentPermitValidationError(key);values.set(key,line.slice(key.length+1))});let field=key=>values.get(key)??"",policyText=field("policy");if(policyText.length>MAX_POLICY_LENGTH)throw new AgentPermitValidationError("policy");let policy;try{policy=JSON.parse(policyText)}catch{throw new AgentPermitValidationError("policy")}let issuedAt=parseTime(field("issued_at")),expiresAt=parseTime(field("expires_at"));if(issuedAt===null||expiresAt===null)throw new AgentPermitValidationError("time");let request=normalizeAgentPermitRequest({version:1,agent:field("agent"),agentWallet:field("agent_wallet"),operator:field("operator"),audience:field("audience"),action:{label:field("action"),sha256:field("action_sha256")},policy,cluster:field("cluster"),genesisHash:field("genesis"),entrosAnchorProgram:field("entros_anchor"),agentRegistryProgram:field("agent_registry"),agentCollection:field("agent_collection"),issuedAt,expiresAt,nonce:field("nonce")});if(renderNormalized(request)!==text)throw new AgentPermitValidationError("message");return request}function agentPermitId(request){return permitIdOf(renderAgentPermitMessage(request))}function renderAgentPermitPresentation(permitId){if(!HEX64.test(permitId))throw new AgentPermitValidationError("permitId");return`${AGENT_PERMIT_PRESENTATION_LINE}
4
+ permit:${permitId}`}function strictVerify(signature,message,publicKey){if(typeof signature!="string"||!HEX128.test(signature))return!1;let key=canonicalKeyBytes(publicKey);if(!key)return!1;try{return import_ed25519.ed25519.verify(hexToBytes(signature),message,key,{zip215:!1})}catch{return!1}}function verifyNormalized(value,signatures){let message=renderNormalized(value),permitId=permitIdOf(message);return{permitId,operator:strictVerify(signatures.operatorSignature,encoder.encode(message),value.operator),presentation:strictVerify(signatures.presentationSignature,encoder.encode(renderAgentPermitPresentation(permitId)),value.agentWallet)}}function verifyAgentPermitSignatures(request,signatures){let{operator,presentation}=verifyNormalized(normalizeAgentPermitRequest(request),signatures);return{operator,presentation}}function settlementClock(nowSeconds){if(!integer2(nowSeconds,1,AGENT_PERMIT_LIMITS.maxTimeSeconds))throw new AgentPermitValidationError("clock");return nowSeconds}function precheckAgentPermit(input){let now=settlementClock(input.nowSeconds),request;try{request=normalizeAgentPermitRequest(input.request)}catch{return{ok:!1,reason:"invalid_permit",request:null,permitId:null}}let signatures=verifyNormalized(request,input),{permitId}=signatures;return request.issuedAt>now+AGENT_PERMIT_LIMITS.clockSkewSeconds?{ok:!1,reason:"invalid_permit",request,permitId}:now>=request.expiresAt?{ok:!1,reason:"permit_expired",request,permitId}:signatures.operator?signatures.presentation?{ok:!0,request,permitId}:{ok:!1,reason:"invalid_presentation",request,permitId}:{ok:!1,reason:"invalid_signature",request,permitId}}function isAgentStateEvidence(value){if(!record2(value)||!exactKeys2(value,["cluster","genesisHash","coreProgram","agentRegistryProgram","agentCollection","agent","agentAccount","owner","cachedOwner","agentWallet","agentWalletStatus","readContextSlot"])||value.cluster!==AGENT_PERMIT_NETWORK.cluster||value.genesisHash!==AGENT_PERMIT_NETWORK.genesisHash||value.coreProgram!==AGENT_PERMIT_NETWORK.coreProgram||value.agentRegistryProgram!==AGENT_PERMIT_NETWORK.agentRegistryProgram||value.agentCollection!==AGENT_PERMIT_NETWORK.agentCollection||!address(value.agent)||!address(value.agentAccount)||!address(value.owner)||!address(value.cachedOwner)||value.agentWallet!==null&&!address(value.agentWallet)||!integer2(value.readContextSlot,0,Number.MAX_SAFE_INTEGER))return!1;let expected=value.cachedOwner!==value.owner?"stale":value.agentWallet===null?"unbound":"bound";return value.agentWalletStatus===expected}function agentStateReason(reason){return reason==="wrong_cluster"||reason==="agent_missing"||reason==="agent_unregistered"?reason:"agent_invalid"}function evaluateAgentPermit(input){let now=settlementClock(input.nowSeconds),precheck=precheckAgentPermit(input),base={permitId:precheck.permitId,request:precheck.request,evaluatedAt:now,expiresAt:precheck.request?.expiresAt??null,agentState:null,policy:null},deny=reason=>({...base,decision:"deny",reason});if(!precheck.ok)return deny(precheck.reason);let{request}=precheck,state=input.agentState;if(!record2(state))return deny("agent_invalid");if(state.status==="unavailable")return{...base,decision:"unavailable",reason:"agent_unavailable"};if(state.status!=="available")return deny(agentStateReason(state.reason));if(!isAgentStateEvidence(state.evidence)||state.evidence.agent!==request.agent)return deny("agent_invalid");let evidence=state.evidence;if(base.agentState=evidence,evidence.owner!==request.operator)return deny("owner_changed");if(evidence.agentWalletStatus==="stale")return deny("agent_wallet_stale");if(evidence.agentWalletStatus==="unbound")return deny("agent_wallet_unbound");if(evidence.agentWallet!==request.agentWallet)return deny("agent_wallet_changed");let policy;try{policy=evaluatePolicy(request.policy,input.operatorEvidence,now)}catch{return deny("invalid_evidence")}if(base.policy=policy,policy.decision==="unavailable")return{...base,decision:"unavailable",reason:"state_unavailable"};if(policy.decision==="deny"){let reason=policy.reason;return deny(reason==="score_below_minimum"||reason==="verification_stale"||reason==="attestation_required"?reason:"invalid_evidence")}return policy.evidence.identity.walletPubkey!==request.operator?deny("invalid_evidence"):(base.expiresAt=Math.min(request.expiresAt,policy.expiresAt),now>=base.expiresAt?deny("permit_expired"):{...base,decision:"allow",reason:"accepted"})}function transactionSignature(value){if(typeof value!="string"||value.length<64||value.length>88)return!1;let bytes=base58Decode(value);return bytes!==null&&bytes.length===64&&base58Encode(bytes)===value}function jsonRecord(input){let value=input;if(typeof input=="string"){if(input.length>1024)return null;try{value=JSON.parse(input)}catch{return null}}return record2(value)?value:null}function encodeAgentPermitApproval(approval){let value=parseAgentPermitApproval({version:1,...approval});if(!value)throw new AgentPermitValidationError("approval");return JSON.stringify({version:1,permitId:value.permitId,operatorSignature:value.operatorSignature,verifiedTransaction:value.verifiedTransaction})}function parseAgentPermitApproval(input){let value=jsonRecord(input);return!value||!exactKeys2(value,["version","permitId","operatorSignature","verifiedTransaction"])||value.version!==1||typeof value.permitId!="string"||!HEX64.test(value.permitId)||typeof value.operatorSignature!="string"||!HEX128.test(value.operatorSignature)||!transactionSignature(value.verifiedTransaction)?null:{version:1,permitId:value.permitId,operatorSignature:value.operatorSignature,verifiedTransaction:value.verifiedTransaction}}function encodeAgentPermitSettlement(bundle){let value=parseAgentPermitSettlement({version:1,...bundle});if(!value)throw new AgentPermitValidationError("settlement");return JSON.stringify({version:1,nonce:value.nonce,operatorSignature:value.operatorSignature,presentationSignature:value.presentationSignature,verifiedTransaction:value.verifiedTransaction})}function parseAgentPermitSettlement(input){let value=jsonRecord(input);return!value||!exactKeys2(value,["version","nonce","operatorSignature","presentationSignature","verifiedTransaction"])||value.version!==1||!digestHex(value.nonce)||typeof value.operatorSignature!="string"||!HEX128.test(value.operatorSignature)||typeof value.presentationSignature!="string"||!HEX128.test(value.presentationSignature)||!transactionSignature(value.verifiedTransaction)?null:{version:1,nonce:value.nonce,operatorSignature:value.operatorSignature,presentationSignature:value.presentationSignature,verifiedTransaction:value.verifiedTransaction}}function base64UrlEncode(text){return btoa(text).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function base64UrlDecode(value){if(!/^[A-Za-z0-9_-]*$/.test(value)||value.length%4===1)return null;try{let padded=value.replace(/-/g,"+").replace(/_/g,"/");return atob(padded+"=".repeat((4-padded.length%4)%4))}catch{return null}}function encodeAgentPermitFragment(request){return`request=${base64UrlEncode(renderAgentPermitMessage(request))}`}function parseAgentPermitFragment(fragment){let body=fragment.startsWith("#")?fragment.slice(1):fragment;if(!body.startsWith("request=")||body.length>8192)return null;let message=base64UrlDecode(body.slice(8));if(message===null)return null;try{return{request:parseAgentPermitMessage(message),message}}catch{return null}}0&&(module.exports={AGENT_PERMIT_LIMITS,AGENT_PERMIT_NETWORK,AGENT_PERMIT_NOTICE_LINE,AGENT_PERMIT_PRESENTATION_LINE,AGENT_PERMIT_VERSION_LINE,AgentPermitValidationError,agentPermitId,createAgentPermitRequest,encodeAgentPermitApproval,encodeAgentPermitFragment,encodeAgentPermitSettlement,evaluateAgentPermit,isAgentPermitAudience,isAgentStateEvidence,normalizeAgentPermitRequest,parseAgentPermitApproval,parseAgentPermitFragment,parseAgentPermitMessage,parseAgentPermitSettlement,precheckAgentPermit,renderAgentPermitMessage,renderAgentPermitPresentation,verifyAgentPermitSignatures});