agent-traffic-gate 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/LICENSE +21 -0
- package/README.md +272 -2
- package/bin/agent-traffic-gate.js +166 -0
- package/package.json +58 -4
- package/src/agents.js +45 -0
- package/src/classify.js +64 -0
- package/src/directory.js +237 -0
- package/src/gate.js +112 -0
- package/src/httpsig.js +232 -0
- package/src/index.js +8 -0
- package/src/policy.js +77 -0
- package/src/sfv.js +199 -0
- package/src/util.js +41 -0
- package/src/verify.js +157 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createGate, ACCEPT_SIGNATURE } from './gate.js';
|
|
2
|
+
export { createVerifier, memoryNonceStore } from './verify.js';
|
|
3
|
+
export { classify, CLASSES, loadBotRanges, botRangesFromJson } from './classify.js';
|
|
4
|
+
export { STORE_POLICY, decide, validatePolicy, memoryLimiter, globToRegExp } from './policy.js';
|
|
5
|
+
export { createDirectoryResolver, checkDirectory, parseSignatureAgent, isPrivateHost, nodeDnsGuard, WELL_KNOWN, MEDIA_TYPE } from './directory.js';
|
|
6
|
+
export { KNOWN_SIGNERS, knownSigner, PROFILES, CHECKED } from './agents.js';
|
|
7
|
+
export { signRequest, signatureBase, describeRequest, parseSignatureHeaders, jwkThumbprint, algFromJwk, ALGORITHMS, SigError } from './httpsig.js';
|
|
8
|
+
export { parseDictionary, parseList, parseItem, serializeDictionary, serializeInnerList, Token, ByteSeq } from './sfv.js';
|
package/src/policy.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Store policy: what to do with each class of traffic on each kind of page.
|
|
2
|
+
// Actions: allow | block | challenge | require-signature | limit:<n>/<window> (for example limit:60/m)
|
|
3
|
+
|
|
4
|
+
export const ACTIONS = ['allow', 'block', 'challenge', 'require-signature'];
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A sensible default for an online store:
|
|
8
|
+
* - browsing and product pages are open to signed agents and verified bots, rate-limited for unproven automation;
|
|
9
|
+
* - cart and checkout accept signed agents and people, refuse unproven automation and crawlers;
|
|
10
|
+
* - admin and login pages are for people only;
|
|
11
|
+
* - fakes are blocked everywhere.
|
|
12
|
+
*/
|
|
13
|
+
export const STORE_POLICY = {
|
|
14
|
+
default: { 'signed-agent': 'allow', 'verified-bot': 'allow', spoofed: 'block', 'claimed-bot': 'limit:30/m', automation: 'limit:30/m', unknown: 'allow' },
|
|
15
|
+
areas: [
|
|
16
|
+
{ name: 'checkout', paths: ['/cart*', '/checkout*', '/checkouts/*', '/api/checkout*', '/api/cart*', '/wc-api/*', '/?wc-ajax=*', '/payment*'],
|
|
17
|
+
rules: { 'signed-agent': 'allow', 'verified-bot': 'block', 'claimed-bot': 'block', automation: 'require-signature', unknown: 'allow' } },
|
|
18
|
+
{ name: 'account', paths: ['/account*', '/my-account*', '/login*', '/register*', '/password*'],
|
|
19
|
+
rules: { 'signed-agent': 'allow', 'verified-bot': 'block', 'claimed-bot': 'block', automation: 'block', unknown: 'allow' } },
|
|
20
|
+
{ name: 'admin', paths: ['/admin*', '/wp-admin*', '/wp-login.php*', '/xmlrpc.php*', '/.env*', '/.git/*'],
|
|
21
|
+
rules: { 'signed-agent': 'block', 'verified-bot': 'block', 'claimed-bot': 'block', automation: 'block', unknown: 'allow' } },
|
|
22
|
+
],
|
|
23
|
+
// Per-agent or per-bot overrides, by id: for example { GPTBot: 'block', CCBot: 'block' } to keep training crawlers out.
|
|
24
|
+
agents: {},
|
|
25
|
+
// For Visa Trusted Agent Protocol: areas where a signed agent must declare payment intent (agent-payer-auth).
|
|
26
|
+
requirePayIntent: [],
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const globCache = new Map();
|
|
30
|
+
export function globToRegExp(glob) {
|
|
31
|
+
if (globCache.has(glob)) return globCache.get(glob);
|
|
32
|
+
const re = new RegExp(`^${glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\?/g, '\\?').replace(/\*/g, '.*')}$`, 'i');
|
|
33
|
+
if (globCache.size < 1000) globCache.set(glob, re);
|
|
34
|
+
return re;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function validatePolicy(p) {
|
|
38
|
+
const problems = [];
|
|
39
|
+
const okAction = (a) => ACTIONS.includes(a) || /^limit:\d+\/(?:s|m|h)$/.test(a);
|
|
40
|
+
const classes = ['signed-agent', 'verified-bot', 'spoofed', 'claimed-bot', 'automation', 'unknown'];
|
|
41
|
+
for (const [k, a] of Object.entries(p.default || {})) { if (!classes.includes(k)) problems.push(`default: unknown class ${k}`); if (!okAction(a)) problems.push(`default.${k}: unknown action ${a}`); }
|
|
42
|
+
for (const area of p.areas || []) {
|
|
43
|
+
if (!Array.isArray(area.paths) || !area.paths.length) problems.push(`area ${area.name || '?'} has no paths`);
|
|
44
|
+
for (const [k, a] of Object.entries(area.rules || {})) { if (!classes.includes(k)) problems.push(`area ${area.name}: unknown class ${k}`); if (!okAction(a)) problems.push(`area ${area.name}.${k}: unknown action ${a}`); }
|
|
45
|
+
}
|
|
46
|
+
for (const [k, a] of Object.entries(p.agents || {})) if (!okAction(a)) problems.push(`agents.${k}: unknown action ${a}`);
|
|
47
|
+
if ((p.default?.spoofed || 'block') === 'allow') problems.push('spoofed traffic is allowed by default; that defeats the gate');
|
|
48
|
+
return problems;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Decide what to do. Returns { action, area, reason, limit? }. */
|
|
52
|
+
export function decide(policy, { path, query = '' }, c) {
|
|
53
|
+
const target = `${path}${query}`;
|
|
54
|
+
const area = (policy.areas || []).find((a) => a.paths.some((g) => globToRegExp(g).test(target) || globToRegExp(g).test(path)));
|
|
55
|
+
let action = (area?.rules && area.rules[c.class]) || policy.default?.[c.class] || (c.class === 'spoofed' ? 'block' : 'allow');
|
|
56
|
+
let reason = `${c.class}${area ? ` in ${area.name}` : ''}`;
|
|
57
|
+
if (c.id && policy.agents && policy.agents[c.id] && c.class !== 'spoofed') { action = policy.agents[c.id]; reason = `override for ${c.id}`; }
|
|
58
|
+
if (area && (policy.requirePayIntent || []).includes(area.name) && c.class === 'signed-agent' && c.intent !== 'pay' && action === 'allow') { action = 'require-signature'; reason = `${area.name} needs a payment-intent signature`; }
|
|
59
|
+
const lim = /^limit:(\d+)\/(s|m|h)$/.exec(action);
|
|
60
|
+
if (lim) return { action: 'limit', limit: { count: Number(lim[1]), window: { s: 1, m: 60, h: 3600 }[lim[2]] }, area: area?.name || null, reason };
|
|
61
|
+
return { action, area: area?.name || null, reason };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Fixed-window counter per key, in memory. Swap for Redis or KV across servers. */
|
|
65
|
+
export function memoryLimiter({ max = 100000 } = {}) {
|
|
66
|
+
const buckets = new Map();
|
|
67
|
+
return {
|
|
68
|
+
async hit(key, { count, window }, now) {
|
|
69
|
+
const slot = Math.floor(now / window);
|
|
70
|
+
const k = `${key}|${window}`;
|
|
71
|
+
const b = buckets.get(k);
|
|
72
|
+
if (!b || b.slot !== slot) { if (buckets.size > max) buckets.clear(); buckets.set(k, { slot, n: 1 }); return { ok: true, remaining: count - 1, reset: (slot + 1) * window - now }; }
|
|
73
|
+
b.n++;
|
|
74
|
+
return { ok: b.n <= count, remaining: Math.max(0, count - b.n), reset: (slot + 1) * window - now };
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
package/src/sfv.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { b64decode, b64encode } from './util.js';
|
|
2
|
+
|
|
3
|
+
// Structured Field Values for HTTP (RFC 9651): the parts HTTP Message Signatures need.
|
|
4
|
+
// Parsing follows the algorithms in RFC 9651 Section 4.2; serialisation follows Section 4.1,
|
|
5
|
+
// because RFC 9421 builds the signature base from the serialised form.
|
|
6
|
+
|
|
7
|
+
export class Token { constructor(v) { this.value = v; } toString() { return this.value; } }
|
|
8
|
+
export class ByteSeq { constructor(bytes) { this.bytes = bytes; } }
|
|
9
|
+
|
|
10
|
+
export class SfvError extends Error {}
|
|
11
|
+
const fail = (m) => { throw new SfvError(m); };
|
|
12
|
+
|
|
13
|
+
const TCHAR = /[!#$%&'*+\-.^_`|~0-9A-Za-z:/]/;
|
|
14
|
+
const KEY_START = /[a-z*]/;
|
|
15
|
+
const KEY_CHAR = /[a-z0-9_\-.*]/;
|
|
16
|
+
|
|
17
|
+
class Parser {
|
|
18
|
+
constructor(s) { this.s = s; this.i = 0; }
|
|
19
|
+
peek() { return this.s[this.i]; }
|
|
20
|
+
done() { return this.i >= this.s.length; }
|
|
21
|
+
ows() { while (this.s[this.i] === ' ' || this.s[this.i] === '\t') this.i++; }
|
|
22
|
+
sp() { while (this.s[this.i] === ' ') this.i++; }
|
|
23
|
+
|
|
24
|
+
key() {
|
|
25
|
+
if (!KEY_START.test(this.peek() || '')) fail(`key must start with a lowercase letter or * at ${this.i}`);
|
|
26
|
+
let k = '';
|
|
27
|
+
while (!this.done() && KEY_CHAR.test(this.peek())) k += this.s[this.i++];
|
|
28
|
+
return k;
|
|
29
|
+
}
|
|
30
|
+
bareItem() {
|
|
31
|
+
const c = this.peek();
|
|
32
|
+
if (c === '-' || /[0-9]/.test(c || '')) return this.number();
|
|
33
|
+
if (c === '"') return this.string();
|
|
34
|
+
if (c === '*' || /[A-Za-z]/.test(c || '')) return this.token();
|
|
35
|
+
if (c === ':') return this.bytes();
|
|
36
|
+
if (c === '?') return this.boolean();
|
|
37
|
+
return fail(`unexpected character ${JSON.stringify(c)} at ${this.i}`);
|
|
38
|
+
}
|
|
39
|
+
number() {
|
|
40
|
+
let sign = 1;
|
|
41
|
+
if (this.peek() === '-') { sign = -1; this.i++; }
|
|
42
|
+
let num = '';
|
|
43
|
+
let dec = false;
|
|
44
|
+
while (!this.done()) {
|
|
45
|
+
const c = this.peek();
|
|
46
|
+
if (/[0-9]/.test(c)) num += c;
|
|
47
|
+
else if (c === '.' && !dec) { if (num.length > 12) fail('decimal integer part too long'); dec = true; num += c; }
|
|
48
|
+
else break;
|
|
49
|
+
this.i++;
|
|
50
|
+
if (!dec && num.length > 15) fail('integer too long');
|
|
51
|
+
if (dec && num.length > 16) fail('decimal too long');
|
|
52
|
+
}
|
|
53
|
+
if (!num || num.endsWith('.')) fail('invalid number');
|
|
54
|
+
if (dec && num.split('.')[1].length > 3) fail('too many decimal places');
|
|
55
|
+
return sign * Number(num);
|
|
56
|
+
}
|
|
57
|
+
string() {
|
|
58
|
+
this.i++;
|
|
59
|
+
let out = '';
|
|
60
|
+
while (!this.done()) {
|
|
61
|
+
const c = this.s[this.i++];
|
|
62
|
+
if (c === '\\') {
|
|
63
|
+
const n = this.s[this.i++];
|
|
64
|
+
if (n !== '"' && n !== '\\') fail('invalid escape in string');
|
|
65
|
+
out += n;
|
|
66
|
+
} else if (c === '"') return out;
|
|
67
|
+
else if (c.charCodeAt(0) < 0x20 || c.charCodeAt(0) > 0x7e) fail('invalid character in string');
|
|
68
|
+
else out += c;
|
|
69
|
+
}
|
|
70
|
+
return fail('unterminated string');
|
|
71
|
+
}
|
|
72
|
+
token() {
|
|
73
|
+
let t = '';
|
|
74
|
+
while (!this.done() && TCHAR.test(this.peek())) t += this.s[this.i++];
|
|
75
|
+
return new Token(t);
|
|
76
|
+
}
|
|
77
|
+
bytes() {
|
|
78
|
+
this.i++;
|
|
79
|
+
const end = this.s.indexOf(':', this.i);
|
|
80
|
+
if (end < 0) fail('unterminated byte sequence');
|
|
81
|
+
const b64 = this.s.slice(this.i, end);
|
|
82
|
+
if (!/^[A-Za-z0-9+/=]*$/.test(b64)) fail('invalid base64 in byte sequence');
|
|
83
|
+
this.i = end + 1;
|
|
84
|
+
return new ByteSeq(b64decode(b64));
|
|
85
|
+
}
|
|
86
|
+
boolean() {
|
|
87
|
+
this.i++;
|
|
88
|
+
const c = this.s[this.i++];
|
|
89
|
+
if (c === '1') return true;
|
|
90
|
+
if (c === '0') return false;
|
|
91
|
+
return fail('invalid boolean');
|
|
92
|
+
}
|
|
93
|
+
params() {
|
|
94
|
+
const p = new Map();
|
|
95
|
+
while (this.peek() === ';') {
|
|
96
|
+
this.i++;
|
|
97
|
+
this.sp();
|
|
98
|
+
const k = this.key();
|
|
99
|
+
let v = true;
|
|
100
|
+
if (this.peek() === '=') { this.i++; v = this.bareItem(); }
|
|
101
|
+
p.set(k, v);
|
|
102
|
+
}
|
|
103
|
+
return p;
|
|
104
|
+
}
|
|
105
|
+
item() { const v = this.bareItem(); return [v, this.params()]; }
|
|
106
|
+
innerList() {
|
|
107
|
+
if (this.peek() !== '(') fail('expected (');
|
|
108
|
+
this.i++;
|
|
109
|
+
const items = [];
|
|
110
|
+
while (!this.done()) {
|
|
111
|
+
this.sp();
|
|
112
|
+
if (this.peek() === ')') { this.i++; return [items, this.params()]; }
|
|
113
|
+
items.push(this.item());
|
|
114
|
+
if (this.peek() !== ' ' && this.peek() !== ')') fail('expected space or ) in inner list');
|
|
115
|
+
}
|
|
116
|
+
return fail('unterminated inner list');
|
|
117
|
+
}
|
|
118
|
+
itemOrInnerList() { return this.peek() === '(' ? this.innerList() : this.item(); }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const prep = (s) => String(s ?? '').replace(/^[ \t]+|[ \t]+$/g, '');
|
|
122
|
+
|
|
123
|
+
export function parseDictionary(s) {
|
|
124
|
+
const p = new Parser(prep(s));
|
|
125
|
+
const out = new Map();
|
|
126
|
+
if (p.done()) return out;
|
|
127
|
+
while (!p.done()) {
|
|
128
|
+
const k = p.key();
|
|
129
|
+
let member;
|
|
130
|
+
if (p.peek() === '=') { p.i++; member = p.itemOrInnerList(); } else member = [true, p.params()];
|
|
131
|
+
out.set(k, member);
|
|
132
|
+
p.ows();
|
|
133
|
+
if (p.done()) return out;
|
|
134
|
+
if (p.peek() !== ',') fail(`expected , at ${p.i}`);
|
|
135
|
+
p.i++;
|
|
136
|
+
p.ows();
|
|
137
|
+
if (p.done()) fail('trailing comma');
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function parseList(s) {
|
|
143
|
+
const p = new Parser(prep(s));
|
|
144
|
+
const out = [];
|
|
145
|
+
while (!p.done()) {
|
|
146
|
+
out.push(p.itemOrInnerList());
|
|
147
|
+
p.ows();
|
|
148
|
+
if (p.done()) return out;
|
|
149
|
+
if (p.peek() !== ',') fail('expected ,');
|
|
150
|
+
p.i++;
|
|
151
|
+
p.ows();
|
|
152
|
+
if (p.done()) fail('trailing comma');
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function parseItem(s) {
|
|
158
|
+
const p = new Parser(prep(s));
|
|
159
|
+
const it = p.item();
|
|
160
|
+
if (!p.done()) fail('unexpected data after item');
|
|
161
|
+
return it;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ---------------- serialisation (RFC 9651 Section 4.1)
|
|
165
|
+
|
|
166
|
+
export function serializeBareItem(v) {
|
|
167
|
+
if (v instanceof Token) return v.value;
|
|
168
|
+
if (v instanceof ByteSeq) return `:${b64encode(v.bytes)}:`;
|
|
169
|
+
if (typeof v === 'boolean') return v ? '?1' : '?0';
|
|
170
|
+
if (typeof v === 'number') {
|
|
171
|
+
if (Number.isInteger(v)) return String(v);
|
|
172
|
+
return String(Math.round(v * 1000) / 1000).replace(/^(-?\d+)$/, '$1.0');
|
|
173
|
+
}
|
|
174
|
+
if (typeof v === 'string') {
|
|
175
|
+
if (/[\x00-\x1f\x7f-\uffff]/.test(v)) fail('string with non-ASCII characters cannot be serialised');
|
|
176
|
+
return `"${v.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
177
|
+
}
|
|
178
|
+
return fail('cannot serialise value');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function serializeParams(params) {
|
|
182
|
+
let out = '';
|
|
183
|
+
for (const [k, v] of params) out += v === true ? `;${k}` : `;${k}=${serializeBareItem(v)}`;
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function serializeItem([v, params]) { return serializeBareItem(v) + serializeParams(params); }
|
|
188
|
+
|
|
189
|
+
export function serializeInnerList([items, params]) {
|
|
190
|
+
return `(${items.map(serializeItem).join(' ')})${serializeParams(params)}`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function serializeMember(m) { return Array.isArray(m[0]) ? serializeInnerList(m) : serializeItem(m); }
|
|
194
|
+
|
|
195
|
+
export function serializeDictionary(dict) {
|
|
196
|
+
return [...dict].map(([k, m]) => (m[0] === true && !Array.isArray(m[0]) ? `${k}${serializeParams(m[1])}` : `${k}=${serializeMember(m)}`)).join(', ');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function serializeList(list) { return list.map(serializeMember).join(', '); }
|
package/src/util.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Small helpers that work the same in Node, Deno, Bun, Cloudflare Workers and Vercel Edge (no Buffer).
|
|
2
|
+
|
|
3
|
+
const enc = new TextEncoder();
|
|
4
|
+
export const utf8 = (s) => enc.encode(s);
|
|
5
|
+
|
|
6
|
+
export function b64encode(bytes) {
|
|
7
|
+
let s = '';
|
|
8
|
+
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
9
|
+
return btoa(s);
|
|
10
|
+
}
|
|
11
|
+
export function b64decode(s) {
|
|
12
|
+
const bin = atob(s);
|
|
13
|
+
const out = new Uint8Array(bin.length);
|
|
14
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
export const b64url = (bytes) => b64encode(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
18
|
+
export const b64urlDecode = (s) => b64decode(s.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (s.length % 4)) % 4));
|
|
19
|
+
|
|
20
|
+
export const subtle = () => {
|
|
21
|
+
const s = globalThis.crypto?.subtle;
|
|
22
|
+
if (!s) throw new Error('Web Crypto (crypto.subtle) is not available in this runtime. Use Node.js 20 or newer.');
|
|
23
|
+
return s;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
export async function sha256(bytes) { return new Uint8Array(await subtle().digest('SHA-256', bytes)); }
|
|
27
|
+
|
|
28
|
+
/** Header lookup that accepts a Fetch Headers object, a Node headers object, a Map or a plain object. */
|
|
29
|
+
export function headerGetter(headers) {
|
|
30
|
+
if (!headers) return () => null;
|
|
31
|
+
if (typeof headers.get === 'function' && !(headers instanceof Map)) return (n) => headers.get(n);
|
|
32
|
+
const lower = new Map();
|
|
33
|
+
const entries = headers instanceof Map ? headers.entries() : Object.entries(headers);
|
|
34
|
+
for (const [k, v] of entries) {
|
|
35
|
+
const key = k.toLowerCase();
|
|
36
|
+
const val = Array.isArray(v) ? v.join(', ') : v == null ? null : String(v);
|
|
37
|
+
if (val == null) continue;
|
|
38
|
+
lower.set(key, lower.has(key) ? `${lower.get(key)}, ${val}` : val);
|
|
39
|
+
}
|
|
40
|
+
return (n) => (lower.has(n.toLowerCase()) ? lower.get(n.toLowerCase()) : null);
|
|
41
|
+
}
|
package/src/verify.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// Verify the signatures on an incoming request (Web Bot Auth, and Visa Trusted Agent Protocol if configured).
|
|
2
|
+
import { describeRequest, parseSignatureHeaders, signatureBase, verifyBytes, checkContentDigest, jwkThumbprint, algFromJwk, ALGORITHMS, SigError } from './httpsig.js';
|
|
3
|
+
import { parseSignatureAgent, normalizeAgentUrl, createDirectoryResolver, nodeDnsGuard } from './directory.js';
|
|
4
|
+
import { knownSigner, PROFILES } from './agents.js';
|
|
5
|
+
|
|
6
|
+
/** In-memory nonce store with expiry. Replace with Redis or KV for more than one server. */
|
|
7
|
+
export function memoryNonceStore({ max = 100000 } = {}) {
|
|
8
|
+
const seen = new Map();
|
|
9
|
+
return {
|
|
10
|
+
async checkAndSet(nonce, ttlSeconds, now) {
|
|
11
|
+
if (seen.size > max) for (const [k, until] of seen) { if (until < now) seen.delete(k); if (seen.size <= max * 0.9) break; }
|
|
12
|
+
const until = seen.get(nonce);
|
|
13
|
+
if (until && until >= now) return false;
|
|
14
|
+
seen.set(nonce, now + ttlSeconds);
|
|
15
|
+
return true;
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Create a verifier.
|
|
22
|
+
* opts: {
|
|
23
|
+
* profiles: ['web-bot-auth'] (add 'visa-tap' to accept Visa Trusted Agent Protocol),
|
|
24
|
+
* resolver: directory resolver (default: fetches Signature-Agent directories),
|
|
25
|
+
* staticKeys: JWKs you already trust (identifier is then the key thumbprint, or the url you give),
|
|
26
|
+
* tapKeys: async (keyid) => JWK for Visa TAP keys (from Visa's registry),
|
|
27
|
+
* nonceStore: { checkAndSet(nonce, ttl, now) } for replay protection (required for visa-tap),
|
|
28
|
+
* clockSkew: 60, maxWindow: overrides the profile limit, now: () => seconds,
|
|
29
|
+
* fetchImpl, log
|
|
30
|
+
* }
|
|
31
|
+
*/
|
|
32
|
+
export function createVerifier(opts = {}) {
|
|
33
|
+
const profiles = (opts.profiles || ['web-bot-auth']).map((p) => { if (!PROFILES[p]) throw new Error(`unknown profile ${p}`); return [p, PROFILES[p]]; });
|
|
34
|
+
const resolver = opts.resolver || createDirectoryResolver({ fetchImpl: opts.fetchImpl, log: opts.log, strict: opts.strictDirectory, now: opts.now, allow: opts.allowSigners, dnsGuard: opts.dnsGuard === false ? null : opts.dnsGuard || (opts.fetchImpl ? null : nodeDnsGuard) });
|
|
35
|
+
const now = opts.now || (() => Math.floor(Date.now() / 1000));
|
|
36
|
+
const skew = opts.clockSkew ?? 60;
|
|
37
|
+
const nonceStore = opts.nonceStore || null;
|
|
38
|
+
const staticKeys = opts.staticKeys || [];
|
|
39
|
+
|
|
40
|
+
async function verifyOne(msg, e, agentHeader, profileName, profile) {
|
|
41
|
+
const r = { label: e.label, tag: e.params.tag, profile: profileName, keyid: e.params.keyid ?? null, alg: e.params.alg ?? null, created: e.params.created ?? null, expires: e.params.expires ?? null, nonce: e.params.nonce ?? null, covered: e.covered, checks: [] };
|
|
42
|
+
const fail = (status, reason) => ({ ...r, ok: false, status, reason });
|
|
43
|
+
const pass = (c) => r.checks.push(c);
|
|
44
|
+
if (!e.signature) return fail('malformed', `no Signature value for label ${e.label}`);
|
|
45
|
+
for (const p of ['created', 'expires', 'keyid']) if (e.params[p] == null) return fail('malformed', `missing required parameter ${p}`);
|
|
46
|
+
if (typeof e.params.created !== 'number' || typeof e.params.expires !== 'number') return fail('malformed', 'created and expires must be integers');
|
|
47
|
+
if (profile.requireNonce && !e.params.nonce) return fail('malformed', 'this profile requires a nonce');
|
|
48
|
+
if (profile.requireAny && !profile.requireAny.some((c) => e.names.includes(c))) return fail('malformed', `signature must cover ${profile.requireAny.join(' or ')}`);
|
|
49
|
+
if (profile.requireAll) for (const c of profile.requireAll) if (!e.names.includes(c)) return fail('malformed', `signature must cover ${c}`);
|
|
50
|
+
pass('required parameters and components present');
|
|
51
|
+
|
|
52
|
+
const t = now();
|
|
53
|
+
if (e.params.created > t + skew) return fail('not-yet-valid', `created is ${e.params.created - t}s in the future`);
|
|
54
|
+
if (e.params.expires < t - skew) return fail('expired', `expired ${t - e.params.expires}s ago`);
|
|
55
|
+
if (e.params.expires <= e.params.created) return fail('malformed', 'expires is not after created');
|
|
56
|
+
const maxWindow = opts.maxWindow ?? profile.maxWindow;
|
|
57
|
+
if (e.params.expires - e.params.created > maxWindow) return fail('too-long', `valid for ${e.params.expires - e.params.created}s; this gate accepts at most ${maxWindow}s`);
|
|
58
|
+
pass('within its validity window');
|
|
59
|
+
|
|
60
|
+
// Which Signature-Agent member does this signature cover?
|
|
61
|
+
let agentUrl = null;
|
|
62
|
+
if (agentHeader && agentHeader.kind !== 'invalid') {
|
|
63
|
+
const coveredMember = e.member[0].find(([n, p]) => n === 'signature-agent' && (p.get('key') === e.label || (!p.has('key') && agentHeader.kind === 'legacy')));
|
|
64
|
+
const keyed = e.member[0].find(([n, p]) => n === 'signature-agent' && p.has('key'));
|
|
65
|
+
if (coveredMember) {
|
|
66
|
+
const entry = agentHeader.kind === 'legacy' ? agentHeader.entries[0] : agentHeader.entries.find((x) => x.label === (coveredMember[1].get('key')));
|
|
67
|
+
if (entry) agentUrl = entry.uri;
|
|
68
|
+
} else if (keyed && agentHeader.kind === 'current') {
|
|
69
|
+
// Covers another label's member: allowed for chaining, but it is not this signature's identity.
|
|
70
|
+
}
|
|
71
|
+
if (!agentUrl && profile.needsAgentHeader) r.checks.push('Signature-Agent is present but this signature does not cover its member, so it cannot be attributed to that URL');
|
|
72
|
+
} else if (profile.needsAgentHeader) r.checks.push('no Signature-Agent header: identity falls back to the key thumbprint');
|
|
73
|
+
|
|
74
|
+
// Find the key.
|
|
75
|
+
let jwk = null; let identity = null; let bound = false; let known = null; let thumb = null;
|
|
76
|
+
try {
|
|
77
|
+
if (profileName === 'visa-tap') {
|
|
78
|
+
if (!opts.tapKeys) return fail('unknown-key', 'Visa TAP signature received, but no tapKeys resolver is configured');
|
|
79
|
+
jwk = await opts.tapKeys(e.params.keyid);
|
|
80
|
+
if (!jwk) return fail('unknown-key', `Visa TAP key ${e.params.keyid} not found`);
|
|
81
|
+
identity = `visa-tap:${e.params.keyid}`;
|
|
82
|
+
} else if (agentUrl) {
|
|
83
|
+
const res = await resolver.resolve(agentUrl, e.params.keyid);
|
|
84
|
+
jwk = res.key.jwk; thumb = res.key.thumbprint || null; identity = res.url; bound = res.bound; known = knownSigner(res.url);
|
|
85
|
+
if (res.problems?.length) r.directoryProblems = res.problems;
|
|
86
|
+
} else {
|
|
87
|
+
for (const k of staticKeys) {
|
|
88
|
+
const jw = k.jwk || k;
|
|
89
|
+
if ((await jwkThumbprint(jw)) === e.params.keyid || jw.kid === e.params.keyid) { jwk = jw; identity = k.url ? normalizeAgentUrl(k.url) : `key:${e.params.keyid}`; known = k.url ? knownSigner(k.url) : null; break; }
|
|
90
|
+
}
|
|
91
|
+
if (!jwk) return fail('unknown-key', 'no Signature-Agent to fetch keys from, and the key is not in staticKeys');
|
|
92
|
+
}
|
|
93
|
+
} catch (err) {
|
|
94
|
+
if (err instanceof SigError && err.code === 'unknown-key') return fail('unknown-key', err.message);
|
|
95
|
+
if (err instanceof SigError && err.code === 'bad-agent') return fail('bad-agent', err.message);
|
|
96
|
+
return fail('directory-error', err.message);
|
|
97
|
+
}
|
|
98
|
+
pass('key found');
|
|
99
|
+
|
|
100
|
+
// Web Bot Auth keyids are JWK thumbprints: check the key really matches.
|
|
101
|
+
if (profileName === 'web-bot-auth') {
|
|
102
|
+
const tp = thumb || await jwkThumbprint(jwk);
|
|
103
|
+
if (tp !== e.params.keyid && jwk.kid !== e.params.keyid) return fail('unknown-key', 'keyid does not match the key');
|
|
104
|
+
}
|
|
105
|
+
const alg = e.params.alg || algFromJwk(jwk);
|
|
106
|
+
if (!alg) return fail('malformed', 'cannot tell the signature algorithm (no alg parameter and the key does not imply one)');
|
|
107
|
+
if (/^hmac/i.test(alg)) return fail('bad-alg', 'shared-secret HMAC signatures are not accepted');
|
|
108
|
+
if (!ALGORITHMS[alg]) return fail('bad-alg', `algorithm ${alg} is not supported`);
|
|
109
|
+
if (jwk.alg && algFromJwk(jwk) && algFromJwk(jwk) !== alg) return fail('bad-alg', `signature says ${alg} but the key is for ${algFromJwk(jwk)}`);
|
|
110
|
+
|
|
111
|
+
let base;
|
|
112
|
+
try { base = signatureBase(msg, e.member); } catch (err) { return fail(err.code === 'missing-component' ? 'invalid' : 'malformed', err.message); }
|
|
113
|
+
let ok = false;
|
|
114
|
+
try { ok = await verifyBytes(alg, jwk, base, e.signature); } catch (err) { return fail('invalid', `verification error: ${err.message}`); }
|
|
115
|
+
if (!ok) return fail('invalid', 'signature does not match');
|
|
116
|
+
pass('signature verifies');
|
|
117
|
+
|
|
118
|
+
if (e.names.includes('content-digest')) {
|
|
119
|
+
if (msg.body == null) r.checks.push('content-digest is covered but the body was not given, so it was not compared');
|
|
120
|
+
else { const d = await checkContentDigest(msg.header('content-digest'), msg.body); if (!d.ok) return fail('invalid', d.reason); pass('body matches Content-Digest'); }
|
|
121
|
+
}
|
|
122
|
+
if (e.params.nonce && nonceStore) {
|
|
123
|
+
const ttl = Math.max(1, e.params.expires - now() + skew);
|
|
124
|
+
if (!(await nonceStore.checkAndSet(`${identity}|${e.params.nonce}`, ttl, now()))) return fail('replay', 'this nonce was already used');
|
|
125
|
+
pass('nonce not seen before');
|
|
126
|
+
} else if (profile.requireNonce && !nonceStore) r.checks.push('nonce not checked for replay: no nonceStore configured');
|
|
127
|
+
|
|
128
|
+
return { ...r, ok: true, status: 'verified', alg, identity, bound, known, intent: profile.intents?.[e.params.tag] || null };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
resolver,
|
|
133
|
+
/** Verify a request. Returns { status, verified, signatures: [...], agent, reason } */
|
|
134
|
+
async verify(request) {
|
|
135
|
+
const msg = describeRequest(request);
|
|
136
|
+
let entries;
|
|
137
|
+
try { entries = parseSignatureHeaders(msg); } catch (err) { return { status: 'malformed', verified: false, reason: err.message, signatures: [] }; }
|
|
138
|
+
if (!entries) return { status: 'unsigned', verified: false, signatures: [] };
|
|
139
|
+
const agentHeader = parseSignatureAgent(msg.header('signature-agent'));
|
|
140
|
+
const results = [];
|
|
141
|
+
for (const e of entries) {
|
|
142
|
+
const prof = profiles.find(([, p]) => p.tags.includes(e.params.tag));
|
|
143
|
+
if (!prof) { results.push({ label: e.label, tag: e.params.tag ?? null, ok: false, status: 'ignored', reason: `tag ${e.params.tag ?? '(none)'} is not one this gate accepts` }); continue; }
|
|
144
|
+
results.push(await verifyOne(msg, e, agentHeader, prof[0], prof[1]));
|
|
145
|
+
}
|
|
146
|
+
const good = results.filter((x) => x.ok);
|
|
147
|
+
// Prefer a payment-network signature, then an attributed URL, then a bare key.
|
|
148
|
+
const best = good.sort((a, b) => (b.profile === 'visa-tap') - (a.profile === 'visa-tap') || (b.identity?.startsWith('https:') ? 1 : 0) - (a.identity?.startsWith('https:') ? 1 : 0))[0];
|
|
149
|
+
if (best) {
|
|
150
|
+
return { status: 'verified', verified: true, signatures: results, agent: { identity: best.identity, id: best.known?.id || null, name: best.known?.name || (best.identity?.startsWith('https:') ? new URL(best.identity).host : best.identity), operator: best.known?.operator || null, kind: best.known?.kind || null, bound: best.bound, intent: best.intent, profile: best.profile } };
|
|
151
|
+
}
|
|
152
|
+
const considered = results.filter((x) => x.status !== 'ignored');
|
|
153
|
+
const worst = considered.find((x) => ['invalid', 'replay', 'bad-alg'].includes(x.status)) || considered[0] || results[0];
|
|
154
|
+
return { status: considered.length ? worst.status : 'unsigned', verified: false, reason: worst?.reason, signatures: results, claimed: agentHeader?.entries?.map((x) => x.uri) || [] };
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|