blocknet 0.0.0-stage → 0.7.1

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/src/license.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Licences and plans.
3
+ *
4
+ * Blocknet is free to run. A licence key from Acific Labs unlocks the features teams pay for: more
5
+ * console seats, audit export, Prometheus metrics and single sign-on. A key is a signed JSON document
6
+ * (Ed25519), checked offline against Acific's public key: no phoning home, nothing sent anywhere.
7
+ *
8
+ * A licence NEVER affects the request path: network rules, payment decisions, budgets and approvals
9
+ * work the same on every plan, with or without a key, valid or expired. When a licence lapses, paid
10
+ * features keep working for a 14-day grace period, then switch off; the admin token and existing
11
+ * password accounts always keep working, so nobody is locked out.
12
+ */
13
+ import { createPublicKey, verify } from 'node:crypto';
14
+ import { existsSync, readFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+
17
+ /** Acific Labs' licence-signing public key. The private key never leaves Acific. */
18
+ export const ACIFIC_LICENSE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
19
+ MCowBQYDK2VwAyEAUDKCdvNsCIEZw1D5Y1ZOCGHLrb2HIoa5sV7Rgw+eFYI=
20
+ -----END PUBLIC KEY-----
21
+ `;
22
+
23
+ export const GRACE_DAYS = 14;
24
+ const DAY = 86_400_000;
25
+
26
+ /** What each plan includes. `seats` is console users; null means unlimited. */
27
+ export const PLANS = {
28
+ free: { name: 'Free', seats: 3, auditExport: false, metrics: false, advisor: false, sso: false },
29
+ team: { name: 'Team', seats: 25, auditExport: true, metrics: true, advisor: true, sso: false },
30
+ enterprise: { name: 'Enterprise', seats: null, auditExport: true, metrics: true, advisor: true, sso: true },
31
+ };
32
+
33
+ export const FEATURE_LABEL = {
34
+ seats: 'more console users',
35
+ auditExport: 'audit log export',
36
+ metrics: 'Prometheus metrics',
37
+ advisor: 'the policy advisor',
38
+ sso: 'single sign-on',
39
+ };
40
+
41
+ /**
42
+ * Checks a licence key. Returns the licence's claims, or throws with a plain reason.
43
+ * Format: base64url(JSON claims) + "." + base64url(Ed25519 signature over the first part).
44
+ */
45
+ export function verifyLicense(text, publicKey = ACIFIC_LICENSE_PUBLIC_KEY) {
46
+ const key = String(text ?? '').trim();
47
+ const [body, sig, extra] = key.split('.');
48
+ if (!body || !sig || extra !== undefined) throw new Error('this is not a Blocknet licence key');
49
+ let ok = false;
50
+ try {
51
+ ok = verify(null, Buffer.from(body), createPublicKey(publicKey), Buffer.from(sig, 'base64url'));
52
+ } catch {}
53
+ if (!ok) throw new Error('this licence key was not issued by Acific Labs, or it was changed');
54
+ const claims = JSON.parse(Buffer.from(body, 'base64url').toString());
55
+ if (claims.v !== 1 || !PLANS[claims.plan] || claims.plan === 'free') throw new Error('this licence key is for an unknown plan');
56
+ return claims;
57
+ }
58
+
59
+ /** Where the key comes from: config.license, $BLOCKNET_LICENSE, or <home>/license. */
60
+ export function findLicenseKey(config, home) {
61
+ if (config.license) return { key: config.license, from: 'config file' };
62
+ if (process.env.BLOCKNET_LICENSE) return { key: process.env.BLOCKNET_LICENSE, from: 'BLOCKNET_LICENSE' };
63
+ const file = join(home, 'license');
64
+ if (existsSync(file)) return { key: readFileSync(file, 'utf8').trim(), from: file };
65
+ return null;
66
+ }
67
+
68
+ /**
69
+ * The plan in force right now, with what it includes and why.
70
+ * @returns {{plan: string, name: string, seats: number|null, auditExport: boolean, metrics: boolean, sso: boolean,
71
+ * license: object|null, status: 'none'|'active'|'grace'|'expired'|'invalid', message: string|null}}
72
+ */
73
+ export function entitlements(found, { now = Date.now(), publicKey } = {}) {
74
+ const free = (status, message, license = null) => ({ plan: 'free', ...PLANS.free, license, status, message });
75
+ if (!found?.key) return free('none', null);
76
+ let claims;
77
+ try {
78
+ claims = verifyLicense(found.key, publicKey);
79
+ } catch (err) {
80
+ return free('invalid', `Licence key from ${found.from} ignored: ${err.message}. Running on the Free plan.`);
81
+ }
82
+ const license = {
83
+ id: claims.id,
84
+ customer: claims.customer,
85
+ plan: claims.plan,
86
+ seats: claims.seats ?? PLANS[claims.plan].seats,
87
+ issuedAt: claims.issuedAt,
88
+ expiresAt: claims.expiresAt,
89
+ from: found.from,
90
+ };
91
+ const expires = Date.parse(claims.expiresAt);
92
+ const plan = { plan: claims.plan, ...PLANS[claims.plan], seats: license.seats, license };
93
+ if (now <= expires) return { ...plan, status: 'active', message: null };
94
+ if (now <= expires + GRACE_DAYS * DAY) {
95
+ const left = Math.ceil((expires + GRACE_DAYS * DAY - now) / DAY);
96
+ return { ...plan, status: 'grace', message: `Your ${plan.name} licence expired on ${claims.expiresAt.slice(0, 10)}. Paid features stop in ${left} day${left === 1 ? '' : 's'}. Renew: contact@acificlabs.com` };
97
+ }
98
+ return free('expired', `Your ${plan.name} licence expired on ${claims.expiresAt.slice(0, 10)}. Running on the Free plan; nothing about traffic changed. Renew: contact@acificlabs.com`, license);
99
+ }
100
+
101
+ /** An error for a feature the current plan doesn't include (HTTP 402). */
102
+ export function upgradeNeeded(feature, ent) {
103
+ const needs = feature === 'sso' ? 'Enterprise' : 'Team';
104
+ return Object.assign(new Error(`${cap(FEATURE_LABEL[feature])} needs the ${needs} plan (you're on ${ent.name}). Get a licence: contact@acificlabs.com`), {
105
+ status: 402,
106
+ expose: true,
107
+ extra: { upgrade: { feature, plan: needs.toLowerCase(), current: ent.plan } },
108
+ });
109
+ }
110
+
111
+ const cap = (s) => (s.startsWith('the ') ? 'The' + s.slice(3) : s[0].toUpperCase() + s.slice(1));
package/src/mcp.js ADDED
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Blocknet as an MCP server (stdio, newline-delimited JSON-RPC 2.0).
3
+ *
4
+ * Gives an AI client (Claude Code, Claude Desktop, Cursor, …) a `fetch` tool whose
5
+ * every call goes through the Blocknet gateway, plus tools to check a payment and
6
+ * the budget. Run with `blocknet mcp`. stdout carries the protocol only; logs go to stderr.
7
+ */
8
+ import { createInterface } from 'node:readline';
9
+ import { VERSION } from './config.js';
10
+
11
+ const MAX_BODY = 50_000;
12
+
13
+ export const TOOLS = [
14
+ {
15
+ name: 'fetch',
16
+ description:
17
+ 'Fetch a URL through Blocknet, the security and spending control for this agent. Blocknet applies network rules, ' +
18
+ 'and when a service asks to be paid it decides (allow, review by a person, or deny) within a budget. ' +
19
+ 'If a request is blocked or a payment is refused, do not try to reach that service another way.',
20
+ inputSchema: {
21
+ type: 'object',
22
+ properties: {
23
+ url: { type: 'string', description: 'Absolute http(s) URL' },
24
+ method: { type: 'string', description: 'HTTP method, default GET' },
25
+ headers: { type: 'object', additionalProperties: { type: 'string' }, description: 'Request headers' },
26
+ body: { type: 'string', description: 'Request body for POST, PUT or PATCH' },
27
+ approval: { type: 'string', description: 'Approval id from Blocknet, only when retrying a signed payment' },
28
+ },
29
+ required: ['url'],
30
+ },
31
+ },
32
+ {
33
+ name: 'payment_status',
34
+ description: 'Check whether a payment Blocknet held for review has been approved or denied by a person.',
35
+ inputSchema: {
36
+ type: 'object',
37
+ properties: { approval: { type: 'string', description: 'Approval id from a fetch result' } },
38
+ required: ['approval'],
39
+ },
40
+ },
41
+ {
42
+ name: 'budget',
43
+ description: "Show today's spending: spent, held for approved payments, and what's left.",
44
+ inputSchema: { type: 'object', properties: {} },
45
+ },
46
+ ];
47
+
48
+ /** Turns a tool call into text for the model. Exported for tests. */
49
+ export async function callTool(name, args, { gateway, fetchImpl: baseFetch = fetch, agentKey = process.env.BLOCKNET_AGENT_KEY }) {
50
+ const fetchImpl = (url, init = {}) =>
51
+ baseFetch(url, agentKey ? { ...init, headers: { ...init.headers, 'x-blocknet-key': agentKey } } : init);
52
+ const text = (t, isError = false) => ({ content: [{ type: 'text', text: t }], isError });
53
+
54
+ if (name === 'budget') {
55
+ const res = await fetchImpl(`${gateway}/v1/budget`);
56
+ if (res.status === 401) return text('Blocknet needs this agent\'s key: set BLOCKNET_AGENT_KEY for the MCP server.', true);
57
+ const b = await res.json();
58
+ const mine = b.agent ? `\nThis agent (${b.agent.name}): spent $${b.agent.spentUsd}, held $${b.agent.reservedUsd}, left $${b.agent.remainingUsd} of $${b.agent.dailyBudgetUsd}` : '';
59
+ return text(`Spent today: $${b.spentUsd}\nHeld for approved payments: $${b.reservedUsd}\nLeft: $${b.remainingUsd} of $${b.dailyBudgetUsd}${mine}`);
60
+ }
61
+
62
+ if (name === 'payment_status') {
63
+ const res = await fetchImpl(`${gateway}/v1/approvals/${encodeURIComponent(args.approval ?? '')}`);
64
+ if (res.status === 404) return text('No payment with that approval id.', true);
65
+ const a = await res.json();
66
+ const note = {
67
+ pending: 'Still waiting for a person. Check again later.',
68
+ approved: 'Approved. The payment can be signed and the request retried with this approval id.',
69
+ denied: 'Denied. Do not pay this service.',
70
+ }[a.status];
71
+ return text(`Payment to ${a.host}: ${a.status}. ${note}`);
72
+ }
73
+
74
+ if (name === 'fetch') {
75
+ const res = await fetchImpl(`${gateway}/v1/fetch`, {
76
+ method: 'POST',
77
+ headers: { 'content-type': 'application/json' },
78
+ body: JSON.stringify({ url: args.url, method: args.method, headers: args.headers, body: args.body, approval: args.approval }),
79
+ });
80
+ const raw = await res.text();
81
+ let json = null;
82
+ try {
83
+ json = JSON.parse(raw);
84
+ } catch {}
85
+
86
+ if (res.status === 403 && json?.blocked) return text(`Blocked by Blocknet: ${json.reasons.join('; ')}`, true);
87
+ if (res.status === 400 && json?.error) return text(json.error, true);
88
+ if (res.status === 401) return text(`Blocknet refused the call: ${json?.error ?? 'agent key required'}. Set BLOCKNET_AGENT_KEY for the MCP server.`, true);
89
+
90
+ if (res.status === 402 && json?.blocknet) {
91
+ const d = json.blocknet;
92
+ const price = `$${d.option.amountUsd} ${d.option.asset} on ${d.option.network}`;
93
+ const lines = [`The service asks to be paid ${price}.`, `Blocknet decision: ${d.decision}. ${d.reasons.join('; ')}.`];
94
+ if (d.decision === 'allow') {
95
+ lines.push(
96
+ `Approval id: ${d.approval} (single use, expires in a few minutes).`,
97
+ 'To pay, a wallet must sign this payment requirement and you retry fetch with the approval id and a PAYMENT-SIGNATURE header. Without a wallet, tell the user the price and that payment is approved.',
98
+ `Payment requirement: ${JSON.stringify(json.paymentRequired)}`,
99
+ );
100
+ } else if (d.decision === 'review') {
101
+ lines.push(`A person must approve it in the Blocknet admin console or with "blocknet approve". Approval id: ${d.approval}. Use payment_status to check.`);
102
+ } else {
103
+ lines.push('Do not pay this service.');
104
+ }
105
+ lines.push(`Budget left today: $${d.budgetRemainingUsd}.`);
106
+ return text(lines.join('\n'), d.decision === 'deny');
107
+ }
108
+
109
+ const contentType = res.headers.get('content-type') ?? '';
110
+ const body = raw.length > MAX_BODY ? `${raw.slice(0, MAX_BODY)}\n…[truncated ${raw.length - MAX_BODY} characters]` : raw;
111
+ return text(`HTTP ${res.status}${contentType ? ` (${contentType})` : ''}\n\n${body}`, res.status >= 400);
112
+ }
113
+
114
+ return text(`Unknown tool: ${name}`, true);
115
+ }
116
+
117
+ /** Runs the server on the given streams until input closes. */
118
+ export function runMcpServer({ gateway, input = process.stdin, output = process.stdout, fetchImpl = fetch }) {
119
+ gateway = gateway.replace(/\/$/, '');
120
+ const write = (msg) => output.write(JSON.stringify({ jsonrpc: '2.0', ...msg }) + '\n');
121
+ const rl = createInterface({ input, crlfDelay: Infinity });
122
+
123
+ rl.on('line', async (line) => {
124
+ if (!line.trim()) return;
125
+ let msg;
126
+ try {
127
+ msg = JSON.parse(line);
128
+ } catch {
129
+ return write({ id: null, error: { code: -32700, message: 'Parse error' } });
130
+ }
131
+ const { id, method, params = {} } = msg;
132
+ if (id === undefined || id === null) return; // notification
133
+
134
+ try {
135
+ if (method === 'initialize') {
136
+ return write({
137
+ id,
138
+ result: {
139
+ protocolVersion: params.protocolVersion ?? '2025-06-18',
140
+ capabilities: { tools: {} },
141
+ serverInfo: { name: 'blocknet', version: VERSION },
142
+ instructions:
143
+ 'Use the fetch tool for web and API requests. Blocknet enforces network rules and decides on payments; respect its decisions.',
144
+ },
145
+ });
146
+ }
147
+ if (method === 'ping') return write({ id, result: {} });
148
+ if (method === 'tools/list') return write({ id, result: { tools: TOOLS } });
149
+ if (method === 'tools/call') {
150
+ const result = await callTool(params.name, params.arguments ?? {}, { gateway, fetchImpl }).catch((err) => ({
151
+ content: [{ type: 'text', text: `Blocknet is not reachable at ${gateway}: ${err.message}` }],
152
+ isError: true,
153
+ }));
154
+ return write({ id, result });
155
+ }
156
+ write({ id, error: { code: -32601, message: `Method not found: ${method}` } });
157
+ } catch (err) {
158
+ write({ id, error: { code: -32603, message: err.message } });
159
+ }
160
+ });
161
+
162
+ return new Promise((resolve) => rl.on('close', resolve));
163
+ }
package/src/notify.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Approval notifications: when a payment waits for a person, Blocknet posts it to a webhook,
3
+ * so nobody has to watch the console.
4
+ *
5
+ * The JSON body has `text` (Slack incoming webhooks) and `content` (Discord) with the same message,
6
+ * plus the structured `approval` for anything else. Sending never blocks or changes a decision;
7
+ * a failure is written to the audit log.
8
+ */
9
+ export function createNotifier(notify = {}, { ledger, fetchImpl = fetch, dashboardUrl } = {}) {
10
+ // `notify` is read at send time, so changing the webhook in the console applies at once
11
+ return {
12
+ /** @param {object} approval a pending approval */
13
+ pending(approval) {
14
+ const url = (typeof notify === 'function' ? notify() : notify)?.webhookUrl;
15
+ if (!url) return;
16
+ const who = approval.agent ? ` from agent ${approval.agent}` : '';
17
+ const message =
18
+ `Blocknet: a payment needs your approval${who}. ` +
19
+ `$${approval.option.amountUsd} ${approval.option.asset} to ${approval.host}. ` +
20
+ `Why: ${approval.reasons.join('; ')}. ` +
21
+ (dashboardUrl ? `Approve or deny: ${dashboardUrl}` : `Approval id: ${approval.id}`);
22
+ fetchImpl(url, {
23
+ method: 'POST',
24
+ headers: { 'content-type': 'application/json' },
25
+ body: JSON.stringify({ text: message, content: message, approval }),
26
+ signal: AbortSignal.timeout(5000),
27
+ })
28
+ .then((res) => {
29
+ if (!res.ok) throw new Error(`webhook answered ${res.status}`);
30
+ })
31
+ .catch((err) => ledger?.record({ type: 'notify_failed', id: approval.id, error: String(err.message ?? err) }));
32
+ },
33
+ };
34
+ }
package/src/policy.js ADDED
@@ -0,0 +1,69 @@
1
+ import { matchAny } from './hosts.js';
2
+
3
+ /**
4
+ * Decisions:
5
+ * allow - proceed without asking anyone
6
+ * review - hold for human approval
7
+ * deny - refuse
8
+ */
9
+
10
+ export function evaluateNetwork(host, network = {}) {
11
+ const denied = matchAny(host, network.deny);
12
+ if (denied) return { decision: 'deny', reasons: [`host matches deny rule "${denied}"`] };
13
+ const allowed = matchAny(host, network.allow);
14
+ if (allowed) return { decision: 'allow', reasons: [`host matches allow rule "${allowed}"`] };
15
+ const fallback = network.default ?? 'allow';
16
+ return { decision: fallback, reasons: [`no rule matched; default is ${fallback}`] };
17
+ }
18
+
19
+ /**
20
+ * @param {object} p
21
+ * @param {import('./x402.js').PaymentOption} p.option
22
+ * @param {boolean} p.acceptable whether the option meets network/asset policy
23
+ * @param {{score:number|null, source:string}} p.trust
24
+ * @param {number} p.spentTodayUsd spent + reserved today, by this agent (or everyone, without agents)
25
+ * @param {number} [p.teamRemainingUsd] with per-agent budgets: what's left of the global daily budget
26
+ * @param {object} p.config Blocknet config (already narrowed to the agent, if any)
27
+ */
28
+ export function evaluatePayment({ option, acceptable, trust, spentTodayUsd, teamRemainingUsd, config }) {
29
+ const pay = config.payments ?? {};
30
+ const tr = config.trust ?? {};
31
+ const reasons = [];
32
+ let decision = 'allow';
33
+ const escalate = (d, why) => {
34
+ reasons.push(why);
35
+ const rank = { allow: 0, review: 1, deny: 2 };
36
+ if (rank[d] > rank[decision]) decision = d;
37
+ };
38
+
39
+ if (!acceptable) escalate('deny', `payment network/asset ${option.network}/${option.asset} not allowed`);
40
+
41
+ if (pay.maxPerRequestUsd != null && option.amountUsd > pay.maxPerRequestUsd) {
42
+ escalate('deny', `price $${option.amountUsd} exceeds per-request limit $${pay.maxPerRequestUsd}`);
43
+ }
44
+
45
+ const remaining = (pay.dailyBudgetUsd ?? Infinity) - spentTodayUsd;
46
+ if (option.amountUsd > remaining) {
47
+ escalate('deny', `price $${option.amountUsd} exceeds remaining daily budget $${round(remaining)}`);
48
+ }
49
+ if (teamRemainingUsd != null && option.amountUsd > teamRemainingUsd) {
50
+ escalate('deny', `price $${option.amountUsd} exceeds what's left of the team's daily budget $${round(teamRemainingUsd)}`);
51
+ }
52
+
53
+ if (trust.score == null) {
54
+ escalate(tr.unknown ?? 'review', `no reputation data for this service (${trust.source})`);
55
+ } else if (tr.minScore != null && trust.score < tr.minScore) {
56
+ escalate(tr.belowMin ?? 'deny', `trust score ${trust.score} below minimum ${tr.minScore}`);
57
+ } else {
58
+ reasons.push(`trust score ${trust.score} (${trust.source})`);
59
+ }
60
+
61
+ if (pay.reviewAboveUsd != null && option.amountUsd > pay.reviewAboveUsd) {
62
+ escalate('review', `price $${option.amountUsd} above auto-approve threshold $${pay.reviewAboveUsd}`);
63
+ }
64
+
65
+ if (decision === 'allow') reasons.push('approved by policy');
66
+ return { decision, reasons, remainingUsd: round(teamRemainingUsd != null ? Math.min(remaining, teamRemainingUsd) : remaining) };
67
+ }
68
+
69
+ export const round = (n) => (Number.isFinite(n) ? Math.round(n * 1e6) / 1e6 : n);
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Console sessions and sign-in rate limits.
3
+ *
4
+ * A session is a random 256-bit token in an HttpOnly cookie. Only its SHA-256 is stored (sessions.json),
5
+ * so a copy of the file can't be used to sign in. Each session has a CSRF token, an idle timeout
6
+ * and an absolute lifetime, and carries the user's sessionVersion: bumping it ends all their sessions.
7
+ */
8
+ import { createHash, randomBytes } from 'node:crypto';
9
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
10
+ import { dirname } from 'node:path';
11
+
12
+ const sha = (s) => createHash('sha256').update(s).digest('hex');
13
+ const DAY = 24 * 60 * 60 * 1000;
14
+
15
+ export class SessionStore {
16
+ /**
17
+ * @param {string|null} path
18
+ * @param {{idleHours?: number, maxDays?: number}} [opts]
19
+ */
20
+ constructor(path, { idleHours = 12, maxDays = 7 } = {}) {
21
+ this.path = path;
22
+ this.idleMs = idleHours * 60 * 60 * 1000;
23
+ this.maxMs = maxDays * DAY;
24
+ /** @type {Map<string, object>} hash -> session */
25
+ this.map = new Map();
26
+ if (path && existsSync(path)) {
27
+ try {
28
+ for (const s of JSON.parse(readFileSync(path, 'utf8'))) this.map.set(s.hash, s);
29
+ } catch {
30
+ this.map.clear(); // unreadable: everyone signs in again
31
+ }
32
+ }
33
+ this.prune();
34
+ }
35
+
36
+ /** @returns {{token: string, session: object}} */
37
+ create(user, extra = {}) {
38
+ const token = randomBytes(32).toString('base64url');
39
+ const now = Date.now();
40
+ const session = {
41
+ hash: sha(token),
42
+ userId: user.id,
43
+ version: user.sessionVersion ?? 1,
44
+ csrf: randomBytes(24).toString('base64url'),
45
+ createdAt: now,
46
+ lastSeenAt: now,
47
+ ...extra,
48
+ };
49
+ this.map.set(session.hash, session);
50
+ this.save();
51
+ return { token, session };
52
+ }
53
+
54
+ /** The live session for a cookie token, or null. Touches lastSeenAt (saved at most once a minute). */
55
+ get(token, users) {
56
+ if (!token) return null;
57
+ const s = this.map.get(sha(token));
58
+ if (!s) return null;
59
+ const now = Date.now();
60
+ const user = users.get(s.userId);
61
+ if (!user || user.disabled || (user.sessionVersion ?? 1) !== s.version || now - s.lastSeenAt > this.idleMs || now - s.createdAt > this.maxMs) {
62
+ this.map.delete(s.hash);
63
+ this.save();
64
+ return null;
65
+ }
66
+ if (now - s.lastSeenAt > 60_000) {
67
+ s.lastSeenAt = now;
68
+ this.save();
69
+ }
70
+ return { session: s, user };
71
+ }
72
+
73
+ destroy(token) {
74
+ if (token && this.map.delete(sha(token))) this.save();
75
+ }
76
+
77
+ destroyUser(userId, exceptHash) {
78
+ for (const [h, s] of this.map) if (s.userId === userId && h !== exceptHash) this.map.delete(h);
79
+ this.save();
80
+ }
81
+
82
+ prune() {
83
+ const now = Date.now();
84
+ for (const [h, s] of this.map) if (now - s.lastSeenAt > this.idleMs || now - s.createdAt > this.maxMs) this.map.delete(h);
85
+ }
86
+
87
+ save() {
88
+ if (!this.path) return;
89
+ this.prune();
90
+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
91
+ const tmp = `${this.path}.tmp`;
92
+ writeFileSync(tmp, JSON.stringify([...this.map.values()]), { mode: 0o600 });
93
+ renameSync(tmp, this.path);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Sign-in rate limits: 5 failures per email, or 20 per address, within 15 minutes.
99
+ * In memory: a restart resets it, which is acceptable for a limiter.
100
+ */
101
+ export class LoginLimiter {
102
+ constructor({ perAccount = 5, perAddress = 20, windowMs = 15 * 60 * 1000 } = {}) {
103
+ Object.assign(this, { perAccount, perAddress, windowMs });
104
+ this.failures = new Map(); // key -> [timestamps]
105
+ }
106
+ #recent(key) {
107
+ const cutoff = Date.now() - this.windowMs;
108
+ const list = (this.failures.get(key) ?? []).filter((t) => t > cutoff);
109
+ this.failures.set(key, list);
110
+ return list;
111
+ }
112
+ /** Seconds to wait, or 0 when a try is allowed. */
113
+ retryAfter(email, address) {
114
+ const a = this.#recent(`e:${email}`);
115
+ const b = this.#recent(`a:${address}`);
116
+ const blocked = (a.length >= this.perAccount && a) || (b.length >= this.perAddress && b);
117
+ return blocked ? Math.ceil((blocked[0] + this.windowMs - Date.now()) / 1000) : 0;
118
+ }
119
+ fail(email, address) {
120
+ this.#recent(`e:${email}`).push(Date.now());
121
+ this.#recent(`a:${address}`).push(Date.now());
122
+ }
123
+ succeed(email) {
124
+ this.failures.delete(`e:${email}`);
125
+ }
126
+ }
127
+
128
+ /** Parses a Cookie header into an object. */
129
+ export function parseCookies(header = '') {
130
+ const out = {};
131
+ for (const part of header.split(';')) {
132
+ const i = part.indexOf('=');
133
+ if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
134
+ }
135
+ return out;
136
+ }
137
+
138
+ export function cookie(name, value, { maxAgeSeconds, secure, path = '/', sameSite = 'Lax' } = {}) {
139
+ return [
140
+ `${name}=${encodeURIComponent(value)}`,
141
+ `Path=${path}`,
142
+ 'HttpOnly',
143
+ `SameSite=${sameSite}`,
144
+ ...(secure ? ['Secure'] : []),
145
+ ...(maxAgeSeconds != null ? [`Max-Age=${maxAgeSeconds}`] : []),
146
+ ].join('; ');
147
+ }