@kodentuzo/spotcraft 0.0.0-stage → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +81 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +196 -0
- package/dist/project.d.ts +41 -0
- package/dist/project.js +152 -0
- package/dist/provision.d.ts +57 -0
- package/dist/provision.js +163 -0
- package/dist/stack.d.ts +87 -0
- package/dist/stack.js +317 -0
- package/package.json +56 -4
package/dist/project.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { access, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { basename, dirname, join } from 'node:path';
|
|
4
|
+
import { appRoleName } from "./provision.js";
|
|
5
|
+
import { LOCAL_ISSUER, poolUrl, smtpUrl } from "./stack.js";
|
|
6
|
+
const exists = (path) => access(path).then(() => true, () => false);
|
|
7
|
+
/**
|
|
8
|
+
* The repository's root: the nearest folder up from `dir` with `.git` or `pnpm-workspace.yaml`,
|
|
9
|
+
* else `dir`. Every deployable in a repository shares its stack (ADR 0037).
|
|
10
|
+
*/
|
|
11
|
+
export async function findRoot(dir) {
|
|
12
|
+
for (let current = dir;; current = dirname(current)) {
|
|
13
|
+
if ((await exists(join(current, '.git'))) ||
|
|
14
|
+
(await exists(join(current, 'pnpm-workspace.yaml'))))
|
|
15
|
+
return current;
|
|
16
|
+
if (dirname(current) === current)
|
|
17
|
+
return dir;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** A name for the repository's stack: its folder's name, made safe for Compose. */
|
|
21
|
+
export function repoSlug(root) {
|
|
22
|
+
const slug = basename(root)
|
|
23
|
+
.toLowerCase()
|
|
24
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
25
|
+
.replace(/^-+|-+$/g, '')
|
|
26
|
+
.slice(0, 40)
|
|
27
|
+
.replace(/-+$/, '');
|
|
28
|
+
return slug || 'repo';
|
|
29
|
+
}
|
|
30
|
+
export async function readSpotcraftJson(dir) {
|
|
31
|
+
let text;
|
|
32
|
+
try {
|
|
33
|
+
text = await readFile(join(dir, 'spotcraft.json'), 'utf8');
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error.code === 'ENOENT')
|
|
37
|
+
return {};
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
let parsed;
|
|
41
|
+
try {
|
|
42
|
+
parsed = JSON.parse(text);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
throw new Error('spotcraft.json is not valid JSON');
|
|
46
|
+
}
|
|
47
|
+
const { name, migrate } = (parsed ?? {});
|
|
48
|
+
if (name !== undefined && typeof name !== 'string')
|
|
49
|
+
throw new Error('spotcraft.json: "name" must be a string');
|
|
50
|
+
if (migrate !== undefined && typeof migrate !== 'string')
|
|
51
|
+
throw new Error('spotcraft.json: "migrate" must be a command, as a string');
|
|
52
|
+
return { ...(name ? { name } : {}), ...(migrate ? { migrate } : {}) };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The app's name: `--name`, else `name` in spotcraft.json, else the `name` in package.json,
|
|
56
|
+
* made into a Spotcraft app name (`@acme/Blog_API` → `blog-api`). Throws when none gives a
|
|
57
|
+
* valid one.
|
|
58
|
+
*/
|
|
59
|
+
export async function appName(dir, flag) {
|
|
60
|
+
let candidate = flag ?? (await readSpotcraftJson(dir)).name;
|
|
61
|
+
if (!candidate) {
|
|
62
|
+
let pkg;
|
|
63
|
+
try {
|
|
64
|
+
pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8'));
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
throw new Error('No spotcraft.json or package.json here; pass the app name with --name');
|
|
68
|
+
}
|
|
69
|
+
if (typeof pkg.name !== 'string')
|
|
70
|
+
throw new Error('package.json has no name; pass --name');
|
|
71
|
+
candidate = pkg.name
|
|
72
|
+
.replace(/^@[^/]+\//, '')
|
|
73
|
+
.toLowerCase()
|
|
74
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
75
|
+
.replace(/^[^a-z]+|-+$/g, '')
|
|
76
|
+
.slice(0, 32)
|
|
77
|
+
.replace(/-+$/, '');
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
appRoleName(candidate);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
throw new Error(`"${candidate}" is not a Spotcraft app name (lower-case letters, digits and dashes, 2–32 characters); pass --name`);
|
|
84
|
+
}
|
|
85
|
+
return candidate;
|
|
86
|
+
}
|
|
87
|
+
/** KEY=value lines of a .env file (comments and blank lines skipped). */
|
|
88
|
+
export function parseEnv(text) {
|
|
89
|
+
const entries = new Map();
|
|
90
|
+
for (const line of text.split(/\r?\n/)) {
|
|
91
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line);
|
|
92
|
+
if (match)
|
|
93
|
+
entries.set(match[1], match[2].trim());
|
|
94
|
+
}
|
|
95
|
+
return entries;
|
|
96
|
+
}
|
|
97
|
+
async function readEnvFile(path) {
|
|
98
|
+
try {
|
|
99
|
+
return await readFile(path, 'utf8');
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (error.code === 'ENOENT')
|
|
103
|
+
return '';
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The settings an app gets locally, with the names the server uses (ADR 0034): its database
|
|
109
|
+
* URL and schema, the local pool and mail, and an APP_SECRET kept if .env already has one.
|
|
110
|
+
* An app that still has its own database (from before ADR 0034) gets that database and the
|
|
111
|
+
* kit's AUTH_SECRET instead of a schema.
|
|
112
|
+
*/
|
|
113
|
+
export async function localEnv(dir, stack, app) {
|
|
114
|
+
const existing = parseEnv(await readEnvFile(join(dir, '.env')));
|
|
115
|
+
const secret = (key) => existing.get(key) || randomBytes(32).toString('base64url');
|
|
116
|
+
if (!app.schema) {
|
|
117
|
+
return new Map([
|
|
118
|
+
['DATABASE_URL', app.databaseUrl],
|
|
119
|
+
['AUTH_SECRET', existing.get('AUTH_SECRET') || randomBytes(32).toString('hex')],
|
|
120
|
+
]);
|
|
121
|
+
}
|
|
122
|
+
return new Map([
|
|
123
|
+
['DATABASE_URL', app.databaseUrl],
|
|
124
|
+
['DATABASE_SCHEMA', app.schema],
|
|
125
|
+
['APP_NAME', app.name],
|
|
126
|
+
['APP_SECRET', secret('APP_SECRET')],
|
|
127
|
+
['PUBLIC_URL', 'http://localhost:3000'],
|
|
128
|
+
['AUTH_URL', poolUrl(stack)],
|
|
129
|
+
['AUTH_ISSUER', LOCAL_ISSUER],
|
|
130
|
+
['AUTH_JWKS_URL', `${poolUrl(stack)}/jwks`],
|
|
131
|
+
['SMTP_URL', smtpUrl(stack)],
|
|
132
|
+
['MAIL_FROM', `${app.name}@localhost`],
|
|
133
|
+
]);
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Adds the variables .env doesn't have yet, at the end, and leaves every existing line alone.
|
|
137
|
+
* Returns which were added and which were already there (possibly with another value).
|
|
138
|
+
*/
|
|
139
|
+
export async function writeMissing(dir, values) {
|
|
140
|
+
const path = join(dir, '.env');
|
|
141
|
+
const text = await readEnvFile(path);
|
|
142
|
+
const existing = parseEnv(text);
|
|
143
|
+
const added = [...values.keys()].filter((key) => !existing.has(key));
|
|
144
|
+
const kept = [...values.keys()].filter((key) => existing.has(key));
|
|
145
|
+
if (added.length > 0) {
|
|
146
|
+
const lines = added.map((key) => `${key}=${values.get(key)}`);
|
|
147
|
+
const separator = text === '' || text.endsWith('\n') ? '' : '\n';
|
|
148
|
+
const header = '# Local stack (spotcraft dev)\n';
|
|
149
|
+
await writeFile(path, `${text}${separator}${header}${lines.join('\n')}\n`);
|
|
150
|
+
}
|
|
151
|
+
return { added, kept };
|
|
152
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Where apps live in Postgres. Only tests use another one, to keep apart. */
|
|
2
|
+
export interface Instance {
|
|
3
|
+
/** The one database every app shares, like a Supabase project. */
|
|
4
|
+
database: string;
|
|
5
|
+
/**
|
|
6
|
+
* The role every app role belongs to. The user pool grants it `SELECT` and `REFERENCES` on
|
|
7
|
+
* `auth.users` (ADR 0035), so apps get those rights without the pool knowing each app.
|
|
8
|
+
*/
|
|
9
|
+
group: string;
|
|
10
|
+
}
|
|
11
|
+
export declare const INSTANCE: Instance;
|
|
12
|
+
/**
|
|
13
|
+
* The app's role and schema: `blog-api` → `app_blog_api` (names never contain `_`). Apps made
|
|
14
|
+
* before ADR 0034 also have a database of this name.
|
|
15
|
+
*/
|
|
16
|
+
export declare function appRoleName(name: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* Where the app's tables live: its schema in the instance database, its own database (from
|
|
19
|
+
* before ADR 0034), or nowhere yet. The schema wins: an app that moved keeps its old database
|
|
20
|
+
* until someone drops it.
|
|
21
|
+
*/
|
|
22
|
+
export declare function appLayout(adminUrl: string, name: string, { database: instance }?: Instance): Promise<'schema' | 'database' | 'none'>;
|
|
23
|
+
export interface ProvisionOptions {
|
|
24
|
+
/** The app's name, e.g. `blog`; its role and schema are `app_blog`. */
|
|
25
|
+
name: string;
|
|
26
|
+
/** The password of the app's role; set again on every run. */
|
|
27
|
+
password: string;
|
|
28
|
+
instance?: Instance;
|
|
29
|
+
/**
|
|
30
|
+
* Sets up the schema even though the app still has its own database (from before ADR 0034):
|
|
31
|
+
* the start of moving it there. Its own database stays as it was.
|
|
32
|
+
*/
|
|
33
|
+
move?: boolean;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Creates (or brings up to date) an app's role and schema in the instance database, connected
|
|
37
|
+
* as `adminUrl`: a role with CREATEDB and CREATEROLE, the agent's on the server. Running it
|
|
38
|
+
* again changes nothing except the password, if it changed. Returns the database the app
|
|
39
|
+
* connects to.
|
|
40
|
+
*
|
|
41
|
+
* The role owns its schema and has it as its `search_path`. It may connect to the instance
|
|
42
|
+
* database and nothing else: no schemas of its own, no other app's. An app that still has its
|
|
43
|
+
* own database (from before ADR 0034) keeps it, and gets no schema until it moves (`move`).
|
|
44
|
+
*/
|
|
45
|
+
export declare function provision(adminUrl: string, { name, password, instance: where, move }: ProvisionOptions): Promise<{
|
|
46
|
+
database: string;
|
|
47
|
+
}>;
|
|
48
|
+
/**
|
|
49
|
+
* Drops the app's schema and everything in it, and nothing else: a move that failed leaves the
|
|
50
|
+
* app in its own database, as before.
|
|
51
|
+
*/
|
|
52
|
+
export declare function dropSchema(adminUrl: string, name: string, { database: instance }?: Instance): Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Drops an app's schema (with everything in it), its own database if it still has one, and its
|
|
55
|
+
* role. Nothing happens for what doesn't exist.
|
|
56
|
+
*/
|
|
57
|
+
export declare function purge(adminUrl: string, name: string, { database: instance }?: Instance): Promise<void>;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// App schemas in the instance database: the same code on the server (the agent) and on a laptop
|
|
2
|
+
// (`spotcraft dev`), so an app's place in Postgres looks the same in both (ADRs 0034 and 0036).
|
|
3
|
+
import pg from 'pg';
|
|
4
|
+
const { Client, escapeIdentifier: id, escapeLiteral: lit } = pg;
|
|
5
|
+
export const INSTANCE = { database: 'apps', group: 'spotcraft_app' };
|
|
6
|
+
/** Spotcraft app names (the agent's NAME pattern); they become role and schema names. */
|
|
7
|
+
const APP_NAME = /^[a-z][a-z0-9-]{0,30}[a-z0-9]$/;
|
|
8
|
+
/**
|
|
9
|
+
* The app's role and schema: `blog-api` → `app_blog_api` (names never contain `_`). Apps made
|
|
10
|
+
* before ADR 0034 also have a database of this name.
|
|
11
|
+
*/
|
|
12
|
+
export function appRoleName(name) {
|
|
13
|
+
if (!APP_NAME.test(name))
|
|
14
|
+
throw new Error(`Not a valid app name: ${name}`);
|
|
15
|
+
return `app_${name.replaceAll('-', '_')}`;
|
|
16
|
+
}
|
|
17
|
+
/** Limits per app role, so one app can't starve the others on the shared server. */
|
|
18
|
+
const CONNECTION_LIMIT = 20;
|
|
19
|
+
const STATEMENT_TIMEOUT = '30s';
|
|
20
|
+
const IDLE_IN_TRANSACTION_TIMEOUT = '60s';
|
|
21
|
+
/** Runs `fn` connected as the admin (to `database`, or the URL's) and always disconnects. */
|
|
22
|
+
async function asAdmin(adminUrl, database, fn) {
|
|
23
|
+
const url = new URL(adminUrl);
|
|
24
|
+
if (database)
|
|
25
|
+
url.pathname = `/${database}`;
|
|
26
|
+
const client = new Client({ connectionString: url.toString() });
|
|
27
|
+
await client.connect();
|
|
28
|
+
try {
|
|
29
|
+
return await fn(client);
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
await client.end();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const currentUser = async (c) => (await c.query('SELECT current_user AS me')).rows[0].me;
|
|
36
|
+
const exists = async (c, sql, value) => Boolean((await c.query(sql, [value])).rowCount);
|
|
37
|
+
/**
|
|
38
|
+
* Where the app's tables live: its schema in the instance database, its own database (from
|
|
39
|
+
* before ADR 0034), or nowhere yet. The schema wins: an app that moved keeps its old database
|
|
40
|
+
* until someone drops it.
|
|
41
|
+
*/
|
|
42
|
+
export function appLayout(adminUrl, name, { database: instance } = INSTANCE) {
|
|
43
|
+
const role = appRoleName(name);
|
|
44
|
+
return asAdmin(adminUrl, undefined, async (admin) => {
|
|
45
|
+
const hasInstance = await exists(admin, 'SELECT 1 FROM pg_database WHERE datname = $1', instance);
|
|
46
|
+
const hasSchema = hasInstance &&
|
|
47
|
+
(await asAdmin(adminUrl, instance, (db) => exists(db, 'SELECT 1 FROM pg_namespace WHERE nspname = $1', role)));
|
|
48
|
+
if (hasSchema)
|
|
49
|
+
return 'schema';
|
|
50
|
+
if (await exists(admin, 'SELECT 1 FROM pg_database WHERE datname = $1', role))
|
|
51
|
+
return 'database';
|
|
52
|
+
return 'none';
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Creates the instance database and the app group if they're missing. The admin owns the
|
|
57
|
+
* database; nobody else may connect or create anything in `public`.
|
|
58
|
+
*/
|
|
59
|
+
async function ensureInstance(adminUrl, { database: instance, group }) {
|
|
60
|
+
await asAdmin(adminUrl, undefined, async (admin) => {
|
|
61
|
+
if (!(await exists(admin, 'SELECT 1 FROM pg_roles WHERE rolname = $1', group)))
|
|
62
|
+
await admin.query(`CREATE ROLE ${id(group)} NOLOGIN`);
|
|
63
|
+
if (!(await exists(admin, 'SELECT 1 FROM pg_database WHERE datname = $1', instance))) {
|
|
64
|
+
await admin.query(`CREATE DATABASE ${id(instance)}`);
|
|
65
|
+
await admin.query(`REVOKE ALL ON DATABASE ${id(instance)} FROM PUBLIC`);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
await asAdmin(adminUrl, instance, (db) => db.query('REVOKE ALL ON SCHEMA public FROM PUBLIC'));
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Creates (or brings up to date) an app's role and schema in the instance database, connected
|
|
72
|
+
* as `adminUrl`: a role with CREATEDB and CREATEROLE, the agent's on the server. Running it
|
|
73
|
+
* again changes nothing except the password, if it changed. Returns the database the app
|
|
74
|
+
* connects to.
|
|
75
|
+
*
|
|
76
|
+
* The role owns its schema and has it as its `search_path`. It may connect to the instance
|
|
77
|
+
* database and nothing else: no schemas of its own, no other app's. An app that still has its
|
|
78
|
+
* own database (from before ADR 0034) keeps it, and gets no schema until it moves (`move`).
|
|
79
|
+
*/
|
|
80
|
+
export async function provision(adminUrl, { name, password, instance: where = INSTANCE, move = false }) {
|
|
81
|
+
const role = appRoleName(name);
|
|
82
|
+
if (password.length < 16)
|
|
83
|
+
throw new Error('The app password must have at least 16 characters');
|
|
84
|
+
const ownDatabase = !move && (await appLayout(adminUrl, name, where)) === 'database';
|
|
85
|
+
const instance = where.database;
|
|
86
|
+
if (!ownDatabase)
|
|
87
|
+
await ensureInstance(adminUrl, where);
|
|
88
|
+
await asAdmin(adminUrl, undefined, async (admin) => {
|
|
89
|
+
const me = await currentUser(admin);
|
|
90
|
+
const roleExists = await exists(admin, 'SELECT 1 FROM pg_roles WHERE rolname = $1', role);
|
|
91
|
+
// NOSUPERUSER only on CREATE: Postgres refuses it in ALTER from a non-superuser, even as
|
|
92
|
+
// a no-op, and a role created without it can't gain it from the admin anyway.
|
|
93
|
+
const attributes = `LOGIN NOCREATEDB NOCREATEROLE CONNECTION LIMIT ${CONNECTION_LIMIT} PASSWORD ${lit(password)}`;
|
|
94
|
+
await admin.query(roleExists
|
|
95
|
+
? `ALTER ROLE ${id(role)} ${attributes}`
|
|
96
|
+
: `CREATE ROLE ${id(role)} NOSUPERUSER ${attributes}`);
|
|
97
|
+
await admin.query(`ALTER ROLE ${id(role)} SET statement_timeout = ${lit(STATEMENT_TIMEOUT)}`);
|
|
98
|
+
await admin.query(`ALTER ROLE ${id(role)} SET idle_in_transaction_session_timeout = ${lit(IDLE_IN_TRANSACTION_TIMEOUT)}`);
|
|
99
|
+
// The admin may act as the app (to create what the app owns) without inheriting its rights.
|
|
100
|
+
await admin.query(`GRANT ${id(role)} TO ${id(me)} WITH INHERIT FALSE, SET TRUE`);
|
|
101
|
+
if (ownDatabase) {
|
|
102
|
+
// The layout before ADR 0034: the app owns its database. Only it and the admin connect.
|
|
103
|
+
await admin.query(`SET ROLE ${id(role)}`);
|
|
104
|
+
await admin.query(`REVOKE ALL ON DATABASE ${id(role)} FROM PUBLIC`);
|
|
105
|
+
await admin.query(`GRANT CONNECT, CREATE ON DATABASE ${id(role)} TO ${id(me)}`);
|
|
106
|
+
await admin.query('RESET ROLE');
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
// Only in the instance database: an app that is moving still uses `public` in its own.
|
|
110
|
+
await admin.query(`ALTER ROLE ${id(role)} IN DATABASE ${id(instance)} SET search_path = ${id(role)}`);
|
|
111
|
+
await admin.query(`GRANT ${id(where.group)} TO ${id(role)}`);
|
|
112
|
+
await admin.query(`GRANT CONNECT ON DATABASE ${id(instance)} TO ${id(role)}`);
|
|
113
|
+
});
|
|
114
|
+
if (ownDatabase)
|
|
115
|
+
return { database: role };
|
|
116
|
+
await asAdmin(adminUrl, instance, (db) => db.query(`CREATE SCHEMA IF NOT EXISTS ${id(role)} AUTHORIZATION ${id(role)}`));
|
|
117
|
+
return { database: instance };
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Drops the app's schema and everything in it, and nothing else: a move that failed leaves the
|
|
121
|
+
* app in its own database, as before.
|
|
122
|
+
*/
|
|
123
|
+
export async function dropSchema(adminUrl, name, { database: instance } = INSTANCE) {
|
|
124
|
+
const role = appRoleName(name);
|
|
125
|
+
await asAdmin(adminUrl, instance, async (db) => {
|
|
126
|
+
await db.query(`SET ROLE ${id(role)}`);
|
|
127
|
+
await db.query(`DROP SCHEMA IF EXISTS ${id(role)} CASCADE`);
|
|
128
|
+
await db.query('RESET ROLE');
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Drops an app's schema (with everything in it), its own database if it still has one, and its
|
|
133
|
+
* role. Nothing happens for what doesn't exist.
|
|
134
|
+
*/
|
|
135
|
+
export async function purge(adminUrl, name, { database: instance } = INSTANCE) {
|
|
136
|
+
const role = appRoleName(name);
|
|
137
|
+
const found = await asAdmin(adminUrl, undefined, async (admin) => ({
|
|
138
|
+
role: await exists(admin, 'SELECT 1 FROM pg_roles WHERE rolname = $1', role),
|
|
139
|
+
instance: await exists(admin, 'SELECT 1 FROM pg_database WHERE datname = $1', instance),
|
|
140
|
+
}));
|
|
141
|
+
if (!found.role)
|
|
142
|
+
return;
|
|
143
|
+
if (found.instance) {
|
|
144
|
+
await asAdmin(adminUrl, instance, async (db) => {
|
|
145
|
+
const me = await currentUser(db);
|
|
146
|
+
await db.query(`GRANT ${id(role)} TO ${id(me)} WITH INHERIT FALSE, SET TRUE`);
|
|
147
|
+
// As the app: drops its schema and anything else it owns here, and its grants here.
|
|
148
|
+
await db.query(`SET ROLE ${id(role)}`);
|
|
149
|
+
await db.query(`DROP OWNED BY ${id(role)} CASCADE`);
|
|
150
|
+
await db.query('RESET ROLE');
|
|
151
|
+
await db.query(`REVOKE ALL ON DATABASE ${id(instance)} FROM ${id(role)}`);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
await asAdmin(adminUrl, undefined, async (admin) => {
|
|
155
|
+
const me = await currentUser(admin);
|
|
156
|
+
await admin.query(`GRANT ${id(role)} TO ${id(me)} WITH INHERIT FALSE, SET TRUE`);
|
|
157
|
+
// As the owner, which may drop its database and end its own open connections.
|
|
158
|
+
await admin.query(`SET ROLE ${id(role)}`);
|
|
159
|
+
await admin.query(`DROP DATABASE IF EXISTS ${id(role)} WITH (FORCE)`);
|
|
160
|
+
await admin.query('RESET ROLE');
|
|
161
|
+
await admin.query(`DROP ROLE ${id(role)}`);
|
|
162
|
+
});
|
|
163
|
+
}
|
package/dist/stack.d.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The local stack of one repository (ADR 0037): Postgres set up like the Spotcraft server's,
|
|
3
|
+
* the user pool, and Mailpit to catch email, as the Compose project
|
|
4
|
+
* `spotcraft-dev-<repo>-<hash>`. Tests keep the values below equal to the server's files.
|
|
5
|
+
*/
|
|
6
|
+
export declare const PROJECT_PREFIX = "spotcraft-dev-";
|
|
7
|
+
/**
|
|
8
|
+
* A new stack's Compose project: the repository folder's slug and 6 hex characters of a hash of
|
|
9
|
+
* its absolute path, so two checkouts with the same folder name get their own stacks.
|
|
10
|
+
*/
|
|
11
|
+
export declare function projectName(root: string, slug: string): string;
|
|
12
|
+
/** The server's Postgres image (infra/server/compose.yaml). */
|
|
13
|
+
export declare const POSTGRES_IMAGE = "postgres:18.7-trixie@sha256:2ea8630df176ad090ec92136dee850397c5af8781e4bcf2e4162593691c61bbc";
|
|
14
|
+
/** Catches every email apps send (SMTP), with a web inbox. */
|
|
15
|
+
export declare const MAILPIT_IMAGE = "axllent/mailpit:v1.33.1@sha256:aef2aacc11f075ec0fb6874275ee4a421e688e11a96ebb296134d1735c7761ce";
|
|
16
|
+
/** The user pool runs from the Spotcraft image of the same version as this CLI. */
|
|
17
|
+
export declare const SPOTCRAFT_IMAGE = "vindotski/spotcraft";
|
|
18
|
+
/** The local pool's `iss`; it names the pool, it is not an address. */
|
|
19
|
+
export declare const LOCAL_ISSUER = "http://localhost/pools/main";
|
|
20
|
+
/** The server's Postgres login rules (infra/server/pg_hba.conf). */
|
|
21
|
+
export declare const PG_HBA = "# TYPE DATABASE USER ADDRESS METHOD\nlocal all postgres peer\nlocal all all reject\nhost all postgres all reject\nhost all all all scram-sha-256\n";
|
|
22
|
+
/** The agent's role, exactly as the deploy script sets it up (infra/remote-deploy.sh). */
|
|
23
|
+
export declare const ADMIN_SQL = "SELECT NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'spotcraft_agent') AS missing \\gset\n\\if :missing\n CREATE ROLE spotcraft_agent LOGIN CREATEDB CREATEROLE PASSWORD :'pw';\n\\else\n ALTER ROLE spotcraft_agent LOGIN CREATEDB CREATEROLE NOSUPERUSER PASSWORD :'pw';\n\\endif\n-- Roles the agent creates (one per app) are ones it may SET ROLE to, which Postgres requires\n-- to make them a database's owner; it doesn't inherit their rights.\nALTER ROLE spotcraft_agent SET createrole_self_grant = 'set';\n-- Apps get CONNECT on their own database only; the built-in ones are the agent's.\nREVOKE CONNECT ON DATABASE postgres, template1 FROM PUBLIC;\nGRANT CONNECT ON DATABASE postgres TO spotcraft_agent;\n-- The database apps share (ADR 0034), owned by the agent, and the group every app role joins.\n-- The agent may grant the group to the app roles it makes, without inheriting its rights.\nSELECT NOT EXISTS (SELECT FROM pg_database WHERE datname = 'apps') AS missing \\gset\n\\if :missing\n CREATE DATABASE apps OWNER spotcraft_agent;\n\\endif\nREVOKE ALL ON DATABASE apps FROM PUBLIC;\nSELECT NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'spotcraft_app') AS missing \\gset\n\\if :missing\n CREATE ROLE spotcraft_app NOLOGIN;\n\\endif\nGRANT spotcraft_app TO spotcraft_agent WITH ADMIN OPTION, INHERIT FALSE;\n-- The user pool's role (ADR 0035): it owns the auth schema in apps, and nothing else.\nSELECT NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'spotcraft_auth') AS missing \\gset\n\\if :missing\n CREATE ROLE spotcraft_auth LOGIN PASSWORD :'auth_pw';\n\\else\n ALTER ROLE spotcraft_auth LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD :'auth_pw';\n\\endif\nGRANT CONNECT ON DATABASE apps TO spotcraft_auth;\n\\c apps\nREVOKE ALL ON SCHEMA public FROM PUBLIC;\nCREATE SCHEMA IF NOT EXISTS auth AUTHORIZATION spotcraft_auth;\n";
|
|
24
|
+
export declare const appPassword: (name: string) => string;
|
|
25
|
+
/** A repository's stack: where it keeps its state, and the ports it was given. */
|
|
26
|
+
export interface Stack {
|
|
27
|
+
/** The Compose project, `spotcraft-dev-<repo>-<hash>` (or `spotcraft-dev-<repo>` from 0.6.0). */
|
|
28
|
+
project: string;
|
|
29
|
+
/** `.spotcraft/` in the repository's root. */
|
|
30
|
+
stateDir: string;
|
|
31
|
+
ports: {
|
|
32
|
+
postgres: number;
|
|
33
|
+
auth: number;
|
|
34
|
+
smtp: number;
|
|
35
|
+
mail: number;
|
|
36
|
+
};
|
|
37
|
+
/** The local pool's secret, made once. */
|
|
38
|
+
authSecret: string;
|
|
39
|
+
}
|
|
40
|
+
/** A free port on 127.0.0.1, as the system hands one out. */
|
|
41
|
+
declare function freePort(): Promise<number>;
|
|
42
|
+
/**
|
|
43
|
+
* The repository's stack, from `.spotcraft/dev.json`, or a new one: free ports and the project
|
|
44
|
+
* name picked once and kept, so URLs in `.env` stay the same. A `dev.json` from 0.6.0 has no
|
|
45
|
+
* project name; it keeps that version's `spotcraft-dev-<slug>`, now written down.
|
|
46
|
+
* `.spotcraft/` ignores itself in git.
|
|
47
|
+
*/
|
|
48
|
+
export declare function loadStack(root: string, slug: string, ports?: typeof freePort): Promise<Stack>;
|
|
49
|
+
export declare const adminUrl: (stack: Stack) => string;
|
|
50
|
+
/**
|
|
51
|
+
* What the app gets, as on the server but on localhost: the instance database, or the app's own
|
|
52
|
+
* one if it still has it (from before ADR 0034).
|
|
53
|
+
*/
|
|
54
|
+
export declare function databaseUrl(stack: Stack, name: string, database?: string): string;
|
|
55
|
+
/** Where apps reach the local pool, mail and its inbox. */
|
|
56
|
+
export declare const poolUrl: (stack: Stack) => string;
|
|
57
|
+
export declare const smtpUrl: (stack: Stack) => string;
|
|
58
|
+
export declare const mailUrl: (stack: Stack) => string;
|
|
59
|
+
/** The pool's image: SPOTCRAFT_DEV_IMAGE (e.g. a local build), else this CLI's version. */
|
|
60
|
+
export declare function poolImage(version: string, env?: NodeJS.ProcessEnv): string;
|
|
61
|
+
/** The Compose file, as JSON (valid YAML), passed to Docker on stdin. */
|
|
62
|
+
export declare function composeFile(stack: Stack, image: string): string;
|
|
63
|
+
export interface RunResult {
|
|
64
|
+
code: number;
|
|
65
|
+
stdout: string;
|
|
66
|
+
stderr: string;
|
|
67
|
+
}
|
|
68
|
+
/** Runs a command without a shell, optionally feeding `input` on stdin. */
|
|
69
|
+
export declare function run(file: string, args: string[], input?: string): Promise<RunResult>;
|
|
70
|
+
export type Runner = typeof run;
|
|
71
|
+
export declare class StackError extends Error {
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Starts the stack (what isn't running yet): Postgres first, then the roles and schemas the
|
|
75
|
+
* deploy script makes on a server, then the user pool and Mailpit, waiting until all are healthy.
|
|
76
|
+
*/
|
|
77
|
+
export declare function up(stack: Stack, image: string, runner?: Runner): Promise<void>;
|
|
78
|
+
/** Stops the stack; the data stays in its volume. */
|
|
79
|
+
export declare function down(stack: Stack, image: string, runner?: Runner): Promise<void>;
|
|
80
|
+
/** Whether the stack's Postgres is running. */
|
|
81
|
+
export declare function isRunning(stack: Stack, runner?: Runner): Promise<boolean>;
|
|
82
|
+
/** Every repository's stack on this machine, running or not, with its state. */
|
|
83
|
+
export declare function listStacks(runner?: Runner): Promise<{
|
|
84
|
+
name: string;
|
|
85
|
+
status: string;
|
|
86
|
+
}[]>;
|
|
87
|
+
export {};
|