Skip to content

Commit

Permalink
✨ Introduce dynamic random numbers support in HTTP requests (#226)
Browse files Browse the repository at this point in the history
Now it is possible to inject randomized numbers into HTTP requests. Specifically, the `$DYNAMIC_RANDOM_NUMBER` placeholders in the request URL or body will be substituted with actual random values. The range for these numbers can be configured using the `RANDOM_MIN` and `RANDOM_MAX` environment variables, which default to `0` and `1000000`, respectively.

Discussion: upptime/upptime#857
  • Loading branch information
artemmukhin authored Oct 4, 2023
1 parent cd14b69 commit 08b4cb9
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
4 changes: 4 additions & 0 deletions src/helpers/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ export const UPDATE_TEMPLATE_CI_SCHEDULE = "0 0 * * *";
export const UPDATES_CI_SCHEDULE = "0 3 * * *";
export const UPTIME_CI_SCHEDULE = "*/5 * * * *";
export const DEFAULT_RUNNER = "ubuntu-latest";

export const DYNAMIC_RANDOM_NUMBER = "$DYNAMIC_RANDOM_NUMBER";
export const RANDOM_MIN_DEFAULT = "0";
export const RANDOM_MAX_DEFAULT = "1000000";
17 changes: 16 additions & 1 deletion src/helpers/environment.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import {RANDOM_MAX_DEFAULT, RANDOM_MIN_DEFAULT, DYNAMIC_RANDOM_NUMBER} from "./constants";

export const replaceEnvironmentVariables = (str: string) => {
Object.keys(process.env).forEach((key) => {
str = str.replace(`$${key}`, process.env[key] || `$${key}`);
Expand All @@ -8,5 +10,18 @@ export const replaceEnvironmentVariables = (str: string) => {
Object.keys(secrets).forEach((key) => {
str = str.replace(`$${key}`, secrets[key] || `$${key}`);
});
return str;
return substituteRandomNumbers(str);
};

const substituteRandomNumbers = (str: string) => {
if (str.includes(DYNAMIC_RANDOM_NUMBER)) {
const min = parseInt(process.env.RANDOM_MIN || RANDOM_MIN_DEFAULT);
const max = parseInt(process.env.RANDOM_MAX || RANDOM_MAX_DEFAULT);
str = str.replaceAll(DYNAMIC_RANDOM_NUMBER, () => getRandomNumber(min, max).toString());
}
return str;
}

/** Return a random integer N such that min <= N <= max */
const getRandomNumber = (min: number, max: number) =>
Math.floor(Math.random() * (max - min + 1)) + min;
2 changes: 1 addition & 1 deletion src/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ export const update = async (shouldCommit = false) => {
const ws = new WebSocket(replaceEnvironmentVariables(site.url));
ws.on("open", function open() {
if (site.body) {
ws.send(site.body);
ws.send(replaceEnvironmentVariables(site.body));
} else {
ws.send("");
}
Expand Down

0 comments on commit 08b4cb9

Please sign in to comment.