@axium/server 0.0.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/dist/cli.js ADDED
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env node
2
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
3
+ if (value !== null && value !== void 0) {
4
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
5
+ var dispose, inner;
6
+ if (async) {
7
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
8
+ dispose = value[Symbol.asyncDispose];
9
+ }
10
+ if (dispose === void 0) {
11
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
12
+ dispose = value[Symbol.dispose];
13
+ if (async) inner = dispose;
14
+ }
15
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
16
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
17
+ env.stack.push({ value: value, dispose: dispose, async: async });
18
+ }
19
+ else if (async) {
20
+ env.stack.push({ async: true });
21
+ }
22
+ return value;
23
+ };
24
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
25
+ return function (env) {
26
+ function fail(e) {
27
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
28
+ env.hasError = true;
29
+ }
30
+ var r, s = 0;
31
+ function next() {
32
+ while (r = env.stack.pop()) {
33
+ try {
34
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
35
+ if (r.dispose) {
36
+ var result = r.dispose.call(r.value);
37
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
38
+ }
39
+ else s |= 1;
40
+ }
41
+ catch (e) {
42
+ fail(e);
43
+ }
44
+ }
45
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
46
+ if (env.hasError) throw env.error;
47
+ }
48
+ return next();
49
+ };
50
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
51
+ var e = new Error(message);
52
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
53
+ });
54
+ import chalk from 'chalk';
55
+ import { Option, program } from 'commander';
56
+ import { sql } from 'kysely';
57
+ import { exec } from 'node:child_process';
58
+ import { randomBytes } from 'node:crypto';
59
+ import * as _db from './database.js';
60
+ program.version('0.0.0').name('axium').description('Axium server CLI');
61
+ // Options shared by multiple commands
62
+ const opts = {
63
+ host: new Option('-H, --host <host>', 'the host of the database.').default('localhost:5432'),
64
+ timeout: new Option('-t, --timeout <ms>', 'how long to wait for commands to complete.').default(1000),
65
+ force: new Option('-f, --force', 'force the operation').default(false),
66
+ verbose: new Option('-v, --verbose', 'verbose output').default(false),
67
+ };
68
+ const axiumDB = program.command('db').alias('database').description('manage the database');
69
+ /** Convenience function for `example... [Done. / error]` */
70
+ async function report(promise, message, success = 'done.') {
71
+ process.stdout.write(message + '... ');
72
+ try {
73
+ const result = await promise;
74
+ console.log(success);
75
+ return result;
76
+ }
77
+ catch (error) {
78
+ throw typeof error == 'object' && 'message' in error ? error.message : error;
79
+ }
80
+ }
81
+ /** Convenience function for `sudo -u postgres psql -c "${command}"`, plus `report` coolness */
82
+ async function runSQL(opts, command, message) {
83
+ let stderr;
84
+ try {
85
+ process.stdout.write(message + '... ');
86
+ const { promise, resolve, reject } = Promise.withResolvers();
87
+ exec(`sudo -u postgres psql -c "${command}"`, { timeout: 1000, ...opts }, (err, _, _stderr) => {
88
+ stderr = _stderr.startsWith('ERROR:') ? _stderr.slice(6).trim() : _stderr;
89
+ if (err)
90
+ reject('[command]');
91
+ else
92
+ resolve();
93
+ });
94
+ await promise;
95
+ console.log('done.');
96
+ }
97
+ catch (error) {
98
+ throw error == '[command]' ? stderr?.slice(0, 100) || 'failed.' : typeof error == 'object' && 'message' in error ? error.message : error;
99
+ }
100
+ }
101
+ function err(message) {
102
+ if (message instanceof Error)
103
+ message = message.message;
104
+ console.error(message.startsWith('\x1b') ? message : chalk.red(message));
105
+ }
106
+ /** Yet another convenience function */
107
+ function exit(message, code = 1) {
108
+ err(message);
109
+ process.exit(code);
110
+ }
111
+ function shouldRecreate(opt) {
112
+ if (opt.skip) {
113
+ console.warn(chalk.yellow('already exists. (skipped)'));
114
+ return true;
115
+ }
116
+ if (opt.force) {
117
+ console.warn(chalk.yellow('already exists. (re-creating)'));
118
+ return false;
119
+ }
120
+ console.warn(chalk.yellow('already exists. Use --skip to skip or --force to re-create.'));
121
+ process.exit(2);
122
+ }
123
+ axiumDB
124
+ .command('init')
125
+ .description('initialize the database')
126
+ .addOption(opts.host)
127
+ .addOption(opts.timeout)
128
+ .addOption(opts.force)
129
+ .addOption(opts.verbose)
130
+ .option('-s, --skip', 'Skip existing database and/or user')
131
+ .action(async (opt) => {
132
+ const env_1 = { stack: [], error: void 0, hasError: false };
133
+ try {
134
+ opt.verbose && opt.force && console.log(chalk.yellow('--force: Protections disabled.'));
135
+ const config = _db.normalizeConfig(opt);
136
+ config.password ??= process.env.PGPASSWORD || randomBytes(32).toString('base64').replaceAll('=', '').replaceAll('/', '_').replaceAll('+', '-');
137
+ await runSQL(opt, 'CREATE DATABASE axium', 'Creating database')
138
+ .catch(async (error) => {
139
+ if (error != 'database "axium" already exists')
140
+ exit(error);
141
+ if (shouldRecreate(opt))
142
+ return;
143
+ await runSQL(opt, 'DROP DATABASE axium', 'Dropping database');
144
+ await runSQL(opt, 'CREATE DATABASE axium', 'Re-creating database');
145
+ })
146
+ .catch(exit);
147
+ const createQuery = `CREATE USER axium WITH ENCRYPTED PASSWORD '${config.password}' LOGIN`;
148
+ await runSQL(opt, createQuery, 'Creating user')
149
+ .catch(async (error) => {
150
+ if (error != 'role "axium" already exists')
151
+ exit(error);
152
+ if (shouldRecreate(opt))
153
+ return;
154
+ await runSQL(opt, 'REVOKE ALL PRIVILEGES ON SCHEMA public FROM axium', 'Revoking schema privileges');
155
+ await runSQL(opt, 'DROP USER axium', 'Dropping user');
156
+ await runSQL(opt, createQuery, 'Re-creating user');
157
+ })
158
+ .catch(exit);
159
+ await runSQL(opt, 'GRANT ALL PRIVILEGES ON DATABASE axium TO axium', 'Granting database privileges').catch(exit);
160
+ await runSQL(opt, 'GRANT ALL PRIVILEGES ON SCHEMA public TO axium', 'Granting schema privileges').catch(exit);
161
+ await runSQL(opt, 'ALTER DATABASE axium OWNER TO axium', 'Setting database owner').catch(exit);
162
+ await runSQL(opt, 'SELECT pg_reload_conf()', 'Reloading configuration').catch(exit);
163
+ const db = __addDisposableResource(env_1, _db.connect(config), true);
164
+ const relationExists = (table) => (error) => (error == `relation "${table}" already exists` ? console.warn(chalk.yellow('already exists.')) : exit(error));
165
+ const created = chalk.green('created.');
166
+ await report(db.schema
167
+ .createTable('User')
168
+ .addColumn('id', 'uuid', col => col.primaryKey().defaultTo(sql `gen_random_uuid()`))
169
+ .addColumn('name', 'text')
170
+ .addColumn('email', 'text', col => col.unique().notNull())
171
+ .addColumn('emailVerified', 'timestamptz')
172
+ .addColumn('image', 'text')
173
+ .execute(), 'Creating table User', created).catch(relationExists('User'));
174
+ await report(db.schema
175
+ .createTable('Account')
176
+ .addColumn('id', 'uuid', col => col.primaryKey().defaultTo(sql `gen_random_uuid()`))
177
+ .addColumn('userId', 'uuid', col => col.references('User.id').onDelete('cascade').notNull())
178
+ .addColumn('type', 'text', col => col.notNull())
179
+ .addColumn('provider', 'text', col => col.notNull())
180
+ .addColumn('providerAccountId', 'text', col => col.notNull())
181
+ .addColumn('refresh_token', 'text')
182
+ .addColumn('access_token', 'text')
183
+ .addColumn('expires_at', 'bigint')
184
+ .addColumn('token_type', 'text')
185
+ .addColumn('scope', 'text')
186
+ .addColumn('id_token', 'text')
187
+ .addColumn('session_state', 'text')
188
+ .execute(), 'Creating table Account', created).catch(relationExists('Account'));
189
+ await report(db.schema.createIndex('Account_userId_index').on('Account').column('userId').execute(), 'Creating index for Account.userId', created).catch(relationExists('Account_userId_index'));
190
+ await report(db.schema
191
+ .createTable('Session')
192
+ .addColumn('id', 'uuid', col => col.primaryKey().defaultTo(sql `gen_random_uuid()`))
193
+ .addColumn('userId', 'uuid', col => col.references('User.id').onDelete('cascade').notNull())
194
+ .addColumn('sessionToken', 'text', col => col.notNull().unique())
195
+ .addColumn('expires', 'timestamptz', col => col.notNull())
196
+ .execute(), 'Creating table Session', created).catch(relationExists('Session'));
197
+ await report(db.schema.createIndex('Session_userId_index').on('Session').column('userId').execute(), 'Creating index for Session.userId', created).catch(relationExists('Session_userId_index'));
198
+ await report(db.schema
199
+ .createTable('VerificationToken')
200
+ .addColumn('identifier', 'text', col => col.notNull())
201
+ .addColumn('token', 'text', col => col.notNull().unique())
202
+ .addColumn('expires', 'timestamptz', col => col.notNull())
203
+ .execute(), 'Creating table VerificationToken', created).catch(relationExists('VerificationToken'));
204
+ await report(db.schema
205
+ .createTable('Authenticator')
206
+ .addColumn('credentialID', 'text', col => col.primaryKey().notNull())
207
+ .addColumn('userId', 'uuid', col => col.notNull().references('User.id').onDelete('cascade').onUpdate('cascade'))
208
+ .addColumn('providerAccountId', 'text', col => col.notNull())
209
+ .addColumn('credentialPublicKey', 'text', col => col.notNull())
210
+ .addColumn('counter', 'integer', col => col.notNull())
211
+ .addColumn('credentialDeviceType', 'text', col => col.notNull())
212
+ .addColumn('credentialBackedUp', 'boolean', col => col.notNull())
213
+ .addColumn('transports', 'text')
214
+ .execute(), 'Creating table Authenticator', created).catch(relationExists('Authenticator'));
215
+ await report(db.schema.createIndex('Authenticator_credentialID_key').on('Authenticator').column('credentialID').execute(), 'Creating index for Authenticator.credentialID', created).catch(relationExists('Authenticator_credentialID_key'));
216
+ console.log('Done!\nPassword: ' + config.password);
217
+ }
218
+ catch (e_1) {
219
+ env_1.error = e_1;
220
+ env_1.hasError = true;
221
+ }
222
+ finally {
223
+ const result_1 = __disposeResources(env_1);
224
+ if (result_1)
225
+ await result_1;
226
+ }
227
+ });
228
+ axiumDB
229
+ .command('status')
230
+ .alias('stats')
231
+ .description('check the status of the database')
232
+ .addOption(opts.host)
233
+ .addOption(opts.verbose)
234
+ .action(async (opt) => _db
235
+ .statusText(opt)
236
+ .then(console.log)
237
+ .catch(() => exit('Unavailable')));
238
+ axiumDB
239
+ .command('drop')
240
+ .description('drop the database')
241
+ .addOption(opts.host)
242
+ .addOption(opts.verbose)
243
+ .addOption(opts.force)
244
+ .addOption(opts.timeout)
245
+ .action(async (opt) => {
246
+ opt.verbose && opt.force && console.log(chalk.yellow('--force: Protections disabled.'));
247
+ _db.normalizeConfig(opt);
248
+ const stats = await _db.status(opt).catch(exit);
249
+ if (!opt.force)
250
+ for (const key of ['users', 'accounts', 'sessions']) {
251
+ if (stats[key] == 0)
252
+ continue;
253
+ console.warn(chalk.yellow(`Database has existing ${key}. Use --force if you really want to drop the database.`));
254
+ process.exit(2);
255
+ }
256
+ await runSQL(opt, 'DROP DATABASE axium', 'Dropping database').catch(exit);
257
+ await runSQL(opt, 'REVOKE ALL PRIVILEGES ON SCHEMA public FROM axium', 'Revoking schema privileges').catch(exit);
258
+ await runSQL(opt, 'DROP USER axium', 'Dropping user').catch(exit);
259
+ });
260
+ program
261
+ .command('status')
262
+ .alias('stats')
263
+ .description('get information about the server')
264
+ .option('-D --db-host <host>', 'the host of the database.', 'localhost:5432')
265
+ .action(async (opt) => {
266
+ console.log('Axium Server v' + program.version());
267
+ process.stdout.write('Database: ');
268
+ await _db
269
+ .statusText({ host: opt.dbHost })
270
+ .then(console.log)
271
+ .catch(() => err('Unavailable'));
272
+ });
273
+ program.parse();
@@ -0,0 +1,116 @@
1
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
+ env.stack.push({ value: value, dispose: dispose, async: async });
17
+ }
18
+ else if (async) {
19
+ env.stack.push({ async: true });
20
+ }
21
+ return value;
22
+ };
23
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
+ return function (env) {
25
+ function fail(e) {
26
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
+ env.hasError = true;
28
+ }
29
+ var r, s = 0;
30
+ function next() {
31
+ while (r = env.stack.pop()) {
32
+ try {
33
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
+ if (r.dispose) {
35
+ var result = r.dispose.call(r.value);
36
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
+ }
38
+ else s |= 1;
39
+ }
40
+ catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
+ if (env.hasError) throw env.error;
46
+ }
47
+ return next();
48
+ };
49
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
+ var e = new Error(message);
51
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
+ });
53
+ import { Kysely, PostgresDialect, sql } from 'kysely';
54
+ import pg from 'pg';
55
+ export function normalizeConfig(config) {
56
+ config.host ??= 'localhost';
57
+ if (!config.port) {
58
+ const [hostname, port] = config.host.split(':');
59
+ config.port = port ? parseInt(port) : 5432;
60
+ config.host = hostname;
61
+ }
62
+ if (config.host.includes(':'))
63
+ config.host = config.host.split(':')[0];
64
+ return config;
65
+ }
66
+ export let database;
67
+ export function connect(config) {
68
+ if (database)
69
+ return database;
70
+ normalizeConfig(config);
71
+ const _db = new Kysely({
72
+ dialect: new PostgresDialect({
73
+ pool: new pg.Pool({
74
+ ...config,
75
+ user: 'axium',
76
+ database: 'axium',
77
+ }),
78
+ }),
79
+ });
80
+ database = Object.assign(_db, {
81
+ async [Symbol.asyncDispose]() {
82
+ await _db.destroy();
83
+ },
84
+ });
85
+ return database;
86
+ }
87
+ export async function status(config) {
88
+ const env_1 = { stack: [], error: void 0, hasError: false };
89
+ try {
90
+ normalizeConfig(config);
91
+ const db = __addDisposableResource(env_1, connect(config), true);
92
+ return {
93
+ users: (await db.selectFrom('User').select(db.fn.countAll().as('count')).executeTakeFirstOrThrow()).count,
94
+ accounts: (await db.selectFrom('Account').select(db.fn.countAll().as('count')).executeTakeFirstOrThrow()).count,
95
+ sessions: (await db.selectFrom('Session').select(db.fn.countAll().as('count')).executeTakeFirstOrThrow()).count,
96
+ };
97
+ }
98
+ catch (e_1) {
99
+ env_1.error = e_1;
100
+ env_1.hasError = true;
101
+ }
102
+ finally {
103
+ const result_1 = __disposeResources(env_1);
104
+ if (result_1)
105
+ await result_1;
106
+ }
107
+ }
108
+ export async function statusText(config) {
109
+ try {
110
+ const stats = await status(config);
111
+ return `${stats.users} users, ${stats.accounts} accounts, ${stats.sessions} sessions`;
112
+ }
113
+ catch (error) {
114
+ throw typeof error == 'object' && 'message' in error ? error.message : error;
115
+ }
116
+ }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * as db from './database.js';
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@axium/server",
3
+ "version": "0.0.1",
4
+ "main": "dist/index.js",
5
+ "author": "James Prevett <axium@jamespre.dev> (https://jamespre.dev)",
6
+ "funding": {
7
+ "type": "individual",
8
+ "url": "https://github.com/sponsors/james-pre"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/james-pre/axium.git"
13
+ },
14
+ "homepage": "https://github.com/james-pre/axium#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/james-pre/axium/issues"
17
+ },
18
+ "types": "dist/index.d.ts",
19
+ "type": "module",
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "bin": {
24
+ "axium": "./dist/cli.js"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc"
28
+ },
29
+ "dependencies": {
30
+ "@types/pg": "^8.11.11",
31
+ "chalk": "^5.4.1",
32
+ "commander": "^13.1.0",
33
+ "kysely": "^0.27.5",
34
+ "pg": "^8.14.1",
35
+ "@auth/kysely-adapter": "^1.8.0"
36
+ }
37
+ }