@apso/cli 0.48.0 → 0.49.0
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/README.md +28 -1
- package/dist/commands/dev.d.ts +2 -0
- package/dist/commands/dev.js +20 -3
- package/dist/commands/generate.js +49 -13
- package/dist/commands/mcp/serve.js +24 -41
- package/dist/commands/schema/diff.js +3 -4
- package/dist/commands/schema/pull.js +13 -11
- package/dist/commands/schema/push.js +6 -5
- package/dist/commands/schema/validate.d.ts +10 -0
- package/dist/commands/schema/validate.js +54 -0
- package/dist/commands/test/access.d.ts +11 -0
- package/dist/commands/test/access.js +65 -0
- package/dist/lib/access/cases.d.ts +120 -0
- package/dist/lib/access/cases.js +1163 -0
- package/dist/lib/access/index.d.ts +4 -0
- package/dist/lib/access/index.js +7 -0
- package/dist/lib/access/report.d.ts +75 -0
- package/dist/lib/access/report.js +118 -0
- package/dist/lib/access/rules.json +207 -0
- package/dist/lib/access/run.d.ts +38 -0
- package/dist/lib/access/run.js +111 -0
- package/dist/lib/access/tokens.d.ts +46 -0
- package/dist/lib/access/tokens.js +139 -0
- package/dist/lib/api/services.d.ts +10 -7
- package/dist/lib/api/services.js +19 -32
- package/dist/lib/apsorc-parser.d.ts +1 -1
- package/dist/lib/apsorc-parser.js +2 -0
- package/dist/lib/deploy/server-push.js +3 -1
- package/dist/lib/generators/go.d.ts +13 -1
- package/dist/lib/generators/go.js +144 -33
- package/dist/lib/generators/python.d.ts +3 -3
- package/dist/lib/generators/python.js +48 -24
- package/dist/lib/generators/typescript.d.ts +3 -5
- package/dist/lib/generators/typescript.js +78 -64
- package/dist/lib/guards.d.ts +111 -13
- package/dist/lib/guards.js +287 -23
- package/dist/lib/templates/go/handlers/handler.eta +8 -8
- package/dist/lib/templates/go/handlers/scope.eta +3 -2
- package/dist/lib/templates/go/index-module.eta +8 -5
- package/dist/lib/templates/go/mcp.eta +307 -0
- package/dist/lib/templates/go/middleware/auth.eta +587 -166
- package/dist/lib/templates/go/middleware/permission.eta +174 -0
- package/dist/lib/templates/go/services/service.eta +37 -16
- package/dist/lib/templates/go/utils/query.eta +37 -2
- package/dist/lib/templates/guards/guards.module.eta +37 -29
- package/dist/lib/templates/guards/index.eta +4 -0
- package/dist/lib/templates/guards/jwt-auth.guard.eta +114 -29
- package/dist/lib/templates/guards/key.guard.eta +280 -0
- package/dist/lib/templates/guards/permission.guard.eta +168 -0
- package/dist/lib/templates/guards/relations.interceptor.eta +124 -0
- package/dist/lib/templates/guards/scope.guard.eta +189 -41
- package/dist/lib/templates/python/auth.eta +354 -95
- package/dist/lib/templates/python/index-module.eta +7 -7
- package/dist/lib/templates/python/mcp.eta +284 -0
- package/dist/lib/templates/python/models/model.eta +6 -5
- package/dist/lib/templates/python/permissions.eta +121 -0
- package/dist/lib/templates/python/routers/router.eta +39 -1
- package/dist/lib/templates/python/schemas/schema.eta +18 -5
- package/dist/lib/templates/python/services/service.eta +38 -15
- package/dist/lib/templates/python/utils/query.eta +52 -25
- package/dist/lib/templates/rest/controller-rest.eta +43 -23
- package/dist/lib/templates/rest/index-module-rest.eta +0 -4
- package/dist/lib/templates/rest/service-rest.eta +3 -44
- package/dist/lib/types/auth.d.ts +84 -80
- package/dist/lib/types/auth.js +77 -60
- package/dist/lib/types/entity.d.ts +17 -9
- package/dist/lib/types/entity.js +3 -0
- package/dist/lib/types/index.d.ts +2 -2
- package/dist/lib/types/index.js +6 -5
- package/dist/lib/utils/crud-deps.d.ts +77 -6
- package/dist/lib/utils/crud-deps.js +197 -14
- package/dist/lib/utils/schema-convert.d.ts +20 -43
- package/dist/lib/utils/schema-convert.js +28 -78
- package/dist/lib/utils/template.d.ts +11 -0
- package/dist/lib/utils/template.js +36 -1
- package/dist/lib/verify/index.d.ts +6 -1
- package/dist/lib/verify/index.js +30 -13
- package/npm-shrinkwrap.json +2 -2
- package/oclif.manifest.json +36 -1
- package/package.json +1 -1
- package/dist/lib/templates/guards/api-key-auth.guard.eta +0 -145
- package/dist/lib/templates/guards/auth.guard.eta +0 -233
package/dist/lib/verify/index.js
CHANGED
|
@@ -6,9 +6,10 @@
|
|
|
6
6
|
* the CLI in a WebContainer) share these steps.
|
|
7
7
|
*/
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.report = exports.cliBinPath = exports.readDotEnv = exports.smokeTest = exports.entityRoute = exports.verifyMigration = exports.supportsPglite = exports.unaccepted = exports.dataLoss = exports.generateMigration = exports.buildBaseline = exports.pgliteEnv = exports.run = void 0;
|
|
9
|
+
exports.report = exports.cliBinPath = exports.readDotEnv = exports.smokeTest = exports.entityRoute = exports.SMOKE_KEY = exports.verifyMigration = exports.supportsPglite = exports.unaccepted = exports.dataLoss = exports.generateMigration = exports.buildBaseline = exports.pgliteEnv = exports.run = void 0;
|
|
10
10
|
const tslib_1 = require("tslib");
|
|
11
11
|
const child_process_1 = require("child_process");
|
|
12
|
+
const crypto_1 = require("crypto");
|
|
12
13
|
const fs = tslib_1.__importStar(require("fs"));
|
|
13
14
|
const http = tslib_1.__importStar(require("http"));
|
|
14
15
|
const net = tslib_1.__importStar(require("net"));
|
|
@@ -439,14 +440,18 @@ const freePort = () => new Promise((resolve, reject) => {
|
|
|
439
440
|
});
|
|
440
441
|
s.on("error", reject);
|
|
441
442
|
});
|
|
443
|
+
// The smoke test's own API key: the service is started with it and every
|
|
444
|
+
// request sends it, so the checks pass whatever the project's .env holds.
|
|
445
|
+
exports.SMOKE_KEY = (0, crypto_1.randomBytes)(16).toString("hex");
|
|
442
446
|
const request = (method, url, body) => new Promise((resolve) => {
|
|
443
447
|
const data = body === undefined ? undefined : JSON.stringify(body);
|
|
444
|
-
const headers =
|
|
445
|
-
|
|
448
|
+
const headers = {
|
|
449
|
+
"x-api-key": exports.SMOKE_KEY,
|
|
450
|
+
...(data && {
|
|
446
451
|
"content-type": "application/json",
|
|
447
452
|
"content-length": Buffer.byteLength(data),
|
|
448
|
-
}
|
|
449
|
-
|
|
453
|
+
}),
|
|
454
|
+
};
|
|
450
455
|
http
|
|
451
456
|
.request(url, { method, headers, timeout: 15000 }, (res) => {
|
|
452
457
|
let text = "";
|
|
@@ -497,7 +502,8 @@ async function checkEndpoints(base, language, entities, relationships, done) {
|
|
|
497
502
|
for (const { name } of entities) {
|
|
498
503
|
done({
|
|
499
504
|
name: `GET ${route(name)}`,
|
|
500
|
-
|
|
505
|
+
// 206: a TypeScript service answers a full default page that way.
|
|
506
|
+
...expectStatus(await get(base + route(name)), 200, 206),
|
|
501
507
|
});
|
|
502
508
|
}
|
|
503
509
|
const plan = (0, crud_plan_1.planCrud)(entities, relationships);
|
|
@@ -590,9 +596,9 @@ async function serve(server, port, timeoutMs, done, check) {
|
|
|
590
596
|
* PGlite database synced to their entities; Python and Go services run on the
|
|
591
597
|
* database in DATABASE_URL.
|
|
592
598
|
*/
|
|
593
|
-
async function smokeTest(projectDir, entities, relationships = {}, { skipBuild = false, timeoutMs = 60000, language = "typescript", } = {}) {
|
|
599
|
+
async function smokeTest(projectDir, entities, relationships = {}, { skipBuild = false, timeoutMs = 60000, language = "typescript", env: extraEnv = {}, check = (base, done) => checkEndpoints(base, language, entities, relationships, done), } = {}) {
|
|
594
600
|
if (language !== "typescript")
|
|
595
|
-
return smokeTestOnDatabaseUrl(projectDir,
|
|
601
|
+
return smokeTestOnDatabaseUrl(projectDir, language, timeoutMs, extraEnv, check);
|
|
596
602
|
if (!supportsPglite(projectDir))
|
|
597
603
|
return NO_PGLITE;
|
|
598
604
|
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "apso-pglite-"));
|
|
@@ -609,9 +615,15 @@ async function smokeTest(projectDir, entities, relationships = {}, { skipBuild =
|
|
|
609
615
|
const port = await freePort();
|
|
610
616
|
const server = (0, child_process_1.spawn)(process.execPath, ["dist/main"], {
|
|
611
617
|
cwd: projectDir,
|
|
612
|
-
env: {
|
|
618
|
+
env: {
|
|
619
|
+
...process.env,
|
|
620
|
+
...(0, exports.pgliteEnv)(dataDir),
|
|
621
|
+
APP_PORT: String(port),
|
|
622
|
+
APSO_API_KEY: exports.SMOKE_KEY,
|
|
623
|
+
...extraEnv,
|
|
624
|
+
},
|
|
613
625
|
});
|
|
614
|
-
await serve(server, port, timeoutMs, done, (base) =>
|
|
626
|
+
await serve(server, port, timeoutMs, done, (base) => check(base, done));
|
|
615
627
|
return { ok: steps.every((s) => s.ok), steps };
|
|
616
628
|
}
|
|
617
629
|
finally {
|
|
@@ -656,7 +668,7 @@ const skipped = (output) => ({
|
|
|
656
668
|
* one in DATABASE_URL (environment first, then .env), as configured: the
|
|
657
669
|
* smoke test never creates tables, and it skips when no database answers.
|
|
658
670
|
*/
|
|
659
|
-
async function smokeTestOnDatabaseUrl(projectDir,
|
|
671
|
+
async function smokeTestOnDatabaseUrl(projectDir, language, timeoutMs, extraEnv, check) {
|
|
660
672
|
const env = { ...readDotEnv(projectDir), ...process.env };
|
|
661
673
|
if (!env.DATABASE_URL)
|
|
662
674
|
return skipped("No DATABASE_URL in the environment or .env, so there is no database to run the service against. Set it and rerun.");
|
|
@@ -681,7 +693,12 @@ async function smokeTestOnDatabaseUrl(projectDir, entities, relationships, langu
|
|
|
681
693
|
return s.ok;
|
|
682
694
|
};
|
|
683
695
|
const port = await freePort();
|
|
684
|
-
const serverEnv = {
|
|
696
|
+
const serverEnv = {
|
|
697
|
+
...env,
|
|
698
|
+
PORT: String(port),
|
|
699
|
+
APSO_API_KEY: exports.SMOKE_KEY,
|
|
700
|
+
...extraEnv,
|
|
701
|
+
};
|
|
685
702
|
const binDir = fs.mkdtempSync(path.join(os.tmpdir(), "apso-smoke-"));
|
|
686
703
|
try {
|
|
687
704
|
let server;
|
|
@@ -705,7 +722,7 @@ async function smokeTestOnDatabaseUrl(projectDir, entities, relationships, langu
|
|
|
705
722
|
String(port),
|
|
706
723
|
], { cwd: projectDir, env: serverEnv });
|
|
707
724
|
}
|
|
708
|
-
await serve(server, port, timeoutMs, done, (base) =>
|
|
725
|
+
await serve(server, port, timeoutMs, done, (base) => check(base, done));
|
|
709
726
|
return { ok: steps.every((s) => s.ok), steps };
|
|
710
727
|
}
|
|
711
728
|
finally {
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@apso/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.49.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@apso/cli",
|
|
9
|
-
"version": "0.
|
|
9
|
+
"version": "0.49.0",
|
|
10
10
|
"license": "Apache-2.0",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@apso/schema-tools": "^0.2.2",
|
package/oclif.manifest.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "0.
|
|
2
|
+
"version": "0.49.0",
|
|
3
3
|
"commands": {
|
|
4
4
|
"config": {
|
|
5
5
|
"id": "config",
|
|
@@ -1318,6 +1318,41 @@
|
|
|
1318
1318
|
"flags": {},
|
|
1319
1319
|
"args": {}
|
|
1320
1320
|
},
|
|
1321
|
+
"test:access": {
|
|
1322
|
+
"id": "test:access",
|
|
1323
|
+
"description": "Start the service and prove the access rules on this project's own schema: who may call, tenant scope (scopeBy), permissions, API keys and MCP tools. Test sign-ins are signed by a local issuer with the claim names from the auth block; the service is pointed at it through AUTH_JWT_ISSUER and AUTH_JWKS_URI for this run only. Rows are created for two test tenants and deleted afterwards. TypeScript services run on a local PGlite database; Python and Go services run on the database in DATABASE_URL. Prints pass or fail per rule and exits 1 on any failure",
|
|
1324
|
+
"strict": true,
|
|
1325
|
+
"pluginName": "@apso/cli",
|
|
1326
|
+
"pluginAlias": "@apso/cli",
|
|
1327
|
+
"pluginType": "core",
|
|
1328
|
+
"aliases": [],
|
|
1329
|
+
"hiddenAliases": [],
|
|
1330
|
+
"examples": [
|
|
1331
|
+
"$ apso test access",
|
|
1332
|
+
"$ apso test access --json"
|
|
1333
|
+
],
|
|
1334
|
+
"flags": {
|
|
1335
|
+
"skip-build": {
|
|
1336
|
+
"name": "skip-build",
|
|
1337
|
+
"type": "boolean",
|
|
1338
|
+
"description": "Use the existing dist/ build instead of building first (TypeScript)",
|
|
1339
|
+
"allowNo": false
|
|
1340
|
+
},
|
|
1341
|
+
"verbose": {
|
|
1342
|
+
"name": "verbose",
|
|
1343
|
+
"type": "boolean",
|
|
1344
|
+
"description": "Print every case, not only the failures",
|
|
1345
|
+
"allowNo": false
|
|
1346
|
+
},
|
|
1347
|
+
"json": {
|
|
1348
|
+
"name": "json",
|
|
1349
|
+
"type": "boolean",
|
|
1350
|
+
"description": "Print the result as JSON",
|
|
1351
|
+
"allowNo": false
|
|
1352
|
+
}
|
|
1353
|
+
},
|
|
1354
|
+
"args": {}
|
|
1355
|
+
},
|
|
1321
1356
|
"test:smoke": {
|
|
1322
1357
|
"id": "test:smoke",
|
|
1323
1358
|
"description": "Start the service and call /health, every entity's list endpoint, and a create/read/delete of one row per entity. TypeScript services run on a local PGlite database; Python and Go services run on the database in DATABASE_URL (rows are created and deleted there, tables are not created) and the check is skipped when none answers",
|
package/package.json
CHANGED
|
@@ -1,145 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* AuthGuard - application API keys stored as SHA-256 hashes on <%= it.apiKey.apiKeyEntity %>
|
|
3
|
-
*
|
|
4
|
-
* Auto-generated by Apso CLI from .apsorc auth configuration
|
|
5
|
-
*
|
|
6
|
-
* This guard:
|
|
7
|
-
* - Reads the key from the <%= it.apiKey.apiKeyHeader %> header
|
|
8
|
-
* - Looks up the <%= it.apiKey.apiKeyEntity %> row whose <%= it.apiKey.keyField %> is the key's hex SHA-256
|
|
9
|
-
<% if (it.apiKey.hasStatus) { %>
|
|
10
|
-
* - Rejects keys whose status is not "active"
|
|
11
|
-
<% } %>
|
|
12
|
-
<% if (it.apiKey.hasExpiresAt) { %>
|
|
13
|
-
* - Rejects keys past expiresAt
|
|
14
|
-
<% } %>
|
|
15
|
-
* - Attaches a normalized AuthContext to request.auth
|
|
16
|
-
*
|
|
17
|
-
* DO NOT EDIT - Changes will be overwritten on next scaffold
|
|
18
|
-
*/
|
|
19
|
-
import {
|
|
20
|
-
Injectable,
|
|
21
|
-
CanActivate,
|
|
22
|
-
ExecutionContext,
|
|
23
|
-
UnauthorizedException,
|
|
24
|
-
} from '@nestjs/common';
|
|
25
|
-
import { Reflector } from '@nestjs/core';
|
|
26
|
-
import { InjectRepository } from '@nestjs/typeorm';
|
|
27
|
-
import { Repository } from 'typeorm';
|
|
28
|
-
import { createHash } from 'crypto';
|
|
29
|
-
|
|
30
|
-
import { <%= it.apiKey.apiKeyEntity %> } from '../<%= it.apiKey.apiKeyEntity %>/<%= it.apiKey.apiKeyEntity %>.entity';
|
|
31
|
-
|
|
32
|
-
export const IS_PUBLIC_KEY = 'isPublic';
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Decorator to mark a route as public (skips authentication)
|
|
36
|
-
* Usage: @Public()
|
|
37
|
-
*/
|
|
38
|
-
export const Public =
|
|
39
|
-
() => (target: any, key?: string, descriptor?: PropertyDescriptor) => {
|
|
40
|
-
Reflect.defineMetadata(IS_PUBLIC_KEY, true, descriptor?.value || target);
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Normalized auth context attached to authenticated requests.
|
|
45
|
-
* This is what scopeBy and RBAC consume.
|
|
46
|
-
*/
|
|
47
|
-
export interface AuthContext {
|
|
48
|
-
userId?: string;
|
|
49
|
-
serviceId: string;
|
|
50
|
-
workspaceId?: string;
|
|
51
|
-
organizationId?: string;
|
|
52
|
-
roles: string[];
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
@Injectable()
|
|
56
|
-
export class AuthGuard implements CanActivate {
|
|
57
|
-
constructor(
|
|
58
|
-
private reflector: Reflector,
|
|
59
|
-
@InjectRepository(<%= it.apiKey.apiKeyEntity %>)
|
|
60
|
-
private apiKeyRepository: Repository<<%= it.apiKey.apiKeyEntity %>>,
|
|
61
|
-
) {}
|
|
62
|
-
|
|
63
|
-
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
64
|
-
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
|
65
|
-
context.getHandler(),
|
|
66
|
-
context.getClass(),
|
|
67
|
-
]);
|
|
68
|
-
if (isPublic) {
|
|
69
|
-
return true;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
// The template's health check stays public for load balancer probes.
|
|
73
|
-
const req = context.switchToHttp().getRequest();
|
|
74
|
-
if (req.method === 'GET' && /^\/health\/?$/.test(req.path)) {
|
|
75
|
-
return true;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
const request = context.switchToHttp().getRequest();
|
|
79
|
-
const key = request.headers['<%= it.apiKey.apiKeyHeader %>'];
|
|
80
|
-
if (typeof key !== 'string' || !key) {
|
|
81
|
-
throw new UnauthorizedException('No API key provided');
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
const hash = createHash('sha256').update(key).digest('hex');
|
|
85
|
-
const record: any = await this.apiKeyRepository.findOne({
|
|
86
|
-
where: { <%= it.apiKey.keyField %>: hash } as any,
|
|
87
|
-
});
|
|
88
|
-
if (!record) {
|
|
89
|
-
throw new UnauthorizedException('Invalid API key');
|
|
90
|
-
}
|
|
91
|
-
<% if (it.apiKey.hasStatus) { %>
|
|
92
|
-
if (record.status !== 'active') {
|
|
93
|
-
throw new UnauthorizedException('API key is not active');
|
|
94
|
-
}
|
|
95
|
-
<% } %>
|
|
96
|
-
<% if (it.apiKey.hasExpiresAt) { %>
|
|
97
|
-
if (record.expiresAt && new Date(record.expiresAt) <= new Date()) {
|
|
98
|
-
throw new UnauthorizedException('API key has expired');
|
|
99
|
-
}
|
|
100
|
-
<% } %>
|
|
101
|
-
|
|
102
|
-
const tenant =
|
|
103
|
-
record.<%= it.apiKey.workspaceField %> != null
|
|
104
|
-
? String(record.<%= it.apiKey.workspaceField %>)
|
|
105
|
-
: undefined;
|
|
106
|
-
<% if (it.apiKey.roleField) { %>
|
|
107
|
-
const role = record.<%= it.apiKey.roleField %>;
|
|
108
|
-
const roles = Array.isArray(role) ? role.map(String) : role ? [String(role)] : [];
|
|
109
|
-
<% } else { %>
|
|
110
|
-
const roles: string[] = [];
|
|
111
|
-
<% } %>
|
|
112
|
-
const auth: AuthContext = {
|
|
113
|
-
serviceId: String(record.id),
|
|
114
|
-
workspaceId: tenant,
|
|
115
|
-
organizationId: tenant,
|
|
116
|
-
roles,
|
|
117
|
-
};
|
|
118
|
-
|
|
119
|
-
request.auth = auth;
|
|
120
|
-
request.user = { id: auth.serviceId, ...auth };
|
|
121
|
-
// Read by ScopeGuard's scope lookup.
|
|
122
|
-
request.workspaceId = tenant;
|
|
123
|
-
request.organizationId = tenant;
|
|
124
|
-
return true;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* Helper function to get AuthContext from request
|
|
130
|
-
* Use this in controllers/services to access the authenticated context
|
|
131
|
-
*/
|
|
132
|
-
export function getAuthContext(request: any): AuthContext | undefined {
|
|
133
|
-
return request?.auth;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Helper function to require AuthContext (throws if not present)
|
|
138
|
-
*/
|
|
139
|
-
export function requireAuthContext(request: any): AuthContext {
|
|
140
|
-
const ctx = getAuthContext(request);
|
|
141
|
-
if (!ctx) {
|
|
142
|
-
throw new UnauthorizedException('Authentication required');
|
|
143
|
-
}
|
|
144
|
-
return ctx;
|
|
145
|
-
}
|
|
@@ -1,233 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* AuthGuard - Authentication guard for <%= it.authConfig.provider %> provider
|
|
3
|
-
*
|
|
4
|
-
* Auto-generated by Apso CLI from .apsorc auth configuration
|
|
5
|
-
*
|
|
6
|
-
* This guard:
|
|
7
|
-
* - Validates session tokens from cookies/headers
|
|
8
|
-
* - Loads user and organization context
|
|
9
|
-
* - Attaches normalized AuthContext to requests
|
|
10
|
-
*
|
|
11
|
-
* DO NOT EDIT - Changes will be overwritten on next scaffold
|
|
12
|
-
*/
|
|
13
|
-
import {
|
|
14
|
-
Injectable,
|
|
15
|
-
CanActivate,
|
|
16
|
-
ExecutionContext,
|
|
17
|
-
UnauthorizedException,
|
|
18
|
-
} from '@nestjs/common';
|
|
19
|
-
import { Reflector } from '@nestjs/core';
|
|
20
|
-
import { InjectRepository } from '@nestjs/typeorm';
|
|
21
|
-
import { Repository } from 'typeorm';
|
|
22
|
-
|
|
23
|
-
// Entity imports (from sibling autogen folders)
|
|
24
|
-
import { <%= it.authConfig.sessionEntity %> } from '../<%= it.authConfig.sessionEntity %>/<%= it.authConfig.sessionEntity %>.entity';
|
|
25
|
-
import { <%= it.authConfig.userEntity %> } from '../<%= it.authConfig.userEntity %>/<%= it.authConfig.userEntity %>.entity';
|
|
26
|
-
<% if (it.authConfig.accountUserEntity) { %>
|
|
27
|
-
import { <%= it.authConfig.accountUserEntity %> } from '../<%= it.authConfig.accountUserEntity %>/<%= it.authConfig.accountUserEntity %>.entity';
|
|
28
|
-
<% } %>
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Metadata key for marking routes as public (no auth required)
|
|
32
|
-
*/
|
|
33
|
-
export const IS_PUBLIC_KEY = 'isPublic';
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Decorator to mark a route as public (skips authentication)
|
|
37
|
-
* Usage: @Public()
|
|
38
|
-
*/
|
|
39
|
-
export const Public =
|
|
40
|
-
() => (target: any, key?: string, descriptor?: PropertyDescriptor) => {
|
|
41
|
-
Reflect.defineMetadata(IS_PUBLIC_KEY, true, descriptor?.value || target);
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Normalized auth context attached to authenticated requests.
|
|
46
|
-
* This is what scopeBy and RBAC consume.
|
|
47
|
-
*/
|
|
48
|
-
export interface AuthContext {
|
|
49
|
-
userId?: string;
|
|
50
|
-
email?: string;
|
|
51
|
-
workspaceId?: string;
|
|
52
|
-
organizationId?: string;
|
|
53
|
-
roles: string[];
|
|
54
|
-
user?: <%= it.authConfig.userEntity %>;
|
|
55
|
-
session?: <%= it.authConfig.sessionEntity %>;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Extended request type with auth context
|
|
60
|
-
*/
|
|
61
|
-
export interface AuthenticatedRequest extends Request {
|
|
62
|
-
auth: AuthContext;
|
|
63
|
-
user: <%= it.authConfig.userEntity %>;
|
|
64
|
-
session: <%= it.authConfig.sessionEntity %>;
|
|
65
|
-
// Legacy compatibility aliases
|
|
66
|
-
accountId?: string;
|
|
67
|
-
accountRole?: string;
|
|
68
|
-
organizationId?: string;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
@Injectable()
|
|
72
|
-
export class AuthGuard implements CanActivate {
|
|
73
|
-
constructor(
|
|
74
|
-
private reflector: Reflector,
|
|
75
|
-
@InjectRepository(<%= it.authConfig.sessionEntity %>)
|
|
76
|
-
private sessionRepository: Repository<<%= it.authConfig.sessionEntity %>>,
|
|
77
|
-
@InjectRepository(<%= it.authConfig.userEntity %>)
|
|
78
|
-
private userRepository: Repository<<%= it.authConfig.userEntity %>>,
|
|
79
|
-
<% if (it.authConfig.accountUserEntity) { %>
|
|
80
|
-
@InjectRepository(<%= it.authConfig.accountUserEntity %>)
|
|
81
|
-
private accountUserRepository: Repository<<%= it.authConfig.accountUserEntity %>>,
|
|
82
|
-
<% } %>
|
|
83
|
-
) {}
|
|
84
|
-
|
|
85
|
-
async canActivate(context: ExecutionContext): Promise<boolean> {
|
|
86
|
-
// Check if route is marked as public
|
|
87
|
-
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
|
88
|
-
context.getHandler(),
|
|
89
|
-
context.getClass(),
|
|
90
|
-
]);
|
|
91
|
-
|
|
92
|
-
if (isPublic) {
|
|
93
|
-
return true;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// The template's health check stays public for load balancer probes.
|
|
97
|
-
const req = context.switchToHttp().getRequest();
|
|
98
|
-
if (req.method === 'GET' && /^\/health\/?$/.test(req.path)) {
|
|
99
|
-
return true;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
const request = context.switchToHttp().getRequest();
|
|
103
|
-
const token = this.extractToken(request);
|
|
104
|
-
|
|
105
|
-
if (!token) {
|
|
106
|
-
throw new UnauthorizedException('No session token provided');
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
try {
|
|
110
|
-
// Find session by token
|
|
111
|
-
const sessionRecord = await this.sessionRepository.findOne({
|
|
112
|
-
where: { token },
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
if (!sessionRecord) {
|
|
116
|
-
throw new UnauthorizedException('Invalid session token');
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
// Check if session is expired
|
|
120
|
-
if (new Date(sessionRecord.expiresAt) < new Date()) {
|
|
121
|
-
throw new UnauthorizedException('Session expired');
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// Get user from session
|
|
125
|
-
const user = await this.userRepository.findOne({
|
|
126
|
-
where: { id: sessionRecord.userId },
|
|
127
|
-
});
|
|
128
|
-
|
|
129
|
-
if (!user) {
|
|
130
|
-
throw new UnauthorizedException('User not found');
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
<% if (it.authConfig.accountUserEntity) { %>
|
|
134
|
-
// Get user's organization through <%= it.authConfig.accountUserEntity %> junction
|
|
135
|
-
const accountUser = await this.accountUserRepository.findOne({
|
|
136
|
-
where: { userId: user.id },
|
|
137
|
-
});
|
|
138
|
-
|
|
139
|
-
if (!accountUser) {
|
|
140
|
-
throw new UnauthorizedException('User not associated with any organization');
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
const organizationId = accountUser.<%= it.authConfig.organizationField %>;
|
|
144
|
-
const role = accountUser.<%= it.authConfig.roleField %> || 'member';
|
|
145
|
-
<% } else { %>
|
|
146
|
-
// No account user entity configured - using user-level organization
|
|
147
|
-
const organizationId = (user as any).<%= it.authConfig.organizationField %> || undefined;
|
|
148
|
-
const role = (user as any).<%= it.authConfig.roleField %> || 'member';
|
|
149
|
-
<% } %>
|
|
150
|
-
|
|
151
|
-
// Build normalized AuthContext
|
|
152
|
-
const authContext: AuthContext = {
|
|
153
|
-
userId: user.id,
|
|
154
|
-
email: user.email,
|
|
155
|
-
workspaceId: organizationId,
|
|
156
|
-
organizationId: organizationId,
|
|
157
|
-
roles: [role],
|
|
158
|
-
user: user,
|
|
159
|
-
session: sessionRecord,
|
|
160
|
-
};
|
|
161
|
-
|
|
162
|
-
// Attach to request
|
|
163
|
-
(request as any).auth = authContext;
|
|
164
|
-
(request as any).user = user;
|
|
165
|
-
(request as any).session = sessionRecord;
|
|
166
|
-
|
|
167
|
-
// Legacy compatibility - attach directly to request root
|
|
168
|
-
(request as any).accountId = organizationId;
|
|
169
|
-
(request as any).accountRole = role;
|
|
170
|
-
(request as any).organizationId = organizationId;
|
|
171
|
-
|
|
172
|
-
return true;
|
|
173
|
-
} catch (error) {
|
|
174
|
-
if (error instanceof UnauthorizedException) {
|
|
175
|
-
throw error;
|
|
176
|
-
}
|
|
177
|
-
console.error('Auth guard error:', error);
|
|
178
|
-
throw new UnauthorizedException('Authentication failed');
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
/**
|
|
183
|
-
* Extract session token from request
|
|
184
|
-
* Checks: Authorization header (Bearer), cookies, X-Session-Token header
|
|
185
|
-
*/
|
|
186
|
-
private extractToken(request: any): string | undefined {
|
|
187
|
-
// Check Authorization header first (Bearer token)
|
|
188
|
-
const authHeader = request.headers.authorization;
|
|
189
|
-
if (authHeader && authHeader.startsWith('Bearer ')) {
|
|
190
|
-
return authHeader.substring(7);
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
// Check for session token in cookies
|
|
194
|
-
const cookies = request.cookies || {};
|
|
195
|
-
<% if (it.authConfig.cookiePrefix) { %>
|
|
196
|
-
const cookieName = '<%= it.authConfig.cookiePrefix %>.session_token';
|
|
197
|
-
const sessionToken =
|
|
198
|
-
cookies[cookieName] ||
|
|
199
|
-
cookies['better-auth.session_token'] ||
|
|
200
|
-
cookies['session_token'];
|
|
201
|
-
<% } else { %>
|
|
202
|
-
const sessionToken =
|
|
203
|
-
cookies['better-auth.session_token'] ||
|
|
204
|
-
cookies['session_token'];
|
|
205
|
-
<% } %>
|
|
206
|
-
|
|
207
|
-
if (sessionToken) {
|
|
208
|
-
return sessionToken;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
// Check X-Session-Token header
|
|
212
|
-
return request.headers['x-session-token'];
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/**
|
|
217
|
-
* Helper function to get AuthContext from request
|
|
218
|
-
* Use this in controllers/services to access the authenticated context
|
|
219
|
-
*/
|
|
220
|
-
export function getAuthContext(request: any): AuthContext | undefined {
|
|
221
|
-
return request?.auth;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
/**
|
|
225
|
-
* Helper function to require AuthContext (throws if not present)
|
|
226
|
-
*/
|
|
227
|
-
export function requireAuthContext(request: any): AuthContext {
|
|
228
|
-
const ctx = getAuthContext(request);
|
|
229
|
-
if (!ctx) {
|
|
230
|
-
throw new UnauthorizedException('Authentication required');
|
|
231
|
-
}
|
|
232
|
-
return ctx;
|
|
233
|
-
}
|