0ff1b05553
* feat(entitlements): partition the self-host bypass so connector capabilities fall through to grants; capability_grants.source accepts 'connector' Sovereign plan WS3 PR3: ships dark, nothing changes for hosted. - lib/entitlements/keys.ts: CONNECTOR_CAPABILITIES = bank_sync, skatteverket, org_lookup, migration (services Accounted operates that a self-hosted instance cannot provide itself) + isConnectorCapability(). Separate from PAID_CAPABILITIES and outside the trial-seed trigger on purpose: a hosted company can never hold a connector grant. - lib/entitlements/has-capability.ts: isPaywallBypassed() -> isBypassedFor(key). Hosted: byte-identical (dev / DISABLE_PAYWALL bypass, FORCE_PAYWALL wins, else the grant lookup). Self-host: local capabilities always on (FORCE_PAYWALL included, as the existing test demands); connector capabilities behave like hosted, i.e. dev bypass, FORCE_PAYWALL, else the grant lookup where the connector sync will write source='connector' rows. getCompanyEntitlements on a self-host: local paid keys + active connector keys, state 'paid' with an active connector grant else 'none' (never the hosted trial copy). - Migration 20260820122000: capability_grants.source CHECK gains 'connector', found through pg_constraint (the CHECK was declared inline and auto-named; Postgres stores IN as = ANY, matched accordingly). pg-real test: connector accepted, unknown source rejected, upsert on the (scope, key, source) identity, trial seed writes no connector rows. - Tests: self-hosted connector matrix (local all-on without DB, connector gated by grant/expiry, dev bypass all-on, FORCE_PAYWALL gates connector keys only, bulk resolution, entitlements shape); two pre-existing tests that asserted the old "self-host holds connector keys" contract updated to the new one. Verified: full unit suite green, pg-real suite for lib/entitlements green against a local supabase/postgres with every migration applied, lint ratchet, guards. Deferred to the instance-wiring PR: adding the connector extensions to the self-host Docker preset (dead-end upsells until a key can be issued). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(entitlements): fold the self-host branch into the existing grants query One .or(scopeFilter), not two: the duplicated helper pushed the no-phantom-columns unresolvable-expression count to 380/379. Behaviour is unchanged; the self-host matrix tests still pass. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(connect): hosted connector-key registry + validate RPC + entitlements endpoint; instance sync writes connector grants hourly Sovereign plan WS3 PR4 ("key infra enabling manual sales"), stacked on the entitlement partition (#1747). Nothing is purchasable yet; this is the plumbing both ends need before the first manually issued key. Hosted side: - Migration 20260820123000: connector_keys (SHA-256 key_hash, prefix, org_number, pinned instance_url, scopes, status, Stripe ids, current_period_end, per-minute rate limit, active_company_count, last_seen/synced) and connector_usage_events (per-request metering, separate from metered_events whose company_id references hosted companies). RLS on, NO policies: service role only. RPC validate_and_increment_connector_key copies the api_keys pattern (FOR UPDATE, minute window, suspended reported not counted, revoked = no row) and is REVOKEd from PUBLIC/anon/authenticated, GRANTed to service_role. pg-real test covers validate/count, unknown+revoked, suspended, rate limit, execute privileges per role, RLS invisibility, usage cascade. - lib/connect/contract.ts (shared wire types), lib/connect/hosted/keys.ts (generate/hash/validate -> 401/403/429 mapping), with-connector-auth.ts (Bearer or X-Connector-Key, one usage row per request, 500 envelope on handler throw), /api/connect/entitlements GET + POST (records active_company_count, pins instance_url on first report, never moves a pinned one), scripts/issue-connector-key.ts (dry run unless --confirm, prints the key once + the .env lines). Instance side: - lib/connect/instance/config.ts (GNUBOK_CONNECTOR_KEY, GNUBOK_CONNECT_URL default https://app.gnubok.se), sync.ts: reports the active company count and writes source='connector' grants for every company x covered scope, expires_at = min(now+72h, period_end+3d); 401/403 or a non-active status deletes them (freeze-and-retain); network/5xx/429 leave them alone. /api/connector/sync/cron (hourly) runs it; not_configured without a key. - Crontab generator gains EXTRA_JOBS (variant-only jobs not in vercel.json, with reasons) + drift tests; docker/crontab.self-hosted regenerated with the hourly sync. Docs (SELF-HOSTING connector section, env templates), DECISIONS. Tests: 52 new unit tests (keys, auth wrapper, route, config, sync outcomes and grant arithmetic, cron route, crontab EXTRA_JOBS) + 7 pg-real tests run locally against supabase/postgres with every migration applied. no-phantom-columns ceiling +1 with a reason (the bulk grant upsert). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(connect): update pg test to re-versioned migration 20260831190000 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb * fix(connect): RPC errors answer 503 not 401; X-Connector-Key wins over Authorization A hosted DB error mapped to 401 made the instance sync treat a pooler blip as key revocation and delete its entire connector grant cache, zeroing the 72h offline grace. 503 lands in the sync's keep-grants branch (already test-pinned). Bearer-first extraction hashed the upstream token on dual-header proxied calls, 401ing the exact shape X-Connector-Key exists for. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb * fix(connect): sync deletes grants only on a body-proven connector rejection, never bare 401/403 A WAF challenge page, edge deployment protection, or an egress proxy answers 401/403 without the hosted app ever running; trusting status alone wiped the instance's 72h offline grant cache within the hour. Deletion now requires the hosted route's own rejection code in the JSON body; codeless 401/403 keeps grants (server_error branch). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb * fix(connect): PR #1748 review batch: https-only connect URL, atomic pin, prefix-gated Bearer, deferred metering, entitlements validation, integer months - GNUBOK_CONNECT_URL must be https (http only for loopback); invalid or plaintext URLs disable the connector instead of sending the key. - instance_url pin update filters on IS NULL; a lost race re-reads and reports the winner's pin. - extractConnectorKey: a Bearer is the connector credential only with the gnubok_ck_ prefix; upstream Bearer falls through to X-Connector-Key. - Usage metering runs via after() off the response path (inline outside a request scope). - Sync validates entitlements shape: unknown status or malformed current_period_end keeps grants (server_error), never deletes. - issue-connector-key rejects fractional --months. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UzNkSsR18pLFitJdYn8QEb --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Emil <emilmattsson14@gmail.com>
302 lines
12 KiB
TypeScript
302 lines
12 KiB
TypeScript
#!/usr/bin/env npx tsx
|
|
/**
|
|
* Crontab generator: emits docker/crontab.hosted and docker/crontab.self-hosted
|
|
* from the `crons` array in vercel.json.
|
|
*
|
|
* vercel.json is the single source of truth for what runs on a schedule. The
|
|
* Docker deployments run the same HTTP endpoints through supercronic, so their
|
|
* crontabs are generated from that array instead of hand-maintained.
|
|
*
|
|
* Hand-maintaining them is exactly what went wrong: seven of sixteen jobs were
|
|
* missing from Docker entirely (recurring invoices never sent, webhooks never
|
|
* dispatched, idempotency_keys grew unbounded), /api/tax-deadlines/cron had
|
|
* degraded from daily to "0 0 2 1 *" (once a year, on 2 January), and
|
|
* /api/documents/verify/cron ran weekly against a daily vercel.json.
|
|
*
|
|
* Usage:
|
|
* npx tsx scripts/generate-crontabs.ts # rewrite both crontabs
|
|
* npm run crontabs:generate # same, via package.json
|
|
*
|
|
* scripts/__tests__/generate-crontabs.test.ts fails CI if the committed files
|
|
* drift from vercel.json again.
|
|
*/
|
|
|
|
import { readFileSync, writeFileSync } from 'node:fs'
|
|
import { join, dirname } from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
|
|
const __filename = fileURLToPath(import.meta.url)
|
|
const ROOT = dirname(dirname(__filename))
|
|
const VERCEL_JSON_PATH = join(ROOT, 'vercel.json')
|
|
const DOCKER_DIR = join(ROOT, 'docker')
|
|
|
|
export type CrontabVariant = 'hosted' | 'self-hosted'
|
|
|
|
export const VARIANTS: readonly CrontabVariant[] = ['hosted', 'self-hosted']
|
|
|
|
export interface VercelCron {
|
|
path: string
|
|
schedule: string
|
|
}
|
|
|
|
/** The compose file that bind-mounts each variant, quoted in the file header. */
|
|
const MOUNTED_BY: Record<CrontabVariant, string> = {
|
|
hosted: 'docker-compose.hosted.yml',
|
|
'self-hosted': 'docker-compose.yml',
|
|
}
|
|
|
|
/**
|
|
* The invocation. `${CRON_SECRET}` and `${APP_URL}` are expanded by the shell
|
|
* supercronic runs each job under; both come from the cron service's
|
|
* environment in docker-compose.yml. Not a template literal on purpose: the
|
|
* `${...}` must reach the file verbatim.
|
|
*/
|
|
const CURL_PREFIX = 'curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}'
|
|
|
|
/**
|
|
* Paths in vercel.json deliberately NOT emitted into the Docker crontabs, each
|
|
* with its reason. A silent omission is drift; this table is the only
|
|
* sanctioned way to leave a scheduled endpoint out of a self-hosted install.
|
|
*
|
|
* Empty, and that is the reviewed answer rather than an oversight:
|
|
*
|
|
* - Extension endpoints stay in, including extensions the self-hosted preset
|
|
* does not enable. docker/extensions.self-hosted.json turns on five
|
|
* extensions, but the preset only drives the runtime registry: the
|
|
* Dockerfile builds the whole app/ tree, so every extension cron route is
|
|
* compiled into the image either way. And every one of them answers HTTP
|
|
* 200 with a no-op body when its extension is unconfigured (skatteverket
|
|
* checks SKATTEVERKET_ENABLED, stripe checks STRIPE_SECRET_KEY plus
|
|
* STRIPE_CONNECT_CLIENT_ID, cloud-backup and enable-banking simply find no
|
|
* rows). An unused extension therefore costs one cheap request at its
|
|
* cadence, and a self-hoster who enables it later does not have to discover
|
|
* that the schedule was never there. This also matches the pre-existing
|
|
* intent: the hand-written crontabs already listed enable-banking and
|
|
* skattekonto, neither of which is in the self-hosted preset.
|
|
* - /api/sandbox/cleanup/cron stays in. The sandbox is a database flag
|
|
* (company_settings.is_sandbox), not a hosted-only build flag, and the
|
|
* cleanup_expired_sandbox_users RPC ships in supabase/migrations
|
|
* (20260311120000_sandbox_support.sql), so a self-hosted database has it.
|
|
* With no sandbox users it deletes 0 rows and returns 200.
|
|
*/
|
|
export const EXCLUDED_PATHS: Readonly<Record<string, string>> = {}
|
|
|
|
/**
|
|
* Per-variant schedule overrides, path to cron expression. This is where a
|
|
* deliberate hosted/self-hosted divergence gets recorded, so it reads as a
|
|
* decision with a reason instead of as drift in a hand-edited file.
|
|
*
|
|
* Empty on both variants: every job currently runs the vercel.json cadence
|
|
* everywhere. Two candidates were considered and rejected:
|
|
*
|
|
* - /api/documents/verify/cron ran weekly ("0 3 * * 0") in the hand-written
|
|
* crontabs against a daily vercel.json. Not a load concession: the run is
|
|
* capped at 200 documents (DOCUMENT_VERIFY_BATCH_SIZE) and walks a
|
|
* nulls-first queue, so weekly drains the WORM integrity queue seven times
|
|
* slower on a check that exists to satisfy BFL 7-year retention. The weekly
|
|
* cadence also sat in crontab.hosted, which is not a small box (the two
|
|
* files were byte-identical), so it cannot have been a self-hosted
|
|
* concession. Treated as drift and realigned to daily.
|
|
* - /api/webhooks/dispatch/cron at "* * * * *" is 1440 requests/day that
|
|
* self-hosted was not making before. Left at parity anyway: the retry
|
|
* ladder in lib/webhooks/dispatcher.ts opens with a 60-second first retry,
|
|
* which a coarser tick would silently stretch, and each tick is one indexed
|
|
* query that returns immediately when nothing is due. See the load note in
|
|
* the generated file header.
|
|
*/
|
|
export const SCHEDULE_OVERRIDES: Readonly<
|
|
Record<CrontabVariant, Readonly<Record<string, string>>>
|
|
> = {
|
|
hosted: {},
|
|
'self-hosted': {},
|
|
}
|
|
|
|
/**
|
|
* Jobs that exist in ONE variant only and therefore have no vercel.json entry
|
|
* (vercel.json is the hosted schedule). Each carries its reason, the same
|
|
* discipline as EXCLUDED_PATHS: a self-hosted-only endpoint that silently
|
|
* lacked a schedule would be dead code that looks alive.
|
|
*
|
|
* Rendered after the vercel.json jobs under their own comment line. The
|
|
* crontab drift test checks both halves: the vercel.json mirror AND that
|
|
* every EXTRA_JOBS path is a real cron route that vercel.json does NOT
|
|
* schedule (the moment it does, the entry must go).
|
|
*/
|
|
export interface ExtraJob {
|
|
path: string
|
|
schedule: string
|
|
reason: string
|
|
}
|
|
|
|
export const EXTRA_JOBS: Readonly<Record<CrontabVariant, readonly ExtraJob[]>> = {
|
|
hosted: [],
|
|
'self-hosted': [
|
|
{
|
|
path: '/api/connector/sync/cron',
|
|
schedule: '17 * * * *',
|
|
reason:
|
|
'Self-hosted only: refreshes the source=connector capability grants from the instance\'s ' +
|
|
'GNUBOK_CONNECTOR_KEY (hourly; grants carry a 72h offline grace). Hosted has no connector ' +
|
|
'key, so the route is not in vercel.json; an instance without a key answers not_configured.',
|
|
},
|
|
],
|
|
}
|
|
|
|
/** Read and shape-check the `crons` array. */
|
|
export function readVercelCrons(vercelJson: string): VercelCron[] {
|
|
const parsed = JSON.parse(vercelJson) as { crons?: VercelCron[] }
|
|
const crons = parsed.crons ?? []
|
|
|
|
for (const cron of crons) {
|
|
if (typeof cron.path !== 'string' || !cron.path.startsWith('/api/')) {
|
|
throw new Error(`vercel.json: cron path must start with /api/, got ${JSON.stringify(cron.path)}`)
|
|
}
|
|
if (typeof cron.schedule !== 'string' || cron.schedule.trim().split(/\s+/).length !== 5) {
|
|
throw new Error(
|
|
`vercel.json: ${cron.path} needs a 5-field cron expression, got ${JSON.stringify(cron.schedule)}`,
|
|
)
|
|
}
|
|
}
|
|
|
|
const seen = new Set<string>()
|
|
for (const cron of crons) {
|
|
if (seen.has(cron.path)) throw new Error(`vercel.json: duplicate cron path ${cron.path}`)
|
|
seen.add(cron.path)
|
|
}
|
|
|
|
return crons
|
|
}
|
|
|
|
/** The schedule a given variant should run a path on. */
|
|
export function scheduleFor(cron: VercelCron, variant: CrontabVariant): string {
|
|
return SCHEDULE_OVERRIDES[variant][cron.path] ?? cron.schedule
|
|
}
|
|
|
|
function buildHeader(variant: CrontabVariant): string[] {
|
|
return [
|
|
'# AUTO-GENERATED: do not edit. Run `npm run crontabs:generate` to regenerate.',
|
|
'#',
|
|
`# Variant: ${variant} (bind-mounted by ${MOUNTED_BY[variant]}).`,
|
|
'# Source of truth: the `crons` array in vercel.json. Paths, order and',
|
|
'# cadence mirror it exactly; scripts/__tests__/generate-crontabs.test.ts',
|
|
'# fails CI if this file drifts from it.',
|
|
'#',
|
|
'# Consumed by supercronic (docker/cron.Dockerfile), bind-mounted read-only',
|
|
'# at /etc/supercronic/crontab. Times are UTC: the cron container sets no TZ',
|
|
'# and Alpine defaults to UTC, same as Vercel Cron. supercronic skips a tick',
|
|
'# whose previous run is still going (overlapping is off by default), so a',
|
|
'# slow endpoint cannot pile up.',
|
|
'#',
|
|
'# Extension endpoints are listed unconditionally, including extensions this',
|
|
"# image's preset does not enable. Each answers 200 with a no-op body when",
|
|
'# its extension is unconfigured, so an unused one costs a single cheap',
|
|
'# request, and enabling it later needs no crontab change.',
|
|
'#',
|
|
'# Load note: /api/webhooks/dispatch/cron runs every minute, 1440 requests a',
|
|
'# day. Each tick is one indexed query that returns immediately when no',
|
|
'# delivery is due, and the per-minute cadence is what makes the dispatcher',
|
|
'# 60-second first retry actually happen after 60 seconds. Change it only',
|
|
'# through SCHEDULE_OVERRIDES in scripts/generate-crontabs.ts, never by',
|
|
'# editing this file.',
|
|
'',
|
|
]
|
|
}
|
|
|
|
/** Render one crontab. Always LF, always newline-terminated. */
|
|
export function buildCrontab(
|
|
crons: VercelCron[],
|
|
variant: CrontabVariant,
|
|
options: {
|
|
excluded?: Readonly<Record<string, string>>
|
|
overrides?: Readonly<Record<CrontabVariant, Readonly<Record<string, string>>>>
|
|
extraJobs?: Readonly<Record<CrontabVariant, readonly ExtraJob[]>>
|
|
} = {},
|
|
): string {
|
|
const excluded = options.excluded ?? EXCLUDED_PATHS
|
|
const overrides = options.overrides ?? SCHEDULE_OVERRIDES
|
|
|
|
const jobs = crons
|
|
.filter((cron) => !(cron.path in excluded))
|
|
.map((cron) => ({
|
|
path: cron.path,
|
|
schedule: overrides[variant][cron.path] ?? cron.schedule,
|
|
}))
|
|
|
|
const extraJobs = (options.extraJobs ?? EXTRA_JOBS)[variant]
|
|
|
|
// Align the commands: pad to the widest schedule plus two spaces, the same
|
|
// column convention the hand-written files used.
|
|
const width = [...jobs, ...extraJobs].reduce((max, job) => Math.max(max, job.schedule.length), 0) + 2
|
|
|
|
const lines = [
|
|
...buildHeader(variant),
|
|
...jobs.map((job) => `${job.schedule.padEnd(width)}${CURL_PREFIX}${job.path}`),
|
|
...(extraJobs.length > 0
|
|
? [
|
|
'',
|
|
`# ${variant}-only jobs, not in vercel.json: see EXTRA_JOBS in scripts/generate-crontabs.ts`,
|
|
...extraJobs.map((job) => `${job.schedule.padEnd(width)}${CURL_PREFIX}${job.path}`),
|
|
]
|
|
: []),
|
|
]
|
|
|
|
return `${lines.join('\n')}\n`
|
|
}
|
|
|
|
function main(): void {
|
|
const crons = readVercelCrons(readFileSync(VERCEL_JSON_PATH, 'utf8'))
|
|
|
|
for (const path of Object.keys(EXCLUDED_PATHS)) {
|
|
if (!crons.some((cron) => cron.path === path)) {
|
|
throw new Error(`EXCLUDED_PATHS lists ${path}, which is not in vercel.json. Remove the stale entry.`)
|
|
}
|
|
}
|
|
for (const variant of VARIANTS) {
|
|
for (const path of Object.keys(SCHEDULE_OVERRIDES[variant])) {
|
|
if (!crons.some((cron) => cron.path === path)) {
|
|
throw new Error(
|
|
`SCHEDULE_OVERRIDES.${variant} lists ${path}, which is not in vercel.json. Remove the stale entry.`,
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
for (const variant of VARIANTS) {
|
|
for (const job of EXTRA_JOBS[variant]) {
|
|
if (crons.some((cron) => cron.path === job.path)) {
|
|
throw new Error(
|
|
`EXTRA_JOBS.${variant} lists ${job.path}, which vercel.json now schedules. Remove the extra entry.`,
|
|
)
|
|
}
|
|
}
|
|
}
|
|
|
|
for (const variant of VARIANTS) {
|
|
const target = join(DOCKER_DIR, `crontab.${variant}`)
|
|
writeFileSync(target, buildCrontab(crons, variant), 'utf8')
|
|
const emitted = crons.filter((cron) => !(cron.path in EXCLUDED_PATHS)).length + EXTRA_JOBS[variant].length
|
|
const overridden = Object.keys(SCHEDULE_OVERRIDES[variant]).length
|
|
console.log(
|
|
`Wrote docker/crontab.${variant}: ${emitted} jobs` +
|
|
(overridden > 0 ? `, ${overridden} schedule override(s)` : ''),
|
|
)
|
|
}
|
|
|
|
const skipped = Object.keys(EXCLUDED_PATHS)
|
|
if (skipped.length > 0) {
|
|
console.log(`Excluded ${skipped.length} path(s): ${skipped.join(', ')}`)
|
|
} else {
|
|
console.log('No exclusions: every vercel.json cron runs on Docker too.')
|
|
}
|
|
}
|
|
|
|
// Only run when invoked directly (not when imported by tests).
|
|
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
|
try {
|
|
main()
|
|
} catch (err) {
|
|
console.error(err instanceof Error ? err.message : err)
|
|
process.exit(1)
|
|
}
|
|
}
|