@meghjs/cli 0.5.2 → 0.5.4
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/commands/migrate.d.ts +23 -5
- package/dist/commands/migrate.js +44 -6
- package/dist/commands/new.js +7 -1
- package/dist/generators/auth-files.d.ts +37 -0
- package/dist/generators/auth-files.js +198 -0
- package/dist/generators/auth.d.ts +26 -0
- package/dist/generators/auth.js +542 -0
- package/dist/generators/factory.d.ts +25 -0
- package/dist/generators/factory.js +159 -0
- package/dist/generators/make.d.ts +38 -0
- package/dist/generators/make.js +176 -0
- package/dist/generators/migration-schema.d.ts +5 -0
- package/dist/generators/migration-schema.js +25 -2
- package/dist/generators/orm-model.d.ts +6 -1
- package/dist/generators/orm-model.js +31 -2
- package/dist/generators/resource.d.ts +21 -0
- package/dist/generators/resource.js +17 -3
- package/dist/generators/scaffold.d.ts +76 -0
- package/dist/generators/scaffold.js +353 -0
- package/dist/generators/update-model.d.ts +21 -0
- package/dist/generators/update-model.js +129 -0
- package/dist/program.js +175 -6
- package/dist/templates/cascade.d.ts +37 -0
- package/dist/templates/cascade.js +87 -0
- package/dist/templates/catalog/common.d.ts +1 -0
- package/dist/templates/catalog/common.js +63 -0
- package/dist/templates/catalog/construction.d.ts +1 -0
- package/dist/templates/catalog/construction.js +138 -0
- package/dist/templates/catalog/crm.d.ts +1 -0
- package/dist/templates/catalog/crm.js +81 -0
- package/dist/templates/catalog/ecommerce.d.ts +1 -0
- package/dist/templates/catalog/ecommerce.js +143 -0
- package/dist/templates/catalog/education.d.ts +1 -0
- package/dist/templates/catalog/education.js +80 -0
- package/dist/templates/catalog/hr.d.ts +1 -0
- package/dist/templates/catalog/hr.js +83 -0
- package/dist/templates/catalog/logistics.d.ts +1 -0
- package/dist/templates/catalog/logistics.js +60 -0
- package/dist/templates/catalog/marketing.d.ts +1 -0
- package/dist/templates/catalog/marketing.js +104 -0
- package/dist/templates/catalog/medical.d.ts +1 -0
- package/dist/templates/catalog/medical.js +147 -0
- package/dist/templates/catalog/pos.d.ts +1 -0
- package/dist/templates/catalog/pos.js +110 -0
- package/dist/templates/catalog/real-estate.d.ts +1 -0
- package/dist/templates/catalog/real-estate.js +171 -0
- package/dist/templates/fields.d.ts +64 -0
- package/dist/templates/fields.js +331 -0
- package/dist/templates/index.d.ts +27 -0
- package/dist/templates/index.js +175 -0
- package/dist/templates/migration.d.ts +7 -0
- package/dist/templates/migration.js +80 -0
- package/dist/templates/template.d.ts +37 -0
- package/dist/templates/template.js +36 -0
- package/dist/utils/dialect.d.ts +8 -0
- package/dist/utils/dialect.js +57 -0
- package/package.json +17 -5
- package/readme.md +30 -1
- package/stubs/controllers/model-controller.stub +10 -1
- package/stubs/seeders/database-seeder.stub +8 -0
- package/stubs/seeders/seeder.stub +10 -0
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/** Where apps used to export their own Kysely instance. Still used when present. */
|
|
2
2
|
export declare const LEGACY_CONNECTION = "src/database/connection.ts";
|
|
3
3
|
export declare const DEFAULT_MIGRATIONS = "src/database/migrations";
|
|
4
|
+
export declare const DEFAULT_SEEDERS = "src/database/seeders";
|
|
5
|
+
export declare const DEFAULT_FACTORIES = "src/database/factories";
|
|
4
6
|
export type DatabasePaths = {
|
|
5
7
|
/**
|
|
6
8
|
* A module exporting the app's own Kysely instance (`default` or `db`),
|
|
@@ -14,20 +16,36 @@ export type DatabasePaths = {
|
|
|
14
16
|
settings: Record<string, unknown>;
|
|
15
17
|
/** Folder of migration files. */
|
|
16
18
|
migrations: string;
|
|
19
|
+
/** Folder of seeder files. */
|
|
20
|
+
seeders: string;
|
|
21
|
+
/** Folder of model factory files. */
|
|
22
|
+
factories: string;
|
|
17
23
|
};
|
|
18
|
-
/** `megh.database` / `megh.migrations` from package.json, else the defaults. */
|
|
24
|
+
/** `megh.database` / `megh.migrations` / `megh.seeders` from package.json, else the defaults. */
|
|
19
25
|
export declare function databasePaths(root: string, pkg?: Record<string, any>): DatabasePaths;
|
|
20
|
-
export type MigrateAction = "latest" | "rollback" | "reset" | "refresh" | "status";
|
|
26
|
+
export type MigrateAction = "latest" | "rollback" | "reset" | "refresh" | "status" | "seed";
|
|
21
27
|
export type MigrateOptions = {
|
|
22
28
|
cwd?: string;
|
|
23
29
|
step?: number;
|
|
24
30
|
};
|
|
25
31
|
/** Run a migration action in a child process and return its result. */
|
|
26
|
-
export declare function runMigrations(action: MigrateAction, opts?: MigrateOptions): any;
|
|
27
|
-
export
|
|
32
|
+
export declare function runMigrations(action: MigrateAction, opts?: MigrateOptions & SeedOptions): any;
|
|
33
|
+
export type SeedOptions = {
|
|
34
|
+
/** Run this seeder instead of the `database` seeder (or all of them). */
|
|
35
|
+
seeder?: string;
|
|
36
|
+
/** Seed even when NODE_ENV is production. */
|
|
37
|
+
force?: boolean;
|
|
38
|
+
};
|
|
39
|
+
/** Run the seeders: `seeder`, else the `database` seeder, else all in file order. */
|
|
40
|
+
export declare function dbSeed(opts?: MigrateOptions & SeedOptions): string[];
|
|
41
|
+
export declare function migrate(opts?: MigrateOptions & SeedOptions & {
|
|
42
|
+
seed?: boolean;
|
|
43
|
+
}): string[];
|
|
28
44
|
export declare function migrateRollback(opts?: MigrateOptions): string[];
|
|
29
45
|
export declare function migrateReset(opts?: MigrateOptions): string[];
|
|
30
|
-
export declare function migrateRefresh(opts?: MigrateOptions
|
|
46
|
+
export declare function migrateRefresh(opts?: MigrateOptions & SeedOptions & {
|
|
47
|
+
seed?: boolean;
|
|
48
|
+
}): {
|
|
31
49
|
down: string[];
|
|
32
50
|
up: string[];
|
|
33
51
|
};
|
package/dist/commands/migrate.js
CHANGED
|
@@ -3,9 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.DEFAULT_MIGRATIONS = exports.LEGACY_CONNECTION = void 0;
|
|
6
|
+
exports.DEFAULT_FACTORIES = exports.DEFAULT_SEEDERS = exports.DEFAULT_MIGRATIONS = exports.LEGACY_CONNECTION = void 0;
|
|
7
7
|
exports.databasePaths = databasePaths;
|
|
8
8
|
exports.runMigrations = runMigrations;
|
|
9
|
+
exports.dbSeed = dbSeed;
|
|
9
10
|
exports.migrate = migrate;
|
|
10
11
|
exports.migrateRollback = migrateRollback;
|
|
11
12
|
exports.migrateReset = migrateReset;
|
|
@@ -23,7 +24,9 @@ const project_1 = require("../utils/project");
|
|
|
23
24
|
/** Where apps used to export their own Kysely instance. Still used when present. */
|
|
24
25
|
exports.LEGACY_CONNECTION = "src/database/connection.ts";
|
|
25
26
|
exports.DEFAULT_MIGRATIONS = "src/database/migrations";
|
|
26
|
-
|
|
27
|
+
exports.DEFAULT_SEEDERS = "src/database/seeders";
|
|
28
|
+
exports.DEFAULT_FACTORIES = "src/database/factories";
|
|
29
|
+
/** `megh.database` / `megh.migrations` / `megh.seeders` from package.json, else the defaults. */
|
|
27
30
|
function databasePaths(root, pkg = (0, project_1.readPackageJson)(root)) {
|
|
28
31
|
const conf = pkg?.megh ?? {};
|
|
29
32
|
const legacy = path_1.default.resolve(root, exports.LEGACY_CONNECTION);
|
|
@@ -36,6 +39,8 @@ function databasePaths(root, pkg = (0, project_1.readPackageJson)(root)) {
|
|
|
36
39
|
connection,
|
|
37
40
|
settings: conf.database && typeof conf.database === "object" ? conf.database : {},
|
|
38
41
|
migrations: path_1.default.resolve(root, typeof conf.migrations === "string" ? conf.migrations : exports.DEFAULT_MIGRATIONS),
|
|
42
|
+
seeders: path_1.default.resolve(root, typeof conf.seeders === "string" ? conf.seeders : exports.DEFAULT_SEEDERS),
|
|
43
|
+
factories: path_1.default.resolve(root, typeof conf.factories === "string" ? conf.factories : exports.DEFAULT_FACTORIES),
|
|
39
44
|
};
|
|
40
45
|
}
|
|
41
46
|
const MARKER = "__MEGH_MIGRATE__";
|
|
@@ -48,7 +53,7 @@ const MARKER = "__MEGH_MIGRATE__";
|
|
|
48
53
|
const WORKER = `
|
|
49
54
|
const fs = require("fs");
|
|
50
55
|
const path = require("path");
|
|
51
|
-
const [root, connection, settings, folder, action, args] = JSON.parse(process.argv[process.argv.length - 1]);
|
|
56
|
+
const [root, connection, settings, folder, seedersFolder, action, args] = JSON.parse(process.argv[process.argv.length - 1]);
|
|
52
57
|
const send = (value) => console.log(${JSON.stringify(MARKER)} + JSON.stringify(value));
|
|
53
58
|
(async () => {
|
|
54
59
|
let db;
|
|
@@ -71,6 +76,18 @@ const send = (value) => console.log(${JSON.stringify(MARKER)} + JSON.stringify(v
|
|
|
71
76
|
}
|
|
72
77
|
db = core.createDatabase(core.resolveDatabaseOptions(settings));
|
|
73
78
|
}
|
|
79
|
+
if (action === "seed") {
|
|
80
|
+
const [name, force] = args;
|
|
81
|
+
if (typeof core.Seeders !== "function") throw new Error("This @meghjs/core version has no seeders; upgrade it.");
|
|
82
|
+
if (process.env.NODE_ENV === "production" && !force) {
|
|
83
|
+
throw new Error("NODE_ENV is production. Pass --force to seed anyway.");
|
|
84
|
+
}
|
|
85
|
+
// Models in the seeders use the ORM connection.
|
|
86
|
+
if (core.Model && typeof core.Model.useConnection === "function") core.Model.useConnection(db);
|
|
87
|
+
const seeders = new core.Seeders(db, { folder: seedersFolder });
|
|
88
|
+
send({ ok: true, result: await seeders.run(name || undefined) });
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
74
91
|
const migrations = new core.Migrations(db, { folder });
|
|
75
92
|
send({ ok: true, result: await migrations[action](...args) });
|
|
76
93
|
} catch (e) {
|
|
@@ -105,6 +122,14 @@ function compiled(root) {
|
|
|
105
122
|
for (const [file, error] of migrationsCompiler.compileAll())
|
|
106
123
|
failures.set(file, error);
|
|
107
124
|
}
|
|
125
|
+
// Seeders likewise; a missing folder just has no seeders.
|
|
126
|
+
const seedersCompiler = inside(layout.srcDir, paths.seeders)
|
|
127
|
+
? app
|
|
128
|
+
: new compiler_1.SwcCompiler(paths.seeders, path_1.default.join(cacheDir, "seeders"), layout.compilerOptions);
|
|
129
|
+
if (seedersCompiler !== app && fs_1.default.existsSync(paths.seeders)) {
|
|
130
|
+
for (const [file, error] of seedersCompiler.compileAll())
|
|
131
|
+
failures.set(file, error);
|
|
132
|
+
}
|
|
108
133
|
if (failures.size) {
|
|
109
134
|
const list = [...failures].map(([f, e]) => `${rel(f)}: ${e.split("\n")[0]}`).join("\n ");
|
|
110
135
|
throw new errors_1.CliError(`Compilation failed:\n ${list}`);
|
|
@@ -117,14 +142,15 @@ function compiled(root) {
|
|
|
117
142
|
settings: paths.settings,
|
|
118
143
|
// outFileFor maps a file; map a placeholder inside the folder and take its directory.
|
|
119
144
|
migrations: path_1.default.dirname(migrationsCompiler.outFileFor(path_1.default.join(paths.migrations, "x.ts"))),
|
|
145
|
+
seeders: path_1.default.dirname(seedersCompiler.outFileFor(path_1.default.join(paths.seeders, "x.ts"))),
|
|
120
146
|
};
|
|
121
147
|
}
|
|
122
148
|
/** Run a migration action in a child process and return its result. */
|
|
123
149
|
function runMigrations(action, opts = {}) {
|
|
124
150
|
const root = (0, project_1.requireProjectRoot)(opts.cwd ?? process.cwd());
|
|
125
151
|
const files = compiled(root);
|
|
126
|
-
const args = action === "rollback" ? [opts.step ?? 1] : [];
|
|
127
|
-
const result = (0, child_process_1.spawnSync)(process.execPath, ["-e", WORKER, JSON.stringify([root, files.connection, files.settings, files.migrations, action, args])], {
|
|
152
|
+
const args = action === "rollback" ? [opts.step ?? 1] : action === "seed" ? [opts.seeder ?? null, opts.force === true] : [];
|
|
153
|
+
const result = (0, child_process_1.spawnSync)(process.execPath, ["-e", WORKER, JSON.stringify([root, files.connection, files.settings, files.migrations, files.seeders, action, args])], {
|
|
128
154
|
cwd: root,
|
|
129
155
|
encoding: "utf8",
|
|
130
156
|
env: { ...process.env, NODE_ENV: process.env.NODE_ENV ?? "development" },
|
|
@@ -142,7 +168,9 @@ function runMigrations(action, opts = {}) {
|
|
|
142
168
|
const out = JSON.parse(line.slice(MARKER.length));
|
|
143
169
|
if (!out.ok) {
|
|
144
170
|
const done = out.completed.length ? `\nCompleted before the failure:\n ${out.completed.join("\n ")}` : "";
|
|
145
|
-
|
|
171
|
+
// A seed runs in one transaction: a failure saves nothing.
|
|
172
|
+
const rolledBack = action === "seed" && /^Seeder /.test(out.error) ? "\nNothing was saved." : "";
|
|
173
|
+
throw new errors_1.CliError(`${out.error}${done}${rolledBack}`);
|
|
146
174
|
}
|
|
147
175
|
return out.result;
|
|
148
176
|
}
|
|
@@ -154,9 +182,17 @@ function list(names, verb, empty) {
|
|
|
154
182
|
for (const name of names)
|
|
155
183
|
log_1.log.success(`${verb} ${name}`);
|
|
156
184
|
}
|
|
185
|
+
/** Run the seeders: `seeder`, else the `database` seeder, else all in file order. */
|
|
186
|
+
function dbSeed(opts = {}) {
|
|
187
|
+
const names = runMigrations("seed", opts);
|
|
188
|
+
list(names, "Seeded:", "Nothing to seed: there are no seeders. Create one with: megh make:seeder <name>");
|
|
189
|
+
return names;
|
|
190
|
+
}
|
|
157
191
|
function migrate(opts = {}) {
|
|
158
192
|
const names = runMigrations("latest", opts);
|
|
159
193
|
list(names, "Migrated:", "Nothing to migrate.");
|
|
194
|
+
if (opts.seed)
|
|
195
|
+
dbSeed(opts);
|
|
160
196
|
return names;
|
|
161
197
|
}
|
|
162
198
|
function migrateRollback(opts = {}) {
|
|
@@ -173,6 +209,8 @@ function migrateRefresh(opts = {}) {
|
|
|
173
209
|
const result = runMigrations("refresh", opts);
|
|
174
210
|
list(result.down, "Rolled back:", "Nothing to roll back.");
|
|
175
211
|
list(result.up, "Migrated:", "Nothing to migrate.");
|
|
212
|
+
if (opts.seed)
|
|
213
|
+
dbSeed(opts);
|
|
176
214
|
return result;
|
|
177
215
|
}
|
|
178
216
|
function formatStatus(rows) {
|
package/dist/commands/new.js
CHANGED
|
@@ -47,6 +47,7 @@ const path_1 = __importDefault(require("path"));
|
|
|
47
47
|
const errors_1 = require("../errors");
|
|
48
48
|
const log_1 = require("../utils/log");
|
|
49
49
|
const names_1 = require("../utils/names");
|
|
50
|
+
const make_1 = require("../generators/make");
|
|
50
51
|
const stubs_1 = require("../utils/stubs");
|
|
51
52
|
const env_types_1 = require("../utils/env-types");
|
|
52
53
|
exports.PACKAGE_MANAGERS = ["npm", "yarn", "pnpm"];
|
|
@@ -86,6 +87,7 @@ const DEP_VERSIONS = {
|
|
|
86
87
|
"@vitest/coverage-v8": "^4.1.12",
|
|
87
88
|
"unplugin-swc": "^2.0.0",
|
|
88
89
|
"@swc/core": "^1.16.20",
|
|
90
|
+
"@faker-js/faker": "^10.6.0",
|
|
89
91
|
};
|
|
90
92
|
function isDirEmpty(dir) {
|
|
91
93
|
return fs_1.default.readdirSync(dir).length === 0;
|
|
@@ -195,6 +197,9 @@ function packageJson(name, features, minimal, database = DEFAULT_DATABASE) {
|
|
|
195
197
|
pickDev("@types/node", "typescript");
|
|
196
198
|
if (!minimal)
|
|
197
199
|
pickDev("@swc/core", "@vitest/coverage-v8", "unplugin-swc", "vitest");
|
|
200
|
+
// Model factories (megh make:factory) fill rows with Faker values.
|
|
201
|
+
if (features.includes("orm"))
|
|
202
|
+
pickDev("@faker-js/faker");
|
|
198
203
|
const scripts = {
|
|
199
204
|
"start:dev": "megh serve",
|
|
200
205
|
build: "megh build",
|
|
@@ -320,6 +325,7 @@ async function createApplication(name, opts = {}) {
|
|
|
320
325
|
if (database === "sqlite")
|
|
321
326
|
gitignore = gitignore.replace(/\n*$/, "\n") + "database.sqlite\n";
|
|
322
327
|
add("src/database/migrations/.gitkeep", "");
|
|
328
|
+
add("src/database/seeders/database.seeder.ts", (0, make_1.renderEntrySeeder)([]));
|
|
323
329
|
}
|
|
324
330
|
add(".gitignore", gitignore);
|
|
325
331
|
add(".env", env);
|
|
@@ -366,7 +372,7 @@ async function createApplication(name, opts = {}) {
|
|
|
366
372
|
if (database !== "sqlite")
|
|
367
373
|
console.log(log_1.c.dim(" # set DATABASE_URL in .env"));
|
|
368
374
|
console.log(log_1.c.cyan(" npx megh make:migration create_users_table"));
|
|
369
|
-
console.log(log_1.c.cyan(" npx megh migrate"));
|
|
375
|
+
console.log(log_1.c.cyan(" npx megh migrate --seed"));
|
|
370
376
|
}
|
|
371
377
|
console.log(log_1.c.cyan(` ${devCommand(pm)}`));
|
|
372
378
|
if (features.includes("openapi") || features.includes("scalar")) {
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Source of the files `scaffold:auth` and `scaffold:rbac` write. Each renderer
|
|
3
|
+
* gets the plan (strategy, role mode, permissions) and the columns the
|
|
4
|
+
* users table ends up with, so the code only uses columns that exist.
|
|
5
|
+
*/
|
|
6
|
+
export type AuthStrategy = "jwt" | "api-key" | "both";
|
|
7
|
+
export type RoleMode = "none" | "single" | "multiple";
|
|
8
|
+
export interface AuthPlan {
|
|
9
|
+
/** Undefined for `scaffold:rbac` (no sign-in endpoints). */
|
|
10
|
+
strategy?: AuthStrategy;
|
|
11
|
+
roles: RoleMode;
|
|
12
|
+
permissions: boolean;
|
|
13
|
+
/** Columns of the users table. */
|
|
14
|
+
userColumns: Set<string>;
|
|
15
|
+
}
|
|
16
|
+
/** The choices alone, before the users table is known. */
|
|
17
|
+
export type AuthChoice = Omit<AuthPlan, "userColumns">;
|
|
18
|
+
export declare const usesJwt: (p: AuthChoice) => boolean;
|
|
19
|
+
export declare const usesApiKeys: (p: AuthChoice) => boolean;
|
|
20
|
+
export declare const usesRoles: (p: AuthChoice) => boolean;
|
|
21
|
+
/** Import paths between the generated files, relative to each file. */
|
|
22
|
+
export interface Paths {
|
|
23
|
+
/** From `src/auth/` to `src/models/`, etc. */
|
|
24
|
+
rel(from: string, to: string): string;
|
|
25
|
+
}
|
|
26
|
+
/** The relation path `authenticate` eager loads: `roles.permissions`, `role`, … */
|
|
27
|
+
export declare function rolesRelation(plan: AuthPlan): string | undefined;
|
|
28
|
+
export declare function renderPassword(): string;
|
|
29
|
+
export declare function renderJwt(): string;
|
|
30
|
+
export declare function renderApiKeys(): string;
|
|
31
|
+
export declare function renderAuthentication(plan: AuthPlan, p: Paths): string;
|
|
32
|
+
export declare function renderAuthorization(plan: AuthPlan, p: Paths): string;
|
|
33
|
+
export declare function renderRbac(plan: AuthPlan, p: Paths): string;
|
|
34
|
+
export declare function renderRolesSeeder(plan: AuthPlan, p: Paths, seederFile: string): string;
|
|
35
|
+
export declare function renderAuthDto(plan: AuthPlan): string;
|
|
36
|
+
export declare function renderAuthService(plan: AuthPlan, p: Paths): string;
|
|
37
|
+
export declare function renderAuthController(plan: AuthPlan, p: Paths): string;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Source of the files `scaffold:auth` and `scaffold:rbac` write. Each renderer
|
|
4
|
+
* gets the plan (strategy, role mode, permissions) and the columns the
|
|
5
|
+
* users table ends up with, so the code only uses columns that exist.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.usesRoles = exports.usesApiKeys = exports.usesJwt = void 0;
|
|
9
|
+
exports.rolesRelation = rolesRelation;
|
|
10
|
+
exports.renderPassword = renderPassword;
|
|
11
|
+
exports.renderJwt = renderJwt;
|
|
12
|
+
exports.renderApiKeys = renderApiKeys;
|
|
13
|
+
exports.renderAuthentication = renderAuthentication;
|
|
14
|
+
exports.renderAuthorization = renderAuthorization;
|
|
15
|
+
exports.renderRbac = renderRbac;
|
|
16
|
+
exports.renderRolesSeeder = renderRolesSeeder;
|
|
17
|
+
exports.renderAuthDto = renderAuthDto;
|
|
18
|
+
exports.renderAuthService = renderAuthService;
|
|
19
|
+
exports.renderAuthController = renderAuthController;
|
|
20
|
+
const usesJwt = (p) => p.strategy === "jwt" || p.strategy === "both";
|
|
21
|
+
exports.usesJwt = usesJwt;
|
|
22
|
+
const usesApiKeys = (p) => p.strategy === "api-key" || p.strategy === "both";
|
|
23
|
+
exports.usesApiKeys = usesApiKeys;
|
|
24
|
+
const usesRoles = (p) => p.roles !== "none";
|
|
25
|
+
exports.usesRoles = usesRoles;
|
|
26
|
+
/** The relation path `authenticate` eager loads: `roles.permissions`, `role`, … */
|
|
27
|
+
function rolesRelation(plan) {
|
|
28
|
+
if (!(0, exports.usesRoles)(plan))
|
|
29
|
+
return undefined;
|
|
30
|
+
const base = plan.roles === "single" ? "role" : "roles";
|
|
31
|
+
return plan.permissions ? `${base}.permissions` : base;
|
|
32
|
+
}
|
|
33
|
+
const lines = (...parts) => parts.filter((p) => typeof p === "string").join("\n");
|
|
34
|
+
function renderPassword() {
|
|
35
|
+
return `import { randomBytes, scrypt, timingSafeEqual } from "crypto";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Password hashing with scrypt (built into Node.js). Hashes are stored as
|
|
39
|
+
* \`scrypt$<salt>$<hash>\` in hex.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
const KEY_LENGTH = 64;
|
|
43
|
+
|
|
44
|
+
function derive(password: string, salt: Buffer, length: number): Promise<Buffer> {
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
scrypt(password, salt, length, (err, key) => (err ? reject(err) : resolve(key)));
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function hashPassword(password: string): Promise<string> {
|
|
51
|
+
const salt = randomBytes(16);
|
|
52
|
+
const hash = await derive(password, salt, KEY_LENGTH);
|
|
53
|
+
return \`scrypt$\${salt.toString("hex")}$\${hash.toString("hex")}\`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether \`password\` matches a hash from hashPassword(), in constant time. */
|
|
57
|
+
export async function verifyPassword(password: string, stored: string | null | undefined): Promise<boolean> {
|
|
58
|
+
const [scheme, salt, hash] = (stored ?? "").split("$");
|
|
59
|
+
if (scheme !== "scrypt" || !salt || !hash) return false;
|
|
60
|
+
const expected = Buffer.from(hash, "hex");
|
|
61
|
+
const actual = await derive(password, Buffer.from(salt, "hex"), expected.length);
|
|
62
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
63
|
+
}
|
|
64
|
+
`;
|
|
65
|
+
}
|
|
66
|
+
function renderJwt() {
|
|
67
|
+
return `import { sign, verify, type SignOptions } from "jsonwebtoken";
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* HS256 access tokens signed with JWT_SECRET, valid for JWT_EXPIRES_IN
|
|
71
|
+
* (default "1d"). Both are read from .env.
|
|
72
|
+
*/
|
|
73
|
+
|
|
74
|
+
function secret(): string {
|
|
75
|
+
const value = process.env.JWT_SECRET;
|
|
76
|
+
if (!value || value.length < 32) {
|
|
77
|
+
throw new Error("Set JWT_SECRET in .env to a random string of at least 32 characters.");
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function tokenLifetime(): string {
|
|
83
|
+
return process.env.JWT_EXPIRES_IN || "1d";
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function signToken(userId: number): string {
|
|
87
|
+
return sign({}, secret(), {
|
|
88
|
+
algorithm: "HS256",
|
|
89
|
+
subject: String(userId),
|
|
90
|
+
expiresIn: tokenLifetime() as SignOptions["expiresIn"],
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The user id of a valid, unexpired token, or null. */
|
|
95
|
+
export function verifyToken(token: string): number | null {
|
|
96
|
+
const key = secret();
|
|
97
|
+
try {
|
|
98
|
+
const payload = verify(token, key, { algorithms: ["HS256"] });
|
|
99
|
+
const id = typeof payload === "object" ? Number(payload.sub) : NaN;
|
|
100
|
+
return Number.isInteger(id) ? id : null;
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
`;
|
|
106
|
+
}
|
|
107
|
+
function renderApiKeys() {
|
|
108
|
+
return `import { createHash, randomBytes } from "crypto";
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* API keys: \`mk_\` and 43 random characters. Only the SHA-256 hash is stored,
|
|
112
|
+
* so a key can be shown once, when it is created.
|
|
113
|
+
*/
|
|
114
|
+
|
|
115
|
+
/** Request header carrying the key (lower-case, as Node reads headers). */
|
|
116
|
+
export const API_KEY_HEADER = "x-api-key";
|
|
117
|
+
|
|
118
|
+
export function generateApiKey(): { key: string; prefix: string; hash: string } {
|
|
119
|
+
const key = \`mk_\${randomBytes(32).toString("base64url")}\`;
|
|
120
|
+
return { key, prefix: key.slice(0, 11), hash: hashApiKey(key) };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function hashApiKey(key: string): string {
|
|
124
|
+
return createHash("sha256").update(key).digest("hex");
|
|
125
|
+
}
|
|
126
|
+
`;
|
|
127
|
+
}
|
|
128
|
+
function renderAuthentication(plan, p) {
|
|
129
|
+
const file = "src/auth/authentication.ts";
|
|
130
|
+
const relation = rolesRelation(plan);
|
|
131
|
+
const query = relation ? `User.with(${JSON.stringify(relation)}).where("id", id).first()` : `User.where("id", id).first()`;
|
|
132
|
+
const active = plan.userColumns.has("is_active");
|
|
133
|
+
const how = [(0, exports.usesJwt)(plan) && "an `Authorization: Bearer <token>` header", (0, exports.usesApiKeys)(plan) && "an `X-API-Key` header"]
|
|
134
|
+
.filter(Boolean)
|
|
135
|
+
.join(" or ");
|
|
136
|
+
return lines(`import { AppService, MeghAuthentication, type IRequest, type Row } from "@meghjs/core";`, `import { User } from "${p.rel(file, "src/models/user.model.ts")}";`, (0, exports.usesApiKeys)(plan) && `import { ApiKey } from "${p.rel(file, "src/models/api-key.model.ts")}";`, (0, exports.usesApiKeys)(plan) && `import { API_KEY_HEADER, hashApiKey } from "./api-keys";`, (0, exports.usesJwt)(plan) && `import { verifyToken } from "./jwt";`, ``, `/**`, ` * Who is calling: ${how}. The user it returns becomes \`request.user\``, ` * (\`@AuthUser()\` in controllers)${relation ? `, with \`${relation}\` loaded` : ""}. Registered with`, ` * app.useAuthentication(AppAuthentication).`, ` */`, `@AppService`, `export class AppAuthentication extends MeghAuthentication<Row<User>> {`, ` async authenticate(request: IRequest): Promise<Row<User> | null> {`, (0, exports.usesJwt)(plan) &&
|
|
137
|
+
lines(` const header = request.headers.authorization;`, ` if (typeof header === "string" && header.startsWith("Bearer ")) {`, ` const id = verifyToken(header.slice(7).trim());`, ` return id === null ? null : this.findUser(id);`, ` }`), (0, exports.usesApiKeys)(plan) &&
|
|
138
|
+
lines(``, ` const key = request.headers[API_KEY_HEADER];`, ` if (typeof key === "string" && key !== "") {`, ` const record = await ApiKey.findBy("key_hash", hashApiKey(key));`, ` if (!record || record.revoked_at || (record.expires_at && record.expires_at <= new Date())) return null;`, ` record.last_used_at = new Date();`, ` await record.save();`, ` return this.findUser(record.user_id);`, ` }`), ` return null;`, ` }`, ``, ` private async findUser(id: number): Promise<Row<User> | null> {`, ` const user = await ${query};`, active ? ` return user && user.is_active !== false ? user : null;` : ` return user ?? null;`, ` }`, `}`, ``);
|
|
139
|
+
}
|
|
140
|
+
function renderAuthorization(plan, p) {
|
|
141
|
+
const file = "src/auth/authorization.ts";
|
|
142
|
+
const roles = (0, exports.usesRoles)(plan);
|
|
143
|
+
return lines(`import { CanAuthorize, UnauthorizedException, type IRequest, type Row } from "@meghjs/core";`, `import type { User } from "${p.rel(file, "src/models/user.model.ts")}";`, roles && `import { ${plan.permissions ? "hasPermission, hasRole" : "hasRole"} } from "./rbac";`, ``, `export type AuthorizeOptions = {`, roles && ` /** Any of these roles (slug or name). */`, roles && ` roles?: string[];`, plan.permissions && ` /** Any of these permissions. */`, plan.permissions && ` permissions?: string[];`, `};`, ``, `/**`, ` * \`@Authorized()\`: the caller must be signed in (401 otherwise).`, roles && ` * \`@Authorized({ roles: ["admin"] })\`: and have one of these roles (403 otherwise).`, plan.permissions && ` * \`@Authorized({ permissions: ["users.manage"] })\`: and one of these permissions.`, ` * Registered with app.useAuthorization(AppAuthorization).`, ` */`, `@CanAuthorize`, `export class AppAuthorization {`, ` async authorize(request: IRequest, options: AuthorizeOptions = {}): Promise<boolean> {`, ` const user = request.user as Row<User> | undefined;`, ` if (!user) throw new UnauthorizedException("Sign in to continue.");`, roles && ` if (options.roles?.length && !(await hasRole(user, options.roles))) return false;`, plan.permissions &&
|
|
144
|
+
` if (options.permissions?.length && !(await hasPermission(user, options.permissions))) return false;`, roles ? ` return true;` : lines(` void options;`, ` return true;`), ` }`, `}`, ``);
|
|
145
|
+
}
|
|
146
|
+
function renderRbac(plan, p) {
|
|
147
|
+
const file = "src/auth/rbac.ts";
|
|
148
|
+
const single = plan.roles === "single";
|
|
149
|
+
return lines(`import type { Row } from "@meghjs/core";`, `import { Role } from "${p.rel(file, "src/models/role.model.ts")}";`, plan.permissions && `import type { Permission } from "${p.rel(file, "src/models/permission.model.ts")}";`, `import type { User } from "${p.rel(file, "src/models/user.model.ts")}";`, ``, `/**`, single
|
|
150
|
+
? ` * Role checks. Each user has at most one role (users.role_id).`
|
|
151
|
+
: ` * Role checks. A user has any number of roles (the user_roles table).`, plan.permissions && ` * Roles grant permissions (the role_permissions table).`, ` * Relations loaded by AppAuthentication are used as they are; otherwise they are queried.`, ` */`, ``, `/** The user's roles. */`, `export async function rolesOf(user: Row<User>): Promise<Row<Role>[]> {`, single
|
|
152
|
+
? lines(` const loaded: unknown = (user as { role?: unknown }).role;`, ` if (loaded && typeof loaded === "object") return [loaded as Row<Role>];`, ` if (user.role_id == null) return [];`, ` const role = await Role.find(user.role_id);`, ` return role ? [role] : [];`)
|
|
153
|
+
: lines(` const loaded: unknown = (user as { roles?: unknown }).roles;`, ` if (Array.isArray(loaded)) return loaded as Row<Role>[];`, ` return user.related("roles").get();`), `}`, ``, `/** Whether the user has any of these roles (slug or name). */`, `export async function hasRole(user: Row<User>, roles: string[]): Promise<boolean> {`, ` return (await rolesOf(user)).some((role) => roles.includes(role.slug) || roles.includes(role.name));`, `}`, plan.permissions &&
|
|
154
|
+
lines(``, `/** Names of the permissions the user's roles grant. */`, `export async function permissionsOf(user: Row<User>): Promise<string[]> {`, ` const names = new Set<string>();`, ` for (const role of await rolesOf(user)) {`, ` const loaded: unknown = (role as { permissions?: unknown }).permissions;`, ` const permissions = Array.isArray(loaded)`, ` ? (loaded as Row<Permission>[])`, ` : await role.related("permissions").get();`, ` for (const permission of permissions) names.add(permission.name);`, ` }`, ` return [...names];`, `}`, ``, `/** Whether the user's roles grant any of these permissions. */`, `export async function hasPermission(user: Row<User>, permissions: string[]): Promise<boolean> {`, ` const granted = await permissionsOf(user);`, ` return permissions.some((name) => granted.includes(name));`, `}`), ``, single
|
|
155
|
+
? `/** Give the user the role with this slug (replacing its role). False if there is no such role. */`
|
|
156
|
+
: `/** Give the user the role with this slug. False if there is no such role. */`, `export async function assignRole(user: Row<User>, slug: string): Promise<boolean> {`, ` const role = await Role.findBy("slug", slug);`, ` if (!role) return false;`, single
|
|
157
|
+
? lines(` user.role_id = role.id!;`, ` await user.save();`)
|
|
158
|
+
: lines(` const current = await user.related("roles").get();`, ` if (!current.some((r) => r.id === role.id)) await user.related("roles").attach(role);`), ` return true;`, `}`, ``);
|
|
159
|
+
}
|
|
160
|
+
function renderRolesSeeder(plan, p, seederFile) {
|
|
161
|
+
return lines(`import { defineSeeder } from "@meghjs/core";`, plan.permissions && `import { Permission } from "${p.rel(seederFile, "src/models/permission.model.ts")}";`, `import { Role } from "${p.rel(seederFile, "src/models/role.model.ts")}";`, ``, `/** The roles (and permissions) the app starts with. Safe to run again. */`, `const ROLES = [`, ` { name: "Admin", slug: "admin", description: "Full access" },`, ` { name: "User", slug: "user", description: "A signed-up user" },`, `];`, plan.permissions &&
|
|
162
|
+
lines(``, `/** Permissions per role slug. Check them with @Authorized({ permissions: [...] }). */`, `const PERMISSIONS: Record<string, string[]> = {`, ` admin: ["users.view", "users.manage", "roles.manage"],`, ` user: [],`, `};`), ``, `export default defineSeeder({`, ` async run() {`, ` for (const data of ROLES) {`, plan.permissions
|
|
163
|
+
? ` const role = (await Role.findBy("slug", data.slug)) ?? (await Role.create(data));`
|
|
164
|
+
: lines(` if (await Role.findBy("slug", data.slug)) continue;`, ` await Role.create(data);`), plan.permissions &&
|
|
165
|
+
lines(` const granted = await role.related("permissions").get();`, ` for (const name of PERMISSIONS[data.slug] ?? []) {`, ` const permission =`, ` (await Permission.findBy("name", name)) ??`, ` (await Permission.create({ name, group: name.split(".")[0], description: null }));`, ` if (!granted.some((p) => p.id === permission.id)) await role.related("permissions").attach(permission);`, ` }`), ` }`, ` },`, `});`, ``);
|
|
166
|
+
}
|
|
167
|
+
function renderAuthDto(plan) {
|
|
168
|
+
const api = (0, exports.usesApiKeys)(plan);
|
|
169
|
+
const name = plan.userColumns.has("name");
|
|
170
|
+
const validators = ["IsEmail", "IsString", "MaxLength", "MinLength", ...(api ? ["IsDate", "IsOptional"] : [])].sort();
|
|
171
|
+
return lines(api && `import { Type } from "class-transformer";`, `import { ${validators.join(", ")} } from "class-validator";`, ``, `/** \`POST /auth/register\` */`, `export class RegisterDto {`, name && lines(` @IsString()`, ` @MaxLength(255)`, ` name!: string;`, ``), ` @IsEmail()`, ` @MaxLength(255)`, ` email!: string;`, ``, ` @IsString()`, ` @MinLength(8)`, ` @MaxLength(128)`, ` password!: string;`, `}`, ``, `/** \`POST /auth/login\` */`, `export class LoginDto {`, ` @IsEmail()`, ` email!: string;`, ``, ` @IsString()`, ` password!: string;`, `}`, api &&
|
|
172
|
+
lines(``, `/** \`POST /auth/api-keys\` */`, `export class CreateApiKeyDto {`, ` @IsString()`, ` @MaxLength(100)`, ` name!: string;`, ``, ` @IsOptional()`, ` @Type(() => Date)`, ` @IsDate()`, ` expires_at?: Date;`, `}`), ``);
|
|
173
|
+
}
|
|
174
|
+
function renderAuthService(plan, p) {
|
|
175
|
+
const file = "src/services/auth.service.ts";
|
|
176
|
+
const jwt = (0, exports.usesJwt)(plan);
|
|
177
|
+
const api = (0, exports.usesApiKeys)(plan);
|
|
178
|
+
const cols = plan.userColumns;
|
|
179
|
+
const coreImports = ["AppService", "BadRequestException", "UnauthorizedException", ...(api ? ["NotFoundException"] : [])].sort();
|
|
180
|
+
const dtos = ["LoginDto", "RegisterDto", ...(api ? ["CreateApiKeyDto"] : [])].sort();
|
|
181
|
+
const createFields = [cols.has("name") && "name: input.name", "email: input.email", "password: await hashPassword(input.password)"]
|
|
182
|
+
.filter(Boolean)
|
|
183
|
+
.join(", ");
|
|
184
|
+
return lines(`import { ${coreImports.join(", ")}, type Row } from "@meghjs/core";`, `import { User } from "${p.rel(file, "src/models/user.model.ts")}";`, api && `import { ApiKey } from "${p.rel(file, "src/models/api-key.model.ts")}";`, `import { ${dtos.join(", ")} } from "${p.rel(file, "src/dtos/auth.dto.ts")}";`, `import { hashPassword, verifyPassword } from "${p.rel(file, "src/auth/password.ts")}";`, jwt && `import { signToken, tokenLifetime } from "${p.rel(file, "src/auth/jwt.ts")}";`, api && `import { generateApiKey } from "${p.rel(file, "src/auth/api-keys.ts")}";`, (0, exports.usesRoles)(plan) && `import { assignRole } from "${p.rel(file, "src/auth/rbac.ts")}";`, ``, (0, exports.usesRoles)(plan) && `/** Role given to users who register (created by the roles seeder). */`, (0, exports.usesRoles)(plan) && `const DEFAULT_ROLE = "user";`, (0, exports.usesRoles)(plan) && ``, `@AppService`, `export class AuthService {`, ` async register(input: RegisterDto) {`, ` if (await User.findBy("email", input.email)) {`, ` throw new BadRequestException("That email is already registered.");`, ` }`, ` const user = await User.create({ ${createFields} });`, (0, exports.usesRoles)(plan) && ` await assignRole(user, DEFAULT_ROLE);`, ` return this.issue(user);`, ` }`, ``, ` async login(input: LoginDto) {`, ` const user = await User.findBy("email", input.email);`, ` const valid = !!user && (await verifyPassword(input.password, user.password));`, cols.has("is_active")
|
|
185
|
+
? ` if (!user || !valid || user.is_active === false) throw new UnauthorizedException("Invalid email or password.");`
|
|
186
|
+
: ` if (!user || !valid) throw new UnauthorizedException("Invalid email or password.");`, cols.has("last_login_at") && lines(` user.last_login_at = new Date();`, ` await user.save();`), ` return this.issue(user);`, ` }`, ``, jwt
|
|
187
|
+
? lines(` /** A signed-in response: an access token for the Authorization header. */`, ` private async issue(user: Row<User>) {`, ` return { token_type: "Bearer", access_token: signToken(user.id!), expires_in: tokenLifetime(), user };`, ` }`)
|
|
188
|
+
: lines(` /** A signed-in response: a new API key for the X-API-Key header. */`, ` private async issue(user: Row<User>) {`, ` const { key } = await this.createApiKey(user, { name: "login" });`, ` return { api_key: key, user };`, ` }`), api &&
|
|
189
|
+
lines(``, ` listApiKeys(user: Row<User>) {`, ` return ApiKey.where("user_id", user.id!).whereNull("revoked_at").orderBy("id", "desc").get();`, ` }`, ``, ` /** A new key. The key itself is only returned here; the database keeps its hash. */`, ` async createApiKey(user: Row<User>, input: CreateApiKeyDto) {`, ` const { key, prefix, hash } = generateApiKey();`, ` const record = await ApiKey.create({`, ` user_id: user.id!,`, ` name: input.name,`, ` prefix,`, ` key_hash: hash,`, ` expires_at: input.expires_at ?? null,`, ` });`, ` return { ...record.toJSON(), key };`, ` }`, ``, ` async revokeApiKey(user: Row<User>, id: number) {`, ` const record = await ApiKey.where("user_id", user.id!).where("id", id).first();`, ` if (!record || record.revoked_at) throw new NotFoundException("API key not found.");`, ` record.revoked_at = new Date();`, ` await record.save();`, ` return { message: "API key revoked." };`, ` }`), `}`, ``);
|
|
190
|
+
}
|
|
191
|
+
function renderAuthController(plan, p) {
|
|
192
|
+
const file = "src/controllers/auth.controller.ts";
|
|
193
|
+
const api = (0, exports.usesApiKeys)(plan);
|
|
194
|
+
const core = ["ApiController", "AuthUser", "Authorized", "Body", "Get", "Post", ...(api ? ["Delete", "Param"] : [])].sort();
|
|
195
|
+
const dtos = ["LoginDto", "RegisterDto", ...(api ? ["CreateApiKeyDto"] : [])].sort();
|
|
196
|
+
return lines(`import { ${core.join(", ")}, type Row } from "@meghjs/core";`, `import { ${dtos.join(", ")} } from "${p.rel(file, "src/dtos/auth.dto.ts")}";`, `import type { User } from "${p.rel(file, "src/models/user.model.ts")}";`, `import { AuthService } from "${p.rel(file, "src/services/auth.service.ts")}";`, ``, `@ApiController("/auth")`, `export class AuthController {`, ` constructor(private readonly authService: AuthService) {}`, ``, ` @Post("/register")`, ` register(@Body() body: RegisterDto) {`, ` return this.authService.register(body);`, ` }`, ``, ` @Post("/login")`, ` login(@Body() body: LoginDto) {`, ` return this.authService.login(body);`, ` }`, ``, ` @Authorized()`, ` @Get("/me")`, ` me(@AuthUser() user: Row<User>) {`, ` return user;`, ` }`, api &&
|
|
197
|
+
lines(``, ` @Authorized()`, ` @Get("/api-keys")`, ` apiKeys(@AuthUser() user: Row<User>) {`, ` return this.authService.listApiKeys(user);`, ` }`, ``, ` @Authorized()`, ` @Post("/api-keys")`, ` createApiKey(@AuthUser() user: Row<User>, @Body() body: CreateApiKeyDto) {`, ` return this.authService.createApiKey(user, body);`, ` }`, ``, ` @Authorized()`, ` @Delete("/api-keys/:id")`, ` revokeApiKey(@AuthUser() user: Row<User>, @Param("id") id: number) {`, ` return this.authService.revokeApiKey(user, Number(id));`, ` }`), `}`, ``);
|
|
198
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type AuthPlan, type AuthStrategy, type RoleMode } from "./auth-files";
|
|
2
|
+
export type { AuthStrategy, RoleMode } from "./auth-files";
|
|
3
|
+
export declare const AUTH_STRATEGIES: readonly AuthStrategy[];
|
|
4
|
+
export declare const ROLE_MODES: readonly RoleMode[];
|
|
5
|
+
export type AuthOptions = {
|
|
6
|
+
cwd?: string;
|
|
7
|
+
/** scaffold:auth only. Prompted for when missing in a terminal; default `jwt`. */
|
|
8
|
+
strategy?: string;
|
|
9
|
+
/** Prompted for when missing in a terminal; default `none` for scaffold:auth, `multiple` for scaffold:rbac. */
|
|
10
|
+
roles?: string;
|
|
11
|
+
/** Roles grant permissions. Prompted for when missing in a terminal. */
|
|
12
|
+
permissions?: boolean;
|
|
13
|
+
/** Overwrite generated auth files that already exist. */
|
|
14
|
+
force?: boolean;
|
|
15
|
+
/** Prompt when run in a terminal. */
|
|
16
|
+
interactive?: boolean;
|
|
17
|
+
/** Clock for migration timestamps (tests). */
|
|
18
|
+
now?: Date;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* `scaffold:auth`: sign-up and sign-in with JWTs, API keys or both, and
|
|
22
|
+
* optionally roles (one or many per user) with permissions.
|
|
23
|
+
*/
|
|
24
|
+
export declare function scaffoldAuth(opts?: AuthOptions): Promise<AuthPlan>;
|
|
25
|
+
/** `scaffold:rbac`: roles (and permissions) for an app's users, without sign-in. */
|
|
26
|
+
export declare function scaffoldRbac(opts?: AuthOptions): Promise<AuthPlan>;
|