supabase-keepalive and supabase-keep-alive were both already taken/blocked on npm (an unrelated package and npm's publish-time name-similarity filter), so this ships on the registry as supabase-stay-awake instead. Adds the one-command scheduled-ping setup the CLI was missing: `setup` copies itself to ~/.supabase-stay-awake/ping.js and installs a daily user crontab line (zero signup to us, no GitHub); `list`/`uninstall` manage it; falls back to printing the line (never hangs) if crontab can't be written. Also points every README/CLI example at the published package instead of the npx --yes git+... form, and fixes the stale git.ereboslab.com links to rithub.dev (the domain itself already 301s there). Published and verified live: npm install in a clean dir, help/setup/list/ uninstall/one-off-ping all run correctly against the real registry. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
359 lines
13 KiB
JavaScript
Executable File
359 lines
13 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
'use strict';
|
|
|
|
// Supabase keep-alive CLI.
|
|
// One real database read through a project's REST API, so a free Supabase
|
|
// project never sits idle for 7 days and gets paused. Same check as the
|
|
// workflow / shell script in this repository
|
|
// (https://rithub.dev/caelum0x/supabase-keep-alive-action),
|
|
// packaged so it can run from `npx` or any cron without GitHub.
|
|
//
|
|
// One-off check:
|
|
// npx supabase-stay-awake --url https://REF.supabase.co --key ANON_KEY [--table keepalive] [--rpc fn]
|
|
// Set up a free daily cron job so you never have to run it again:
|
|
// npx supabase-stay-awake setup --url https://REF.supabase.co --key ANON_KEY --table keepalive
|
|
// or via env vars:
|
|
// SUPABASE_URL=https://REF.supabase.co SUPABASE_ANON_KEY=... node supabase-keep-alive.js --table keepalive
|
|
|
|
const fs = require('fs');
|
|
const os = require('os');
|
|
const path = require('path');
|
|
const { execFileSync } = require('child_process');
|
|
|
|
const PAUSED_CODE = 540;
|
|
const HOME_DIR = path.join(os.homedir(), '.supabase-stay-awake');
|
|
const SCRIPT_COPY = path.join(HOME_DIR, 'ping.js');
|
|
const LOG_FILE = path.join(HOME_DIR, 'keepalive.log');
|
|
const MARKER_PREFIX = '# supabase-stay-awake:';
|
|
|
|
function parseArgs(argv) {
|
|
const out = { retries: 3, timeout: 20, select: '*', time: '06:17' };
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const a = argv[i];
|
|
const next = () => argv[++i];
|
|
switch (a) {
|
|
case '--url': out.url = next(); break;
|
|
case '--key': case '--anon-key': out.key = next(); break;
|
|
case '--table': out.table = next(); break;
|
|
case '--select': out.select = next(); break;
|
|
case '--rpc': out.rpc = next(); break;
|
|
case '--rpc-body': out.rpcBody = next(); break;
|
|
case '--retries': out.retries = parseInt(next(), 10); break;
|
|
case '--timeout': out.timeout = parseInt(next(), 10); break;
|
|
case '--time': out.time = next(); break;
|
|
case '--all': out.all = true; break;
|
|
case '--help': case '-h': out.help = true; break;
|
|
default: break;
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function help() {
|
|
console.log(`supabase-stay-awake - stop a free Supabase project pausing
|
|
|
|
Usage (one-off check):
|
|
supabase-stay-awake --url https://REF.supabase.co --key ANON_KEY [options]
|
|
|
|
Usage (set up a free recurring ping, no GitHub, no signup to us):
|
|
supabase-stay-awake setup --url https://REF.supabase.co --key ANON_KEY --table keepalive [--time HH:MM]
|
|
supabase-stay-awake list
|
|
supabase-stay-awake uninstall --url https://REF.supabase.co (or --all)
|
|
|
|
Options:
|
|
--url <url> Project origin, https://<ref>.supabase.co (or SUPABASE_URL)
|
|
--key <key> Anon public key (or SUPABASE_ANON_KEY)
|
|
--table <name> Table to read: GET /rest/v1/<table>?select=<select>&limit=1
|
|
--select <cols> Columns for --table (default *)
|
|
--rpc <name> Function to call: POST /rest/v1/rpc/<name>
|
|
--rpc-body <json> JSON body for --rpc (default {})
|
|
--retries <n> Retries after the first attempt (default 3)
|
|
--timeout <s> Per-request timeout in seconds (default 20)
|
|
--time <HH:MM> Daily time for 'setup' (local time, default 06:17)
|
|
|
|
Exit codes: 0 ok, 1 paused or failed.
|
|
|
|
What 'setup' does: copies this script to ~/.supabase-stay-awake/ping.js and adds one line to
|
|
your user crontab that runs it once a day with 'node' directly (no npx, no network call once
|
|
installed, nothing sent to us). 'list' prints installed jobs, 'uninstall' removes them. Needs
|
|
'crontab' (every Mac and Linux box has it); on a machine without it, 'setup' prints the line to
|
|
add to your own scheduler instead of failing silently.
|
|
|
|
A backend that does not pause idle projects: https://scribase.com/supabase-project-paused?utm_source=cli&utm_medium=cli&utm_campaign=supabase-keep-alive
|
|
(Scribase: Postgres + Auth + Storage + Realtime, idle projects scale to zero and wake
|
|
on request instead of pausing. First project free, no card.)`);
|
|
}
|
|
|
|
function sleep(ms) {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
async function request(url, key, path, opts) {
|
|
const { method = 'GET', body, retries, timeoutSec } = opts;
|
|
let attempt = 0;
|
|
let delay = 2000;
|
|
for (;;) {
|
|
attempt++;
|
|
const controller = new AbortController();
|
|
const timer = setTimeout(() => controller.abort(), timeoutSec * 1000);
|
|
let code = 0;
|
|
let text = '';
|
|
const start = Date.now();
|
|
try {
|
|
const res = await fetch(url + path, {
|
|
method,
|
|
signal: controller.signal,
|
|
headers: {
|
|
apikey: key,
|
|
Authorization: `Bearer ${key}`,
|
|
Accept: 'application/json',
|
|
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
},
|
|
body,
|
|
});
|
|
code = res.status;
|
|
text = await res.text().catch(() => '');
|
|
} catch {
|
|
code = 0;
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
const ms = Date.now() - start;
|
|
console.log(`${method} ${path} -> HTTP ${code || 'ERR'} (${ms}ms, attempt ${attempt})`);
|
|
if (code === PAUSED_CODE) return { code, text, attempt };
|
|
if ((code === 0 || code === 429 || (code >= 500 && code < 600)) && attempt <= retries) {
|
|
await sleep(delay);
|
|
delay *= 2;
|
|
continue;
|
|
}
|
|
return { code, text, attempt };
|
|
}
|
|
}
|
|
|
|
const CRON_TIMEOUT_MS = 5000;
|
|
|
|
function hasCrontab() {
|
|
try {
|
|
execFileSync('crontab', ['-l'], { stdio: ['ignore', 'ignore', 'ignore'], timeout: CRON_TIMEOUT_MS });
|
|
return true;
|
|
} catch (err) {
|
|
// exit code 1 with no stdout just means "no crontab yet", which is fine;
|
|
// ENOENT means the binary itself is missing, and a timeout (e.g. an OS
|
|
// permission prompt nobody can click in a non-interactive shell) both mean
|
|
// "cannot use cron here" just as much as a missing binary does.
|
|
return !(err && (err.code === 'ENOENT' || err.signal));
|
|
}
|
|
}
|
|
|
|
function readCrontab() {
|
|
try {
|
|
return execFileSync('crontab', ['-l'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: CRON_TIMEOUT_MS });
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
// Returns true on success, false if the write could not be made (caller falls
|
|
// back to printing the line instead of throwing).
|
|
function writeCrontab(text) {
|
|
try {
|
|
execFileSync('crontab', ['-'], { input: text, stdio: ['pipe', 'ignore', 'ignore'], timeout: CRON_TIMEOUT_MS });
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function cronCommand(url, key, table, rpc) {
|
|
const parts = [`node "${SCRIPT_COPY}"`, `--url "${url}"`, `--key "${key}"`];
|
|
if (table) parts.push(`--table "${table}"`);
|
|
if (rpc) parts.push(`--rpc "${rpc}"`);
|
|
return parts.join(' ');
|
|
}
|
|
|
|
function cmdSetup(args) {
|
|
const url = (args.url || process.env.SUPABASE_URL || '').replace(/\/+$/, '');
|
|
const key = args.key || process.env.SUPABASE_ANON_KEY || '';
|
|
if (!url || !key) {
|
|
console.error('error: --url and --key are required for setup. Run with --help.');
|
|
return 1;
|
|
}
|
|
if (!args.table && !args.rpc) {
|
|
console.error('error: setup needs --table <name> (or --rpc <name>) so the daily run is a real database read.');
|
|
return 1;
|
|
}
|
|
const m = /^(\d{1,2}):(\d{2})$/.exec(args.time || '06:17');
|
|
if (!m) {
|
|
console.error(`error: --time must look like HH:MM (got ${args.time})`);
|
|
return 1;
|
|
}
|
|
const hour = parseInt(m[1], 10);
|
|
const minute = parseInt(m[2], 10);
|
|
if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
|
|
console.error(`error: --time out of range (got ${args.time})`);
|
|
return 1;
|
|
}
|
|
|
|
fs.mkdirSync(HOME_DIR, { recursive: true });
|
|
fs.copyFileSync(__filename, SCRIPT_COPY);
|
|
const host = url.replace(/^https?:\/\//, '');
|
|
const marker = `${MARKER_PREFIX}${host}`;
|
|
const line = `${minute} ${hour} * * * ${cronCommand(url, key, args.table, args.rpc)} >> "${LOG_FILE}" 2>&1 ${marker}`;
|
|
|
|
const printFallback = (why) => {
|
|
if (why) console.log(why);
|
|
console.log('Add this line with your own scheduler (cron, launchd, Task Scheduler) instead:');
|
|
console.log('');
|
|
console.log(line);
|
|
console.log('');
|
|
console.log(`(the script was copied to ${SCRIPT_COPY} so the line above works as-is)`);
|
|
};
|
|
|
|
if (!hasCrontab()) {
|
|
printFallback('No usable crontab on this machine.');
|
|
return 0;
|
|
}
|
|
|
|
const existing = readCrontab();
|
|
const kept = existing.split('\n').filter((l) => l.trim() && !l.includes(marker));
|
|
kept.push(line);
|
|
if (!writeCrontab(kept.join('\n') + '\n')) {
|
|
printFallback('Could not write the crontab (permission prompt or restricted shell).');
|
|
return 0;
|
|
}
|
|
|
|
console.log(`ok: daily ping for ${host} installed at ${m[1].padStart(2, '0')}:${m[2]} local time.`);
|
|
console.log(`Logs: ${LOG_FILE}`);
|
|
console.log(`Check it any time: crontab -l | grep '${marker}'`);
|
|
console.log(`Remove it: supabase-stay-awake uninstall --url ${url}`);
|
|
return 0;
|
|
}
|
|
|
|
function cmdList() {
|
|
if (!hasCrontab()) {
|
|
console.log('No crontab on this machine (nothing installed by setup).');
|
|
return 0;
|
|
}
|
|
const lines = readCrontab().split('\n').filter((l) => l.includes(MARKER_PREFIX));
|
|
if (lines.length === 0) {
|
|
console.log('No supabase-stay-awake jobs installed. Run: supabase-stay-awake setup --url ... --key ... --table ...');
|
|
return 0;
|
|
}
|
|
console.log(`${lines.length} job(s) installed:`);
|
|
for (const l of lines) console.log(l);
|
|
return 0;
|
|
}
|
|
|
|
function cmdUninstall(args) {
|
|
if (!hasCrontab()) {
|
|
console.log('No crontab on this machine; nothing to remove.');
|
|
return 0;
|
|
}
|
|
const existing = readCrontab();
|
|
let removed = 0;
|
|
const kept = existing.split('\n').filter((l) => {
|
|
if (!l.includes(MARKER_PREFIX)) return true;
|
|
if (args.all) { removed++; return false; }
|
|
const host = args.url ? args.url.replace(/^https?:\/\//, '').replace(/\/+$/, '') : null;
|
|
if (host && l.includes(`${MARKER_PREFIX}${host}`)) { removed++; return false; }
|
|
return true;
|
|
});
|
|
if (removed === 0) {
|
|
console.log(args.all || args.url
|
|
? 'Nothing matched; no job removed.'
|
|
: 'Pass --url <the project url> or --all to pick which job(s) to remove.');
|
|
return args.all || args.url ? 0 : 1;
|
|
}
|
|
const ok = writeCrontab(kept.filter((l) => l.trim()).join('\n') + (kept.some((l) => l.trim()) ? '\n' : ''));
|
|
if (!ok) {
|
|
console.error('error: could not write the crontab (permission prompt or restricted shell). Nothing was changed.');
|
|
return 1;
|
|
}
|
|
console.log(`ok: removed ${removed} job(s).`);
|
|
return 0;
|
|
}
|
|
|
|
async function main() {
|
|
const argv = process.argv.slice(2);
|
|
const sub = ['setup', 'list', 'uninstall'].includes(argv[0]) ? argv[0] : null;
|
|
const args = parseArgs(sub ? argv.slice(1) : argv);
|
|
if (args.help) {
|
|
help();
|
|
return 0;
|
|
}
|
|
if (sub === 'setup') return cmdSetup(args);
|
|
if (sub === 'list') return cmdList();
|
|
if (sub === 'uninstall') return cmdUninstall(args);
|
|
|
|
const url = (args.url || process.env.SUPABASE_URL || '').replace(/\/+$/, '');
|
|
const key = args.key || process.env.SUPABASE_ANON_KEY || '';
|
|
if (!url || !key) {
|
|
console.error('error: --url/SUPABASE_URL and --key/SUPABASE_ANON_KEY are required. Run with --help.');
|
|
return 1;
|
|
}
|
|
if (!/^https?:\/\/[A-Za-z0-9.-]+(:\d+)?$/.test(url)) {
|
|
console.error(`error: --url must be the project origin only, like https://abcdefgh.supabase.co (got ${url})`);
|
|
return 1;
|
|
}
|
|
const opts = { retries: args.retries, timeoutSec: args.timeout };
|
|
|
|
const root = await request(url, key, '/rest/v1/', opts);
|
|
if (root.code === PAUSED_CODE) {
|
|
console.error(`::error:: project is PAUSED (HTTP 540). Restore it from the Supabase dashboard (Restore project); this cannot unpause it.`);
|
|
console.error('A backend that does not pause idle projects: https://scribase.com/supabase-project-paused?utm_source=cli&utm_medium=cli&utm_campaign=supabase-keep-alive');
|
|
return 1;
|
|
}
|
|
if (root.code === 401 || root.code === 403) {
|
|
console.error(`error: anon key rejected (HTTP ${root.code}). Check SUPABASE_ANON_KEY belongs to this project.`);
|
|
return 1;
|
|
}
|
|
if (root.code === 0) {
|
|
console.error('error: could not reach the project (DNS, TLS, or timeout). Check SUPABASE_URL.');
|
|
return 1;
|
|
}
|
|
if (root.code < 200 || root.code >= 300) {
|
|
console.error(`error: REST root answered HTTP ${root.code}: ${root.text.slice(0, 200)}`);
|
|
return 1;
|
|
}
|
|
|
|
if (args.table) {
|
|
const q = await request(url, key, `/rest/v1/${args.table}?select=${encodeURIComponent(args.select)}&limit=1`, opts);
|
|
if (q.code === PAUSED_CODE) {
|
|
console.error('::error:: project is PAUSED (HTTP 540) during the table read.');
|
|
return 1;
|
|
}
|
|
if (q.code === 404) {
|
|
console.error(`error: table '${args.table}' not found through the REST API (HTTP 404).`);
|
|
return 1;
|
|
}
|
|
if (q.code < 200 || q.code >= 300) {
|
|
console.error(`error: table read answered HTTP ${q.code}: ${q.text.slice(0, 200)}`);
|
|
return 1;
|
|
}
|
|
} else if (args.rpc) {
|
|
const q = await request(url, key, `/rest/v1/rpc/${args.rpc}`, {
|
|
...opts,
|
|
method: 'POST',
|
|
body: args.rpcBody || '{}',
|
|
});
|
|
if (q.code === PAUSED_CODE) {
|
|
console.error('::error:: project is PAUSED (HTTP 540) during the rpc call.');
|
|
return 1;
|
|
}
|
|
if (q.code < 200 || q.code >= 300) {
|
|
console.error(`error: rpc call answered HTTP ${q.code}: ${q.text.slice(0, 200)}`);
|
|
return 1;
|
|
}
|
|
} else {
|
|
console.warn('warning: no --table or --rpc given; only the REST root was pinged, which may not count as database activity.');
|
|
}
|
|
|
|
console.log('ok: project is awake.');
|
|
return 0;
|
|
}
|
|
|
|
main().then((code) => process.exit(code), (err) => {
|
|
console.error('error:', err && err.message ? err.message : err);
|
|
process.exit(1);
|
|
});
|