From 55cdd9079f0dd0be3abfc4423a1cef1383a67e27 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 00:55:15 +0000 Subject: [PATCH] feat(recipes): seven recipes built on run-on-each MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - env-file-to-kubernetes-secret: .env → Secret manifest with data: (not stringData, which kubectl's YAML 1.1 reads on/yes/no as booleans) - convert-unix-timestamps-in-json: flatten → per-value epoch → ISO → unflatten - decode-jwts-in-log-file: every distinct token's payload, date claims as ISO - remove-tracking-parameters-from-urls: curated drop list per bare link - hash-email-list-for-customer-match: Google's normalization, SHA-256 per line - extract-domains-from-urls: hostname per line with the browser's URL rules - parse-user-agents-from-access-log: UA field per line → CSV Guides name each recipe's limits; the pages people paste secrets or personal data into explain the editor's input history and share links. decode-kubernetes-secret links back to the .env recipe. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016MBDS61t2hQgzoraTNWAvz --- CHANGELOG.md | 7 + src/recipes/_generated/index.ts | 130 ++++++++++++++++++ src/recipes/_generated/loaders.ts | 7 + src/recipes/_generated/static.ts | 36 +++-- .../convert-unix-timestamps-in-json/guide.md | 40 ++++++ .../convert-unix-timestamps-in-json/recipe.ts | 50 +++++++ src/recipes/decode-jwts-in-log-file/guide.md | 28 ++++ src/recipes/decode-jwts-in-log-file/recipe.ts | 41 ++++++ .../decode-kubernetes-secret/recipe.ts | 2 +- .../env-file-to-kubernetes-secret/guide.md | 36 +++++ .../env-file-to-kubernetes-secret/recipe.ts | 92 +++++++++++++ .../extract-domains-from-urls/guide.md | 33 +++++ .../extract-domains-from-urls/recipe.ts | 55 ++++++++ .../guide.md | 34 +++++ .../recipe.ts | 44 ++++++ .../guide.md | 31 +++++ .../recipe.ts | 77 +++++++++++ .../guide.md | 34 +++++ .../recipe.ts | 93 +++++++++++++ 19 files changed, 858 insertions(+), 12 deletions(-) create mode 100644 src/recipes/convert-unix-timestamps-in-json/guide.md create mode 100644 src/recipes/convert-unix-timestamps-in-json/recipe.ts create mode 100644 src/recipes/decode-jwts-in-log-file/guide.md create mode 100644 src/recipes/decode-jwts-in-log-file/recipe.ts create mode 100644 src/recipes/env-file-to-kubernetes-secret/guide.md create mode 100644 src/recipes/env-file-to-kubernetes-secret/recipe.ts create mode 100644 src/recipes/extract-domains-from-urls/guide.md create mode 100644 src/recipes/extract-domains-from-urls/recipe.ts create mode 100644 src/recipes/hash-email-list-for-customer-match/guide.md create mode 100644 src/recipes/hash-email-list-for-customer-match/recipe.ts create mode 100644 src/recipes/parse-user-agents-from-access-log/guide.md create mode 100644 src/recipes/parse-user-agents-from-access-log/recipe.ts create mode 100644 src/recipes/remove-tracking-parameters-from-urls/guide.md create mode 100644 src/recipes/remove-tracking-parameters-from-urls/recipe.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e79044..9f16983 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Added + +- **Seven recipes built on run on each**: turn a `.env` file into a Kubernetes Secret; convert Unix timestamps + in a JSON response to dates; decode every JWT in a log, HAR file or curl trace; remove tracking parameters + from a list of URLs; hash an email list with SHA-256 for Customer Match; extract the domain from each URL in + a list; parse the user agents of an access log into a CSV. + ### Changed - Recipe pages show what runs inside a run-on-each or branch step: every nested step with its link, the diff --git a/src/recipes/_generated/index.ts b/src/recipes/_generated/index.ts index d99bafc..ec91708 100644 --- a/src/recipes/_generated/index.ts +++ b/src/recipes/_generated/index.ts @@ -50,6 +50,24 @@ export const RECIPE_INDEX: RecipeMeta[] = [ "stepCount": 6, "published": "2026-10-07" }, + { + "slug": "convert-unix-timestamps-in-json", + "name": "Convert Unix timestamps in a JSON response to dates", + "summary": "Paste an API response and get the same JSON back with its epoch seconds and milliseconds turned into ISO 8601 dates at any depth, while small ids, prices and phone numbers stay as they are.", + "category": "Web & APIs", + "utilityIds": [ + "json_flatten", + "json_unflatten", + "timestamp_convert" + ], + "chain": [ + "flatten to paths", + "convert epoch values", + "rebuild the JSON" + ], + "stepCount": 3, + "published": "2026-10-08" + }, { "slug": "decode-cloudwatch-logs-data", "name": "Decode CloudWatch Logs subscription data", @@ -116,6 +134,25 @@ export const RECIPE_INDEX: RecipeMeta[] = [ "stepCount": 5, "published": "2026-10-07" }, + { + "slug": "decode-jwts-in-log-file", + "name": "Decode every JWT in a log or HAR file", + "summary": "Paste a log, a HAR export or a curl -v trace and read the claims of every JSON Web Token in it, each once, with iat, exp and auth_time shown as dates instead of epoch seconds.", + "category": "Web & APIs", + "utilityIds": [ + "extract_preset", + "jsonl_to_json", + "jwt_decode", + "timestamp_convert" + ], + "chain": [ + "find every token", + "decode each token", + "one JSON array" + ], + "stepCount": 3, + "published": "2026-10-08" + }, { "slug": "decode-kubernetes-secret", "name": "Decode a Kubernetes Secret", @@ -156,6 +193,26 @@ export const RECIPE_INDEX: RecipeMeta[] = [ "stepCount": 5, "published": "2026-10-07" }, + { + "slug": "env-file-to-kubernetes-secret", + "name": "Turn a .env file into a Kubernetes Secret", + "summary": "Paste a .env file and get a Secret manifest with every value Base64-encoded under data, ready for kubectl apply, with quotes, export prefixes, comments and multi-line values handled.", + "category": "DevOps & Config", + "utilityIds": [ + "base64_encode", + "env_to_json", + "json_to_yaml", + "replace" + ], + "chain": [ + "parse the .env file", + "encode every value", + "wrap in a Secret", + "json to yaml" + ], + "stepCount": 4, + "published": "2026-10-08" + }, { "slug": "excel-column-to-sql-in-clause", "name": "Turn an Excel column into a SQL IN clause", @@ -178,6 +235,24 @@ export const RECIPE_INDEX: RecipeMeta[] = [ "published": "2026-10-07", "updated": "2026-10-08" }, + { + "slug": "extract-domains-from-urls", + "name": "Extract the domain from a list of URLs", + "summary": "Paste a column of links and get each one’s hostname on the same line, lowercased and without www., whether or not the link starts with https://, so it pastes back beside its URL.", + "category": "Data & Spreadsheets", + "utilityIds": [ + "jsonpath", + "line_affix", + "replace", + "url_parse" + ], + "chain": [ + "hostname of every URL", + "drop www." + ], + "stepCount": 2, + "published": "2026-10-08" + }, { "slug": "fix-bash-bad-interpreter", "name": "Fix ^M bad interpreter errors in a shell script", @@ -221,6 +296,25 @@ export const RECIPE_INDEX: RecipeMeta[] = [ "stepCount": 6, "published": "2026-10-07" }, + { + "slug": "hash-email-list-for-customer-match", + "name": "Hash an email list for Customer Match", + "summary": "Paste a column of customer emails and get one SHA-256 hash per line, normalized the way Google Ads Customer Match expects, with header and blank rows kept so rows still line up.", + "category": "Writing & Marketing", + "utilityIds": [ + "case", + "hash", + "replace" + ], + "chain": [ + "remove spaces and quotes", + "change case", + "drop Gmail dots", + "SHA-256 every address" + ], + "stepCount": 4, + "published": "2026-10-08" + }, { "slug": "nested-json-to-csv", "name": "Convert nested JSON to CSV", @@ -239,6 +333,42 @@ export const RECIPE_INDEX: RecipeMeta[] = [ "stepCount": 3, "published": "2026-10-07" }, + { + "slug": "parse-user-agents-from-access-log", + "name": "Parse user agents from an access log into a CSV", + "summary": "Paste nginx or Apache access log lines, or a column of user-agent strings, and get a CSV row per line with the browser, OS, device and a bot flag.", + "category": "Web & APIs", + "utilityIds": [ + "json_to_csv", + "jsonl_to_json", + "replace", + "user_agent_parse" + ], + "chain": [ + "keep the user-agent field", + "parse every line", + "collect into an array", + "pick columns as CSV" + ], + "stepCount": 4, + "published": "2026-10-08" + }, + { + "slug": "remove-tracking-parameters-from-urls", + "name": "Remove tracking parameters from a list of URLs", + "summary": "Paste links one per line and get them back without utm_ tags, fbclid, gclid, srsltid and other click ids, with the parameters a page needs, the order and any #anchor kept.", + "category": "Writing & Marketing", + "utilityIds": [ + "query_params_normalize", + "unescape_html" + ], + "chain": [ + "undo &", + "clean every link" + ], + "stepCount": 2, + "published": "2026-10-08" + }, { "slug": "spring-boot-yaml-to-env-vars", "name": "Convert Spring Boot application.yml to environment variables", diff --git a/src/recipes/_generated/loaders.ts b/src/recipes/_generated/loaders.ts index 5d4f4fe..5c4dd1b 100644 --- a/src/recipes/_generated/loaders.ts +++ b/src/recipes/_generated/loaders.ts @@ -5,15 +5,22 @@ import type { Recipe } from '../types' export const RECIPE_LOADERS: Record Promise<{ recipe: Recipe; guide: string }>> = { "bulk-utm-link-builder": () => Promise.all([import('../bulk-utm-link-builder/recipe'), import('../bulk-utm-link-builder/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "clean-chatgpt-text": () => Promise.all([import('../clean-chatgpt-text/recipe'), import('../clean-chatgpt-text/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), + "convert-unix-timestamps-in-json": () => Promise.all([import('../convert-unix-timestamps-in-json/recipe'), import('../convert-unix-timestamps-in-json/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "decode-cloudwatch-logs-data": () => Promise.all([import('../decode-cloudwatch-logs-data/recipe'), import('../decode-cloudwatch-logs-data/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "decode-flask-session-cookie": () => Promise.all([import('../decode-flask-session-cookie/recipe'), import('../decode-flask-session-cookie/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "decode-helm-release-secret": () => Promise.all([import('../decode-helm-release-secret/recipe'), import('../decode-helm-release-secret/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), + "decode-jwts-in-log-file": () => Promise.all([import('../decode-jwts-in-log-file/recipe'), import('../decode-jwts-in-log-file/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "decode-kubernetes-secret": () => Promise.all([import('../decode-kubernetes-secret/recipe'), import('../decode-kubernetes-secret/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "decode-saml-request": () => Promise.all([import('../decode-saml-request/recipe'), import('../decode-saml-request/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), + "env-file-to-kubernetes-secret": () => Promise.all([import('../env-file-to-kubernetes-secret/recipe'), import('../env-file-to-kubernetes-secret/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "excel-column-to-sql-in-clause": () => Promise.all([import('../excel-column-to-sql-in-clause/recipe'), import('../excel-column-to-sql-in-clause/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), + "extract-domains-from-urls": () => Promise.all([import('../extract-domains-from-urls/recipe'), import('../extract-domains-from-urls/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "fix-bash-bad-interpreter": () => Promise.all([import('../fix-bash-bad-interpreter/recipe'), import('../fix-bash-bad-interpreter/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "fix-pdf-line-breaks": () => Promise.all([import('../fix-pdf-line-breaks/recipe'), import('../fix-pdf-line-breaks/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), + "hash-email-list-for-customer-match": () => Promise.all([import('../hash-email-list-for-customer-match/recipe'), import('../hash-email-list-for-customer-match/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "nested-json-to-csv": () => Promise.all([import('../nested-json-to-csv/recipe'), import('../nested-json-to-csv/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), + "parse-user-agents-from-access-log": () => Promise.all([import('../parse-user-agents-from-access-log/recipe'), import('../parse-user-agents-from-access-log/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), + "remove-tracking-parameters-from-urls": () => Promise.all([import('../remove-tracking-parameters-from-urls/recipe'), import('../remove-tracking-parameters-from-urls/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "spring-boot-yaml-to-env-vars": () => Promise.all([import('../spring-boot-yaml-to-env-vars/recipe'), import('../spring-boot-yaml-to-env-vars/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), "unescape-stringified-json": () => Promise.all([import('../unescape-stringified-json/recipe'), import('../unescape-stringified-json/guide.md?raw')]).then(([r, g]) => ({ recipe: r.default, guide: g.default })), } diff --git a/src/recipes/_generated/static.ts b/src/recipes/_generated/static.ts index 4231312..8915e1c 100644 --- a/src/recipes/_generated/static.ts +++ b/src/recipes/_generated/static.ts @@ -2,17 +2,24 @@ import type { Recipe } from '../types' import r0 from '../bulk-utm-link-builder/recipe' import r1 from '../clean-chatgpt-text/recipe' -import r2 from '../decode-cloudwatch-logs-data/recipe' -import r3 from '../decode-flask-session-cookie/recipe' -import r4 from '../decode-helm-release-secret/recipe' -import r5 from '../decode-kubernetes-secret/recipe' -import r6 from '../decode-saml-request/recipe' -import r7 from '../excel-column-to-sql-in-clause/recipe' -import r8 from '../fix-bash-bad-interpreter/recipe' -import r9 from '../fix-pdf-line-breaks/recipe' -import r10 from '../nested-json-to-csv/recipe' -import r11 from '../spring-boot-yaml-to-env-vars/recipe' -import r12 from '../unescape-stringified-json/recipe' +import r2 from '../convert-unix-timestamps-in-json/recipe' +import r3 from '../decode-cloudwatch-logs-data/recipe' +import r4 from '../decode-flask-session-cookie/recipe' +import r5 from '../decode-helm-release-secret/recipe' +import r6 from '../decode-jwts-in-log-file/recipe' +import r7 from '../decode-kubernetes-secret/recipe' +import r8 from '../decode-saml-request/recipe' +import r9 from '../env-file-to-kubernetes-secret/recipe' +import r10 from '../excel-column-to-sql-in-clause/recipe' +import r11 from '../extract-domains-from-urls/recipe' +import r12 from '../fix-bash-bad-interpreter/recipe' +import r13 from '../fix-pdf-line-breaks/recipe' +import r14 from '../hash-email-list-for-customer-match/recipe' +import r15 from '../nested-json-to-csv/recipe' +import r16 from '../parse-user-agents-from-access-log/recipe' +import r17 from '../remove-tracking-parameters-from-urls/recipe' +import r18 from '../spring-boot-yaml-to-env-vars/recipe' +import r19 from '../unescape-stringified-json/recipe' export const STATIC_RECIPES: Recipe[] = [ r0, @@ -28,4 +35,11 @@ export const STATIC_RECIPES: Recipe[] = [ r10, r11, r12, + r13, + r14, + r15, + r16, + r17, + r18, + r19, ] diff --git a/src/recipes/convert-unix-timestamps-in-json/guide.md b/src/recipes/convert-unix-timestamps-in-json/guide.md new file mode 100644 index 0000000..0f60984 --- /dev/null +++ b/src/recipes/convert-unix-timestamps-in-json/guide.md @@ -0,0 +1,40 @@ +--- +title: Convert Unix Timestamps in JSON to Readable Dates +description: Paste an API response and turn every epoch seconds or milliseconds value into an ISO 8601 date at any depth, leaving the rest of the JSON as it was. +--- + +## Reading dates in an API response + +Most APIs send dates as Unix time: `"created_at": 1790848800` in seconds, or `"ts": 1790848800123` in milliseconds. That is compact and unambiguous for code, and unreadable for a person comparing two orders or checking when a token expires. Converting them one at a time means copying each number into a converter and back, and a response with a page of fifty records has a hundred or more of them, at different depths and under different names. + +A find-and-replace over the raw text cannot do it either, because the replacement is not fixed text: every number becomes a different date. This recipe keeps the JSON as JSON, finds every value that looks like a timestamp wherever it sits, converts it, and gives you the response back in its own shape. + +## What each step does + +[JSON flatten](/util/json_flatten/) turns the document into a single object of paths and values, such as `data[0].created_at` or `[2].ts` for a top-level array. That brings every value, however deeply nested, to the top level, where the next step can visit them one by one. Keys that contain dots or brackets are quoted in the path, so they survive the trip back. + +The second step runs [timestamp convert](/util/timestamp_convert/) on each value on its own, set to ISO 8601 in UTC, but only when the value matches a pattern: 10 digits starting with 12 to 19 (seconds) or 13 digits starting the same way (milliseconds), with an optional fraction. Numbers written as strings, such as `"issued_at": "1790848800"`, match too. Everything else, including `null`, short numbers and text, passes through untouched. To see local time instead, change the timezone in step 2 to an IANA name such as `Europe/Paris`, which gives `2026-10-01T12:00:00.000+02:00`, or switch convert to to `sql` or `rfc2822` for those formats. + +[JSON unflatten](/util/json_unflatten/) then rebuilds the nesting from the paths, in the original key order. + +## What it can mistake for a date + +The pattern looks only at the value, never at its key, so it covers the years 2008 to 2033: from 2008-01-10 (`1200000000`) to 2033-05-18 (`1999999999`). Anything else of that shape is converted too: + +- money in micros, such as a Google Ads `costMicros` of `1500000000` for 1,500 in the account currency; +- byte counts between 1.2 and 2 GB; +- ids of 10 or 13 digits that start with 12 to 19, such as some Google Ads customer ids. + +Dates outside that window stay numbers, and so do microseconds (16 digits) and nanoseconds (19 digits). Scan the output for fields that should not have turned into dates, and fix those by hand or leave them out of what you paste. + +Integers larger than 2^53 (about 9 × 10^15) cannot be held exactly by JavaScript, so a 19-digit id comes back rounded, `1712345678901234567` as `1712345678901234700`. APIs that send such ids usually include a string copy (`id_str` and similar); read that one. + +## Input it cannot read + +The input has to be one JSON document. JSON Lines (one object per line), `curl -i` output with the HTTP headers on top, JSON with comments or trailing commas, and a Python dict printed with single quotes and `True` all stop at the first step with "invalid JSON". Copy only the body, or convert it first. A field whose value is a JSON document stored as a string keeps its timestamps unconverted: decode it with the [unescape stringified JSON](/recipes/unescape-stringified-json/) recipe, then run this one. + +One run converts at most 100,000 values. A larger response stops at step 2 with a message saying how many it has: split it, or use jq. + +## The same in jq + +`jq 'walk(if type == "number" and . >= 1200000000 and . < 2000000000 then todate elif type == "number" and . >= 1200000000000 and . < 2000000000000 then (. / 1000 | todate) else . end)'` does the same for numbers, with no size limit, but drops the milliseconds and leaves timestamps written as strings alone. diff --git a/src/recipes/convert-unix-timestamps-in-json/recipe.ts b/src/recipes/convert-unix-timestamps-in-json/recipe.ts new file mode 100644 index 0000000..ab373ea --- /dev/null +++ b/src/recipes/convert-unix-timestamps-in-json/recipe.ts @@ -0,0 +1,50 @@ +import type { Recipe } from '../types' +import { each, laneStep, step } from '../define' + +/** 10-digit epoch seconds or 13-digit epoch milliseconds from 2008-01-10 to 2033-05-18, optional fraction. */ +const EPOCH = '^1[2-9]\\d{8}(?:\\d{3})?(?:\\.\\d+)?$' + +const recipe: Recipe = { + slug: 'convert-unix-timestamps-in-json', + name: 'Convert Unix timestamps in a JSON response to dates', + summary: + 'Paste an API response and get the same JSON back with its epoch seconds and milliseconds turned into ISO 8601 dates at any depth, while small ids, prices and phone numbers stay as they are.', + category: 'Web & APIs', + primaryQuery: 'convert unix timestamps in json to dates', + published: '2026-10-08', + related: ['unescape-stringified-json', 'nested-json-to-csv'], + steps: [ + step('flatten', 'json_flatten', { arrayNotation: 'bracket', indent: 2 }, + 'Turns the response into one path per value, such as data[0].created_at, so the next step reaches timestamps at any depth, inside a top-level array too. Keys containing dots or brackets are quoted, so they rebuild exactly.', + { label: 'flatten to paths' }), + each('convert', { mode: 'json-values' }, [ + laneStep('to-iso', 'timestamp_convert', { to: 'iso', timezone: 'UTC' }, { condition: { kind: 'regex', pattern: EPOCH } }), + ], + 'Converts each value on its own, but only a 10-digit seconds or 13-digit milliseconds number between 2008 and 2033. Small ids, prices, phone numbers and expires_in durations do not match and stay as they are; the guide lists the numbers that can.', + { label: 'convert epoch values' }), + step('unflatten', 'json_unflatten', { indent: 2 }, + 'Rebuilds the nesting from the paths, in the original key order, so you get the response back in its own shape with readable dates where the numbers were.', + { label: 'rebuild the JSON' }), + ], + samples: [ + { + id: 'orders-list', + title: 'List endpoint (epoch seconds)', + input: "{\n \"data\": [\n {\n \"id\": 48213,\n \"status\": \"shipped\",\n \"amount\": 4999,\n \"currency\": \"usd\",\n \"created_at\": 1790848800,\n \"shipped_at\": 1790942522,\n \"customer\": {\n \"name\": \"Dana Whitfield\",\n \"phone\": \"4155550123\"\n }\n },\n {\n \"id\": 48214,\n \"status\": \"pending\",\n \"amount\": 1250,\n \"currency\": \"usd\",\n \"created_at\": 1790856061,\n \"shipped_at\": null,\n \"customer\": {\n \"name\": \"Luis Ortega\",\n \"phone\": \"2025550147\"\n }\n }\n ],\n \"has_more\": true,\n \"next_cursor\": \"b3JkZXI6NDgyMTQ\"\n}\n", + output: "{\n \"data\": [\n {\n \"id\": 48213,\n \"status\": \"shipped\",\n \"amount\": 4999,\n \"currency\": \"usd\",\n \"created_at\": \"2026-10-01T10:00:00.000Z\",\n \"shipped_at\": \"2026-10-02T12:02:02.000Z\",\n \"customer\": {\n \"name\": \"Dana Whitfield\",\n \"phone\": \"4155550123\"\n }\n },\n {\n \"id\": 48214,\n \"status\": \"pending\",\n \"amount\": 1250,\n \"currency\": \"usd\",\n \"created_at\": \"2026-10-01T12:01:01.000Z\",\n \"shipped_at\": null,\n \"customer\": {\n \"name\": \"Luis Ortega\",\n \"phone\": \"2025550147\"\n }\n }\n ],\n \"has_more\": true,\n \"next_cursor\": \"b3JkZXI6NDgyMTQ\"\n}", + }, + { + id: 'events-array', + title: 'Top-level array (milliseconds)', + input: "[\n {\n \"event\": \"login\",\n \"user_id\": 1042,\n \"ip\": \"203.0.113.24\",\n \"ts\": 1790848800123\n },\n {\n \"event\": \"export_started\",\n \"user_id\": 1042,\n \"ip\": \"203.0.113.24\",\n \"ts\": 1790848865410\n },\n {\n \"event\": \"export_failed\",\n \"user_id\": 1042,\n \"ip\": \"203.0.113.24\",\n \"ts\": 1790848901007,\n \"error_code\": 413,\n \"size_bytes\": 1073741824\n }\n]\n", + output: "[\n {\n \"event\": \"login\",\n \"user_id\": 1042,\n \"ip\": \"203.0.113.24\",\n \"ts\": \"2026-10-01T10:00:00.123Z\"\n },\n {\n \"event\": \"export_started\",\n \"user_id\": 1042,\n \"ip\": \"203.0.113.24\",\n \"ts\": \"2026-10-01T10:01:05.410Z\"\n },\n {\n \"event\": \"export_failed\",\n \"user_id\": 1042,\n \"ip\": \"203.0.113.24\",\n \"ts\": \"2026-10-01T10:01:41.007Z\",\n \"error_code\": 413,\n \"size_bytes\": 1073741824\n }\n]", + }, + { + id: 'token-response', + title: 'OAuth token response', + input: "{\n \"access_token\": \"at_7Qm2vX9kLp4RzT8wN3bY\",\n \"token_type\": \"Bearer\",\n \"expires_in\": 3600,\n \"expires_at\": 1790852400,\n \"issued_at\": \"1790848800\",\n \"refresh_expires_in\": 2592000,\n \"scope\": \"orders:read orders:write\"\n}\n", + output: "{\n \"access_token\": \"at_7Qm2vX9kLp4RzT8wN3bY\",\n \"token_type\": \"Bearer\",\n \"expires_in\": 3600,\n \"expires_at\": \"2026-10-01T11:00:00.000Z\",\n \"issued_at\": \"2026-10-01T10:00:00.000Z\",\n \"refresh_expires_in\": 2592000,\n \"scope\": \"orders:read orders:write\"\n}", + }, + ], +} +export default recipe diff --git a/src/recipes/decode-jwts-in-log-file/guide.md b/src/recipes/decode-jwts-in-log-file/guide.md new file mode 100644 index 0000000..66e1819 --- /dev/null +++ b/src/recipes/decode-jwts-in-log-file/guide.md @@ -0,0 +1,28 @@ +--- +title: Decode Every JWT in a Log, HAR or curl Trace at Once +description: Paste a log, a HAR export or a curl -v trace and read the payload of every JSON Web Token in it, each once, with iat, exp and auth_time as dates. +--- + +## Debugging with more than one token + +When a sign-in flow or an API call fails, the evidence is usually a pile of text: an access log with a bearer token on every line, a HAR file exported from the browser's network panel, or the output of `curl -v`. The tokens in it hold what you need to know (who the user was, which audience and scopes the token was issued for, when it expired) but each one is a long `eyJ…` string, and a JWT debugger takes them one at a time. You copy a token out, paste it, convert `exp` from epoch seconds in your head, and repeat for the next request, often only to find it was the same token again. + +This recipe finds every token in what you paste, decodes each distinct one, and lists their payloads together, with the time claims already turned into dates. + +## What each step does + +[extract matches](/util/extract_preset/), set to JWTs, pulls out every string shaped like a token: `eyJ` followed by base64url parts separated by dots. It does not care where the token sits, so an `Authorization` header, a `?access_token=` query parameter, a cookie and a JSON response body all work, and with unique on, a token sent with fifty requests appears once. + +The second step runs on each token on its own. [JWT decode](/util/jwt_decode/) reads the payload, the middle part, as JSON. A nested "run on each" then visits every claim and runs [timestamp convert](/util/timestamp_convert/) on the ones that hold epoch seconds between 2014 and 2033 (`iat`, `exp`, `nbf`, `auth_time` and custom claims like them), writing them as ISO 8601 in UTC. Strings, ids, arrays such as `groups` and other numbers stay as they are. A token that fails to decode is reported in the step's error and comes out as an empty line, which [JSONL to JSON](/util/jsonl_to_json/) skips while it gathers the payloads into one indented array, in the order the tokens first appeared. + +## Limits + +- Tokens that were URL-encoded (`Bearer%20eyJ…`, padding written as `%3D`) or wrapped across lines by a terminal are not decoded: at most a piece of one is found and reported as not a JWT. Run the text through a URL decoder, or join the lines, first. +- Strings that look like tokens but are not signed JWTs are reported and left out: a two-part fragment, an encrypted token (JWE, five parts), and a Flask session cookie, which starts the same way (read that one with the [Flask session cookie](/recipes/decode-flask-session-cookie/) recipe). +- Chrome and Edge 130 and later export HAR files without `Authorization` and `Cookie` headers. To include them, turn on *Allow to generate HAR with sensitive data* in DevTools settings under Network, then export again. +- Only the payload is shown, and nothing is verified: a decoded payload says what the token claims, not that the claims are true. To check a signature against a key or secret, use [JWT verify](/util/jwt_verify/). Whether a token has expired is for you to compare against its `exp`, since the page shows the same result on any date. +- Timestamps before mid-2014 or after May 2033 stay as numbers, as do claims in milliseconds. + +## Tokens in logs are live credentials + +Every access token you paste here works until it expires, and a refresh token often for weeks. The decoding runs in your browser and nothing you paste is uploaded, but treat the input like a password: "Open in the editor" hands it to the editor, which keeps recent inputs in this browser unless you open the History menu on its input panel and untick remember inputs, and a share link carries the input in the URL. If a log with tokens in it has been shared, attached to a ticket or committed anywhere, rotate the credentials and revoke the refresh tokens rather than waiting for them to expire, and ask whoever owns the logging to stop writing them. diff --git a/src/recipes/decode-jwts-in-log-file/recipe.ts b/src/recipes/decode-jwts-in-log-file/recipe.ts new file mode 100644 index 0000000..1b4ecc4 --- /dev/null +++ b/src/recipes/decode-jwts-in-log-file/recipe.ts @@ -0,0 +1,41 @@ +import type { Recipe } from '../types' +import { each, laneEach, laneStep, step } from '../define' + +/** A JWT NumericDate (RFC 7519: seconds) from 2014-05-13 to 2033-05-18, optional fraction. */ +const NUMERIC_DATE = '^1[4-9]\\d{8}(?:\\.\\d+)?$' + +const recipe: Recipe = { + slug: 'decode-jwts-in-log-file', + name: 'Decode every JWT in a log or HAR file', + summary: + 'Paste a log, a HAR export or a curl -v trace and read the claims of every JSON Web Token in it, each once, with iat, exp and auth_time shown as dates instead of epoch seconds.', + category: 'Web & APIs', + primaryQuery: 'decode multiple jwt tokens', + published: '2026-10-08', + related: ['decode-flask-session-cookie', 'decode-saml-request'], + steps: [ + step('find-tokens', 'extract_preset', { type: ['jwt'], unique: true }, + 'Pulls out every JWT-shaped string, eyJ followed by dot-separated base64url parts, wherever it sits: an Authorization header, a query string, a cookie or a JSON body. With unique on, a token repeated on many requests is listed once.', + { label: 'find every token' }), + each('decode', { mode: 'lines' }, [ + laneStep('payload', 'jwt_decode', { part: 'payload' }, { onError: 'stop' }), + laneEach('dates', { mode: 'json-values' }, [ + laneStep('to-iso', 'timestamp_convert', { to: 'iso', timezone: 'UTC' }, { condition: { kind: 'regex', pattern: NUMERIC_DATE } }), + ], { label: 'dates in every claim' }), + ], + 'Decodes each token on its own line into its payload claims, then turns every claim holding epoch seconds, such as iat, exp, nbf and auth_time, into an ISO date. A token that will not decode is reported and left out.', + { label: 'decode each token', onError: 'empty' }), + step('to-array', 'jsonl_to_json', { indent: 2 }, + 'Gathers the one-line results into one indented JSON array, so the claims of each token read top to bottom and the blank lines left by tokens that failed are skipped.', + { label: 'one JSON array' }), + ], + samples: [ + { id: 'api-log', title: 'API access log', input: "2026-10-01T10:00:02Z INFO api req=7f3a2c GET /v1/orders 200 ip=203.0.113.24 auth=\"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20vIiwic3ViIjoidXNlcl8xMDQyIiwiYXVkIjoiaHR0cHM6Ly9hcGkuZXhhbXBsZS5jb20iLCJzY29wZSI6Im9yZGVyczpyZWFkIG9yZGVyczp3cml0ZSIsImlhdCI6MTc5MDg0ODgwMCwiZXhwIjoxNzkwODUyNDAwfQ.Q0weDVzdgqPTVK7_TgAwc4swSUMMxLj7HhXtvrXEk6c\"\n2026-10-01T10:05:00Z INFO api req=7f3a31 GET /v1/reports/daily 200 ip=198.51.100.7 auth=\"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20vIiwic3ViIjoic3ZjLXJlcG9ydGluZyIsImF1ZCI6Imh0dHBzOi8vYXBpLmV4YW1wbGUuY29tIiwic2NvcGUiOiJyZXBvcnRzOnJlYWQiLCJpYXQiOjE3OTA4NDkxMDAsImV4cCI6MTc5MDg1MDAwMH0.2Ssep5A2qoTMJB8B0AFaUzFjy6b-NCtSpgREyTpn9s8\"\n2026-10-01T10:05:12Z INFO api req=7f3a35 POST /v1/orders 201 ip=203.0.113.24 auth=\"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20vIiwic3ViIjoidXNlcl8xMDQyIiwiYXVkIjoiaHR0cHM6Ly9hcGkuZXhhbXBsZS5jb20iLCJzY29wZSI6Im9yZGVyczpyZWFkIG9yZGVyczp3cml0ZSIsImlhdCI6MTc5MDg0ODgwMCwiZXhwIjoxNzkwODUyNDAwfQ.Q0weDVzdgqPTVK7_TgAwc4swSUMMxLj7HhXtvrXEk6c\"\n2026-10-01T10:06:40Z WARN api req=7f3a3b GET /v1/orders/48214 401 ip=192.0.2.55 auth=\"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20vIiwic3ViIjoidXNlcl8yMDg3IiwiYXVkIjoiaHR0cHM6Ly9hcGkuZXhhbXBsZS5jb20iLCJzY29wZSI6Im9yZGVyczpyZWFkIiwiaWF0IjoxNzkwODQxNjAwLCJleHAiOjE3OTA4NDUyMDB9.A1V9syT-hpUrWVCzrzA1nfSzEAR8MKnDzTTAfAwL-mA\" err=\"token expired\"\n", output: "[\n {\n \"iss\": \"https://auth.example.com/\",\n \"sub\": \"user_1042\",\n \"aud\": \"https://api.example.com\",\n \"scope\": \"orders:read orders:write\",\n \"iat\": \"2026-10-01T10:00:00.000Z\",\n \"exp\": \"2026-10-01T11:00:00.000Z\"\n },\n {\n \"iss\": \"https://auth.example.com/\",\n \"sub\": \"svc-reporting\",\n \"aud\": \"https://api.example.com\",\n \"scope\": \"reports:read\",\n \"iat\": \"2026-10-01T10:05:00.000Z\",\n \"exp\": \"2026-10-01T10:20:00.000Z\"\n },\n {\n \"iss\": \"https://auth.example.com/\",\n \"sub\": \"user_2087\",\n \"aud\": \"https://api.example.com\",\n \"scope\": \"orders:read\",\n \"iat\": \"2026-10-01T08:00:00.000Z\",\n \"exp\": \"2026-10-01T09:00:00.000Z\"\n }\n]", + }, + { id: 'har-export', title: 'HAR export (OIDC sign-in)', input: "{\n \"log\": {\n \"version\": \"1.2\",\n \"creator\": {\n \"name\": \"WebInspector\",\n \"version\": \"537.36\"\n },\n \"entries\": [\n {\n \"startedDateTime\": \"2026-10-02T10:00:00.912Z\",\n \"request\": {\n \"method\": \"POST\",\n \"url\": \"https://auth.example.com/oauth/token\",\n \"httpVersion\": \"HTTP/2\",\n \"headers\": [\n {\n \"name\": \"content-type\",\n \"value\": \"application/x-www-form-urlencoded\"\n }\n ],\n \"postData\": {\n \"mimeType\": \"application/x-www-form-urlencoded\",\n \"text\": \"grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&client_id=web-dashboard\"\n }\n },\n \"response\": {\n \"status\": 200,\n \"statusText\": \"\",\n \"content\": {\n \"mimeType\": \"application/json\",\n \"text\": \"{\\\"access_token\\\":\\\"eyJhbGciOiJIUzI1NiIsInR5cCI6ImF0K2p3dCIsImtpZCI6ImstMjAyNi0wOSJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20vIiwic3ViIjoidXNlcl8zMzExIiwiYXVkIjoiaHR0cHM6Ly9hcGkuZXhhbXBsZS5jb20iLCJjbGllbnRfaWQiOiJ3ZWItZGFzaGJvYXJkIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSB0aWNrZXRzOnJlYWQiLCJpYXQiOjE3OTA5MzUyMDEsImV4cCI6MTc5MDkzNjEwMSwianRpIjoiOWMxZTdhNTItM2YwYi00ZDhlLWE2YzItNWI5ZDBlNGY3YTEzIn0.j2K78UyJsvhVJ-sZCAnX5pKAEqdUhj-KhAus-mQGT18\\\",\\\"id_token\\\":\\\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImstMjAyNi0wOSJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20vIiwic3ViIjoidXNlcl8zMzExIiwiYXVkIjoid2ViLWRhc2hib2FyZCIsImVtYWlsIjoibWFyYS5saW5kcXZpc3RAZXhhbXBsZS5vcmciLCJuYW1lIjoiTWFyYSBMaW5kcXZpc3QiLCJncm91cHMiOlsic3VwcG9ydCIsImJpbGxpbmctdmlld2VycyJdLCJhdXRoX3RpbWUiOjE3OTA5MzUyMDAsImlhdCI6MTc5MDkzNTIwMSwiZXhwIjoxNzkwOTM4ODAxLCJub25jZSI6Im4tNGI3ZTFkIn0.mb4O4U4MOjrP5OhIoFX8YN2xRQqBCykasf2mQHQ6uaQ\\\",\\\"token_type\\\":\\\"Bearer\\\",\\\"expires_in\\\":900}\"\n }\n }\n },\n {\n \"startedDateTime\": \"2026-10-02T10:00:02.087Z\",\n \"request\": {\n \"method\": \"GET\",\n \"url\": \"https://api.example.com/v1/tickets?status=open\",\n \"httpVersion\": \"HTTP/2\",\n \"headers\": [\n {\n \"name\": \"authorization\",\n \"value\": \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6ImF0K2p3dCIsImtpZCI6ImstMjAyNi0wOSJ9.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20vIiwic3ViIjoidXNlcl8zMzExIiwiYXVkIjoiaHR0cHM6Ly9hcGkuZXhhbXBsZS5jb20iLCJjbGllbnRfaWQiOiJ3ZWItZGFzaGJvYXJkIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSB0aWNrZXRzOnJlYWQiLCJpYXQiOjE3OTA5MzUyMDEsImV4cCI6MTc5MDkzNjEwMSwianRpIjoiOWMxZTdhNTItM2YwYi00ZDhlLWE2YzItNWI5ZDBlNGY3YTEzIn0.j2K78UyJsvhVJ-sZCAnX5pKAEqdUhj-KhAus-mQGT18\"\n },\n {\n \"name\": \"accept\",\n \"value\": \"application/json\"\n }\n ]\n },\n \"response\": {\n \"status\": 200,\n \"statusText\": \"\",\n \"content\": {\n \"mimeType\": \"application/json\",\n \"text\": \"{\\\"tickets\\\":[]}\"\n }\n }\n }\n ]\n }\n}\n", output: "[\n {\n \"iss\": \"https://auth.example.com/\",\n \"sub\": \"user_3311\",\n \"aud\": \"https://api.example.com\",\n \"client_id\": \"web-dashboard\",\n \"scope\": \"openid profile tickets:read\",\n \"iat\": \"2026-10-02T10:00:01.000Z\",\n \"exp\": \"2026-10-02T10:15:01.000Z\",\n \"jti\": \"9c1e7a52-3f0b-4d8e-a6c2-5b9d0e4f7a13\"\n },\n {\n \"iss\": \"https://auth.example.com/\",\n \"sub\": \"user_3311\",\n \"aud\": \"web-dashboard\",\n \"email\": \"mara.lindqvist@example.org\",\n \"name\": \"Mara Lindqvist\",\n \"groups\": [\n \"support\",\n \"billing-viewers\"\n ],\n \"auth_time\": \"2026-10-02T10:00:00.000Z\",\n \"iat\": \"2026-10-02T10:00:01.000Z\",\n \"exp\": \"2026-10-02T11:00:01.000Z\",\n \"nonce\": \"n-4b7e1d\"\n }\n]", + }, + { id: 'curl-trace', title: 'curl -v trace (unsigned token)', input: "* Trying 192.0.2.10:8443...\n* Connected to dev-api.example.com (192.0.2.10) port 8443\n> GET /v1/admin/users HTTP/1.1\n> Host: dev-api.example.com:8443\n> User-Agent: curl/8.5.0\n> Accept: */*\n> Authorization: Bearer eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ0ZXN0LXVzZXIiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE3OTEwMjE2MDAsImV4cCI6MTc5MTAyNTIwMH0.\n>\n< HTTP/1.1 403 Forbidden\n< content-type: application/json\n< www-authenticate: Bearer error=\"invalid_token\", error_description=\"unsigned tokens are not accepted\"\n<\n{\"error\":\"invalid_token\"}\n", output: "[\n {\n \"sub\": \"test-user\",\n \"role\": \"admin\",\n \"iat\": \"2026-10-03T10:00:00.000Z\",\n \"exp\": \"2026-10-03T11:00:00.000Z\"\n }\n]", + }, + ], +} +export default recipe diff --git a/src/recipes/decode-kubernetes-secret/recipe.ts b/src/recipes/decode-kubernetes-secret/recipe.ts index 25e730b..8b6ce69 100644 --- a/src/recipes/decode-kubernetes-secret/recipe.ts +++ b/src/recipes/decode-kubernetes-secret/recipe.ts @@ -9,7 +9,7 @@ const recipe: Recipe = { category: 'DevOps & Config', primaryQuery: 'decode kubernetes secret', published: '2026-10-07', - related: ['decode-helm-release-secret', 'spring-boot-yaml-to-env-vars'], + related: ['env-file-to-kubernetes-secret', 'decode-helm-release-secret', 'spring-boot-yaml-to-env-vars'], steps: [ step('to-json', 'yaml_to_json', { indent: 2, allDocuments: false }, 'kubectl prints a Secret as YAML by default and as JSON with -o json. JSON is also valid YAML, so one parse handles both and hands the next step a JSON document.'), diff --git a/src/recipes/env-file-to-kubernetes-secret/guide.md b/src/recipes/env-file-to-kubernetes-secret/guide.md new file mode 100644 index 0000000..18f8823 --- /dev/null +++ b/src/recipes/env-file-to-kubernetes-secret/guide.md @@ -0,0 +1,36 @@ +--- +title: Convert a .env File to a Kubernetes Secret Manifest +description: Paste a .env file and get a Kubernetes Secret in YAML, every value Base64-encoded under data, with quotes, comments, export and multi-line values handled. +--- + +## Why kubectl --from-env-file is not enough + +The quick route from a `.env` file to a Secret is `kubectl create secret generic app-env --from-env-file=.env --dry-run=client -o yaml`. It reads every line as `KEY=value` and nothing more, which is not how the file was written for the tools that normally read it. Checked with kubectl 1.37: + +- Quotes stay in the value. `DATABASE_URL="postgres://…"` is stored with both quote marks, and the connection string your app reads starts with `"`. +- An inline comment becomes part of the value: `REDIS_URL=redis://cache:6379/0 # session store` stores the comment and the spaces before it. Trailing whitespace is kept too. +- `export NODE_ENV=production`, common in files that are also sourced by a shell, is rejected as an invalid key. +- A quoted value spread over several lines, such as a PEM certificate, is rejected. + +None of these produce an obvious error in the cluster. The Secret applies cleanly and the pod gets a value that is subtly wrong. + +## What each step does + +[.env to JSON](/util/env_to_json/) parses the file the way application loaders do: comments and blank lines are skipped, an `export` prefix is dropped, quotes are removed, escapes such as `\n` inside double quotes are decoded, and a quoted value may span lines. An unquoted value ends where a `#` follows a space, which matches python-dotenv and Docker Compose. Node's `dotenv` package cuts an unquoted value at any `#`, so quote every value that contains one, and all three read it alike. References such as `${DB_HOST}` are kept as written; tick expand ${VAR} in step 1 to substitute values defined earlier in the file. A line that is not `KEY=value` stops the recipe there, with its line number, instead of producing a half-empty Secret. + +The second step runs [Base64 encode](/util/base64_encode/) on every value of the resulting object on its own, so each variable keeps its name and gets its own encoded value, which is what a Secret's `data` field holds. An empty value stays empty. A [replace](/util/replace/) then wraps the map in a `v1` Secret of type `Opaque`, and [JSON to YAML](/util/json_to_yaml/) writes the manifest in the order of your file. + +The recipe fills `data`, not `stringData`. `stringData` accepts plain text and would make the encoding step unnecessary, but kubectl parses manifests as YAML 1.1, where an unquoted `on`, `off`, `yes` or `no` is a boolean: `ENABLE_SIGNUPS: on` would reach the cluster as `true`. Base64 text never looks like a boolean or a number, so every value arrives exactly as written. + +## Limits and things to check + +- Variable names are not quoted, and kubectl's YAML 1.1 parser reads the names `y`, `n`, `yes`, `no`, `on` and `off`, in any case, as booleans: a variable called `ON` turns into a key named `true`. Rename such variables, or quote those keys in the output. +- The Secret is named `app-env` in step 3, with no namespace. Change the name there to the one your Deployment's `envFrom` or `secretKeyRef` uses, and add a namespace to the metadata or pass `-n` to `kubectl apply`. +- Keys are not checked against what Kubernetes allows in a Secret (letters, digits, `-`, `_` and `.`). A key with any other character is rejected by the API server when you apply the manifest. +- Base64 is an encoding, not encryption. Anyone who can read the manifest can read every value, so do not commit it to a repository as it is: encrypt it with [SOPS](https://github.com/getsops/sops) or turn it into a [Sealed Secret](https://github.com/bitnami-labs/sealed-secrets) first. + +To read a Secret back, the [decode a Kubernetes Secret](/recipes/decode-kubernetes-secret/) recipe does the reverse. + +## What happens to what you paste + +The recipe runs in your browser, and this page stores nothing you type. Two things on it do keep a copy, though. "Open in the editor" hands your input to the editor, which remembers recent inputs in this browser (in IndexedDB) so you can bring them back: to stop that, open the History menu on the editor's input panel and untick remember inputs, and use clear all to remove what is already there. A share link from the editor carries the input in the address after the `#`, so a link made from a real `.env` file is a copy of its secrets. Use made-up values when you want to show someone the result. diff --git a/src/recipes/env-file-to-kubernetes-secret/recipe.ts b/src/recipes/env-file-to-kubernetes-secret/recipe.ts new file mode 100644 index 0000000..33abaf7 --- /dev/null +++ b/src/recipes/env-file-to-kubernetes-secret/recipe.ts @@ -0,0 +1,92 @@ +import type { Recipe } from '../types' +import { each, laneStep, step } from '../define' + +const recipe: Recipe = { + slug: 'env-file-to-kubernetes-secret', + name: 'Turn a .env file into a Kubernetes Secret', + summary: + 'Paste a .env file and get a Secret manifest with every value Base64-encoded under data, ready for kubectl apply, with quotes, export prefixes, comments and multi-line values handled.', + category: 'DevOps & Config', + primaryQuery: 'env file to kubernetes secret', + published: '2026-10-08', + related: ['decode-kubernetes-secret', 'spring-boot-yaml-to-env-vars'], + steps: [ + step('parse', 'env_to_json', { typed: false, expand: false, indent: 2 }, + 'Parses the file: comments, blank lines and export prefixes are dropped, quotes come off and a quoted value can span lines. An unquoted value ends where a # follows a space, as in python-dotenv and Docker Compose. A malformed line stops the recipe here rather than producing a broken Secret.', + { label: 'parse the .env file', onError: 'stop' }), + each('encode-values', { mode: 'json-values' }, [laneStep('b64', 'base64_encode')], + 'Base64-encodes every value on its own and keeps it under its variable name, because a Secret stores each data entry encoded separately. Encoded values also cannot be misread as YAML booleans, the way kubectl reads a plain on, yes or no.', + { label: 'encode every value' }), + step('wrap', 'replace', { + pattern: '^([\\s\\S]*)$', + replacement: '{"apiVersion":"v1","kind":"Secret","metadata":{"name":"app-env"},"type":"Opaque","data":$1}', + regex: true, + flags: '', + }, + 'Puts the encoded map under data in a v1 Secret of type Opaque named app-env. Change the name here, or in the finished YAML, to the one your Deployment references.', + { label: 'wrap in a Secret' }), + step('yaml', 'json_to_yaml', { indent: 2, lineWidth: 80, sortKeys: false }, + 'Writes the manifest as YAML for kubectl apply -f or a GitOps repository. Keys keep the order of the .env file, and long encoded values stay on one line.'), + ], + samples: [ + { + id: 'app-env', + title: 'App .env with quotes and comments', + input: `# payments-api, production +export NODE_ENV=production +PORT=8080 +DATABASE_URL="postgres://payments:p%40ss-2026@db.example.com:5432/payments?sslmode=require" +REDIS_URL=redis://cache.example.com:6379/0 # session store +SESSION_SECRET='k9$Lm#2vQ!x7-not-a-real-secret' +ENABLE_SIGNUPS=on +MAINTENANCE_MODE=no +`, + output: `apiVersion: v1 +kind: Secret +metadata: + name: app-env +type: Opaque +data: + NODE_ENV: cHJvZHVjdGlvbg== + PORT: ODA4MA== + DATABASE_URL: cG9zdGdyZXM6Ly9wYXltZW50czpwJTQwc3MtMjAyNkBkYi5leGFtcGxlLmNvbTo1NDMyL3BheW1lbnRzP3NzbG1vZGU9cmVxdWlyZQ== + REDIS_URL: cmVkaXM6Ly9jYWNoZS5leGFtcGxlLmNvbTo2Mzc5LzA= + SESSION_SECRET: azkkTG0jMnZRIXg3LW5vdC1hLXJlYWwtc2VjcmV0 + ENABLE_SIGNUPS: b24= + MAINTENANCE_MODE: bm8= +`, + }, + { + id: 'multiline-cert', + title: 'Multi-line certificate and empty value', + input: `# internal services trust this CA +CA_CERT="-----BEGIN CERTIFICATE----- +MIIBKjCB3aADAgECAgIgJjAFBgMrZXAwNDEcMBoGA1UEAwwTRXhhbXBsZSBJbnRl +cm5hbCBDQTEUMBIGA1UECgwLRXhhbXBsZSBPcmcwHhcNMjYwMTAxMDAwMDAwWhcN +MzYwMTAxMDAwMDAwWjA0MRwwGgYDVQQDDBNFeGFtcGxlIEludGVybmFsIENBMRQw +EgYDVQQKDAtFeGFtcGxlIE9yZzAqMAUGAytlcAMhAAOhB7/zzhC+HXDdGOdLwJln +5NYwm6UNXx3chmQSVTG4oxMwETAPBgNVHRMBAf8EBTADAQH/MAUGAytlcANBANcT +bXDvEJHs87LUbmNnvVIVfR+KPug9ppwhd2FW1C57UK4e3OmANrUxUuAPCjFKQnDA +iHXMCAnWQypzTbkMnAw= +-----END CERTIFICATE-----" +SMTP_HOST=smtp.example.org +SMTP_FROM="Example Alerts " +WELCOME_TEXT="Hello,\\nyour account is ready." +SENTRY_DSN= +`, + output: `apiVersion: v1 +kind: Secret +metadata: + name: app-env +type: Opaque +data: + CA_CERT: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJLakNCM2FBREFnRUNBZ0lnSmpBRkJnTXJaWEF3TkRFY01Cb0dBMVVFQXd3VFJYaGhiWEJzWlNCSmJuUmwKY201aGJDQkRRVEVVTUJJR0ExVUVDZ3dMUlhoaGJYQnNaU0JQY21jd0hoY05Nall3TVRBeE1EQXdNREF3V2hjTgpNell3TVRBeE1EQXdNREF3V2pBME1Sd3dHZ1lEVlFRRERCTkZlR0Z0Y0d4bElFbHVkR1Z5Ym1Gc0lFTkJNUlF3CkVnWURWUVFLREF0RmVHRnRjR3hsSUU5eVp6QXFNQVVHQXl0bGNBTWhBQU9oQjcvenpoQytIWERkR09kTHdKbG4KNU5Zd202VU5YeDNjaG1RU1ZURzRveE13RVRBUEJnTlZIUk1CQWY4RUJUQURBUUgvTUFVR0F5dGxjQU5CQU5jVApiWER2RUpIczg3TFVibU5udlZJVmZSK0tQdWc5cHB3aGQyRlcxQzU3VUs0ZTNPbUFOclV4VXVBUENqRktRbkRBCmlIWE1DQW5XUXlwelRia01uQXc9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0= + SMTP_HOST: c210cC5leGFtcGxlLm9yZw== + SMTP_FROM: RXhhbXBsZSBBbGVydHMgPGFsZXJ0c0BleGFtcGxlLm9yZz4= + WELCOME_TEXT: SGVsbG8sCnlvdXIgYWNjb3VudCBpcyByZWFkeS4= + SENTRY_DSN: "" +`, + }, + ], +} +export default recipe diff --git a/src/recipes/extract-domains-from-urls/guide.md b/src/recipes/extract-domains-from-urls/guide.md new file mode 100644 index 0000000..a7d9461 --- /dev/null +++ b/src/recipes/extract-domains-from-urls/guide.md @@ -0,0 +1,33 @@ +--- +title: Extract the Domain From Each URL in a List +description: Paste a column of links and get the hostname of each on the same row, lowercased and without www., with or without https://, ports and paths removed. +--- + +## Getting the site out of a list of links + +A backlink export, a crawl report or a column of referrers usually needs one thing from each URL: which site it points to. With a short, tidy list a spreadsheet formula does the job, for example `=REGEXEXTRACT(A2, "^(?:https?://)?(?:www\.)?([^/:?#]+)")` in Google Sheets. Real columns are less tidy. Some links start with `https://`, some with `http://` and a port, some with only `www.` or a bare domain. Some carry a user name before an `@`, some are wrapped in quotes from a CSV file, some have a second column pasted after them, and some hosts are in capitals or are IPv6 addresses in brackets. Each of those needs another case in the pattern. + +This recipe reads each line with the same URL rules browsers use, so those cases come out right without a pattern to maintain, and it keeps one output line per input line so the result pastes back next to the column it came from. + +## What each step does + +The first step runs on each line on its own. A [replace](/util/replace/) keeps the first link on the line: leading spaces, quotes and brackets go, and so does everything from the first space, tab, comma, quote or closing bracket on, which drops a second column or the rest of a CSV row. [Prefix / suffix lines](/util/line_affix/) adds `https://` when the line has no scheme of its own, because a URL parser reads `www.example.com/about` without one as a relative path, not a host. [Parse URL](/util/url_parse/) then splits the link into its parts with the browser's rules, which lowercase the host and set aside a port, a user name and password, the path, query and fragment. A [jsonpath query](/util/jsonpath/) keeps only `$.hostname`. A line that cannot be parsed becomes an empty line, so the rows still line up. + +The last step removes a leading `www.` from every hostname, so `www.example.com` and `example.com` count as one site. Other subdomains, such as `shop.` or `blog.`, are kept. + +## A hostname, not the registrable domain + +The result is the full hostname: `shop.example.co.uk` stays `shop.example.co.uk`. Reducing it to the part a company registers, `example.co.uk`, needs the Public Suffix List, which knows that `co.uk` is a suffix like `com`. There is no Public Suffix List utility here. In Python, the `tldextract` package does it; in a spreadsheet, a formula that keeps the last two labels gets most `.com` and `.org` sites right and every `.co.uk` site wrong. + +## Limits + +- The link has to come first on its line. A label in front, as in `Home: https://www.example.com`, gives `home`, and a line that is not a link at all, such as a header row, comes out as its first word. Leave headers out of what you copy, or delete those rows afterwards. +- Internationalized domain names come out in their ASCII form, as browsers send them: `bücher.example` becomes `xn--bcher-kva.example`. +- IP addresses are returned as they are, IPv6 ones in brackets. +- Every input line gives one output line, duplicates included. For a list of distinct sites, add [deduplicate lines](/util/line_dedupe/) at the end, or [sort lines](/util/line_sort/) with remove duplicates ticked. + +To clean the links themselves rather than reduce them to hosts, see [remove tracking parameters from URLs](/recipes/remove-tracking-parameters-from-urls/). + +## The same in code + +In Python, `urllib.parse.urlsplit(u if "://" in u else "https://" + u).hostname` gives the hostname of one link, lowercased, and a loop over the column does the rest. JavaScript's `new URL(u).hostname` follows exactly the rules this recipe uses, including the punycode conversion. diff --git a/src/recipes/extract-domains-from-urls/recipe.ts b/src/recipes/extract-domains-from-urls/recipe.ts new file mode 100644 index 0000000..442c6fc --- /dev/null +++ b/src/recipes/extract-domains-from-urls/recipe.ts @@ -0,0 +1,55 @@ +import type { Recipe } from '../types' +import { each, laneStep, step } from '../define' + +const recipe: Recipe = { + slug: 'extract-domains-from-urls', + name: 'Extract the domain from a list of URLs', + summary: + 'Paste a column of links and get each one’s hostname on the same line, lowercased and without www., whether or not the link starts with https://, so it pastes back beside its URL.', + category: 'Data & Spreadsheets', + primaryQuery: 'extract domain from url list', + published: '2026-10-08', + related: ['remove-tracking-parameters-from-urls', 'bulk-utm-link-builder'], + steps: [ + each('host-each', { mode: 'lines' }, [ + laneStep('clean', 'replace', { pattern: '^[\\s"\'<(]+|[\\s"\'<>),].*$', replacement: '', regex: true, flags: 'g' }, + { label: 'keep the first URL on the line' }), + laneStep('add-scheme', 'line_affix', { prefix: 'https://', suffix: '', skipBlank: true, joinWith: '' }, + { label: 'add https:// if missing', condition: { kind: 'regex', pattern: '^[a-z][a-z0-9+.-]*://', flags: 'i', negate: true } }), + laneStep('parse', 'url_parse', { base: '', decodeParams: true }), + laneStep('hostname', 'jsonpath', { path: '$.hostname', mode: 'first', indent: 2 }, { label: 'keep hostname' }), + ], + 'Parses every line as a URL on its own and keeps only the hostname. Quotes, spaces and any further column (after a tab or comma) are cut off first, and a link without https:// gets it, or the parser would read www.example.com/about as a path.', + { label: 'hostname of every URL', onError: 'empty' }), + step('strip-www', 'replace', { pattern: '^www\\.', replacement: '', regex: true, flags: 'gm' }, + 'Removes a leading www. from each hostname, so www.example.com and example.com count as the same site. Other subdomains such as shop. or blog. are kept.', + { label: 'drop www.' }), + ], + samples: [ + { + id: 'mixed-links', + title: 'Links from a spreadsheet column', + input: 'https://www.example.com/blog/spring-sale?utm_source=newsletter\nhttp://Shop.Example.org:8080/cart\nexample.net/about-us\nwww.example.com/contact\n\n https://partner@api.example.com/v2/orders \n', + output: `example.com +shop.example.org +example.net +example.com + +api.example.com +`, + }, + { + id: 'two-columns', + title: 'Two columns copied from a sheet', + input: 'https://www.example.com\tHome\r\n"https://blog.example.org/2026/launch"\tLaunch post\r\nhttp://192.0.2.10:8080/admin\tStaging admin\r\nhttps://[2001:db8::1]/status\tStatus page\r\n', + output: 'example.com\r\nblog.example.org\r\n192.0.2.10\r\n[2001:db8::1]\r\n', + }, + { + id: 'csv-rows', + title: 'Rows of a CSV file', + input: 'https://www.example.com/pricing,Pricing,2026-10-01\n"https://docs.example.org/start?ref=nav","Getting started",2026-10-02\nhttps://example.net/blog/2026/10/launch,Launch post,2026-10-03\n', + output: 'example.com\ndocs.example.org\nexample.net\n', + }, + ], +} +export default recipe diff --git a/src/recipes/hash-email-list-for-customer-match/guide.md b/src/recipes/hash-email-list-for-customer-match/guide.md new file mode 100644 index 0000000..6c0af81 --- /dev/null +++ b/src/recipes/hash-email-list-for-customer-match/guide.md @@ -0,0 +1,34 @@ +--- +title: Hash an Email List With SHA-256 for Customer Match +description: Normalize and SHA-256 hash a column of customer emails the way Google Ads Customer Match expects, one hash per line, with headers and blank rows kept. +--- + +## Why the normalization matters more than the hash + +Google Ads Customer Match and Meta's Custom Audiences match a customer list against their own users by comparing hashes of email addresses. A hash only matches if the address was written exactly the same way before hashing, and SHA-256 gives a completely different result for `Jane.Doe@Example.com ` (capital letters, trailing space) than for `jane.doe@example.com`. A list exported from a CRM or a spreadsheet is full of those differences: padding spaces, a non-breaking space pasted from a web page, quotes around every cell, mixed case. Hash it as it is and the match rate drops without any error to tell you why. + +Google Ads' own upload screen accepts plain addresses and hashes them for you, following its own rules. This recipe is for the cases where you have to hash first: uploads through the Google Ads API, a partner or clean-room upload, or a policy that only hashes may leave your systems. + +## What each step does + +A [replace](/util/replace/) step deletes spaces, tabs, non-breaking and zero-width spaces, and the double quotes a CSV file wraps cells in, while keeping the line breaks, so each address stays on its own row. [Change case](/util/case/) lowercases everything. + +The third step applies Google's rule for Gmail: dots before the `@` are removed in `gmail.com` and `googlemail.com` addresses, because Gmail ignores them, so `j.smith.84@gmail.com` and `jsmith84@gmail.com` are the same mailbox. Dots in every other domain are kept, because there they can be part of a different mailbox. Plus addressing (`name+promo@…`) is kept for every domain, since neither Google nor Meta asks for it to be removed. + +The last step runs [hash](/util/hash/) with SHA-256 on each line on its own, and only on a line that holds exactly one address. A header row, a blank line and a value that is already a hash pass through as they are, so the output has one row for every input row and lines up with the spreadsheet you copied from. Without the per-line step, the whole list would become a single hash. + +## Meta, and checking your result + +Meta asks for the same trimming and lowercasing but not the Gmail rule. Leave out step 3: the "What if you skip a step?" section above shows exactly that output for the first example. To check that a list was hashed the way Meta expects, look at the second example: `John_Smith@gmail.com` becomes `62a14e44f765419d10fea99367361a727c12365e2520f32218d505ed9aa0f62f`, the hash Meta's own documentation gives for that address. + +## MD5 suppression lists + +Email suppression lists exchanged between senders, such as an advertiser's opt-out list sent to an affiliate, are often MD5 hashes of lowercased addresses. Open the recipe in the editor, leave out the Gmail step, and replace the hash step inside step 4 with [MD5](/util/md5/). Compare against the other party's list only after you both normalize the same way. + +## Limits and privacy + +- Paste the email column only. A line such as `Jane `, a row with several addresses, or a CSV row with other columns is not hashed: it is left as text, with its spaces removed and lowercased, so you can spot and fix it. +- Addresses are not validated. `name@domain` without a dot is hashed like any other. +- Phone numbers, names and postal codes, which Customer Match also accepts, need their own normalization and are not handled here. + +A hashed email is not anonymous: anyone with a list of addresses can hash them and compare. Treat the output as the personal data it is. The hashing runs in your browser and this page stores nothing you paste. "Open in the editor" hands your input to the editor, which keeps recent inputs in this browser unless you open the History menu on its input panel and untick remember inputs (clear all removes what is stored), and a share link carries the input in the URL, so do not share links made from a real customer list. diff --git a/src/recipes/hash-email-list-for-customer-match/recipe.ts b/src/recipes/hash-email-list-for-customer-match/recipe.ts new file mode 100644 index 0000000..db75f97 --- /dev/null +++ b/src/recipes/hash-email-list-for-customer-match/recipe.ts @@ -0,0 +1,44 @@ +import type { Recipe } from '../types' +import { each, laneStep, step } from '../define' + +const recipe: Recipe = { + slug: 'hash-email-list-for-customer-match', + name: 'Hash an email list for Customer Match', + summary: + 'Paste a column of customer emails and get one SHA-256 hash per line, normalized the way Google Ads Customer Match expects, with header and blank rows kept so rows still line up.', + category: 'Writing & Marketing', + primaryQuery: 'hash emails for customer match', + published: '2026-10-08', + related: ['bulk-utm-link-builder'], + steps: [ + step('spaces', 'replace', { pattern: '(?:[^\\S\\r\\n]|["\\u200B-\\u200D\\u2060])+', replacement: '', regex: true, flags: 'g' }, + 'Deletes spaces, tabs, non-breaking and zero-width spaces, and the double quotes a CSV export wraps cells in, while keeping line breaks. One stray character gives a completely different hash that never matches.', + { label: 'remove spaces and quotes' }), + step('lower', 'case', { mode: 'lower' }, + 'Lowercases every address. SHA-256 is case-sensitive, and Google and Meta both lowercase before hashing, so Jane.Doe@Example.com must become jane.doe@example.com first.'), + step('gmail-dots', 'replace', { pattern: '\\.(?=[^@\\s]*@(?:gmail|googlemail)\\.com$)', replacement: '', regex: true, flags: 'gm' }, + 'Google asks for dots before the @ to be removed in gmail.com and googlemail.com addresses, since Gmail ignores them. Dots in every other domain are kept, because there they change the mailbox.', + { label: 'drop Gmail dots' }), + each('hash-each', { mode: 'lines' }, [ + laneStep('sha256', 'hash', { algo: 'SHA-256' }, + { condition: { kind: 'regex', pattern: '^[^@\\s<>,;]+@[^@\\s<>,;]+$' } }), + ], + 'Hashes each line that holds one address into 64 lowercase hex characters. A header row or a line with several addresses is left as text so you can spot it; without this step the whole list would collapse into a single hash.', + { label: 'SHA-256 every address' }), + ], + samples: [ + { + id: 'crm-export', + title: 'Spreadsheet column with a header', + input: 'Email\n Jane.Doe@Example.com \nj.smith.84@gmail.com\n\nALEX.RIVERA@GoogleMail.com \nsupport.team@example.org\n', + output: "email\n86e0b9e56c17cc4d12387e1949b85053fbe73bc3ce5a1188713a9d300cc6133d\n82234fd011a700871151233b13ed254e4d957f86593149137c49c6c926e696ad\n\nd63b7cbbcc312861619bd507dccd1588632340511d5b96a35ec6a22052bdaa39\n884c53e13ea0e5f65527b2d45b1cdb6909d338c096da039fc7233af1a88b8b01\n", + }, + { + id: 'quoted-csv', + title: 'Column copied from a raw CSV file', + input: '"Email"\r\n"John_Smith@gmail.com"\r\n"Pat.Lee@Example.net"\r\n', + output: "email\r\n62a14e44f765419d10fea99367361a727c12365e2520f32218d505ed9aa0f62f\r\na5ba6ed096351a317a33801c0cef8042fd9af41d8d39ec9d1be01c03f6a634a6\r\n", + }, + ], +} +export default recipe diff --git a/src/recipes/parse-user-agents-from-access-log/guide.md b/src/recipes/parse-user-agents-from-access-log/guide.md new file mode 100644 index 0000000..679d012 --- /dev/null +++ b/src/recipes/parse-user-agents-from-access-log/guide.md @@ -0,0 +1,31 @@ +--- +title: Parse User Agents From an Access Log Into a CSV +description: Paste nginx or Apache access log lines, or a list of user-agent strings, and get one CSV row per line with browser, version, OS, device type and a bot flag. +--- + +## From raw log lines to a table you can filter + +Server logs record every visitor's user agent, the long `Mozilla/5.0 (…) AppleWebKit/537.36 …` string that names the browser, its version, the operating system and sometimes the device. That is what you need to answer which browsers to keep supporting, why errors cluster on one platform, or how much of the traffic is crawlers. Read raw, the strings are almost impossible to compare: every browser claims to be Mozilla, Chrome and Edge both mention Safari, and the version that matters sits in a different place in each. + +A user agent parser turns one string into named fields, and that is the catch: it reads one string. Paste a hundred log lines into one and you get a single meaningless result. This recipe pulls the user agent out of each line, parses every line on its own, and writes the results as a CSV that opens in any spreadsheet. + +## What each step does + +The first step is a [replace](/util/replace/) with a regular expression that recognises the combined log format, the default for Apache and the basis of nginx's: the client address, `[time]`, the quoted request, status and size, the quoted referrer and the quoted user agent. It keeps only the user agent, so a referrer URL is never mistaken for it. It also handles nginx's `main` format with a forwarded-for address after the user agent, a syslog or virtual-host prefix in front of the line, and quotes escaped inside a field. A line that is just a user agent, with or without quotes around it, passes through as it is. + +The second step runs [user agent parse](/util/user_agent_parse/), built on ua-parser-js, on each line on its own. Blank lines are parsed too and give an empty row, so the output has exactly one row per input line. [JSONL to JSON](/util/jsonl_to_json/) collects the per-line results into one array, and [JSON to CSV](/util/json_to_csv/) flattens the nested `browser`, `os` and `device` objects into dotted column names and keeps eight of them: browser name and version, OS name and version, device type, vendor and model, and `isBot`. Add or remove names in the last step's columns (comma list), for example `engine.name` or `cpu.architecture`. + +## What a user agent can no longer tell you + +Browsers now freeze or round parts of the string on purpose, a change known as user-agent reduction, and no parser can recover what is not there. Windows 11 reports itself as Windows 10. Chrome, Edge and Safari on a Mac report macOS 10.15.7 whatever the real version. Chrome on Android reports Android 10 and the model `K`, so phone models and newer Android versions are lost. The precise values are only available through client hints headers, which a plain access log does not record. + +`isBot` marks known crawlers such as Googlebot and bingbot, plus command-line clients and libraries like curl and python-requests. A health checker or tool the parser does not know, such as a load balancer probe, gives an empty row with `isBot` false. + +## Limits + +- Rows match input lines by position only: the CSV has a header row, then row N for line N. Paste it beside the log lines or the user-agent column in your spreadsheet, header in the header row, and each row lines up with its source. +- Only the combined format and bare user agents are recognised. The common log format has no user agent, and its lines give empty rows; JSON logs need the user-agent field extracted first. +- One run handles up to 100,000 lines. Larger logs stop at step 2 with a message saying so: split them, or filter them first with grep. +- To count how often each browser appears rather than list every request, sort the browser column and use [count duplicate lines](/util/uniq_count/), or a pivot table. + +On the server itself, `awk -F'"' '{print $6}' access.log` prints the user agent of each combined-format line, ready for `sort | uniq -c`. diff --git a/src/recipes/parse-user-agents-from-access-log/recipe.ts b/src/recipes/parse-user-agents-from-access-log/recipe.ts new file mode 100644 index 0000000..0de2d64 --- /dev/null +++ b/src/recipes/parse-user-agents-from-access-log/recipe.ts @@ -0,0 +1,77 @@ +import type { Recipe } from '../types' +import { each, laneStep, step } from '../define' + +/** + * The user agent of a combined-format log line (any prefix before [time], such as a syslog + * header or a vhost; escaped quotes inside fields; any fields after the UA, such as nginx's + * X-Forwarded-For), or a UA wrapped in quotes. Any other line, a bare UA included, is kept. + */ +const UA_FIELD = String.raw`^(?:.*?\[[^\]]*\] "(?:[^"\\]|\\.)*" \d{3} \S+ "(?:[^"\\]|\\.)*" "((?:[^"\\]|\\.)*)".*|"([^"]*)"[ \t]*)$` + +const COLUMNS = 'browser.name,browser.version,os.name,os.version,device.type,device.vendor,device.model,isBot' + +const LOG = [ + '198.51.100.23 - - [07/Oct/2026:09:12:01 +0000] "GET /pricing HTTP/2.0" 200 18234 "https://www.example.com/blog/build-a-slack-bot/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"', + '203.0.113.5 - - [07/Oct/2026:09:12:04 +0000] "GET / HTTP/2.0" 200 5120 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 17_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Mobile/15E148 Safari/604.1"', + '192.0.2.77 - - [07/Oct/2026:09:12:09 +0000] "GET /docs/ HTTP/2.0" 200 9921 "https://www.example.org/" "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Mobile Safari/537.36"', + '198.51.100.41 - - [07/Oct/2026:09:12:15 +0000] "GET /pricing HTTP/2.0" 200 18234 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.2739.42"', + '203.0.113.88 - - [07/Oct/2026:09:12:20 +0000] "GET /blog/ HTTP/2.0" 200 7310 "https://duckduckgo.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:130.0) Gecko/20100101 Firefox/130.0"', + '192.0.2.150 - - [07/Oct/2026:09:12:31 +0000] "GET /robots.txt HTTP/1.1" 200 68 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"', + '198.51.100.9 - - [07/Oct/2026:09:12:40 +0000] "HEAD /health HTTP/1.1" 200 0 "-" "curl/8.7.1"', +].join('\n') + '\n' + +// The goldens depend on ua-parser-js: a dependency update that changes how these long-stable +// user agents parse fails this recipe's check, which is the point. +const recipe: Recipe = { + slug: 'parse-user-agents-from-access-log', + name: 'Parse user agents from an access log into a CSV', + summary: + 'Paste nginx or Apache access log lines, or a column of user-agent strings, and get a CSV row per line with the browser, OS, device and a bot flag.', + category: 'Web & APIs', + primaryQuery: 'parse user agents from access log', + published: '2026-10-08', + related: ['nested-json-to-csv'], + steps: [ + step('ua-field', 'replace', { pattern: UA_FIELD, replacement: '$1$2', regex: true, flags: 'gm' }, + 'In the combined log format the user agent is the quoted field after the request, status, size and referrer. This keeps only that field, so a referrer URL or a trailing forwarded-for field cannot be read as the browser.', + { label: 'keep the user-agent field' }), + each('parse-each', { mode: 'lines' }, [laneStep('ua', 'user_agent_parse')], + 'The user agent parser reads one string and returns one JSON object. Running it on each line gives every request its own result, as one compact JSON line, and a blank line gets an empty result, so the rows keep lining up with your input.', + // the parser never throws on text, so only an input over the item budget stops here, with that message + { label: 'parse every line', includeEmpty: true, onError: 'stop' }), + step('collect', 'jsonl_to_json', { indent: 2, skipBlank: true, onError: 'error' }, + 'The results arrive as JSON Lines, one object per line. This collects them into a single JSON array, the shape the CSV step expects.', + { label: 'collect into an array' }), + step('csv', 'json_to_csv', { delimiter: ',', header: true, flatten: true, eol: 'lf', columns: COLUMNS }, + 'Flattens the nested browser, os and device objects into dotted column names and keeps the eight columns worth reading, with a header row and one row per input line.', + { label: 'pick columns as CSV' }), + ], + samples: [ + { id: 'nginx-access-log', title: 'nginx access log lines', input: LOG, output: 'browser.name,browser.version,os.name,os.version,device.type,device.vendor,device.model,isBot\nChrome,128.0.0.0,Windows,10,desktop,,,false\nMobile Safari,17.6,iOS,17.6,mobile,Apple,iPhone,false\nMobile Chrome,128.0.0.0,Android,10,mobile,,K,false\nEdge,128.0.2739.42,Windows,10,desktop,,,false\nFirefox,130.0,macOS,10.15,desktop,Apple,Macintosh,false\nGooglebot,2.1,,,,,,true\ncurl,8.7.1,,,,,,true' }, + { + id: 'nginx-main-format', + title: 'nginx main format (Docker image default)', + input: [ + '203.0.113.14 - - [07/Oct/2026:10:01:07 +0000] "GET /metrics HTTP/1.1" 200 5120 "-" "Go-http-client/1.1" "-"', + '198.51.100.62 - - [07/Oct/2026:10:01:09 +0000] "GET /checkout HTTP/1.1" 200 4412 "https://www.example.com/cart" "Mozilla/5.0 (iPad; CPU OS 17_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Mobile/15E148 Safari/604.1" "192.0.2.201"', + '192.0.2.18 - - [07/Oct/2026:10:01:12 +0000] "GET /sitemap.xml HTTP/1.1" 200 1840 "-" "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)" "-"', + ].join('\n') + '\n', + output: 'browser.name,browser.version,os.name,os.version,device.type,device.vendor,device.model,isBot\nGo-http-client,1.1,,,,,,true\nMobile Safari,17.6,iOS,17.6,tablet,Apple,iPad,false\nbingbot,2.0,,,,,,true', + }, + { + id: 'spreadsheet-column', + title: 'User-agent column with gaps', + input: [ + 'Mozilla/5.0 (X11; Linux x86_64; rv:130.0) Gecko/20100101 Firefox/130.0', + '', + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15', + 'Mozilla/5.0 (Linux; Android 14; SM-S921B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/25.0 Chrome/121.0.0.0 Mobile Safari/537.36', + '-', + 'Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)', + 'python-requests/2.32.3', + ].join('\r\n') + '\r\n', + output: 'browser.name,browser.version,os.name,os.version,device.type,device.vendor,device.model,isBot\nFirefox,130.0,Linux,,desktop,,,false\n,,,,,,,false\nSafari,17.6,macOS,10.15.7,desktop,Apple,Macintosh,false\nSamsung Internet,25.0,Android,14,mobile,Samsung,SM-S921B,false\n,,,,,,,false\nbingbot,2.0,,,,,,true\npython-requests,2.32.3,,,,,,true', + }, + ], +} +export default recipe diff --git a/src/recipes/remove-tracking-parameters-from-urls/guide.md b/src/recipes/remove-tracking-parameters-from-urls/guide.md new file mode 100644 index 0000000..eb8f956 --- /dev/null +++ b/src/recipes/remove-tracking-parameters-from-urls/guide.md @@ -0,0 +1,34 @@ +--- +title: Remove Tracking Parameters From a List of URLs +description: Strip utm_ tags, fbclid, gclid, srsltid and other click ids from many links at once, keeping the parameters each page needs, their order and any #anchor. +--- + +## Where tracked links come from + +Links pile up tracking parameters wherever they travel. A page shared from Facebook gains `fbclid`, a click on a Google ad gains `gclid`, `gbraid` and `gad_source`, a product found through Google Shopping gains `srsltid`, and every newsletter adds `utm_source`, `utm_medium` and `utm_campaign` plus the email platform's own ids, such as HubSpot's `_hsenc`, Mailchimp's `mc_eid` or Klaviyo's `_kx`. None of them changes the page. They identify the visit or the person. + +That matters when the links themselves are the data. A content audit or a sitemap check lists the same page five times under five campaign tags. Analytics exports split one landing page into dozens of rows. A link pasted into documentation, a chat or a redirect map carries a click id that belongs to someone else's visit, sometimes their email address in encoded form. Removing the parameters by hand means reading every query string and knowing which names are trackers and which ones the page needs, such as `variant=41`, `page=2` or `q=waterproof+jacket`. + +## What each step does + +[unescape HTML](/util/unescape_html/) turns `&` back into `&`. Links copied from an email template or a page's source are written that way, and without this step the parameter after one would be named `amp;utm_medium`, which no list matches. It decodes only the few escapes HTML requires, so a parameter named `reg` survives instead of becoming the ® sign. + +The second step goes through the text one line at a time and runs [normalize query params](/util/query_params_normalize/) on each line that is one bare link with a query string: a full URL, a protocol-relative `//host/…` link, a root-relative path such as `/pricing?plan=pro` from an analytics report, or a host and path without a scheme. Its drop list holds the tracker names, matched in any capitalization, with `utm_*` and `hsa_*` as wildcards. The tool can also sort, deduplicate and lowercase. Those options are off, so the parameters that stay keep their order and spelling, and a link left with no parameters loses its `?`. Any `#anchor` stays where it was. + +Lines that are not a bare link pass through untouched: a heading or note, a link inside quotes, brackets or parentheses, and a CSV row with commas. That is deliberate. Run over the whole list at once, the tool would read everything after the first `?` as one long query and delete whole links that followed a tracker. + +## Which parameters go, and which stay + +The list covers Google Ads, Merchant Center and Analytics (`gclid`, `gbraid`, `wbraid`, `dclid`, `gad_source`, `gad_campaignid`, `srsltid`, `_gl`, `_ga`), the big social networks (`fbclid`, `igshid`, `igsh`, `msclkid`, `twclid`, `ttclid`, `li_fat_id`), email platforms (Mailchimp, HubSpot, Marketo, MailerLite, Vero, Drip's `__s`, Klaviyo's `_kx`, Kit's `ck_subscriber_id`) and a few more from the ClearURLs and Firefox lists. Add your own names to the drop list in step 2, separated by commas. + +`ref` and `si` are kept on purpose. `ref` often only says where a visitor came from, but some sites use it for referral credit or to choose what the page shows. `si` is the share id that Spotify and YouTube add, yet the name is short and generic enough that other sites use it for parameters they need. Add either to the list when you know it is only tracking on the links you clean. + +## Limits and when not to use it + +- Paste URLs, one per line, not HTML source. A link inside `href="…"` is not a bare link and stays as it is. +- Do not clean the landing page URLs of live ad campaigns. Google Ads attributes a conversion through `gclid`, `gbraid` and `gad_*`, and stripping them from a final URL or a tracking template breaks reporting. +- Parameters after a `#`, as in hash-routed apps (`/#/route?utm_source=x`), are not touched, since they are not part of the query. Queries separated by `;` instead of `&` are read as one parameter. +- Text escaped twice, `&amp;`, is unescaped only once, so the tracker after it stays. +- Spaces around a link are trimmed. Repeated links are kept; add [deduplicate lines](/util/line_dedupe/) at the end for a unique list. + +To add campaign tags rather than remove them, use the [bulk UTM link builder](/recipes/bulk-utm-link-builder/). diff --git a/src/recipes/remove-tracking-parameters-from-urls/recipe.ts b/src/recipes/remove-tracking-parameters-from-urls/recipe.ts new file mode 100644 index 0000000..c12cf9a --- /dev/null +++ b/src/recipes/remove-tracking-parameters-from-urls/recipe.ts @@ -0,0 +1,93 @@ +import type { Recipe } from '../types' +import { each, laneStep, step } from '../define' + +/** + * Click ids and campaign tags that identify the visit, never the page (ClearURLs and + * Firefox lists, vendor docs). `si` (Spotify, YouTube shares) and `ref` stay: on some + * sites they select content. + */ +const TRACKERS = [ + 'utm_*', + // Google Ads, Merchant Center and Analytics + 'gclid', 'gclsrc', 'dclid', 'gbraid', 'wbraid', 'gad_source', 'gad_campaignid', 'srsltid', '_gl', '_ga', + // Meta, Microsoft, X, TikTok, LinkedIn + 'fbclid', 'igshid', 'igsh', 'msclkid', 'twclid', 'ttclid', 'li_fat_id', + // email platforms: Mailchimp, HubSpot, Marketo, MailerLite, Vero, Drip, Klaviyo, Kit + 'mc_cid', 'mc_eid', '_hsenc', '_hsmi', '__hssc', '__hstc', '__hsfp', 'hsCtaTracking', 'hsa_*', 'mkt_tok', + 'ml_subscriber', 'ml_subscriber_hash', 'vero_id', 'vero_conv', '__s', '_kx', 'ck_subscriber_id', + // others in the ClearURLs and Firefox lists + 'yclid', 'oly_anon_id', 'oly_enc_id', 's_cid', 'rb_clickid', 'wickedid', +].join(',') + +/** A character of a bare link: nothing that wraps one (quotes, brackets, parentheses) or separates CSV fields. */ +const URL_CHAR = String.raw`[^\s"'<>()\[\]{}|\\^,]` +/** A line that is one bare link, protocol-relative link, root-relative path or host/path, with a query. */ +const ONE_LINK_WITH_QUERY = String.raw`^\s*(?:https?://|//|/|[a-z0-9-]+(?:\.[a-z0-9-]+)+[/?])` + URL_CHAR + '*\\?' + URL_CHAR + String.raw`+\s*$` + +const recipe: Recipe = { + slug: 'remove-tracking-parameters-from-urls', + name: 'Remove tracking parameters from a list of URLs', + summary: + 'Paste links one per line and get them back without utm_ tags, fbclid, gclid, srsltid and other click ids, with the parameters a page needs, the order and any #anchor kept.', + category: 'Writing & Marketing', + primaryQuery: 'remove tracking parameters from urls', + published: '2026-10-08', + related: ['bulk-utm-link-builder', 'extract-domains-from-urls'], + steps: [ + step('unescape', 'unescape_html', {}, + 'Links copied from an email template or page source write & as &, which turns the next parameter name into amp;utm_source, a name no list matches. Only the basic HTML escapes are undone, so a parameter such as ®= is not turned into ®=.', + { label: 'undo &' }), + each('per-link', { mode: 'lines' }, [ + laneStep('strip', 'query_params_normalize', { + sort: false, dedupe: 'none', dropEmpty: false, drop: TRACKERS, decode: false, lowercaseHost: false, + }, { condition: { kind: 'regex', pattern: ONE_LINK_WITH_QUERY, flags: 'i' }, label: 'drop tracking parameters' }), + ], + 'Cleans one line at a time, and only a line that is a bare link or path with a query: headings, notes, links in quotes or brackets and CSV rows stay as typed. Given the whole list at once, the parameter step would read it as one URL. The parameters it keeps stay in their order.', + { label: 'clean every link' }), + ], + samples: [ + { + id: 'content-audit', + title: 'Links gathered for a content audit', + input: [ + 'https://shop.example.com/products/trail-runner-2?variant=41&utm_source=newsletter&utm_medium=email&utm_campaign=fall_sale_2026', + 'https://www.example.com/blog/choosing-running-shoes?fbclid=IwZXh0bgNhZW0CMTEAARSrOw6IhJ9_y136Cf41Am5NIGKCAbQTOyOlNRfoB4', + 'https://shop.example.com/collections/sale?page=2&gad_source=1&gad_campaignid=21839402711&gclid=Cj0KCQjwUGX1QmH8HPvAUjzF68YqzMp4qDwTG_5DQi3bGeiO_BL9skGVIlG-ImOrWbMY_BwE', + 'https://shop.example.com/products/rain-shell?srsltid=AfmBOoDdEmWqX6LUQ5CYh87r4hTuS1i2p_AP25bEfZswbpTmxm', + 'https://www.example.com/pricing?plan=team&msclkid=316e70c60cf58bf70f3f6cda88f99b0b#compare', + 'https://shop.example.com/search?q=waterproof+jacket&color=blue&color=green&utm_source=onsite', + 'https://shop.example.com/products/gift-card?amount=50&mc_cid=1607f293e8&mc_eid=0e96b356ee', + 'https://www.example.com/contact', + '', + ].join('\n'), + output: 'https://shop.example.com/products/trail-runner-2?variant=41\nhttps://www.example.com/blog/choosing-running-shoes\nhttps://shop.example.com/collections/sale?page=2\nhttps://shop.example.com/products/rain-shell\nhttps://www.example.com/pricing?plan=team#compare\nhttps://shop.example.com/search?q=waterproof+jacket&color=blue&color=green\nhttps://shop.example.com/products/gift-card?amount=50\nhttps://www.example.com/contact\n', + }, + { + id: 'email-html', + title: 'Links from an email template', + input: [ + 'October newsletter: which links still carry trackers?', + 'https://www.example.com/webinars/content-audit?utm_source=hs_email&utm_medium=email&_hsenc=p2ANqtz-CKAYqPpnew5Dlw-AI0c7sOltsJKj9wcESykzUVbpQ2AE3KG9UTrTyGtki73q&_hsmi=289412311', + 'https://www.example.com/guides/seo-audit-checklist?utm_campaign=october_newsletter&hsCtaTracking=7c1f2b9e-4d3a-4e8f-9a61-2b5c8d0e3f47%7C3a9d6e12-5b7c-4f80-a1d2-6e9f0b3c4d58', + 'https://events.example.org/2026/lyon-meetup?ticket=early&mkt_tok=NzQ3LUZXUC0yMDQAAAGIy_W1kaSpeWkF1X3fAfZmhY7-0ZJqnLj48Jg960b#agenda', + 'https://shop.example.com/products/wool-socks?_kx=Hq3vP0a8bmZL6eF2c1dmR4nT9sKwQ.XjK8aB&size=m', + '', + ].join('\n'), + output: 'October newsletter: which links still carry trackers?\nhttps://www.example.com/webinars/content-audit\nhttps://www.example.com/guides/seo-audit-checklist\nhttps://events.example.org/2026/lyon-meetup?ticket=early#agenda\nhttps://shop.example.com/products/wool-socks?size=m\n', + }, + { + id: 'ga4-paths', + title: 'Landing page paths (GA4)', + input: [ + '/pricing?plan=pro&utm_source=linkedin&utm_medium=paid_social&li_fat_id=2caab4c1-ab67-ffd2-3117-998aa6d85563', + '/blog/seo-checklist?srsltid=AfmBOoDdEmWqX6LUQ5CYh87r4hTuS1i2p_AP25bEfZswbpTmxm', + '/?gad_source=1&gbraid=0AAAAADm7yUoR3sj-os6t1hzNFUNKgpC&gclid=Cj0KCQjwUGX1QmH8HPvAUjzF68YqzMp4qDwTG_5DQi3bGeiO_BL9skGVIlG-ImOrWbMY_BwE', + '/docs/getting-started#install', + '/landing/summer?ttclid=E.C.P.pC2MfOaqGWBn6kS4TeBpDnVz65EGpaR04NDbvFH3&ref=tiktok', + '/p/insta-launch?igsh=yj3fkm96jn9fwjuf', + ].join('\n'), + output: '/pricing?plan=pro\n/blog/seo-checklist\n/\n/docs/getting-started#install\n/landing/summer?ref=tiktok\n/p/insta-launch', + }, + ], +} +export default recipe