@sonordev/contracts 2.25.0 → 2.27.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,244 @@
1
+ // src/contracts/public-url-host.ts
2
+ function isPrivateIpv4(a, b) {
3
+ return a === 127 || a === 10 || a === 0 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127 || a >= 224;
4
+ }
5
+ function ipv6Words(host) {
6
+ if (!host.includes(":") || !/^[a-f\d:.]+$/.test(host)) return null;
7
+ let canonical;
8
+ try {
9
+ canonical = new URL(`http://[${host}]/`).hostname.slice(1, -1);
10
+ } catch {
11
+ return null;
12
+ }
13
+ const sides = canonical.split("::");
14
+ const left = sides[0] ? sides[0].split(":") : [];
15
+ const right = sides.length > 1 && sides[1] ? sides[1].split(":") : [];
16
+ return [...left, ...Array(sides.length > 1 ? 8 - left.length - right.length : 0).fill("0"), ...right].map((word) => parseInt(word, 16));
17
+ }
18
+ function isBlockedPublicUrlHost(rawHost) {
19
+ const host = rawHost.toLowerCase().replace(/^\[|\]$/g, "");
20
+ const blockedName = host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal");
21
+ if (host.includes(":") && host.includes("%")) return true;
22
+ const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
23
+ const blockedIp = !!ipv4 && isPrivateIpv4(Number(ipv4[1]), Number(ipv4[2]));
24
+ const words = ipv6Words(host);
25
+ const blockedIpv6 = !!words && // Unspecified/loopback, unique-local, link-local, deprecated site-local
26
+ // and multicast destinations aren't public logo/webhook endpoints.
27
+ (words.every((word) => word === 0) || words.slice(0, 7).every((word) => word === 0) && words[7] === 1 || (words[0] & 65024) === 64512 || (words[0] & 65472) === 65152 || (words[0] & 65472) === 65216 || (words[0] & 65280) === 65280 || // IPv4-mapped and older IPv4-compatible forms carry an IPv4 destination.
28
+ words.slice(0, 5).every((word) => word === 0) && [0, 65535].includes(words[5]) && isPrivateIpv4(words[6] >> 8, words[6] & 255));
29
+ return blockedName || blockedIp || blockedIpv6;
30
+ }
31
+
32
+ // src/contracts/sites-normalize.ts
33
+ function normalizeSiteHost(site2) {
34
+ if (!site2 || typeof site2 !== "string") return null;
35
+ let s = site2.trim().toLowerCase();
36
+ if (!s) return null;
37
+ s = s.replace(/^https?:\/\//, "");
38
+ const slash = s.indexOf("/");
39
+ if (slash >= 0) s = s.slice(0, slash);
40
+ const colon = s.indexOf(":");
41
+ if (colon >= 0) s = s.slice(0, colon);
42
+ s = s.replace(/\.+$/, "");
43
+ return s || null;
44
+ }
45
+
46
+ // src/contracts/sites.ts
47
+ function isNormalizedSiteHost(value) {
48
+ return typeof value === "string" && value.length > 0 && normalizeSiteHost(value) === value;
49
+ }
50
+
51
+ // src/contracts/wire-schema.ts
52
+ function createWireSchema(fail2, isValidationError) {
53
+ const own = (v, k) => Object.prototype.hasOwnProperty.call(v, k);
54
+ const field = (schema, read) => ({ schema, read });
55
+ const text2 = (max = 200, pattern, min = 1) => field({ type: "string", minLength: min, maxLength: max, ...pattern ? { pattern: pattern.source } : {} }, (v, p) => typeof v === "string" && v.length >= min && v.length <= max && (!pattern || pattern.test(v)) ? v : fail2(p, "invalid string"));
56
+ const choice2 = (...values) => field({ type: "string", enum: values }, (v, p) => typeof v === "string" && values.includes(v) ? v : fail2(p, "unsupported value"));
57
+ const literal2 = (value) => field({ const: value }, (v, p) => v === value ? value : fail2(p, "unexpected value"));
58
+ const integer2 = (min = 0, max = Number.MAX_SAFE_INTEGER) => field({ type: "integer", minimum: min, maximum: max }, (v, p) => typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max ? v : fail2(p, "invalid integer"));
59
+ const bool2 = field({ type: "boolean" }, (v, p) => typeof v === "boolean" ? v : fail2(p, "must be boolean"));
60
+ const optional2 = (f) => ({ ...f, optional: true });
61
+ const nullable2 = (f) => field({ anyOf: [f.schema, { type: "null" }] }, (v, p) => v === null ? null : f.read(v, p));
62
+ const list2 = (f, max = 100, min = 0) => field({ type: "array", items: f.schema, minItems: min, maxItems: max }, (v, p) => {
63
+ if (!Array.isArray(v) || v.length < min || v.length > max) fail2(p, "invalid array");
64
+ return v.map((x, i) => f.read(x, `${p}[${i}]`));
65
+ });
66
+ const object2 = (fields) => field({ type: "object", additionalProperties: false, properties: Object.fromEntries(Object.entries(fields).map(([k, f]) => [k, f.schema])), required: Object.keys(fields).filter((k) => !("optional" in fields[k])) }, (v, p) => {
67
+ if (!v || typeof v !== "object" || Array.isArray(v) || ![Object.prototype, null].includes(Object.getPrototypeOf(v))) fail2(p, "must be a plain object");
68
+ const source = v, result = {};
69
+ for (const key of Reflect.ownKeys(source)) if (typeof key !== "string" || !own(fields, key)) fail2(p, "unknown field");
70
+ for (const [key, f] of Object.entries(fields)) {
71
+ if (!own(source, key)) {
72
+ if ("optional" in f) continue;
73
+ fail2(`${p}.${key}`, "required");
74
+ }
75
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
76
+ if (!own(descriptor, "value")) fail2(`${p}.${key}`, "accessors are not wire data");
77
+ result[key] = f.read(descriptor.value, `${p}.${key}`);
78
+ }
79
+ return result;
80
+ });
81
+ const union2 = (...fields) => field({ oneOf: fields.map((f) => f.schema) }, (v, p) => {
82
+ const found = [];
83
+ for (const f of fields) {
84
+ try {
85
+ found.push(f.read(v, p));
86
+ } catch (e) {
87
+ if (!isValidationError(e)) throw e;
88
+ }
89
+ }
90
+ return found.length === 1 ? found[0] : fail2(p, "must match exactly one supported shape");
91
+ });
92
+ const refine2 = (f, check) => field(f.schema, (v, p) => {
93
+ const result = f.read(v, p);
94
+ check(result, p);
95
+ return result;
96
+ });
97
+ return { field, text: text2, choice: choice2, literal: literal2, integer: integer2, bool: bool2, optional: optional2, nullable: nullable2, list: list2, object: object2, union: union2, refine: refine2 };
98
+ }
99
+
100
+ // src/contracts/wire-uuid.ts
101
+ var UUID_V1_TO_V8_PATTERN = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
102
+
103
+ // src/contracts/property-interest.ts
104
+ var PROPERTY_INTEREST_CATEGORY = "real_estate_interest";
105
+ var PROPERTY_INTEREST_EVENT_NAMES = ["property_exposed", "gallery_open", "detail_open", "property_selected"];
106
+ var PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS = 28;
107
+ var PROPERTY_INTEREST_MAX_WINDOW_DAYS = 90;
108
+ var PROPERTY_INTEREST_MAX_LISTINGS = 50;
109
+ var PropertyInterestValidationError = class extends Error {
110
+ constructor(path, reason) {
111
+ super(`${path}: ${reason}`);
112
+ this.path = path;
113
+ this.name = "PropertyInterestValidationError";
114
+ }
115
+ };
116
+ var fail = (path, reason) => {
117
+ throw new PropertyInterestValidationError(path, reason);
118
+ };
119
+ var { bool, choice, integer, list, literal, nullable, object, optional, refine, text, union } = createWireSchema(fail, (error) => error instanceof PropertyInterestValidationError);
120
+ var listingId = text(36, UUID_V1_TO_V8_PATTERN);
121
+ var surface = choice("collection", "detail");
122
+ var site = refine(text(253), (value, at) => {
123
+ if (!isNormalizedSiteHost(value) || isBlockedPublicUrlHost(value)) fail(at, "requires a normalized public site host");
124
+ });
125
+ var instant = refine(text(24, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/), (value, at) => {
126
+ const epoch = Date.parse(value);
127
+ if (!Number.isFinite(epoch) || new Date(epoch).toISOString().replace(".000Z", "Z") !== value.replace(".000Z", "Z")) {
128
+ fail(at, "requires a valid UTC instant");
129
+ }
130
+ });
131
+ var dayMs = 864e5;
132
+ var eventProperties = object({
133
+ schema_version: literal(1),
134
+ listing_id: listingId,
135
+ surface,
136
+ ordinal: optional(integer(1, 1e3))
137
+ });
138
+ var event = object({ category: literal(PROPERTY_INTEREST_CATEGORY), name: choice(...PROPERTY_INTEREST_EVENT_NAMES), properties: eventProperties });
139
+ var parsePropertyInterestEventProperties = (value) => eventProperties.read(value, "propertyInterestEventProperties");
140
+ var parsePropertyInterestEvent = (value) => event.read(value, "propertyInterestEvent");
141
+ var PROPERTY_INTEREST_EVENT_PROPERTIES_JSON_SCHEMA = eventProperties.schema;
142
+ var PROPERTY_INTEREST_EVENT_JSON_SCHEMA = event.schema;
143
+ function checkWindow(from, to, at) {
144
+ const duration = Date.parse(to) - Date.parse(from);
145
+ if (duration <= 0 || duration > PROPERTY_INTEREST_MAX_WINDOW_DAYS * dayMs) fail(at, "requires a positive window of at most 90 days");
146
+ }
147
+ function unique(values, at) {
148
+ if (new Set(values).size !== values.length) fail(at, "duplicate identity");
149
+ }
150
+ var reportRequest = refine(object({
151
+ site,
152
+ from: optional(instant),
153
+ to: optional(instant),
154
+ listingIds: optional(list(listingId, PROPERTY_INTEREST_MAX_LISTINGS, 1)),
155
+ cursor: optional(listingId)
156
+ }), (value, at) => {
157
+ if (value.from && value.to) checkWindow(value.from, value.to, at);
158
+ else if (value.from || value.to) fail(at, "requires both window endpoints or neither");
159
+ if (value.listingIds) unique(value.listingIds.map((id) => id.toLowerCase()), at + ".listingIds");
160
+ if (value.cursor && (!value.from || !value.to || value.listingIds)) {
161
+ fail(at + ".cursor", "requires the original broad report window");
162
+ }
163
+ });
164
+ var parsePropertyInterestReportRequest = (value) => reportRequest.read(value, "propertyInterestReportRequest");
165
+ var PROPERTY_INTEREST_REPORT_REQUEST_JSON_SCHEMA = reportRequest.schema;
166
+ function propertyInterestRateBps(eligibleSessions, exposureSessions) {
167
+ const eligible = integer().read(eligibleSessions, "propertyInterestRate.eligibleSessions");
168
+ const exposure = integer().read(exposureSessions, "propertyInterestRate.exposureSessions");
169
+ if (eligible > exposure) fail("propertyInterestRate", "eligible sessions exceed the exposure cohort");
170
+ if (exposure === 0) return null;
171
+ const denominator = BigInt(exposure);
172
+ return Number((BigInt(eligible) * 10000n + denominator / 2n) / denominator);
173
+ }
174
+ var action = object({ eligibleSessions: integer(), unmatchedSessions: integer(), rateBps: nullable(integer(0, 1e4)) });
175
+ var surfaceReport = refine(object({
176
+ surface,
177
+ exposureSessions: integer(),
178
+ missingSessionEvents: integer(),
179
+ actions: object({ gallery_open: action, detail_open: action, property_selected: action })
180
+ }), (value, at) => {
181
+ for (const [name, counts] of Object.entries(value.actions)) {
182
+ if (counts.eligibleSessions > value.exposureSessions || counts.rateBps !== propertyInterestRateBps(counts.eligibleSessions, value.exposureSessions)) {
183
+ fail(at + ".actions." + name, "requires the exact exposure-normalized rate");
184
+ }
185
+ }
186
+ });
187
+ var tourInquiries = union(
188
+ object({ state: literal("available"), count: integer(), source: literal("native_listing_accepted_tour_form") }),
189
+ object({ state: literal("unavailable"), count: literal(null), source: literal(null) })
190
+ );
191
+ var propertyReport = refine(object({
192
+ listingId,
193
+ displayAddress: nullable(text(240, /^[^\x00-\x1f\x7f]+$/)),
194
+ slug: nullable(text(200, /^[a-z0-9]+(?:-[a-z0-9]+)*$/)),
195
+ status: nullable(choice("active", "pending", "sold", "expired", "withdrawn")),
196
+ surfaces: list(surfaceReport, 2, 2),
197
+ acceptedTourInquiries: tourInquiries
198
+ }), (value, at) => {
199
+ unique(value.surfaces.map((row) => row.surface), at + ".surfaces");
200
+ });
201
+ var report = refine(object({
202
+ schemaVersion: literal(1),
203
+ scope: literal("site"),
204
+ site,
205
+ from: instant,
206
+ to: instant,
207
+ observedAt: instant,
208
+ properties: list(propertyReport, PROPERTY_INTEREST_MAX_LISTINGS),
209
+ hasMore: bool,
210
+ nextCursor: nullable(listingId)
211
+ }), (value, at) => {
212
+ checkWindow(value.from, value.to, at);
213
+ if (Date.parse(value.to) > Date.parse(value.observedAt)) fail(at + ".to", "window extends past the observation");
214
+ unique(value.properties.map((row) => row.listingId.toLowerCase()), at + ".properties");
215
+ if (value.hasMore !== (value.nextCursor !== null)) fail(at + ".hasMore", "must agree with the next cursor");
216
+ if (value.nextCursor && (value.properties.length !== PROPERTY_INTEREST_MAX_LISTINGS || value.properties[value.properties.length - 1]?.listingId.toLowerCase() !== value.nextCursor.toLowerCase())) {
217
+ fail(at + ".nextCursor", "requires the final listing of a full bounded result");
218
+ }
219
+ });
220
+ var parsePropertyInterestReport = (value) => report.read(value, "propertyInterestReport");
221
+ var PROPERTY_INTEREST_REPORT_JSON_SCHEMA = report.schema;
222
+ function parsePropertyInterestReportForRequest(value, request) {
223
+ const result = parsePropertyInterestReport(value);
224
+ const expected = parsePropertyInterestReportRequest(request);
225
+ const at = "propertyInterestReport";
226
+ if (result.site !== expected.site) fail(at + ".site", "does not match the requested site");
227
+ const from = Date.parse(result.from), to = Date.parse(result.to);
228
+ if (expected.from && expected.to) {
229
+ if (from !== Date.parse(expected.from) || to !== Date.parse(expected.to)) {
230
+ fail(at + ".from", "does not match the requested window");
231
+ }
232
+ } else if (to - from !== PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS * dayMs) {
233
+ fail(at + ".from", "does not match the default window duration");
234
+ }
235
+ if (expected.listingIds) {
236
+ const requestedIds = new Set(expected.listingIds.map((id) => id.toLowerCase()));
237
+ if (result.hasMore || result.properties.length !== requestedIds.size || result.properties.some((row) => !requestedIds.has(row.listingId.toLowerCase()))) {
238
+ fail(at + ".properties", "requires exactly the requested listings without pagination");
239
+ }
240
+ }
241
+ return result;
242
+ }
243
+
244
+ export { PROPERTY_INTEREST_CATEGORY, PROPERTY_INTEREST_DEFAULT_WINDOW_DAYS, PROPERTY_INTEREST_EVENT_JSON_SCHEMA, PROPERTY_INTEREST_EVENT_NAMES, PROPERTY_INTEREST_EVENT_PROPERTIES_JSON_SCHEMA, PROPERTY_INTEREST_MAX_LISTINGS, PROPERTY_INTEREST_MAX_WINDOW_DAYS, PROPERTY_INTEREST_REPORT_JSON_SCHEMA, PROPERTY_INTEREST_REPORT_REQUEST_JSON_SCHEMA, PropertyInterestValidationError, parsePropertyInterestEvent, parsePropertyInterestEventProperties, parsePropertyInterestReport, parsePropertyInterestReportForRequest, parsePropertyInterestReportRequest, propertyInterestRateBps };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * What a person's yes may not contain: the ONE quote screen. Pure, no dependencies.
3
+ *
4
+ * The quote is the person's own words, stored on the Ledger beside their approval and copied into the acceptance, so it must not carry a secret. It is also a place an agent
5
+ * must NEVER edit the person's words, so a refusal has to be rare and for a real secret shape: a campaign name ("Q4 BOGO PPC", "SEM_BRAND_EXACT_US",
6
+ * "BrandSearchQ4Retargeting2026") is not one. What it refuses:
7
+ * - credentials by their published shapes (provider key and token prefixes, JWTs, private keys, URLs with a password in them, ?token= parameters);
8
+ * - credentials said in words ("the Stripe key is ...", "password is ...", "wp login: admin/...", a door code);
9
+ * - a payment card (13 to 19 digits that pass Luhn AND begin like a card brand's numbers, so an 18-digit Meta campaign id is not a card), an IBAN (it must pass the mod-97
10
+ * check), a US routing or account number said as one, a social security number;
11
+ * - a token that is named and then given ("auth token 4f9a..."), a bare run of hex of 32 or more, and a bare run of 32 or more letters, digits and token punctuation that is
12
+ * noise and not a name.
13
+ * What it deliberately does NOT refuse: a bare random token of 20 to 31 characters with no prefix and no word before it. Such a token cannot be told from an abbreviation-heavy
14
+ * name by shape, and refusing names is the worse failure here. Prefixes, JWTs and a word like "key" or "token" before the value still catch the real ones.
15
+ *
16
+ * CALLERS CAP THE LENGTH FIRST (refuseQuote does): some patterns here are quadratic on a long run with no space, which a 1,000-character quote cannot make slow.
17
+ */
18
+ /** The longest quote, in UTF-16 units: a sentence or two of "yes, go ahead with the $500", not an essay. */
19
+ export declare const QUOTE_MAX_LENGTH = 1000;
20
+ /**
21
+ * Why a quote can't be stored as the person said it (a credential, a card number, a password), or null when it can. Run it on a quote already cut to QUOTE_MAX_LENGTH
22
+ * (refuseQuote does that first).
23
+ */
24
+ export declare function quoteSecretReason(text: string): string | null;
25
+ /**
26
+ * Whether a quote may come in, in the order that matters: the length cap FIRST (an O(1) comparison, so a quote of any size is refused before anything reads it), then the
27
+ * screen. A value that is not text is not this function's to judge. Use it at intake, once; never on evidence already stored.
28
+ */
29
+ export declare function refuseQuote(quote: unknown): 'too_long' | 'secret' | null;
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+
3
+ // src/contracts/quote-screen.ts
4
+ var QUOTE_MAX_LENGTH = 1e3;
5
+ var PROJECT_API_KEY = /\bsonor_[0-9a-f]{8}_[A-Za-z0-9_-]{8,}/i;
6
+ var NOT_A_VALUE = String.raw`(?!(?:stored|kept|saved|in|on|at|with|managed|shared|the|a|an|our|my|your|their|his|her|not|never|changed|changing|reset|rotated|expired|expiring|expires|updated|required|same|different|written|listed|available|below|above|here|there|somewhere|secret|private|safe|set|missing|wrong|old|new|weak|strong|secure|long|short|case|valid|invalid|correct|incorrect|working|broken|locked|unlocked|known|unknown|temporary|blank|empty|are|were|will|should|must|can|needed|needs|sent|emailed|texted|given|handled|taped)\b)`;
7
+ var KEY_OWNERS = "api|secret|access|private|license|licence|publishable|signing|webhook|admin|master|encryption|ssh|gpg|pgp|client|app|integration|stripe|resend|openai|anthropic|google|aws|square|twilio|sendgrid|mailchimp|mailgun|postmark|github|gitlab|slack|shopify|netlify|vercel|supabase|sonor|cloudflare|zapier|hubspot|paypal|quickbooks|wordpress|wp";
8
+ var CREDENTIAL_NOUN = String.raw`(?:(?:${KEY_OWNERS})\s+(?:api\s+)?(?:key|token|secret)|(?:access|refresh|bearer|auth|api|session|deploy|personal)\s+token|token|client\s+secret|secret)s?`;
9
+ var FOR_SOMETHING = String.raw`(?:\s+(?:for|to|on|at|of|in|with)\s+[^.,;:\n]{1,40}?)?`;
10
+ var IS = String.raw`(?:\b(?:is|was)\b|=|:)`;
11
+ var CREDENTIAL_IS_VALUE = new RegExp(String.raw`\b${CREDENTIAL_NOUN}\b${FOR_SOMETHING}\s*${IS}\s*${NOT_A_VALUE}(?=\S*[\d_])\S{6,}`, "i");
12
+ var PASSWORD_NOUN = String.raw`(?:password|passcode|passwd|pwd|passphrase|pw|(?:admin|wp|wordpress|wifi|wi-fi|login|account|user|email|site|portal|router|db|database|ftp|sftp|ssh|server|cpanel|hosting|dashboard|app|vpn)\s+pass)`;
13
+ var PASSWORD_IS_VALUE = new RegExp(String.raw`\b${PASSWORD_NOUN}\b${FOR_SOMETHING}\s*(?:${IS}|-)\s*${NOT_A_VALUE}\S{3,}`, "i");
14
+ var USER_THEN_PASS = new RegExp(String.raw`\b(?:user(?:name)?|login)\b\s*${IS}?\s*\S+[\s,;/]+(?:and\s+)?(?:the\s+)?(?:pass(?:word)?|pw|pwd)\b\s*(?:${IS}|-)?\s*${NOT_A_VALUE}(?=\S*[A-Za-z])(?=\S*[\d!@#$%^&*?_])\S{4,}`, "i");
15
+ var LOGIN_USER_SECRET = new RegExp(String.raw`\b(?:login|log-?in|credentials|creds)\b\s*${IS}\s*(?!(?:at|on|in|is|the|a|an|via|through|page|screen|link|url)\b)[^\s/]+\s+(?:and\s+|with\s+)?(?=\S*[A-Za-z])(?=\S*[\d!@#$%^&*?])\S{4,}`, "i");
16
+ var LOGIN_EMAIL_SECRET = new RegExp(String.raw`\b(?:login|log-?in|credentials|creds|sign-?in|account)\b[^.\n]{0,40}?[\w.+-]+@[\w-]+(?:\.[\w-]+)+\s*(?:with|and|/|,|:|\|)\s*(?:the\s+)?(?:(?:pass(?:word)?|pw)\s+)?(?:${IS}\s*)?(?=\S*[A-Za-z])(?=\S*[\d!@#$%^&*?])\S{4,}`, "i");
17
+ var NAMED_CODE = new RegExp(String.raw`\b(?:door|gate|alarm|lock|lockbox|lock box|garage|keypad|entry|building|wifi|wi-fi|security|access)\s+(?:code|combo|combination|pin)\b[^.;\n]{0,40}?${IS}\s*#?\d{3,8}`, "i");
18
+ var BARE_LOCK_CODE = new RegExp(String.raw`\b(?:lockbox|lock box|keypad)\b\s*(?:code\s*)?${IS}\s*#?\d{3,8}\b`, "i");
19
+ var NAMED_SERVICE_SECRET = new RegExp(String.raw`\b[A-Z][A-Za-z0-9]+\s+(?:[Aa][Pp][Ii]\s+)?(?:[Kk]ey|[Tt]oken|[Ss]ecret|[Pp]ass(?:word)?)\b\s*${IS}\s*(?=\S*\d)\S{12,}`);
20
+ var SECRET_PATTERNS = [
21
+ // Provider keys
22
+ { re: /\b(?:sk|rk|pk)_(?:live|test)_/i, what: "an API key" },
23
+ { re: /\bsk-(?:proj-|ant-|svcacct-)?[A-Za-z0-9_-]{16,}/, what: "an API key" },
24
+ { re: /\bre_(?=[A-Za-z0-9_]*[0-9A-Z])[A-Za-z0-9_]{12,}/, what: "an API key" },
25
+ { re: /\bwhsec_[A-Za-z0-9+/=]{10,}/, what: "an API key" },
26
+ { re: /\bAIza[0-9A-Za-z_-]{30,}/, what: "an API key" },
27
+ { re: /\bEAAA[A-Za-z0-9_-]{30,}/, what: "an API key" },
28
+ { re: /\bsq0(?:atp|csp|idp)-[A-Za-z0-9_-]{16,}/, what: "an API key" },
29
+ { re: /\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/, what: "an API key" },
30
+ { re: /\b[0-9a-f]{32}-us\d{1,2}\b/, what: "an API key" },
31
+ { re: /\bshp(?:at|ss|ca|pa)_[A-Fa-f0-9]{20,}/, what: "an API key" },
32
+ { re: /\bnpm_[A-Za-z0-9]{30,}/, what: "an API key" },
33
+ { re: /\bsonor_[A-Za-z0-9]{6,}_[A-Za-z0-9_-]{8,}/, what: "an API key" },
34
+ { re: /\bsb_(?:secret|publishable)_[A-Za-z0-9_-]{8,}/, what: "an API key" },
35
+ // Access tokens
36
+ { re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/, what: "an access key" },
37
+ { re: /\bgh[pousr]_[A-Za-z0-9]{20,}/, what: "an access token" },
38
+ { re: /\bgithub_pat_[A-Za-z0-9_]{20,}/, what: "an access token" },
39
+ { re: /\bglpat-[A-Za-z0-9_-]{20,}/, what: "an access token" },
40
+ { re: /\bxox[abprse]-[A-Za-z0-9-]{10,}/, what: "an access token" },
41
+ { re: /hooks\.slack\.com\/services\/[A-Za-z0-9/]{16,}/, what: "an access token" },
42
+ { re: /\bBearer\s+[A-Za-z0-9._~+/-]{12,}=*/i, what: "a login token" },
43
+ { re: /\bBasic\s+[A-Za-z0-9+/]{16,}={0,2}/, what: "a login token" },
44
+ { re: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}/, what: "a login token" },
45
+ { re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/, what: "a private key" },
46
+ { re: /[?&](?:api[_-]?key|access[_-]?token|auth[_-]?token|token|secret|client[_-]?secret|password|pwd|sig|signature)=[^&\s]{6,}/i, what: "an API key" },
47
+ // Credentials said in words: "<service> key is ...", "the token: ...", "password is ...".
48
+ { re: CREDENTIAL_IS_VALUE, what: "an access token" },
49
+ { re: PASSWORD_IS_VALUE, what: "a password" },
50
+ { re: USER_THEN_PASS, what: "a login" },
51
+ { re: LOGIN_EMAIL_SECRET, what: "a login" },
52
+ { re: LOGIN_USER_SECRET, what: "a login" },
53
+ { re: NAMED_CODE, what: "a PIN or access code" },
54
+ { re: BARE_LOCK_CODE, what: "a PIN or access code" },
55
+ { re: /\bkey-[a-z0-9]{24,}\b/i, what: "an API key" },
56
+ { re: NAMED_SERVICE_SECRET, what: "an access token" },
57
+ { re: /\b(?:password|passcode|passwd|pwd|passphrase|pw)\b[:=]?\s+(?=\S*[\d!@#$%^&*?])\S{4,}/i, what: "a password" },
58
+ { re: /\b(?:pin|pin code|pin number|passcode|gate code|door code|alarm code|lock code|lockbox code|access code|security code|garage code|cvv|cvc)\b\s*(?:is|was|=|:|-)?\s*#?\d{3,8}\b/i, what: "a PIN or access code" },
59
+ { re: /\b[a-z][a-z0-9+.-]{0,31}:\/\/[^\s/:@]+:[^\s/@]+@/i, what: "a login" },
60
+ // Bank and identity numbers
61
+ { re: /\b(?:routing|aba|rtn|transit)\s*(?:number|no\.?|#)?\s*(?:is|:|=|-)?\s*\d{9}\b/i, what: "a bank routing number" },
62
+ { re: /\b(?:bank|checking|savings|acct|account)\s*(?:number|no\.?|#)\s*(?:is|:|=|-)?\s*\d[\d -]{4,20}\d\b/i, what: "a bank account number" },
63
+ { re: /\bbank\s+account\s*(?:is|:|=|-)?\s*\d{6,17}\b/i, what: "a bank account number" },
64
+ { re: /\b\d{3}-\d{2}-\d{4}\b/, what: "a social security number" },
65
+ { re: /\b(?:ssn|social security(?: number)?)\b\D{0,15}\d{9}\b/i, what: "a social security number" }
66
+ ];
67
+ function luhn(digits) {
68
+ let sum = 0;
69
+ let double = false;
70
+ for (let i = digits.length - 1; i >= 0; i--) {
71
+ let d = digits.charCodeAt(i) - 48;
72
+ if (double) {
73
+ d *= 2;
74
+ if (d > 9) d -= 9;
75
+ }
76
+ sum += d;
77
+ double = !double;
78
+ }
79
+ return sum % 10 === 0;
80
+ }
81
+ function looksLikeCard(digits) {
82
+ const n = digits.length;
83
+ const head = (k) => Number(digits.slice(0, k));
84
+ if (digits[0] === "4") return n === 13 || n === 16 || n === 19;
85
+ if (n === 16 && (head(2) >= 51 && head(2) <= 55 || head(4) >= 2221 && head(4) <= 2720)) return true;
86
+ if (n === 15 && (head(2) === 34 || head(2) === 37)) return true;
87
+ if (n >= 16 && n <= 19 && (head(4) === 6011 || head(3) >= 644 && head(3) <= 649 || head(2) === 65 || head(2) === 62)) return true;
88
+ if (n >= 16 && n <= 19 && head(4) >= 3528 && head(4) <= 3589) return true;
89
+ if (n >= 14 && n <= 19 && (head(3) >= 300 && head(3) <= 305 || head(2) === 36 || head(2) === 38 || head(2) === 39)) return true;
90
+ if (n >= 12 && n <= 19 && [5018, 5020, 5038, 5893, 6304, 6759, 6761, 6762, 6763].includes(head(4))) return true;
91
+ return false;
92
+ }
93
+ function hasIban(s) {
94
+ for (const [candidate] of s.matchAll(/\b[A-Z]{2}\d{2} ?(?:[A-Z0-9]{4} ?){2,7}[A-Z0-9]{1,4}\b/g)) {
95
+ const compact = candidate.replace(/ /g, "");
96
+ if (compact.length < 15 || compact.length > 34) continue;
97
+ const rearranged = compact.slice(4) + compact.slice(0, 4);
98
+ let remainder = 0;
99
+ for (const ch of rearranged) {
100
+ const value = ch >= "A" && ch <= "Z" ? String(ch.charCodeAt(0) - 55) : ch;
101
+ for (const digit of value) remainder = (remainder * 10 + (digit.charCodeAt(0) - 48)) % 97;
102
+ }
103
+ if (remainder === 1) return true;
104
+ }
105
+ return false;
106
+ }
107
+ function quoteSecretReason(text) {
108
+ const s = typeof text === "string" ? text : "";
109
+ if (!s) return null;
110
+ for (const { re, what } of SECRET_PATTERNS) if (re.test(s)) return what;
111
+ if (PROJECT_API_KEY.test(s)) return "an API key";
112
+ for (const m of s.matchAll(/\b(?:\d[ -]?){13,19}\b/g)) {
113
+ const digits = m[0].replace(/\D/g, "");
114
+ if (digits.length >= 13 && digits.length <= 19 && luhn(digits) && looksLikeCard(digits)) return "a payment card number";
115
+ }
116
+ if (hasIban(s)) return "a bank account number";
117
+ if (hasLoginPair(s)) return "a login";
118
+ if (hasKeyedToken(s) || hasNoiseRun(s)) return "an access token";
119
+ return null;
120
+ }
121
+ function refuseQuote(quote) {
122
+ if (typeof quote !== "string") return null;
123
+ if (quote.length > QUOTE_MAX_LENGTH) return "too_long";
124
+ return quoteSecretReason(quote) === null ? null : "secret";
125
+ }
126
+ function hasKeyedToken(s) {
127
+ const prose = s.replace(/\b(?:https?:\/\/|www\.)\S+/gi, " ");
128
+ if (/\b(?=[0-9a-f]*[a-f])(?=[0-9a-f]*\d)[0-9a-f]{32,}\b/i.test(prose)) return true;
129
+ for (const m of prose.matchAll(/\b(?:token|key|secret|sid)s?\b\s*(?:\b(?:is|was)\b|=|:|-)?\s*([A-Za-z0-9_-]{24,})/gi)) {
130
+ const token = m[1];
131
+ if (!/\d/.test(token) || !/[A-Za-z]/.test(token) || (token.match(/-/g)?.length ?? 0) > 1) continue;
132
+ if (looksLikeName(token) || wordShare(token) >= WORDS_SHARE) continue;
133
+ if (shannonEntropy(token) >= 3.3) return true;
134
+ }
135
+ return false;
136
+ }
137
+ var LOGIN_WORD = /\b(?:login|log-?in|logins|username|user ?name|user id|credentials|creds|sign-?in)\b/gi;
138
+ function hasLoginPair(s) {
139
+ for (const m of s.matchAll(LOGIN_WORD)) {
140
+ const after = s.slice((m.index ?? 0) + m[0].length, (m.index ?? 0) + m[0].length + 80);
141
+ const pair = /(?:^|[\s:=])([^\s/:=]{2,})\s*\/\s*([^\s/]{3,})/.exec(after);
142
+ if (!pair) continue;
143
+ const [, user, password] = pair;
144
+ if (user.includes(".") && !user.includes("@")) continue;
145
+ if (/^https?$/i.test(user) || /^[a-z0-9-]+\.[a-z]{2,}/i.test(password)) continue;
146
+ return true;
147
+ }
148
+ return false;
149
+ }
150
+ function wordShare(run) {
151
+ const body = run.replace(/[-_]/g, "");
152
+ let inWords = 0;
153
+ for (const m of body.matchAll(/[A-Z][a-z]{2,}|[a-z]{4,}/g)) inWords += m[0].length;
154
+ return body.length ? inWords / body.length : 0;
155
+ }
156
+ var WORDS_SHARE = 0.5;
157
+ function looksLikeName(run) {
158
+ const pieces = run.split(/[-_]/).filter(Boolean);
159
+ return pieces.length >= 3 && pieces.every((piece) => piece.length <= 14);
160
+ }
161
+ var NOISE_RUN_LENGTH = 32;
162
+ var NOISE_RUN_ENTROPY = 4;
163
+ function hasNoiseRun(s) {
164
+ const prose = stripAddresses(s.replace(/\b(?:https?:\/\/|www\.)\S+/gi, " "));
165
+ for (const [run] of prose.matchAll(new RegExp(`[A-Za-z0-9_\\-+/=]{${NOISE_RUN_LENGTH},}`, "g"))) {
166
+ if (!/\d/.test(run) || !/[A-Za-z]/.test(run)) continue;
167
+ if (looksLikeName(run) || wordShare(run) >= WORDS_SHARE) continue;
168
+ if (shannonEntropy(run) >= NOISE_RUN_ENTROPY) return true;
169
+ }
170
+ return false;
171
+ }
172
+ function stripAddresses(s) {
173
+ if (!s.includes("@")) return s;
174
+ return s.replace(/\S+/g, (chunk) => {
175
+ const at = chunk.indexOf("@", 1);
176
+ if (at === -1) return chunk;
177
+ const dot = chunk.indexOf(".", at + 2);
178
+ return dot !== -1 && dot <= chunk.length - 2 ? " " : chunk;
179
+ });
180
+ }
181
+ function shannonEntropy(text) {
182
+ const counts = /* @__PURE__ */ new Map();
183
+ for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
184
+ let bits = 0;
185
+ for (const n of counts.values()) {
186
+ const p = n / text.length;
187
+ bits -= p * Math.log2(p);
188
+ }
189
+ return bits;
190
+ }
191
+
192
+ exports.QUOTE_MAX_LENGTH = QUOTE_MAX_LENGTH;
193
+ exports.quoteSecretReason = quoteSecretReason;
194
+ exports.refuseQuote = refuseQuote;