@sonordev/contracts 2.26.0 → 2.28.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.
@@ -0,0 +1,238 @@
1
+ /**
2
+ * The wire contract of the emailed confirmation code behind a Resonance budget approved on a person's word: the routes, the request bodies, the answers,
3
+ * the evidence the Ledger keeps, and the refusals with their HTTP statuses.
4
+ *
5
+ * The flow:
6
+ * 1. The agent asks for a code for a draft: POST {request} body = the mandate draft request the agent will file with -> ConfirmationReceipt
7
+ * The server builds the draft itself, emails the code to the person's VERIFIED login address, and answers where it went. The code is never in an answer.
8
+ * 2. The person reads the code back in chat.
9
+ * 3. The agent files the ledger request, then redeems: POST {redeem} body = ConfirmationRedeemRequest -> ConfirmationRedeemed
10
+ * Single use, bound to that request. The agent stores ConfirmationRedeemed.confirmation in the evidence (OnTheirWordEvidence), never the code.
11
+ * 4. The Ledger asks the origin preview with the evidence BEFORE it claims (a call made with the Ledger's service key, not the agent's token), and accept_version asks the same SQL
12
+ * predicate again.
13
+ * Steps 1 and 3 are made with the AGENT's own session token, never a service key. The code goes only to the person's verified login email, never to an address Sonor reads for automation,
14
+ * and its mail carries the marker below so every read path leaves it out.
15
+ */
16
+ export declare const CONFIRMATION_CODE_DIGITS = 6;
17
+ export declare const CONFIRMATION_MINUTES = 10;
18
+ export declare const CONFIRMATION_MAX_TRIES = 5;
19
+ /** At most this many codes a person is sent an hour for one project... */
20
+ export declare const CONFIRMATION_PER_HOUR = 3;
21
+ /** ...this many an hour across ALL projects... */
22
+ export declare const CONFIRMATION_PER_HOUR_ANY_PROJECT = 6;
23
+ /** ...and this many a day across all projects. A guess budget an agent can not widen by changing project. */
24
+ export declare const CONFIRMATION_PER_DAY = 15;
25
+ /** Nothing is minted when the prepared plan has less than this left: a code could not be used in time. */
26
+ export declare const CONFIRMATION_MIN_PLAN_MINUTES = 2;
27
+ /** A person whose agent has had this many codes locked (five wrong tries each, never redeemed) in the last day is sent no new code until the third-newest of them is a day old... */
28
+ export declare const CONFIRMATION_LOCKS_PER_DAY = 3;
29
+ /** ...and the longest wait any refusal names, in seconds: the lockout and the daily limit are both a day. A `retryAfterSeconds` above this is not the server's. */
30
+ export declare const CONFIRMATION_RETRY_MAX_SECONDS = 86400;
31
+ /** The marker the issue RPC requires in its command. Only a build that emails the verified login address and filters what it reads sends it; an older build is refused before anything is minted. */
32
+ export declare const CONFIRMATION_CONTRACT: 'resonance-confirmation/1';
33
+ /** Where the person said yes. */
34
+ export declare const ON_THEIR_WORD_CHANNEL: 'mcp_chat';
35
+ /** How the code reached them. */
36
+ export declare const ON_THEIR_WORD_CONFIRMATION_CHANNEL: 'email';
37
+ /** The longest quote: quote-screen.ts's cap. */
38
+ export declare const ON_THEIR_WORD_QUOTE_MAX = 1000;
39
+ export declare const CONFIRMATION_REQUEST_ROUTE = "campaigns/:campaignId/plans/:planId/mandate-confirmation";
40
+ export declare const CONFIRMATION_REDEEM_ROUTE = "campaigns/:campaignId/mandate-confirmation/redeem";
41
+ /** The request path with its ids filled in. */
42
+ export declare function confirmationRequestPath(projectId: string, campaignId: string, planId: string): string;
43
+ export declare function confirmationRedeemPath(projectId: string, campaignId: string): string;
44
+ /** In every confirmation email's subject, so a mailbox reader can recognise it and leave it out. */
45
+ export declare const CONFIRMATION_MAIL_SUBJECT_TAG = "[Sonor budget confirmation]";
46
+ /** The header the email carries; its value is CONFIRMATION_MAIL_HEADER_VALUE. */
47
+ export declare const CONFIRMATION_MAIL_HEADER = "X-Sonor-Confirmation";
48
+ export declare const CONFIRMATION_MAIL_HEADER_VALUE = "resonance-mandate";
49
+ /**
50
+ * Whether a message is a confirmation email: its subject carries the tag, or it carries the header. Every place Sonor reads mail for a person or an automation (a connected
51
+ * mailbox, an outreach mailbox, an inbound route) leaves such a message out, so an agent can never read a code from a mailbox it can reach.
52
+ */
53
+ export declare function isConfirmationMail(message: {
54
+ subject?: string | null;
55
+ headers?: Record<string, string | string[] | undefined> | Array<{
56
+ name?: string | null;
57
+ value?: string | null;
58
+ }> | null;
59
+ }): boolean;
60
+ /** A body or answer that isn't the contract's. `failure` says which refusal it is (invalid_request or invalid_code for a request; unavailable for an answer the server shouldn't have sent). */
61
+ export declare class ConfirmationContractError extends Error {
62
+ readonly failure: ConfirmationFailure;
63
+ constructor(message: string, failure?: ConfirmationFailure);
64
+ }
65
+ /** What a person typed as the code: six digits, with the spaces, hyphens and dots people add when they read one out loud taken off. Null for anything else. */
66
+ export declare function readConfirmationCode(typed: unknown): string | null;
67
+ export interface ConfirmationRedeemRequest {
68
+ confirmationId: string;
69
+ /** The ledger request the agent filed for this draft. */
70
+ ledgerActionId: string;
71
+ /** The six digits, as the person read them. */
72
+ code: string;
73
+ }
74
+ /** The redeem body: exactly these three keys, the ids as uuids and the code as six digits (what a person typed is cleaned by readConfirmationCode). */
75
+ export declare function parseConfirmationRedeemRequest(raw: unknown): ConfirmationRedeemRequest;
76
+ export interface ConfirmationReceipt {
77
+ confirmationId: string;
78
+ channel: typeof ON_THEIR_WORD_CONFIRMATION_CHANNEL;
79
+ /** The address the code went to, masked by the server ("p***@example.com"). */
80
+ sentTo: string;
81
+ /** The real deadline: the shorter of ten minutes and the prepared plan's own expiry. Say THIS to the person, not "ten minutes". */
82
+ expiresAt: string;
83
+ /** Whole minutes from the send to `expiresAt` (at least 2, at most 10). */
84
+ minutes: number;
85
+ triesAllowed: number;
86
+ }
87
+ /** The answer to a request for a code. Picks the six fields it knows, so anything else the server said (a code, if it ever did) goes no further. */
88
+ export declare function parseConfirmationReceipt(raw: unknown): ConfirmationReceipt;
89
+ export interface ConfirmationRedeemed {
90
+ confirmation: {
91
+ id: string;
92
+ channel: typeof ON_THEIR_WORD_CONFIRMATION_CHANNEL;
93
+ };
94
+ }
95
+ /** The answer to a redeem: the confirmation to keep in the evidence, its id and channel and nothing else. */
96
+ export declare function parseConfirmationRedeemed(raw: unknown): ConfirmationRedeemed;
97
+ export interface OnTheirWordEvidence {
98
+ /** contacts.id of the agent that took the word and filed the request (created_by is `agent:<this>`). */
99
+ agent: string;
100
+ /** The person's own words, as they said them. */
101
+ quote: string;
102
+ /** The digest of the exact mandate they were shown. */
103
+ mandate_digest: string;
104
+ /** The digest of the exact reviewed plan that mandate belongs to. */
105
+ review_digest: string;
106
+ channel: typeof ON_THEIR_WORD_CHANNEL;
107
+ /** The emailed code that was redeemed for this request: its id, never the code. */
108
+ confirmation: {
109
+ id: string;
110
+ channel: typeof ON_THEIR_WORD_CONFIRMATION_CHANNEL;
111
+ };
112
+ }
113
+ export declare const ON_THEIR_WORD_EVIDENCE_KEYS: readonly ['agent', 'quote', 'mandate_digest', 'review_digest', 'channel', 'confirmation'];
114
+ /**
115
+ * The evidence as a row stores it, or null when it is missing or anything but exactly this shape. The SHAPE only: the quote's length and form (a word in it, no control character,
116
+ * not padded) but NOT its content. The secret screen runs once, at intake (quote-screen.ts refuseQuote); stored evidence is never screened again, so a screen tightened later
117
+ * cannot strand a row that is already claimed.
118
+ */
119
+ export declare function parseOnTheirWordEvidence(value: unknown): OnTheirWordEvidence | null;
120
+ /** What a caller does with a refusal. */
121
+ export type ConfirmationFailure = 'invalid_request' | 'invalid_code' | 'quote_too_long' | 'quote_has_secret' | 'refused' | 'not_allowed' | 'locked' | 'wrong_code' | 'expired' | 'used' | 'no_verified_email' | 'mailbox_automated' | 'rate_limited' | 'rate_limited_daily' | 'person_locked' | 'send_failed' | 'plan_expiring' | 'unavailable';
122
+ /** The code a refusal carries (`code` in the error body, with the RESONANCE_ prefix), its HTTP status and the words a person or an agent reads. */
123
+ export declare const CONFIRMATION_REFUSALS: {
124
+ readonly RESONANCE_CONFIRMATION_COMMAND: {
125
+ readonly status: 400;
126
+ readonly failure: 'invalid_request';
127
+ readonly message: 'That confirmation request was malformed. Ask for a new code.';
128
+ };
129
+ readonly RESONANCE_INVALID_CONFIRMATION: {
130
+ readonly status: 400;
131
+ readonly failure: 'invalid_request';
132
+ readonly message: 'Pass the confirmation id, the ledger request it is for, and the six-digit code the person read back.';
133
+ };
134
+ readonly RESONANCE_INVALID_CONFIRMATION_CODE: {
135
+ readonly status: 400;
136
+ readonly failure: 'invalid_code';
137
+ readonly message: 'The code is six digits. Ask the person to read it back from the email.';
138
+ };
139
+ readonly RESONANCE_QUOTE_TOO_LONG: {
140
+ readonly status: 400;
141
+ readonly failure: 'quote_too_long';
142
+ readonly message: 'Pass only the sentence where they said yes, in 1,000 characters or fewer.';
143
+ };
144
+ readonly RESONANCE_QUOTE_HAS_SECRET: {
145
+ readonly status: 400;
146
+ readonly failure: 'quote_has_secret';
147
+ readonly message: 'That quote looks like it holds a key, password or card number. Pass only the sentence where they said yes, without it.';
148
+ };
149
+ readonly RESONANCE_CONFIRMATION_REFUSED: {
150
+ readonly status: 403;
151
+ readonly failure: 'refused';
152
+ readonly message: "That code can't be used for this budget. Ask for a new one.";
153
+ };
154
+ readonly RESONANCE_CONFIRMATION_STANDING: {
155
+ readonly status: 403;
156
+ readonly failure: 'not_allowed';
157
+ readonly message: 'Only an owner or admin who can approve this budget can be asked to confirm it.';
158
+ };
159
+ readonly RESONANCE_CONFIRMATION_AGENT: {
160
+ readonly status: 403;
161
+ readonly failure: 'not_allowed';
162
+ readonly message: "This agent wasn't set up by the person it acts for. They need to create their own agent token in Sonor first.";
163
+ };
164
+ readonly RESONANCE_CONFIRMATION_LOCKED: {
165
+ readonly status: 403;
166
+ readonly failure: 'locked';
167
+ readonly message: 'Too many wrong tries. Ask for a new code.';
168
+ };
169
+ readonly RESONANCE_CONFIRMATION_WRONG_CODE: {
170
+ readonly status: 403;
171
+ readonly failure: 'wrong_code';
172
+ readonly message: "That's not the code.";
173
+ };
174
+ readonly RESONANCE_CONFIRMATION_EXPIRED: {
175
+ readonly status: 409;
176
+ readonly failure: 'expired';
177
+ readonly message: 'That code has expired. Ask for a new one.';
178
+ };
179
+ readonly RESONANCE_CONFIRMATION_USED: {
180
+ readonly status: 409;
181
+ readonly failure: 'used';
182
+ readonly message: 'That code was already used for another budget. Ask for a new one.';
183
+ };
184
+ readonly RESONANCE_CONFIRMATION_NO_VERIFIED_EMAIL: {
185
+ readonly status: 409;
186
+ readonly failure: 'no_verified_email';
187
+ readonly message: "This person has no verified login email in Sonor, so a code can't be sent. They can approve the budget in Sonor instead.";
188
+ };
189
+ readonly RESONANCE_CONFIRMATION_MAILBOX_AUTOMATED: {
190
+ readonly status: 409;
191
+ readonly failure: 'mailbox_automated';
192
+ readonly message: "This person's login email is a mailbox Sonor reads for automation, so a code can't be sent there. They can approve the budget in Sonor instead.";
193
+ };
194
+ readonly RESONANCE_CONFIRMATION_PLAN_EXPIRING: {
195
+ readonly status: 409;
196
+ readonly failure: 'plan_expiring';
197
+ readonly message: 'The prepared plan is about to expire, so a code could not be used in time. Prepare the plan again, then ask for a code.';
198
+ };
199
+ readonly RESONANCE_CONFIRMATION_RATE: {
200
+ readonly status: 429;
201
+ readonly failure: 'rate_limited';
202
+ readonly message: 'Too many confirmation emails for this person. Try again in an hour, or approve the budget in Sonor.';
203
+ };
204
+ readonly RESONANCE_CONFIRMATION_RATE_HOURLY: {
205
+ readonly status: 429;
206
+ readonly failure: 'rate_limited';
207
+ readonly message: 'Too many confirmation emails for this person in the last hour. Ask again later, or approve the budget in Sonor.';
208
+ };
209
+ readonly RESONANCE_CONFIRMATION_RATE_DAILY: {
210
+ readonly status: 429;
211
+ readonly failure: 'rate_limited_daily';
212
+ readonly message: 'Too many confirmation emails for this person today. Ask again later, or approve the budget in Sonor.';
213
+ };
214
+ readonly RESONANCE_CONFIRMATION_PERSON_LOCKED: {
215
+ readonly status: 429;
216
+ readonly failure: 'person_locked';
217
+ readonly message: "Several of this person's codes were locked by wrong tries today, so no new code will be sent for now. They can approve the budget in Sonor.";
218
+ };
219
+ readonly RESONANCE_CONFIRMATION_EMAIL_FAILED: {
220
+ readonly status: 503;
221
+ readonly failure: 'send_failed';
222
+ readonly message: "We couldn't send the code by email, so no code is active. Try again in a moment, or have the person approve the budget in Sonor.";
223
+ };
224
+ };
225
+ export type ConfirmationRefusalCode = keyof typeof CONFIRMATION_REFUSALS;
226
+ /** How long a refusal says to wait, in words a person reads ("about 12 minutes"). Rounded UP, so a person is never told sooner than it is true; a missing or unreadable wait is "a while". */
227
+ export declare function confirmationWaitWords(seconds: number | null | undefined): string;
228
+ /**
229
+ * What a failed call means. Reads the refusal's `code` (the server's global filter nests the body under `error`) and, failing that, the status: a refusal it doesn't recognise is
230
+ * "unavailable", which approves nothing. `attemptsLeft` rides along on a wrong code only, and `retryAfterSeconds` on the three 429 refusals that can name a wait (hourly, daily and person_locked),
231
+ * both under `data` (the one field the filter forwards: `error.data.attemptsLeft`, `error.data.retryAfterSeconds`). A wrong code with no tries left is the lockout, so it reads as `locked`.
232
+ */
233
+ export declare function confirmationFailureOf(status: number | null | undefined, body: unknown): {
234
+ failure: ConfirmationFailure;
235
+ attemptsLeft: number | null;
236
+ code: ConfirmationRefusalCode | null;
237
+ retryAfterSeconds: number | null;
238
+ };
@@ -0,0 +1,163 @@
1
+ 'use strict';
2
+
3
+ // src/contracts/quote-screen.ts
4
+ var QUOTE_MAX_LENGTH = 1e3;
5
+
6
+ // src/contracts/resonance-confirmation.ts
7
+ var CONFIRMATION_CODE_DIGITS = 6;
8
+ var CONFIRMATION_MINUTES = 10;
9
+ var CONFIRMATION_MAX_TRIES = 5;
10
+ var CONFIRMATION_PER_HOUR = 3;
11
+ var CONFIRMATION_PER_HOUR_ANY_PROJECT = 6;
12
+ var CONFIRMATION_PER_DAY = 15;
13
+ var CONFIRMATION_MIN_PLAN_MINUTES = 2;
14
+ var CONFIRMATION_LOCKS_PER_DAY = 3;
15
+ var CONFIRMATION_RETRY_MAX_SECONDS = 86400;
16
+ var CONFIRMATION_CONTRACT = "resonance-confirmation/1";
17
+ var ON_THEIR_WORD_CHANNEL = "mcp_chat";
18
+ var ON_THEIR_WORD_CONFIRMATION_CHANNEL = "email";
19
+ var ON_THEIR_WORD_QUOTE_MAX = QUOTE_MAX_LENGTH;
20
+ var CONFIRMATION_REQUEST_ROUTE = "campaigns/:campaignId/plans/:planId/mandate-confirmation";
21
+ var CONFIRMATION_REDEEM_ROUTE = "campaigns/:campaignId/mandate-confirmation/redeem";
22
+ function confirmationRequestPath(projectId, campaignId, planId) {
23
+ return `resonance/projects/${projectId}/campaigns/${campaignId}/plans/${planId}/mandate-confirmation`;
24
+ }
25
+ function confirmationRedeemPath(projectId, campaignId) {
26
+ return `resonance/projects/${projectId}/campaigns/${campaignId}/mandate-confirmation/redeem`;
27
+ }
28
+ var CONFIRMATION_MAIL_SUBJECT_TAG = "[Sonor budget confirmation]";
29
+ var CONFIRMATION_MAIL_HEADER = "X-Sonor-Confirmation";
30
+ var CONFIRMATION_MAIL_HEADER_VALUE = "resonance-mandate";
31
+ function isConfirmationMail(message) {
32
+ if (typeof message.subject === "string" && message.subject.includes(CONFIRMATION_MAIL_SUBJECT_TAG)) return true;
33
+ const headers = message.headers;
34
+ if (!headers) return false;
35
+ const wanted = CONFIRMATION_MAIL_HEADER.toLowerCase();
36
+ if (Array.isArray(headers)) return headers.some((h) => typeof h?.name === "string" && h.name.toLowerCase() === wanted && h.value === CONFIRMATION_MAIL_HEADER_VALUE);
37
+ return Object.entries(headers).some(([name, value]) => name.toLowerCase() === wanted && (Array.isArray(value) ? value.includes(CONFIRMATION_MAIL_HEADER_VALUE) : value === CONFIRMATION_MAIL_HEADER_VALUE));
38
+ }
39
+ var ConfirmationContractError = class extends Error {
40
+ constructor(message, failure = "invalid_request") {
41
+ super(message);
42
+ this.name = "ConfirmationContractError";
43
+ this.failure = failure;
44
+ }
45
+ };
46
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
47
+ var isUuid = (value) => typeof value === "string" && UUID.test(value);
48
+ var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
49
+ function readConfirmationCode(typed) {
50
+ if (typeof typed !== "string" || typed.length > 32) return null;
51
+ const code = typed.replace(/[\s.\-–—]/g, "");
52
+ return new RegExp(`^\\d{${CONFIRMATION_CODE_DIGITS}}$`).test(code) ? code : null;
53
+ }
54
+ function parseConfirmationRedeemRequest(raw) {
55
+ if (!isRecord(raw) || Object.keys(raw).some((key) => !["confirmationId", "ledgerActionId", "code"].includes(key)) || !isUuid(raw.confirmationId) || !isUuid(raw.ledgerActionId)) {
56
+ throw new ConfirmationContractError("Pass the confirmation id, the ledger request it is for, and the six-digit code the person read back.");
57
+ }
58
+ const code = readConfirmationCode(raw.code);
59
+ if (code === null) throw new ConfirmationContractError("The code is six digits. Ask the person to read it back from the email.", "invalid_code");
60
+ return { confirmationId: raw.confirmationId.toLowerCase(), ledgerActionId: raw.ledgerActionId.toLowerCase(), code };
61
+ }
62
+ function parseConfirmationReceipt(raw) {
63
+ if (!isRecord(raw)) throw new ConfirmationContractError("The confirmation receipt is not an object.", "unavailable");
64
+ const { confirmationId, channel, sentTo, expiresAt, minutes, triesAllowed } = raw;
65
+ if (!isUuid(confirmationId) || channel !== ON_THEIR_WORD_CONFIRMATION_CHANNEL || typeof sentTo !== "string" || !/^[^\s@]{1,64}@[^\s@]{1,120}$/.test(sentTo) || typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || !Number.isSafeInteger(minutes) || minutes < 1 || minutes > 60 || !Number.isSafeInteger(triesAllowed) || triesAllowed < 1 || triesAllowed > 10) {
66
+ throw new ConfirmationContractError("The confirmation receipt is not the one the server sends.", "unavailable");
67
+ }
68
+ return { confirmationId: confirmationId.toLowerCase(), channel, sentTo, expiresAt, minutes, triesAllowed };
69
+ }
70
+ function parseConfirmationRedeemed(raw) {
71
+ const c = isRecord(raw) ? raw.confirmation : null;
72
+ if (!isRecord(c) || !isUuid(c.id) || c.channel !== ON_THEIR_WORD_CONFIRMATION_CHANNEL) throw new ConfirmationContractError("That is not a redeemed confirmation.", "unavailable");
73
+ return { confirmation: { id: c.id.toLowerCase(), channel: ON_THEIR_WORD_CONFIRMATION_CHANNEL } };
74
+ }
75
+ var ON_THEIR_WORD_EVIDENCE_KEYS = ["agent", "quote", "mandate_digest", "review_digest", "channel", "confirmation"];
76
+ var DIGEST = /^[a-f0-9]{64}$/;
77
+ var CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
78
+ function parseOnTheirWordEvidence(value) {
79
+ if (!isRecord(value) || Object.keys(value).length !== ON_THEIR_WORD_EVIDENCE_KEYS.length) return null;
80
+ const { agent, quote, mandate_digest: mandate, review_digest: review, channel, confirmation } = value;
81
+ if (channel !== ON_THEIR_WORD_CHANNEL || typeof agent !== "string" || !isUuid(agent) || agent !== agent.toLowerCase() || typeof quote !== "string" || CONTROL.test(quote) || quote !== quote.trim() || quote.length > ON_THEIR_WORD_QUOTE_MAX || !/[\p{L}\p{N}]/u.test(quote) || typeof mandate !== "string" || !DIGEST.test(mandate) || typeof review !== "string" || !DIGEST.test(review)) return null;
82
+ if (!isRecord(confirmation) || Object.keys(confirmation).length !== 2 || !isUuid(confirmation.id) || confirmation.id !== confirmation.id.toLowerCase() || confirmation.channel !== ON_THEIR_WORD_CONFIRMATION_CHANNEL) return null;
83
+ return { agent, quote, mandate_digest: mandate, review_digest: review, channel, confirmation: { id: confirmation.id, channel: ON_THEIR_WORD_CONFIRMATION_CHANNEL } };
84
+ }
85
+ var CONFIRMATION_REFUSALS = {
86
+ RESONANCE_CONFIRMATION_COMMAND: { status: 400, failure: "invalid_request", message: "That confirmation request was malformed. Ask for a new code." },
87
+ RESONANCE_INVALID_CONFIRMATION: { status: 400, failure: "invalid_request", message: "Pass the confirmation id, the ledger request it is for, and the six-digit code the person read back." },
88
+ RESONANCE_INVALID_CONFIRMATION_CODE: { status: 400, failure: "invalid_code", message: "The code is six digits. Ask the person to read it back from the email." },
89
+ RESONANCE_QUOTE_TOO_LONG: { status: 400, failure: "quote_too_long", message: "Pass only the sentence where they said yes, in 1,000 characters or fewer." },
90
+ RESONANCE_QUOTE_HAS_SECRET: { status: 400, failure: "quote_has_secret", message: "That quote looks like it holds a key, password or card number. Pass only the sentence where they said yes, without it." },
91
+ RESONANCE_CONFIRMATION_REFUSED: { status: 403, failure: "refused", message: "That code can't be used for this budget. Ask for a new one." },
92
+ RESONANCE_CONFIRMATION_STANDING: { status: 403, failure: "not_allowed", message: "Only an owner or admin who can approve this budget can be asked to confirm it." },
93
+ RESONANCE_CONFIRMATION_AGENT: { status: 403, failure: "not_allowed", message: "This agent wasn't set up by the person it acts for. They need to create their own agent token in Sonor first." },
94
+ RESONANCE_CONFIRMATION_LOCKED: { status: 403, failure: "locked", message: "Too many wrong tries. Ask for a new code." },
95
+ RESONANCE_CONFIRMATION_WRONG_CODE: { status: 403, failure: "wrong_code", message: "That's not the code." },
96
+ RESONANCE_CONFIRMATION_EXPIRED: { status: 409, failure: "expired", message: "That code has expired. Ask for a new one." },
97
+ RESONANCE_CONFIRMATION_USED: { status: 409, failure: "used", message: "That code was already used for another budget. Ask for a new one." },
98
+ RESONANCE_CONFIRMATION_NO_VERIFIED_EMAIL: { status: 409, failure: "no_verified_email", message: "This person has no verified login email in Sonor, so a code can't be sent. They can approve the budget in Sonor instead." },
99
+ RESONANCE_CONFIRMATION_MAILBOX_AUTOMATED: { status: 409, failure: "mailbox_automated", message: "This person's login email is a mailbox Sonor reads for automation, so a code can't be sent there. They can approve the budget in Sonor instead." },
100
+ RESONANCE_CONFIRMATION_PLAN_EXPIRING: { status: 409, failure: "plan_expiring", message: "The prepared plan is about to expire, so a code could not be used in time. Prepare the plan again, then ask for a code." },
101
+ // The one limit the first version of the confirmation SQL answers with. The lockout version replaces it with the hourly and daily answers below; it stays here so
102
+ // a build of this table still reads the older SQL during the window between the two, and an older reader still takes any of the three as a 429.
103
+ RESONANCE_CONFIRMATION_RATE: { status: 429, failure: "rate_limited", message: "Too many confirmation emails for this person. Try again in an hour, or approve the budget in Sonor." },
104
+ RESONANCE_CONFIRMATION_RATE_HOURLY: { status: 429, failure: "rate_limited", message: "Too many confirmation emails for this person in the last hour. Ask again later, or approve the budget in Sonor." },
105
+ RESONANCE_CONFIRMATION_RATE_DAILY: { status: 429, failure: "rate_limited_daily", message: "Too many confirmation emails for this person today. Ask again later, or approve the budget in Sonor." },
106
+ RESONANCE_CONFIRMATION_PERSON_LOCKED: { status: 429, failure: "person_locked", message: "Several of this person's codes were locked by wrong tries today, so no new code will be sent for now. They can approve the budget in Sonor." },
107
+ RESONANCE_CONFIRMATION_EMAIL_FAILED: { status: 503, failure: "send_failed", message: "We couldn't send the code by email, so no code is active. Try again in a moment, or have the person approve the budget in Sonor." }
108
+ };
109
+ function confirmationWaitWords(seconds) {
110
+ if (typeof seconds !== "number" || !Number.isSafeInteger(seconds) || seconds < 1) return "a while";
111
+ const minutes = Math.ceil(seconds / 60);
112
+ if (minutes <= 1) return "a minute";
113
+ if (minutes < 60) return `about ${minutes} minutes`;
114
+ const hours = Math.ceil(minutes / 60);
115
+ return hours === 1 ? "about an hour" : `about ${hours} hours`;
116
+ }
117
+ function confirmationFailureOf(status, body) {
118
+ const record = isRecord(body) ? body : {};
119
+ const inner = isRecord(record.error) ? record.error : record;
120
+ const code = typeof inner.code === "string" ? inner.code : "";
121
+ const known = Object.prototype.hasOwnProperty.call(CONFIRMATION_REFUSALS, code) ? code : null;
122
+ const data = isRecord(inner.data) ? inner.data : {};
123
+ const left = data.attemptsLeft;
124
+ const attemptsLeft = known === "RESONANCE_CONFIRMATION_WRONG_CODE" && Number.isSafeInteger(left) && left >= 0 && left <= CONFIRMATION_MAX_TRIES ? left : null;
125
+ const wait = data.retryAfterSeconds;
126
+ const retryAfterSeconds = (known === "RESONANCE_CONFIRMATION_RATE_HOURLY" || known === "RESONANCE_CONFIRMATION_RATE_DAILY" || known === "RESONANCE_CONFIRMATION_PERSON_LOCKED") && Number.isSafeInteger(wait) && wait >= 1 && wait <= CONFIRMATION_RETRY_MAX_SECONDS ? wait : null;
127
+ if (known === "RESONANCE_CONFIRMATION_WRONG_CODE" && attemptsLeft === 0) return { failure: "locked", attemptsLeft: 0, code: known, retryAfterSeconds: null };
128
+ if (known) return { failure: CONFIRMATION_REFUSALS[known].failure, attemptsLeft, code: known, retryAfterSeconds };
129
+ if (status === 429) return { failure: "rate_limited", attemptsLeft: null, code: null, retryAfterSeconds: null };
130
+ return { failure: "unavailable", attemptsLeft: null, code: null, retryAfterSeconds: null };
131
+ }
132
+
133
+ exports.CONFIRMATION_CODE_DIGITS = CONFIRMATION_CODE_DIGITS;
134
+ exports.CONFIRMATION_CONTRACT = CONFIRMATION_CONTRACT;
135
+ exports.CONFIRMATION_LOCKS_PER_DAY = CONFIRMATION_LOCKS_PER_DAY;
136
+ exports.CONFIRMATION_MAIL_HEADER = CONFIRMATION_MAIL_HEADER;
137
+ exports.CONFIRMATION_MAIL_HEADER_VALUE = CONFIRMATION_MAIL_HEADER_VALUE;
138
+ exports.CONFIRMATION_MAIL_SUBJECT_TAG = CONFIRMATION_MAIL_SUBJECT_TAG;
139
+ exports.CONFIRMATION_MAX_TRIES = CONFIRMATION_MAX_TRIES;
140
+ exports.CONFIRMATION_MINUTES = CONFIRMATION_MINUTES;
141
+ exports.CONFIRMATION_MIN_PLAN_MINUTES = CONFIRMATION_MIN_PLAN_MINUTES;
142
+ exports.CONFIRMATION_PER_DAY = CONFIRMATION_PER_DAY;
143
+ exports.CONFIRMATION_PER_HOUR = CONFIRMATION_PER_HOUR;
144
+ exports.CONFIRMATION_PER_HOUR_ANY_PROJECT = CONFIRMATION_PER_HOUR_ANY_PROJECT;
145
+ exports.CONFIRMATION_REDEEM_ROUTE = CONFIRMATION_REDEEM_ROUTE;
146
+ exports.CONFIRMATION_REFUSALS = CONFIRMATION_REFUSALS;
147
+ exports.CONFIRMATION_REQUEST_ROUTE = CONFIRMATION_REQUEST_ROUTE;
148
+ exports.CONFIRMATION_RETRY_MAX_SECONDS = CONFIRMATION_RETRY_MAX_SECONDS;
149
+ exports.ConfirmationContractError = ConfirmationContractError;
150
+ exports.ON_THEIR_WORD_CHANNEL = ON_THEIR_WORD_CHANNEL;
151
+ exports.ON_THEIR_WORD_CONFIRMATION_CHANNEL = ON_THEIR_WORD_CONFIRMATION_CHANNEL;
152
+ exports.ON_THEIR_WORD_EVIDENCE_KEYS = ON_THEIR_WORD_EVIDENCE_KEYS;
153
+ exports.ON_THEIR_WORD_QUOTE_MAX = ON_THEIR_WORD_QUOTE_MAX;
154
+ exports.confirmationFailureOf = confirmationFailureOf;
155
+ exports.confirmationRedeemPath = confirmationRedeemPath;
156
+ exports.confirmationRequestPath = confirmationRequestPath;
157
+ exports.confirmationWaitWords = confirmationWaitWords;
158
+ exports.isConfirmationMail = isConfirmationMail;
159
+ exports.parseConfirmationReceipt = parseConfirmationReceipt;
160
+ exports.parseConfirmationRedeemRequest = parseConfirmationRedeemRequest;
161
+ exports.parseConfirmationRedeemed = parseConfirmationRedeemed;
162
+ exports.parseOnTheirWordEvidence = parseOnTheirWordEvidence;
163
+ exports.readConfirmationCode = readConfirmationCode;
@@ -0,0 +1,131 @@
1
+ // src/contracts/quote-screen.ts
2
+ var QUOTE_MAX_LENGTH = 1e3;
3
+
4
+ // src/contracts/resonance-confirmation.ts
5
+ var CONFIRMATION_CODE_DIGITS = 6;
6
+ var CONFIRMATION_MINUTES = 10;
7
+ var CONFIRMATION_MAX_TRIES = 5;
8
+ var CONFIRMATION_PER_HOUR = 3;
9
+ var CONFIRMATION_PER_HOUR_ANY_PROJECT = 6;
10
+ var CONFIRMATION_PER_DAY = 15;
11
+ var CONFIRMATION_MIN_PLAN_MINUTES = 2;
12
+ var CONFIRMATION_LOCKS_PER_DAY = 3;
13
+ var CONFIRMATION_RETRY_MAX_SECONDS = 86400;
14
+ var CONFIRMATION_CONTRACT = "resonance-confirmation/1";
15
+ var ON_THEIR_WORD_CHANNEL = "mcp_chat";
16
+ var ON_THEIR_WORD_CONFIRMATION_CHANNEL = "email";
17
+ var ON_THEIR_WORD_QUOTE_MAX = QUOTE_MAX_LENGTH;
18
+ var CONFIRMATION_REQUEST_ROUTE = "campaigns/:campaignId/plans/:planId/mandate-confirmation";
19
+ var CONFIRMATION_REDEEM_ROUTE = "campaigns/:campaignId/mandate-confirmation/redeem";
20
+ function confirmationRequestPath(projectId, campaignId, planId) {
21
+ return `resonance/projects/${projectId}/campaigns/${campaignId}/plans/${planId}/mandate-confirmation`;
22
+ }
23
+ function confirmationRedeemPath(projectId, campaignId) {
24
+ return `resonance/projects/${projectId}/campaigns/${campaignId}/mandate-confirmation/redeem`;
25
+ }
26
+ var CONFIRMATION_MAIL_SUBJECT_TAG = "[Sonor budget confirmation]";
27
+ var CONFIRMATION_MAIL_HEADER = "X-Sonor-Confirmation";
28
+ var CONFIRMATION_MAIL_HEADER_VALUE = "resonance-mandate";
29
+ function isConfirmationMail(message) {
30
+ if (typeof message.subject === "string" && message.subject.includes(CONFIRMATION_MAIL_SUBJECT_TAG)) return true;
31
+ const headers = message.headers;
32
+ if (!headers) return false;
33
+ const wanted = CONFIRMATION_MAIL_HEADER.toLowerCase();
34
+ if (Array.isArray(headers)) return headers.some((h) => typeof h?.name === "string" && h.name.toLowerCase() === wanted && h.value === CONFIRMATION_MAIL_HEADER_VALUE);
35
+ return Object.entries(headers).some(([name, value]) => name.toLowerCase() === wanted && (Array.isArray(value) ? value.includes(CONFIRMATION_MAIL_HEADER_VALUE) : value === CONFIRMATION_MAIL_HEADER_VALUE));
36
+ }
37
+ var ConfirmationContractError = class extends Error {
38
+ constructor(message, failure = "invalid_request") {
39
+ super(message);
40
+ this.name = "ConfirmationContractError";
41
+ this.failure = failure;
42
+ }
43
+ };
44
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
45
+ var isUuid = (value) => typeof value === "string" && UUID.test(value);
46
+ var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
47
+ function readConfirmationCode(typed) {
48
+ if (typeof typed !== "string" || typed.length > 32) return null;
49
+ const code = typed.replace(/[\s.\-–—]/g, "");
50
+ return new RegExp(`^\\d{${CONFIRMATION_CODE_DIGITS}}$`).test(code) ? code : null;
51
+ }
52
+ function parseConfirmationRedeemRequest(raw) {
53
+ if (!isRecord(raw) || Object.keys(raw).some((key) => !["confirmationId", "ledgerActionId", "code"].includes(key)) || !isUuid(raw.confirmationId) || !isUuid(raw.ledgerActionId)) {
54
+ throw new ConfirmationContractError("Pass the confirmation id, the ledger request it is for, and the six-digit code the person read back.");
55
+ }
56
+ const code = readConfirmationCode(raw.code);
57
+ if (code === null) throw new ConfirmationContractError("The code is six digits. Ask the person to read it back from the email.", "invalid_code");
58
+ return { confirmationId: raw.confirmationId.toLowerCase(), ledgerActionId: raw.ledgerActionId.toLowerCase(), code };
59
+ }
60
+ function parseConfirmationReceipt(raw) {
61
+ if (!isRecord(raw)) throw new ConfirmationContractError("The confirmation receipt is not an object.", "unavailable");
62
+ const { confirmationId, channel, sentTo, expiresAt, minutes, triesAllowed } = raw;
63
+ if (!isUuid(confirmationId) || channel !== ON_THEIR_WORD_CONFIRMATION_CHANNEL || typeof sentTo !== "string" || !/^[^\s@]{1,64}@[^\s@]{1,120}$/.test(sentTo) || typeof expiresAt !== "string" || !Number.isFinite(Date.parse(expiresAt)) || !Number.isSafeInteger(minutes) || minutes < 1 || minutes > 60 || !Number.isSafeInteger(triesAllowed) || triesAllowed < 1 || triesAllowed > 10) {
64
+ throw new ConfirmationContractError("The confirmation receipt is not the one the server sends.", "unavailable");
65
+ }
66
+ return { confirmationId: confirmationId.toLowerCase(), channel, sentTo, expiresAt, minutes, triesAllowed };
67
+ }
68
+ function parseConfirmationRedeemed(raw) {
69
+ const c = isRecord(raw) ? raw.confirmation : null;
70
+ if (!isRecord(c) || !isUuid(c.id) || c.channel !== ON_THEIR_WORD_CONFIRMATION_CHANNEL) throw new ConfirmationContractError("That is not a redeemed confirmation.", "unavailable");
71
+ return { confirmation: { id: c.id.toLowerCase(), channel: ON_THEIR_WORD_CONFIRMATION_CHANNEL } };
72
+ }
73
+ var ON_THEIR_WORD_EVIDENCE_KEYS = ["agent", "quote", "mandate_digest", "review_digest", "channel", "confirmation"];
74
+ var DIGEST = /^[a-f0-9]{64}$/;
75
+ var CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
76
+ function parseOnTheirWordEvidence(value) {
77
+ if (!isRecord(value) || Object.keys(value).length !== ON_THEIR_WORD_EVIDENCE_KEYS.length) return null;
78
+ const { agent, quote, mandate_digest: mandate, review_digest: review, channel, confirmation } = value;
79
+ if (channel !== ON_THEIR_WORD_CHANNEL || typeof agent !== "string" || !isUuid(agent) || agent !== agent.toLowerCase() || typeof quote !== "string" || CONTROL.test(quote) || quote !== quote.trim() || quote.length > ON_THEIR_WORD_QUOTE_MAX || !/[\p{L}\p{N}]/u.test(quote) || typeof mandate !== "string" || !DIGEST.test(mandate) || typeof review !== "string" || !DIGEST.test(review)) return null;
80
+ if (!isRecord(confirmation) || Object.keys(confirmation).length !== 2 || !isUuid(confirmation.id) || confirmation.id !== confirmation.id.toLowerCase() || confirmation.channel !== ON_THEIR_WORD_CONFIRMATION_CHANNEL) return null;
81
+ return { agent, quote, mandate_digest: mandate, review_digest: review, channel, confirmation: { id: confirmation.id, channel: ON_THEIR_WORD_CONFIRMATION_CHANNEL } };
82
+ }
83
+ var CONFIRMATION_REFUSALS = {
84
+ RESONANCE_CONFIRMATION_COMMAND: { status: 400, failure: "invalid_request", message: "That confirmation request was malformed. Ask for a new code." },
85
+ RESONANCE_INVALID_CONFIRMATION: { status: 400, failure: "invalid_request", message: "Pass the confirmation id, the ledger request it is for, and the six-digit code the person read back." },
86
+ RESONANCE_INVALID_CONFIRMATION_CODE: { status: 400, failure: "invalid_code", message: "The code is six digits. Ask the person to read it back from the email." },
87
+ RESONANCE_QUOTE_TOO_LONG: { status: 400, failure: "quote_too_long", message: "Pass only the sentence where they said yes, in 1,000 characters or fewer." },
88
+ RESONANCE_QUOTE_HAS_SECRET: { status: 400, failure: "quote_has_secret", message: "That quote looks like it holds a key, password or card number. Pass only the sentence where they said yes, without it." },
89
+ RESONANCE_CONFIRMATION_REFUSED: { status: 403, failure: "refused", message: "That code can't be used for this budget. Ask for a new one." },
90
+ RESONANCE_CONFIRMATION_STANDING: { status: 403, failure: "not_allowed", message: "Only an owner or admin who can approve this budget can be asked to confirm it." },
91
+ RESONANCE_CONFIRMATION_AGENT: { status: 403, failure: "not_allowed", message: "This agent wasn't set up by the person it acts for. They need to create their own agent token in Sonor first." },
92
+ RESONANCE_CONFIRMATION_LOCKED: { status: 403, failure: "locked", message: "Too many wrong tries. Ask for a new code." },
93
+ RESONANCE_CONFIRMATION_WRONG_CODE: { status: 403, failure: "wrong_code", message: "That's not the code." },
94
+ RESONANCE_CONFIRMATION_EXPIRED: { status: 409, failure: "expired", message: "That code has expired. Ask for a new one." },
95
+ RESONANCE_CONFIRMATION_USED: { status: 409, failure: "used", message: "That code was already used for another budget. Ask for a new one." },
96
+ RESONANCE_CONFIRMATION_NO_VERIFIED_EMAIL: { status: 409, failure: "no_verified_email", message: "This person has no verified login email in Sonor, so a code can't be sent. They can approve the budget in Sonor instead." },
97
+ RESONANCE_CONFIRMATION_MAILBOX_AUTOMATED: { status: 409, failure: "mailbox_automated", message: "This person's login email is a mailbox Sonor reads for automation, so a code can't be sent there. They can approve the budget in Sonor instead." },
98
+ RESONANCE_CONFIRMATION_PLAN_EXPIRING: { status: 409, failure: "plan_expiring", message: "The prepared plan is about to expire, so a code could not be used in time. Prepare the plan again, then ask for a code." },
99
+ // The one limit the first version of the confirmation SQL answers with. The lockout version replaces it with the hourly and daily answers below; it stays here so
100
+ // a build of this table still reads the older SQL during the window between the two, and an older reader still takes any of the three as a 429.
101
+ RESONANCE_CONFIRMATION_RATE: { status: 429, failure: "rate_limited", message: "Too many confirmation emails for this person. Try again in an hour, or approve the budget in Sonor." },
102
+ RESONANCE_CONFIRMATION_RATE_HOURLY: { status: 429, failure: "rate_limited", message: "Too many confirmation emails for this person in the last hour. Ask again later, or approve the budget in Sonor." },
103
+ RESONANCE_CONFIRMATION_RATE_DAILY: { status: 429, failure: "rate_limited_daily", message: "Too many confirmation emails for this person today. Ask again later, or approve the budget in Sonor." },
104
+ RESONANCE_CONFIRMATION_PERSON_LOCKED: { status: 429, failure: "person_locked", message: "Several of this person's codes were locked by wrong tries today, so no new code will be sent for now. They can approve the budget in Sonor." },
105
+ RESONANCE_CONFIRMATION_EMAIL_FAILED: { status: 503, failure: "send_failed", message: "We couldn't send the code by email, so no code is active. Try again in a moment, or have the person approve the budget in Sonor." }
106
+ };
107
+ function confirmationWaitWords(seconds) {
108
+ if (typeof seconds !== "number" || !Number.isSafeInteger(seconds) || seconds < 1) return "a while";
109
+ const minutes = Math.ceil(seconds / 60);
110
+ if (minutes <= 1) return "a minute";
111
+ if (minutes < 60) return `about ${minutes} minutes`;
112
+ const hours = Math.ceil(minutes / 60);
113
+ return hours === 1 ? "about an hour" : `about ${hours} hours`;
114
+ }
115
+ function confirmationFailureOf(status, body) {
116
+ const record = isRecord(body) ? body : {};
117
+ const inner = isRecord(record.error) ? record.error : record;
118
+ const code = typeof inner.code === "string" ? inner.code : "";
119
+ const known = Object.prototype.hasOwnProperty.call(CONFIRMATION_REFUSALS, code) ? code : null;
120
+ const data = isRecord(inner.data) ? inner.data : {};
121
+ const left = data.attemptsLeft;
122
+ const attemptsLeft = known === "RESONANCE_CONFIRMATION_WRONG_CODE" && Number.isSafeInteger(left) && left >= 0 && left <= CONFIRMATION_MAX_TRIES ? left : null;
123
+ const wait = data.retryAfterSeconds;
124
+ const retryAfterSeconds = (known === "RESONANCE_CONFIRMATION_RATE_HOURLY" || known === "RESONANCE_CONFIRMATION_RATE_DAILY" || known === "RESONANCE_CONFIRMATION_PERSON_LOCKED") && Number.isSafeInteger(wait) && wait >= 1 && wait <= CONFIRMATION_RETRY_MAX_SECONDS ? wait : null;
125
+ if (known === "RESONANCE_CONFIRMATION_WRONG_CODE" && attemptsLeft === 0) return { failure: "locked", attemptsLeft: 0, code: known, retryAfterSeconds: null };
126
+ if (known) return { failure: CONFIRMATION_REFUSALS[known].failure, attemptsLeft, code: known, retryAfterSeconds };
127
+ if (status === 429) return { failure: "rate_limited", attemptsLeft: null, code: null, retryAfterSeconds: null };
128
+ return { failure: "unavailable", attemptsLeft: null, code: null, retryAfterSeconds: null };
129
+ }
130
+
131
+ export { CONFIRMATION_CODE_DIGITS, CONFIRMATION_CONTRACT, CONFIRMATION_LOCKS_PER_DAY, CONFIRMATION_MAIL_HEADER, CONFIRMATION_MAIL_HEADER_VALUE, CONFIRMATION_MAIL_SUBJECT_TAG, CONFIRMATION_MAX_TRIES, CONFIRMATION_MINUTES, CONFIRMATION_MIN_PLAN_MINUTES, CONFIRMATION_PER_DAY, CONFIRMATION_PER_HOUR, CONFIRMATION_PER_HOUR_ANY_PROJECT, CONFIRMATION_REDEEM_ROUTE, CONFIRMATION_REFUSALS, CONFIRMATION_REQUEST_ROUTE, CONFIRMATION_RETRY_MAX_SECONDS, ConfirmationContractError, ON_THEIR_WORD_CHANNEL, ON_THEIR_WORD_CONFIRMATION_CHANNEL, ON_THEIR_WORD_EVIDENCE_KEYS, ON_THEIR_WORD_QUOTE_MAX, confirmationFailureOf, confirmationRedeemPath, confirmationRequestPath, confirmationWaitWords, isConfirmationMail, parseConfirmationReceipt, parseConfirmationRedeemRequest, parseConfirmationRedeemed, parseOnTheirWordEvidence, readConfirmationCode };