swallowkit 1.0.0-beta.5 → 1.0.0-beta.50
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 +21 -21
- package/README.ja.md +153 -242
- package/README.md +153 -243
- package/dist/__tests__/fixtures.d.ts +22 -0
- package/dist/__tests__/fixtures.d.ts.map +1 -0
- package/dist/__tests__/fixtures.js +146 -0
- package/dist/__tests__/fixtures.js.map +1 -0
- package/dist/cli/commands/add-auth.d.ts +13 -0
- package/dist/cli/commands/add-auth.d.ts.map +1 -0
- package/dist/cli/commands/add-auth.js +759 -0
- package/dist/cli/commands/add-auth.js.map +1 -0
- package/dist/cli/commands/add-connector.d.ts +20 -0
- package/dist/cli/commands/add-connector.d.ts.map +1 -0
- package/dist/cli/commands/add-connector.js +163 -0
- package/dist/cli/commands/add-connector.js.map +1 -0
- package/dist/cli/commands/create-model.d.ts +1 -4
- package/dist/cli/commands/create-model.d.ts.map +1 -1
- package/dist/cli/commands/create-model.js +19 -81
- package/dist/cli/commands/create-model.js.map +1 -1
- package/dist/cli/commands/dev-seeds.d.ts +57 -0
- package/dist/cli/commands/dev-seeds.d.ts.map +1 -0
- package/dist/cli/commands/dev-seeds.js +470 -0
- package/dist/cli/commands/dev-seeds.js.map +1 -0
- package/dist/cli/commands/dev.d.ts +37 -0
- package/dist/cli/commands/dev.d.ts.map +1 -1
- package/dist/cli/commands/dev.js +720 -156
- package/dist/cli/commands/dev.js.map +1 -1
- package/dist/cli/commands/index.d.ts +1 -0
- package/dist/cli/commands/index.d.ts.map +1 -1
- package/dist/cli/commands/index.js +3 -1
- package/dist/cli/commands/index.js.map +1 -1
- package/dist/cli/commands/init.d.ts +67 -0
- package/dist/cli/commands/init.d.ts.map +1 -1
- package/dist/cli/commands/init.js +3080 -1771
- package/dist/cli/commands/init.js.map +1 -1
- package/dist/cli/commands/scaffold.d.ts +13 -0
- package/dist/cli/commands/scaffold.d.ts.map +1 -1
- package/dist/cli/commands/scaffold.js +513 -129
- package/dist/cli/commands/scaffold.js.map +1 -1
- package/dist/cli/index.d.ts +5 -1
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +206 -55
- package/dist/cli/index.js.map +1 -1
- package/dist/core/config.d.ts +14 -3
- package/dist/core/config.d.ts.map +1 -1
- package/dist/core/config.js +172 -5
- package/dist/core/config.js.map +1 -1
- package/dist/core/mock/connector-mock-server.d.ts +101 -0
- package/dist/core/mock/connector-mock-server.d.ts.map +1 -0
- package/dist/core/mock/connector-mock-server.js +480 -0
- package/dist/core/mock/connector-mock-server.js.map +1 -0
- package/dist/core/mock/zod-mock-generator.d.ts +14 -0
- package/dist/core/mock/zod-mock-generator.d.ts.map +1 -0
- package/dist/core/mock/zod-mock-generator.js +163 -0
- package/dist/core/mock/zod-mock-generator.js.map +1 -0
- package/dist/core/operations/create-model.d.ts +15 -0
- package/dist/core/operations/create-model.d.ts.map +1 -0
- package/dist/core/operations/create-model.js +171 -0
- package/dist/core/operations/create-model.js.map +1 -0
- package/dist/core/operations/runtime.d.ts +32 -0
- package/dist/core/operations/runtime.d.ts.map +1 -0
- package/dist/core/operations/runtime.js +225 -0
- package/dist/core/operations/runtime.js.map +1 -0
- package/dist/core/operations/scaffold-machine.d.ts +16 -0
- package/dist/core/operations/scaffold-machine.d.ts.map +1 -0
- package/dist/core/operations/scaffold-machine.js +63 -0
- package/dist/core/operations/scaffold-machine.js.map +1 -0
- package/dist/core/project/manifest.d.ts +92 -0
- package/dist/core/project/manifest.d.ts.map +1 -0
- package/dist/core/project/manifest.js +321 -0
- package/dist/core/project/manifest.js.map +1 -0
- package/dist/core/project/validation.d.ts +20 -0
- package/dist/core/project/validation.d.ts.map +1 -0
- package/dist/core/project/validation.js +226 -0
- package/dist/core/project/validation.js.map +1 -0
- package/dist/core/scaffold/auth-generator.d.ts +63 -0
- package/dist/core/scaffold/auth-generator.d.ts.map +1 -0
- package/dist/core/scaffold/auth-generator.js +1714 -0
- package/dist/core/scaffold/auth-generator.js.map +1 -0
- package/dist/core/scaffold/connector-functions-generator.d.ts +41 -0
- package/dist/core/scaffold/connector-functions-generator.d.ts.map +1 -0
- package/dist/core/scaffold/connector-functions-generator.js +1029 -0
- package/dist/core/scaffold/connector-functions-generator.js.map +1 -0
- package/dist/core/scaffold/functions-generator.d.ts +7 -1
- package/dist/core/scaffold/functions-generator.d.ts.map +1 -1
- package/dist/core/scaffold/functions-generator.js +922 -220
- package/dist/core/scaffold/functions-generator.js.map +1 -1
- package/dist/core/scaffold/model-parser.d.ts +20 -1
- package/dist/core/scaffold/model-parser.d.ts.map +1 -1
- package/dist/core/scaffold/model-parser.js +333 -139
- package/dist/core/scaffold/model-parser.js.map +1 -1
- package/dist/core/scaffold/native-schema-generator.d.ts +13 -0
- package/dist/core/scaffold/native-schema-generator.d.ts.map +1 -0
- package/dist/core/scaffold/native-schema-generator.js +696 -0
- package/dist/core/scaffold/native-schema-generator.js.map +1 -0
- package/dist/core/scaffold/nextjs-generator.d.ts +8 -0
- package/dist/core/scaffold/nextjs-generator.d.ts.map +1 -1
- package/dist/core/scaffold/nextjs-generator.js +326 -182
- package/dist/core/scaffold/nextjs-generator.js.map +1 -1
- package/dist/core/scaffold/openapi-generator.d.ts +3 -0
- package/dist/core/scaffold/openapi-generator.d.ts.map +1 -0
- package/dist/core/scaffold/openapi-generator.js +190 -0
- package/dist/core/scaffold/openapi-generator.js.map +1 -0
- package/dist/core/scaffold/ui-generator.d.ts +13 -4
- package/dist/core/scaffold/ui-generator.d.ts.map +1 -1
- package/dist/core/scaffold/ui-generator.js +772 -663
- package/dist/core/scaffold/ui-generator.js.map +1 -1
- package/dist/database/base-model.d.ts +3 -3
- package/dist/database/base-model.js +3 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/machine/contracts.d.ts +16 -0
- package/dist/machine/contracts.d.ts.map +1 -0
- package/dist/machine/contracts.js +3 -0
- package/dist/machine/contracts.js.map +1 -0
- package/dist/machine/errors.d.ts +11 -0
- package/dist/machine/errors.d.ts.map +1 -0
- package/dist/machine/errors.js +34 -0
- package/dist/machine/errors.js.map +1 -0
- package/dist/machine/index.d.ts +3 -0
- package/dist/machine/index.d.ts.map +1 -0
- package/dist/machine/index.js +156 -0
- package/dist/machine/index.js.map +1 -0
- package/dist/mcp/index.d.ts +25 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +202 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/types/index.d.ts +95 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/package-manager.d.ts +5 -2
- package/dist/utils/package-manager.d.ts.map +1 -1
- package/dist/utils/package-manager.js +34 -13
- package/dist/utils/package-manager.js.map +1 -1
- package/dist/utils/python-uv.d.ts +21 -0
- package/dist/utils/python-uv.d.ts.map +1 -0
- package/dist/utils/python-uv.js +111 -0
- package/dist/utils/python-uv.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +49 -0
- package/dist/version.js.map +1 -0
- package/package.json +84 -74
- package/src/__tests__/__snapshots__/functions-generator.test.ts.snap +1139 -0
- package/src/__tests__/__snapshots__/nextjs-generator.test.ts.snap +206 -0
- package/src/__tests__/__snapshots__/ui-generator.test.ts.snap +532 -0
- package/src/__tests__/auth.test.ts +761 -0
- package/src/__tests__/config.test.ts +295 -0
- package/src/__tests__/connector-functions-generator.test.ts +288 -0
- package/src/__tests__/connector-mock-server.test.ts +439 -0
- package/src/__tests__/connector-model-bff.test.ts +162 -0
- package/src/__tests__/dev-seeds.test.ts +173 -0
- package/src/__tests__/dev.test.ts +287 -0
- package/src/__tests__/fixtures.ts +144 -0
- package/src/__tests__/functions-generator.test.ts +237 -0
- package/src/__tests__/init.test.ts +327 -0
- package/src/__tests__/jest-globals.d.ts +8 -0
- package/src/__tests__/machine.test.ts +356 -0
- package/src/__tests__/mcp.test.ts +145 -0
- package/src/__tests__/model-parser.test.ts +52 -0
- package/src/__tests__/multi-auth.test.ts +133 -0
- package/src/__tests__/nextjs-generator.test.ts +105 -0
- package/src/__tests__/openapi-generator.test.ts +43 -0
- package/src/__tests__/package-manager.test.ts +227 -0
- package/src/__tests__/python-uv.test.ts +48 -0
- package/src/__tests__/scaffold.test.ts +191 -0
- package/src/__tests__/string-utils.test.ts +75 -0
- package/src/__tests__/tsconfig.json +15 -0
- package/src/__tests__/ui-generator.test.ts +144 -0
- package/src/__tests__/zod-mock-generator.test.ts +132 -0
- package/src/cli/commands/add-auth.ts +815 -0
- package/src/cli/commands/add-connector.ts +158 -0
- package/src/cli/commands/create-model.ts +62 -0
- package/src/cli/commands/dev-seeds.ts +614 -0
- package/src/cli/commands/dev.ts +1234 -0
- package/src/cli/commands/index.ts +9 -0
- package/src/cli/commands/init.ts +3902 -0
- package/src/cli/commands/provision.ts +193 -0
- package/src/cli/commands/scaffold.ts +1067 -0
- package/src/cli/index.ts +202 -0
- package/src/core/config.ts +379 -0
- package/src/core/mock/connector-mock-server.ts +555 -0
- package/src/core/mock/zod-mock-generator.ts +205 -0
- package/src/core/operations/create-model.ts +174 -0
- package/src/core/operations/runtime.ts +235 -0
- package/src/core/operations/scaffold-machine.ts +91 -0
- package/src/core/project/manifest.ts +402 -0
- package/src/core/project/validation.ts +245 -0
- package/src/core/scaffold/auth-generator.ts +1760 -0
- package/src/core/scaffold/connector-functions-generator.ts +1133 -0
- package/src/core/scaffold/functions-generator.ts +972 -0
- package/src/core/scaffold/model-parser.ts +847 -0
- package/src/core/scaffold/native-schema-generator.ts +822 -0
- package/src/core/scaffold/nextjs-generator.ts +382 -0
- package/src/core/scaffold/openapi-generator.ts +212 -0
- package/src/core/scaffold/ui-generator.ts +1068 -0
- package/src/database/base-model.ts +184 -0
- package/src/database/client.ts +140 -0
- package/src/database/repository.ts +104 -0
- package/src/database/runtime-check.ts +25 -0
- package/src/index.ts +27 -0
- package/src/machine/contracts.ts +17 -0
- package/src/machine/errors.ts +34 -0
- package/src/machine/index.ts +173 -0
- package/src/mcp/index.ts +209 -0
- package/src/types/index.ts +165 -0
- package/src/utils/package-manager.ts +246 -0
- package/src/utils/python-uv.ts +96 -0
- package/src/version.ts +13 -0
- package/dist/cli/commands/build.d.ts +0 -6
- package/dist/cli/commands/build.d.ts.map +0 -1
- package/dist/cli/commands/build.js +0 -177
- package/dist/cli/commands/build.js.map +0 -1
- package/dist/cli/commands/deploy.d.ts +0 -3
- package/dist/cli/commands/deploy.d.ts.map +0 -1
- package/dist/cli/commands/deploy.js +0 -147
- package/dist/cli/commands/deploy.js.map +0 -1
- package/dist/cli/commands/setup.d.ts +0 -6
- package/dist/cli/commands/setup.d.ts.map +0 -1
- package/dist/cli/commands/setup.js +0 -254
- package/dist/cli/commands/setup.js.map +0 -1
|
@@ -0,0 +1,759 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* SwallowKit Add-Auth コマンド
|
|
4
|
+
* 認証認可基盤ファイルを生成する
|
|
5
|
+
*/
|
|
6
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
7
|
+
if (k2 === undefined) k2 = k;
|
|
8
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
9
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
10
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
11
|
+
}
|
|
12
|
+
Object.defineProperty(o, k2, desc);
|
|
13
|
+
}) : (function(o, m, k, k2) {
|
|
14
|
+
if (k2 === undefined) k2 = k;
|
|
15
|
+
o[k2] = m[k];
|
|
16
|
+
}));
|
|
17
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
18
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
19
|
+
}) : function(o, v) {
|
|
20
|
+
o["default"] = v;
|
|
21
|
+
});
|
|
22
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
23
|
+
var ownKeys = function(o) {
|
|
24
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
25
|
+
var ar = [];
|
|
26
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
27
|
+
return ar;
|
|
28
|
+
};
|
|
29
|
+
return ownKeys(o);
|
|
30
|
+
};
|
|
31
|
+
return function (mod) {
|
|
32
|
+
if (mod && mod.__esModule) return mod;
|
|
33
|
+
var result = {};
|
|
34
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
35
|
+
__setModuleDefault(result, mod);
|
|
36
|
+
return result;
|
|
37
|
+
};
|
|
38
|
+
})();
|
|
39
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
40
|
+
exports.generateSwaAuthContext = generateSwaAuthContext;
|
|
41
|
+
exports.addAuthProviderToRootLayout = addAuthProviderToRootLayout;
|
|
42
|
+
exports.addAuthCommand = addAuthCommand;
|
|
43
|
+
const fs = __importStar(require("fs"));
|
|
44
|
+
const path = __importStar(require("path"));
|
|
45
|
+
const config_1 = require("../../core/config");
|
|
46
|
+
const auth_generator_1 = require("../../core/scaffold/auth-generator");
|
|
47
|
+
const manifest_1 = require("../../core/project/manifest");
|
|
48
|
+
const init_1 = require("./init");
|
|
49
|
+
function writeIfMissing(filePath, content) {
|
|
50
|
+
if (fs.existsSync(filePath))
|
|
51
|
+
return;
|
|
52
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
53
|
+
fs.writeFileSync(filePath, content, "utf-8");
|
|
54
|
+
}
|
|
55
|
+
function defaultCustomJwtConfig() {
|
|
56
|
+
return {
|
|
57
|
+
userConnector: "mysql",
|
|
58
|
+
userTable: "users",
|
|
59
|
+
loginIdColumn: "login_id",
|
|
60
|
+
passwordHashColumn: "password_hash",
|
|
61
|
+
rolesColumn: "roles",
|
|
62
|
+
jwtSecretEnv: "JWT_SECRET",
|
|
63
|
+
tokenExpiry: "24h",
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function setupSwaAuth(cwd, backendLanguage) {
|
|
67
|
+
const helperPath = backendLanguage === "typescript"
|
|
68
|
+
? path.join(cwd, "functions", "src", "auth", "jwt-helper.ts")
|
|
69
|
+
: backendLanguage === "csharp"
|
|
70
|
+
? path.join(cwd, "functions", "Auth", "JwtHelper.cs")
|
|
71
|
+
: path.join(cwd, "functions", "auth", "jwt_helper.py");
|
|
72
|
+
fs.mkdirSync(path.dirname(helperPath), { recursive: true });
|
|
73
|
+
const helper = backendLanguage === "typescript"
|
|
74
|
+
? (0, auth_generator_1.generateSwaAuthHelperTS)()
|
|
75
|
+
: backendLanguage === "csharp"
|
|
76
|
+
? (0, auth_generator_1.generateSwaAuthHelperCSharp)()
|
|
77
|
+
: (0, auth_generator_1.generateSwaAuthHelperPython)();
|
|
78
|
+
fs.writeFileSync(helperPath, helper, "utf-8");
|
|
79
|
+
const callFnPath = path.join(cwd, "lib", "api", "call-function.ts");
|
|
80
|
+
fs.mkdirSync(path.dirname(callFnPath), { recursive: true });
|
|
81
|
+
fs.writeFileSync(callFnPath, (0, auth_generator_1.generateBFFCallFunctionWithSwaAuth)(), "utf-8");
|
|
82
|
+
const authDir = path.join(cwd, "lib", "auth");
|
|
83
|
+
fs.mkdirSync(authDir, { recursive: true });
|
|
84
|
+
fs.writeFileSync(path.join(authDir, "auth-context.tsx"), generateSwaAuthContext(), "utf-8");
|
|
85
|
+
updateRootLayoutWithAuthProvider(cwd);
|
|
86
|
+
const loginDir = path.join(cwd, "app", "login");
|
|
87
|
+
fs.mkdirSync(loginDir, { recursive: true });
|
|
88
|
+
fs.writeFileSync(path.join(loginDir, "page.tsx"), generateSwaLoginPage(), "utf-8");
|
|
89
|
+
updateSwaRouteConfig(cwd);
|
|
90
|
+
}
|
|
91
|
+
function setupExternalTokenAuth(cwd, backendLanguage) {
|
|
92
|
+
const authDir = path.join(cwd, "lib", "auth");
|
|
93
|
+
fs.mkdirSync(authDir, { recursive: true });
|
|
94
|
+
writeIfMissing(path.join(authDir, "external-token-adapter.ts"), (0, auth_generator_1.generateExternalTokenAdapter)());
|
|
95
|
+
fs.writeFileSync(path.join(authDir, "authenticated-fetch.ts"), (0, auth_generator_1.generateAuthenticatedFetch)(), "utf-8");
|
|
96
|
+
fs.writeFileSync(path.join(authDir, "auth-context.tsx"), (0, auth_generator_1.generateExternalTokenAuthContext)(), "utf-8");
|
|
97
|
+
fs.writeFileSync(path.join(cwd, "lib", "api", "call-function.ts"), (0, auth_generator_1.generateBFFCallFunctionWithAuth)(), "utf-8");
|
|
98
|
+
const meDir = path.join(cwd, "app", "api", "auth", "me");
|
|
99
|
+
fs.mkdirSync(meDir, { recursive: true });
|
|
100
|
+
fs.writeFileSync(path.join(meDir, "route.ts"), (0, auth_generator_1.generateExternalTokenBFFMeRoute)(), "utf-8");
|
|
101
|
+
updateRootLayoutWithAuthProvider(cwd);
|
|
102
|
+
if (backendLanguage === "typescript") {
|
|
103
|
+
const verifier = path.join(cwd, "functions", "src", "auth", "external-token-verifier.ts");
|
|
104
|
+
writeIfMissing(verifier, (0, auth_generator_1.generateExternalTokenVerifierTS)());
|
|
105
|
+
fs.writeFileSync(path.join(cwd, "functions", "src", "auth", "jwt-helper.ts"), (0, auth_generator_1.generateExternalTokenHelperTS)(), "utf-8");
|
|
106
|
+
fs.writeFileSync(path.join(cwd, "functions", "src", "auth-me.ts"), (0, auth_generator_1.generateExternalAuthMeTS)(), "utf-8");
|
|
107
|
+
}
|
|
108
|
+
else if (backendLanguage === "csharp") {
|
|
109
|
+
const verifier = path.join(cwd, "functions", "Auth", "ExternalTokenVerifier.cs");
|
|
110
|
+
writeIfMissing(verifier, (0, auth_generator_1.generateExternalTokenVerifierCSharp)());
|
|
111
|
+
fs.writeFileSync(path.join(cwd, "functions", "Auth", "JwtHelper.cs"), (0, auth_generator_1.generateExternalTokenHelperCSharp)(), "utf-8");
|
|
112
|
+
fs.writeFileSync(path.join(cwd, "functions", "Auth", "ExternalAuthMe.cs"), (0, auth_generator_1.generateExternalAuthMeCSharp)(), "utf-8");
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
const verifier = path.join(cwd, "functions", "auth", "external_token_verifier.py");
|
|
116
|
+
writeIfMissing(verifier, (0, auth_generator_1.generateExternalTokenVerifierPython)());
|
|
117
|
+
fs.writeFileSync(path.join(cwd, "functions", "auth", "jwt_helper.py"), (0, auth_generator_1.generateExternalTokenHelperPython)(), "utf-8");
|
|
118
|
+
const authMePath = path.join(cwd, "functions", "blueprints", "auth_me.py");
|
|
119
|
+
fs.mkdirSync(path.dirname(authMePath), { recursive: true });
|
|
120
|
+
fs.writeFileSync(authMePath, (0, auth_generator_1.generateExternalAuthMePython)(), "utf-8");
|
|
121
|
+
updatePythonAuthMeRegistration(cwd);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function updatePythonAuthMeRegistration(cwd) {
|
|
125
|
+
const appPath = path.join(cwd, "functions", "function_app.py");
|
|
126
|
+
if (!fs.existsSync(appPath))
|
|
127
|
+
return;
|
|
128
|
+
const importLine = "from blueprints.auth_me import bp as external_auth_me_bp";
|
|
129
|
+
const registerLine = "app.register_blueprint(external_auth_me_bp)";
|
|
130
|
+
let content = fs.readFileSync(appPath, "utf-8");
|
|
131
|
+
if (content.includes(importLine))
|
|
132
|
+
return;
|
|
133
|
+
const marker = "# SwallowKit scaffold registrations";
|
|
134
|
+
content = content.includes(marker)
|
|
135
|
+
? content.replace(marker, `${importLine}\n${registerLine}\n${marker}`)
|
|
136
|
+
: `${content.trimEnd()}\n${importLine}\n${registerLine}\n`;
|
|
137
|
+
fs.writeFileSync(appPath, content, "utf-8");
|
|
138
|
+
}
|
|
139
|
+
function generateSwaLoginPage() {
|
|
140
|
+
return `'use client';
|
|
141
|
+
export default function LoginPage() {
|
|
142
|
+
return <main><h1>Sign in</h1><a href="/.auth/login/aad?post_login_redirect_uri=/">Sign in with Microsoft</a></main>;
|
|
143
|
+
}
|
|
144
|
+
`;
|
|
145
|
+
}
|
|
146
|
+
function generateSwaAuthContext() {
|
|
147
|
+
return `'use client';
|
|
148
|
+
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
|
|
149
|
+
|
|
150
|
+
export interface AuthUser { id: string; loginId: string; name: string; email: string; roles: string[]; }
|
|
151
|
+
interface AuthContextValue { user: AuthUser | null; loading: boolean; login: () => void; logout: () => void; hasRole: (role: string) => boolean; hasAnyRole: (roles: string[]) => boolean; }
|
|
152
|
+
const AuthContext = createContext<AuthContextValue | null>(null);
|
|
153
|
+
|
|
154
|
+
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
155
|
+
const [user, setUser] = useState<AuthUser | null>(null);
|
|
156
|
+
const [loading, setLoading] = useState(true);
|
|
157
|
+
useEffect(() => {
|
|
158
|
+
fetch('/.auth/me')
|
|
159
|
+
.then(async response => {
|
|
160
|
+
if (!response.ok) throw new Error('SWA authentication is unavailable');
|
|
161
|
+
const body: unknown = await response.json();
|
|
162
|
+
if (!body || typeof body !== 'object' || !('clientPrincipal' in body)) return null;
|
|
163
|
+
const principal = body.clientPrincipal;
|
|
164
|
+
if (!principal || typeof principal !== 'object') return null;
|
|
165
|
+
const value = principal as Record<string, unknown>;
|
|
166
|
+
if (typeof value.userId !== 'string') return null;
|
|
167
|
+
return {
|
|
168
|
+
id: value.userId,
|
|
169
|
+
loginId: typeof value.userDetails === 'string' ? value.userDetails : '',
|
|
170
|
+
name: typeof value.userDetails === 'string' ? value.userDetails : '',
|
|
171
|
+
email: typeof value.userDetails === 'string' ? value.userDetails : '',
|
|
172
|
+
roles: Array.isArray(value.userRoles) ? value.userRoles.filter((role): role is string => typeof role === 'string') : [],
|
|
173
|
+
} satisfies AuthUser;
|
|
174
|
+
})
|
|
175
|
+
.then(setUser)
|
|
176
|
+
.catch(() => setUser(null))
|
|
177
|
+
.finally(() => setLoading(false));
|
|
178
|
+
}, []);
|
|
179
|
+
const login = () => { window.location.href = '/.auth/login/aad?post_login_redirect_uri=/'; };
|
|
180
|
+
const logout = () => { window.location.href = '/.auth/logout?post_logout_redirect_uri=/'; };
|
|
181
|
+
const hasRole = (role: string) => user?.roles.includes(role) ?? false;
|
|
182
|
+
return <AuthContext.Provider value={{ user, loading, login, logout, hasRole, hasAnyRole: roles => roles.some(hasRole) }}>{children}</AuthContext.Provider>;
|
|
183
|
+
}
|
|
184
|
+
export function useAuth() { const value = useContext(AuthContext); if (!value) throw new Error('useAuth must be used within an AuthProvider'); return value; }
|
|
185
|
+
`;
|
|
186
|
+
}
|
|
187
|
+
function addAuthProviderToRootLayout(layout) {
|
|
188
|
+
let updated = layout;
|
|
189
|
+
if (!/import\s*\{[^}]*\bAuthProvider\b[^}]*\}\s*from\s*['"]@\/lib\/auth\/auth-context['"]/.test(updated)) {
|
|
190
|
+
const directive = updated.match(/^(?:\s*['"]use (?:client|server)['"];?\s*\r?\n)/)?.[0] ?? "";
|
|
191
|
+
updated = `${directive}import { AuthProvider } from '@/lib/auth/auth-context';\n${updated.slice(directive.length)}`;
|
|
192
|
+
}
|
|
193
|
+
if (!/<AuthProvider(?:\s|>)/.test(updated)) {
|
|
194
|
+
const childrenIndex = updated.lastIndexOf("{children}");
|
|
195
|
+
if (childrenIndex === -1) {
|
|
196
|
+
throw new Error("Could not find {children} in app/layout.tsx");
|
|
197
|
+
}
|
|
198
|
+
updated = `${updated.slice(0, childrenIndex)}<AuthProvider>{children}</AuthProvider>${updated.slice(childrenIndex + "{children}".length)}`;
|
|
199
|
+
}
|
|
200
|
+
return updated;
|
|
201
|
+
}
|
|
202
|
+
function updateRootLayoutWithAuthProvider(cwd) {
|
|
203
|
+
const layoutPath = path.join(cwd, "app", "layout.tsx");
|
|
204
|
+
if (!fs.existsSync(layoutPath)) {
|
|
205
|
+
throw new Error("app/layout.tsx was not found; cannot install AuthProvider");
|
|
206
|
+
}
|
|
207
|
+
const layout = fs.readFileSync(layoutPath, "utf-8");
|
|
208
|
+
const updated = addAuthProviderToRootLayout(layout);
|
|
209
|
+
if (updated !== layout)
|
|
210
|
+
fs.writeFileSync(layoutPath, updated, "utf-8");
|
|
211
|
+
}
|
|
212
|
+
function updateSwaRouteConfig(cwd) {
|
|
213
|
+
const configPath = path.join(cwd, "staticwebapp.config.json");
|
|
214
|
+
const config = fs.existsSync(configPath) ? JSON.parse(fs.readFileSync(configPath, "utf-8")) : {};
|
|
215
|
+
config.routes = Array.isArray(config.routes)
|
|
216
|
+
? config.routes.filter((route) => route.route !== "/api/*")
|
|
217
|
+
: [];
|
|
218
|
+
config.routes.unshift({ route: "/api/*", allowedRoles: ["authenticated"] });
|
|
219
|
+
config.responseOverrides = { ...(config.responseOverrides || {}), "401": { statusCode: 302, redirect: "/.auth/login/aad?post_login_redirect_uri=.referrer" } };
|
|
220
|
+
fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
|
|
221
|
+
}
|
|
222
|
+
async function addAuthCommand(options) {
|
|
223
|
+
(0, config_1.ensureSwallowKitProject)("add-auth");
|
|
224
|
+
console.log(" SwallowKit Add-Auth: Setting up authentication...\n");
|
|
225
|
+
const provider = (options.provider || "custom-jwt");
|
|
226
|
+
if (!["custom-jwt", "swa", "external-token", "swa-custom", "none"].includes(provider)) {
|
|
227
|
+
console.error(` Unknown provider: ${provider}. Use: custom-jwt | swa | external-token | swa-custom | none`);
|
|
228
|
+
process.exit(1);
|
|
229
|
+
}
|
|
230
|
+
const backendLanguage = (0, config_1.getBackendLanguage)();
|
|
231
|
+
const config = (0, config_1.getValidatedFullConfig)();
|
|
232
|
+
const cwd = process.cwd();
|
|
233
|
+
if (options.scheme) {
|
|
234
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(options.scheme))
|
|
235
|
+
throw new Error("--scheme must start with a letter and contain only letters, digits, '_' or '-'");
|
|
236
|
+
if (provider === "none" || provider === "swa-custom")
|
|
237
|
+
throw new Error(`Provider '${provider}' cannot be added as a named scheme`);
|
|
238
|
+
addNamedScheme(cwd, options.scheme, provider, backendLanguage);
|
|
239
|
+
await (0, manifest_1.syncProjectManifest)();
|
|
240
|
+
console.log(`\n Named authentication scheme '${options.scheme}' added.`);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (provider === "swa-custom") {
|
|
244
|
+
throw new Error("The swa-custom provider is not implemented. Use --provider swa or --provider custom-jwt.");
|
|
245
|
+
}
|
|
246
|
+
if (provider === "none") {
|
|
247
|
+
updateConfigWithAuth(cwd, provider, config.auth?.customJwt || defaultCustomJwtConfig());
|
|
248
|
+
await (0, manifest_1.syncProjectManifest)();
|
|
249
|
+
console.log(" Authentication disabled in swallowkit.config.js");
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (provider === "swa") {
|
|
253
|
+
setupSwaAuth(cwd, backendLanguage);
|
|
254
|
+
updateConfigWithAuth(cwd, provider, config.auth?.customJwt || defaultCustomJwtConfig());
|
|
255
|
+
await (0, manifest_1.syncProjectManifest)();
|
|
256
|
+
console.log("\n SWA built-in authentication setup complete!");
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (provider === "external-token") {
|
|
260
|
+
setupExternalTokenAuth(cwd, backendLanguage);
|
|
261
|
+
updateConfigWithAuth(cwd, provider, config.auth?.customJwt || defaultCustomJwtConfig());
|
|
262
|
+
await (0, manifest_1.syncProjectManifest)();
|
|
263
|
+
console.log("\n External token authentication setup complete!");
|
|
264
|
+
console.log(" Implement the generated frontend adapter and backend verifier before use.");
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
// Read project name from package.json
|
|
268
|
+
const pkgPath = path.join(cwd, "package.json");
|
|
269
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
270
|
+
const projectName = pkg.name || "app";
|
|
271
|
+
// Read shared package name
|
|
272
|
+
const sharedPkgPath = path.join(cwd, "shared", "package.json");
|
|
273
|
+
let sharedPackageName = `@${projectName}/shared`;
|
|
274
|
+
if (fs.existsSync(sharedPkgPath)) {
|
|
275
|
+
const sharedPkg = JSON.parse(fs.readFileSync(sharedPkgPath, "utf-8"));
|
|
276
|
+
sharedPackageName = sharedPkg.name || sharedPackageName;
|
|
277
|
+
}
|
|
278
|
+
// Default custom-jwt config
|
|
279
|
+
const customJwtConfig = config.auth?.customJwt || defaultCustomJwtConfig();
|
|
280
|
+
// custom-jwt setup continues below.
|
|
281
|
+
// 1. Generate shared/models/auth.ts
|
|
282
|
+
console.log(" Generating auth models...");
|
|
283
|
+
const modelsDir = path.join(cwd, "shared", "models");
|
|
284
|
+
fs.mkdirSync(modelsDir, { recursive: true });
|
|
285
|
+
const authModelPath = path.join(modelsDir, "auth.ts");
|
|
286
|
+
fs.writeFileSync(authModelPath, (0, auth_generator_1.generateAuthModels)(), "utf-8");
|
|
287
|
+
console.log(` Created: shared/models/auth.ts`);
|
|
288
|
+
// Ensure shared package has build infrastructure (tsconfig, build script)
|
|
289
|
+
ensureSharedBuildInfrastructure(cwd);
|
|
290
|
+
// Update shared/index.ts to re-export auth
|
|
291
|
+
updateSharedIndex(cwd);
|
|
292
|
+
// Resolve RDB provider for dependency installation
|
|
293
|
+
const connDef = (0, config_1.getConnectorDefinition)(customJwtConfig.userConnector);
|
|
294
|
+
const rdbProvider = connDef?.provider ?? "mysql";
|
|
295
|
+
// 2. Generate Functions auth code
|
|
296
|
+
console.log("\n Generating auth functions...");
|
|
297
|
+
generateFunctionsAuth(cwd, backendLanguage, sharedPackageName, customJwtConfig);
|
|
298
|
+
// 3. Generate BFF auth routes
|
|
299
|
+
console.log("\n Generating BFF auth routes...");
|
|
300
|
+
generateBFFAuth(cwd, projectName, sharedPackageName);
|
|
301
|
+
// 4. Generate proxy
|
|
302
|
+
console.log("\n Generating proxy...");
|
|
303
|
+
const proxyPath = path.join(cwd, "proxy.ts");
|
|
304
|
+
fs.writeFileSync(proxyPath, (0, auth_generator_1.generateProxy)(projectName), "utf-8");
|
|
305
|
+
console.log(` Created: proxy.ts`);
|
|
306
|
+
// 5. Generate login page
|
|
307
|
+
console.log("\n Generating login page...");
|
|
308
|
+
const loginDir = path.join(cwd, "app", "login");
|
|
309
|
+
fs.mkdirSync(loginDir, { recursive: true });
|
|
310
|
+
fs.writeFileSync(path.join(loginDir, "page.tsx"), (0, auth_generator_1.generateLoginPage)(), "utf-8");
|
|
311
|
+
console.log(` Created: app/login/page.tsx`);
|
|
312
|
+
// 6. Generate auth context
|
|
313
|
+
console.log("\n Generating auth context...");
|
|
314
|
+
const authLibDir = path.join(cwd, "lib", "auth");
|
|
315
|
+
fs.mkdirSync(authLibDir, { recursive: true });
|
|
316
|
+
fs.writeFileSync(path.join(authLibDir, "auth-context.tsx"), (0, auth_generator_1.generateAuthContext)(), "utf-8");
|
|
317
|
+
console.log(`✅ Created: lib/auth/auth-context.tsx`);
|
|
318
|
+
// 7. Update callFunction with auth support
|
|
319
|
+
console.log("\n Updating callFunction with auth support...");
|
|
320
|
+
const callFnPath = path.join(cwd, "lib", "api", "call-function.ts");
|
|
321
|
+
const callFnDir = path.dirname(callFnPath);
|
|
322
|
+
fs.mkdirSync(callFnDir, { recursive: true });
|
|
323
|
+
fs.writeFileSync(callFnPath, (0, auth_generator_1.generateBFFCallFunctionWithAuth)(), "utf-8");
|
|
324
|
+
console.log(` Updated: lib/api/call-function.ts`);
|
|
325
|
+
// 8. Update swallowkit.config.js
|
|
326
|
+
console.log("\n Updating configuration...");
|
|
327
|
+
updateConfigWithAuth(cwd, provider, customJwtConfig);
|
|
328
|
+
// 9. Update environment files
|
|
329
|
+
console.log("\n Updating environment files...");
|
|
330
|
+
updateEnvironmentFiles(cwd);
|
|
331
|
+
// 10. Install dependencies
|
|
332
|
+
console.log("\n Installing auth dependencies...");
|
|
333
|
+
await installAuthDependencies(cwd, backendLanguage, rdbProvider);
|
|
334
|
+
await (0, manifest_1.syncProjectManifest)();
|
|
335
|
+
console.log("\n Authentication setup complete!");
|
|
336
|
+
console.log("\n Next steps:");
|
|
337
|
+
console.log(" 1. Review the generated files");
|
|
338
|
+
console.log(" 2. Set JWT_SECRET in functions/local.settings.json");
|
|
339
|
+
if (provider === "custom-jwt") {
|
|
340
|
+
console.log(" 3. Ensure your user database table matches the config");
|
|
341
|
+
console.log(" 4. Add authPolicy to your models for role-based access control:");
|
|
342
|
+
console.log(" export const authPolicy = { roles: ['admin'] };");
|
|
343
|
+
}
|
|
344
|
+
console.log(` 5. Run scaffold to regenerate functions with auth guards`);
|
|
345
|
+
}
|
|
346
|
+
function findObjectEnd(content, open) {
|
|
347
|
+
let depth = 0, quote = "";
|
|
348
|
+
for (let i = open; i < content.length; i++) {
|
|
349
|
+
const ch = content[i];
|
|
350
|
+
if (quote) {
|
|
351
|
+
if (ch === quote && content[i - 1] !== "\\")
|
|
352
|
+
quote = "";
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
if (ch === "'" || ch === '"' || ch === "`") {
|
|
356
|
+
quote = ch;
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
if (ch === "{")
|
|
360
|
+
depth++;
|
|
361
|
+
if (ch === "}" && --depth === 0)
|
|
362
|
+
return i;
|
|
363
|
+
}
|
|
364
|
+
return -1;
|
|
365
|
+
}
|
|
366
|
+
function updateConfigWithNamedScheme(cwd, scheme, provider) {
|
|
367
|
+
var _a, _b;
|
|
368
|
+
const jsPath = path.join(cwd, "swallowkit.config.js");
|
|
369
|
+
const jsonPath = path.join(cwd, "swallowkit.config.json");
|
|
370
|
+
const configPath = fs.existsSync(jsPath) ? jsPath : jsonPath;
|
|
371
|
+
if (!fs.existsSync(configPath))
|
|
372
|
+
throw new Error("swallowkit.config.js or swallowkit.config.json is required");
|
|
373
|
+
if (configPath.endsWith(".json")) {
|
|
374
|
+
const value = JSON.parse(fs.readFileSync(configPath, "utf-8"));
|
|
375
|
+
value.auth ?? (value.auth = {});
|
|
376
|
+
(_a = value.auth).schemes ?? (_a.schemes = {});
|
|
377
|
+
if (value.auth.schemes[scheme])
|
|
378
|
+
throw new Error(`auth.schemes.${scheme} already exists; no files were changed`);
|
|
379
|
+
value.auth.schemes[scheme] = provider === "custom-jwt" ? { provider, customJwt: defaultCustomJwtConfig() } : { provider };
|
|
380
|
+
(_b = value.auth).authorization ?? (_b.authorization = { defaultPolicy: "anonymous", policies: {} });
|
|
381
|
+
fs.writeFileSync(configPath, JSON.stringify(value, null, 2) + "\n", "utf-8");
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
let content = fs.readFileSync(configPath, "utf-8");
|
|
385
|
+
const authMatch = /\bauth\s*:\s*\{/.exec(content);
|
|
386
|
+
const customJwt = defaultCustomJwtConfig();
|
|
387
|
+
const entry = provider === "custom-jwt"
|
|
388
|
+
? `\n ${scheme}: { provider: 'custom-jwt', customJwt: ${JSON.stringify(customJwt)} },`
|
|
389
|
+
: `\n ${scheme}: { provider: '${provider}' },`;
|
|
390
|
+
if (!authMatch) {
|
|
391
|
+
const rootEnd = content.lastIndexOf("}");
|
|
392
|
+
const beforeRootEnd = content.slice(0, rootEnd).trimEnd();
|
|
393
|
+
const separator = beforeRootEnd.endsWith(",") || beforeRootEnd.endsWith("{") ? "" : ",";
|
|
394
|
+
content = `${beforeRootEnd}${separator}\n auth: {\n schemes: {${entry}\n },\n authorization: { defaultPolicy: 'anonymous', policies: {} },\n },\n${content.slice(rootEnd)}`;
|
|
395
|
+
}
|
|
396
|
+
else {
|
|
397
|
+
const authOpen = content.indexOf("{", authMatch.index);
|
|
398
|
+
const authEnd = findObjectEnd(content, authOpen);
|
|
399
|
+
const authBody = content.slice(authOpen + 1, authEnd);
|
|
400
|
+
const schemesMatch = /\bschemes\s*:\s*\{/.exec(authBody);
|
|
401
|
+
if (schemesMatch) {
|
|
402
|
+
const schemesOpen = authOpen + 1 + authBody.indexOf("{", schemesMatch.index);
|
|
403
|
+
const schemesEnd = findObjectEnd(content, schemesOpen);
|
|
404
|
+
const existing = content.slice(schemesOpen + 1, schemesEnd);
|
|
405
|
+
if (new RegExp(`(^|[,\\s])${scheme}\\s*:`).test(existing))
|
|
406
|
+
throw new Error(`auth.schemes.${scheme} already exists; no files were changed`);
|
|
407
|
+
content = content.slice(0, schemesEnd) + entry + "\n " + content.slice(schemesEnd);
|
|
408
|
+
}
|
|
409
|
+
else {
|
|
410
|
+
content = content.slice(0, authOpen + 1) + `\n schemes: {${entry}\n },` + content.slice(authOpen + 1);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
fs.writeFileSync(configPath, content, "utf-8");
|
|
414
|
+
}
|
|
415
|
+
function addNamedScheme(cwd, scheme, provider, language) {
|
|
416
|
+
// Validate/update config before creating files, so duplicate names stop safely.
|
|
417
|
+
updateConfigWithNamedScheme(cwd, scheme, provider);
|
|
418
|
+
const slug = scheme.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
|
|
419
|
+
if (language === "typescript") {
|
|
420
|
+
const dir = path.join(cwd, "functions", "src", "auth", "schemes", slug);
|
|
421
|
+
if (provider === "external-token")
|
|
422
|
+
writeIfMissing(path.join(dir, "verifier.ts"), (0, auth_generator_1.generateExternalTokenVerifierTS)());
|
|
423
|
+
else if (provider === "swa")
|
|
424
|
+
writeIfMissing(path.join(dir, "adapter.ts"), (0, auth_generator_1.generateSwaAuthHelperTS)());
|
|
425
|
+
else
|
|
426
|
+
writeIfMissing(path.join(dir, "jwt-helper.ts"), (0, auth_generator_1.generateJwtHelperTS)());
|
|
427
|
+
}
|
|
428
|
+
else if (language === "csharp") {
|
|
429
|
+
const dir = path.join(cwd, "functions", "Auth", "Schemes", slug);
|
|
430
|
+
if (provider === "external-token")
|
|
431
|
+
writeIfMissing(path.join(dir, "ExternalTokenVerifier.cs"), (0, auth_generator_1.generateNamedExternalTokenVerifierCSharp)(scheme));
|
|
432
|
+
else if (provider === "swa")
|
|
433
|
+
writeIfMissing(path.join(dir, "SwaAdapter.cs"), (0, auth_generator_1.generateSwaAuthHelperCSharp)());
|
|
434
|
+
else
|
|
435
|
+
writeIfMissing(path.join(dir, "JwtHelper.cs"), (0, auth_generator_1.generateJwtHelperCSharp)());
|
|
436
|
+
}
|
|
437
|
+
else {
|
|
438
|
+
const dir = path.join(cwd, "functions", "auth", "schemes", slug.replace(/-/g, "_"));
|
|
439
|
+
if (provider === "external-token")
|
|
440
|
+
writeIfMissing(path.join(dir, "verifier.py"), (0, auth_generator_1.generateNamedExternalTokenVerifierPython)(scheme));
|
|
441
|
+
else if (provider === "swa")
|
|
442
|
+
writeIfMissing(path.join(dir, "adapter.py"), (0, auth_generator_1.generateSwaAuthHelperPython)());
|
|
443
|
+
else
|
|
444
|
+
writeIfMissing(path.join(dir, "jwt_helper.py"), (0, auth_generator_1.generateJwtHelperPython)());
|
|
445
|
+
}
|
|
446
|
+
const clientDir = path.join(cwd, "lib", "auth", "schemes", slug);
|
|
447
|
+
if (provider === "external-token") {
|
|
448
|
+
writeIfMissing(path.join(clientDir, "token-adapter.ts"), (0, auth_generator_1.generateExternalTokenAdapter)());
|
|
449
|
+
writeIfMissing(path.join(clientDir, "authenticated-fetch.ts"), (0, auth_generator_1.generateAuthenticatedFetch)().replace("'./external-token-adapter'", "'./token-adapter'"));
|
|
450
|
+
writeIfMissing(path.join(clientDir, "auth-context.tsx"), (0, auth_generator_1.generateExternalTokenAuthContext)().replace(/external-token-adapter/g, "token-adapter"));
|
|
451
|
+
}
|
|
452
|
+
else if (provider === "swa") {
|
|
453
|
+
writeIfMissing(path.join(clientDir, "auth-context.tsx"), generateSwaAuthContext());
|
|
454
|
+
}
|
|
455
|
+
else if (provider === "custom-jwt") {
|
|
456
|
+
writeIfMissing(path.join(clientDir, "auth-context.tsx"), (0, auth_generator_1.generateAuthContext)());
|
|
457
|
+
}
|
|
458
|
+
const callFunctionPath = path.join(cwd, "lib", "api", "call-function.ts");
|
|
459
|
+
if (!fs.existsSync(callFunctionPath))
|
|
460
|
+
writeIfMissing(callFunctionPath, (0, auth_generator_1.generateBFFCallFunctionWithMultipleAuth)());
|
|
461
|
+
else {
|
|
462
|
+
const current = fs.readFileSync(callFunctionPath, "utf-8");
|
|
463
|
+
if (!current.includes("x-ms-client-principal") || !current.includes("fetchHeaders['Authorization']")) {
|
|
464
|
+
if (current.includes("SwallowKit BFF Call Function Helper"))
|
|
465
|
+
fs.writeFileSync(callFunctionPath, (0, auth_generator_1.generateBFFCallFunctionWithMultipleAuth)(), "utf-8");
|
|
466
|
+
else
|
|
467
|
+
console.warn(" Existing customized lib/api/call-function.ts was preserved. Ensure it forwards Bearer and SWA credentials without logging them.");
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Ensure the shared package has proper build infrastructure
|
|
473
|
+
* (tsconfig.json, build script, typescript devDependency).
|
|
474
|
+
* Required for `dev` command which runs `npm run --workspace=shared build`.
|
|
475
|
+
*/
|
|
476
|
+
function ensureSharedBuildInfrastructure(cwd) {
|
|
477
|
+
const sharedDir = path.join(cwd, "shared");
|
|
478
|
+
const pkgPath = path.join(sharedDir, "package.json");
|
|
479
|
+
if (!fs.existsSync(pkgPath))
|
|
480
|
+
return;
|
|
481
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
482
|
+
let updated = false;
|
|
483
|
+
// Ensure scripts.build exists
|
|
484
|
+
if (!pkg.scripts?.build) {
|
|
485
|
+
if (!pkg.scripts)
|
|
486
|
+
pkg.scripts = {};
|
|
487
|
+
pkg.scripts.build = "tsc";
|
|
488
|
+
pkg.scripts.watch = "tsc --watch";
|
|
489
|
+
updated = true;
|
|
490
|
+
}
|
|
491
|
+
// Ensure main points to compiled output
|
|
492
|
+
if (!pkg.main || pkg.main === "index.ts") {
|
|
493
|
+
pkg.main = "dist/index.js";
|
|
494
|
+
pkg.types = "dist/index.d.ts";
|
|
495
|
+
updated = true;
|
|
496
|
+
}
|
|
497
|
+
// Ensure typescript devDependency
|
|
498
|
+
if (!pkg.devDependencies?.typescript) {
|
|
499
|
+
if (!pkg.devDependencies)
|
|
500
|
+
pkg.devDependencies = {};
|
|
501
|
+
pkg.devDependencies.typescript = "^5.0.0";
|
|
502
|
+
updated = true;
|
|
503
|
+
}
|
|
504
|
+
if (updated) {
|
|
505
|
+
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), "utf-8");
|
|
506
|
+
console.log(` Updated: shared/package.json (added build infrastructure)`);
|
|
507
|
+
}
|
|
508
|
+
// Ensure tsconfig.json exists
|
|
509
|
+
const tsconfigPath = path.join(sharedDir, "tsconfig.json");
|
|
510
|
+
if (!fs.existsSync(tsconfigPath)) {
|
|
511
|
+
fs.writeFileSync(tsconfigPath, JSON.stringify((0, init_1.buildSharedTsConfig)(), null, 2), "utf-8");
|
|
512
|
+
console.log(` Created: shared/tsconfig.json`);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
function updateSharedIndex(cwd) {
|
|
516
|
+
const indexPath = path.join(cwd, "shared", "index.ts");
|
|
517
|
+
if (fs.existsSync(indexPath)) {
|
|
518
|
+
let content = fs.readFileSync(indexPath, "utf-8");
|
|
519
|
+
if (!content.includes("./models/auth")) {
|
|
520
|
+
content += `\nexport { LoginRequest, AuthUser, LoginResponse } from './models/auth';\n`;
|
|
521
|
+
fs.writeFileSync(indexPath, content, "utf-8");
|
|
522
|
+
console.log(` Updated: shared/index.ts`);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
else {
|
|
526
|
+
fs.writeFileSync(indexPath, `export { LoginRequest, AuthUser, LoginResponse } from './models/auth';\n`, "utf-8");
|
|
527
|
+
console.log(` Created: shared/index.ts`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
function generateFunctionsAuth(cwd, backendLanguage, sharedPackageName, config) {
|
|
531
|
+
const functionsDir = path.join(cwd, "functions");
|
|
532
|
+
// Resolve the RDB provider from the connector definition
|
|
533
|
+
const connDef = (0, config_1.getConnectorDefinition)(config.userConnector);
|
|
534
|
+
const provider = connDef?.provider ?? "mysql";
|
|
535
|
+
if (backendLanguage === "typescript") {
|
|
536
|
+
// Auth functions
|
|
537
|
+
const srcDir = path.join(functionsDir, "src");
|
|
538
|
+
fs.mkdirSync(srcDir, { recursive: true });
|
|
539
|
+
fs.writeFileSync(path.join(srcDir, "auth.ts"), (0, auth_generator_1.generateAuthFunctionsTS)(sharedPackageName, config, provider), "utf-8");
|
|
540
|
+
console.log(` Created: functions/src/auth.ts`);
|
|
541
|
+
// JWT helper
|
|
542
|
+
const authDir = path.join(srcDir, "auth");
|
|
543
|
+
fs.mkdirSync(authDir, { recursive: true });
|
|
544
|
+
fs.writeFileSync(path.join(authDir, "jwt-helper.ts"), (0, auth_generator_1.generateJwtHelperTS)(), "utf-8");
|
|
545
|
+
console.log(` Created: functions/src/auth/jwt-helper.ts`);
|
|
546
|
+
}
|
|
547
|
+
else if (backendLanguage === "csharp") {
|
|
548
|
+
const authDir = path.join(functionsDir, "Auth");
|
|
549
|
+
fs.mkdirSync(authDir, { recursive: true });
|
|
550
|
+
fs.writeFileSync(path.join(authDir, "AuthFunctions.cs"), (0, auth_generator_1.generateAuthFunctionsCSharp)(config, provider), "utf-8");
|
|
551
|
+
console.log(` Created: functions/Auth/AuthFunctions.cs`);
|
|
552
|
+
fs.writeFileSync(path.join(authDir, "JwtHelper.cs"), (0, auth_generator_1.generateJwtHelperCSharp)(), "utf-8");
|
|
553
|
+
console.log(` Created: functions/Auth/JwtHelper.cs`);
|
|
554
|
+
}
|
|
555
|
+
else if (backendLanguage === "python") {
|
|
556
|
+
const blueprintsDir = path.join(functionsDir, "blueprints");
|
|
557
|
+
fs.mkdirSync(blueprintsDir, { recursive: true });
|
|
558
|
+
fs.writeFileSync(path.join(blueprintsDir, "auth.py"), (0, auth_generator_1.generateAuthFunctionsPython)(config, provider), "utf-8");
|
|
559
|
+
console.log(` Created: functions/blueprints/auth.py`);
|
|
560
|
+
const authDir = path.join(functionsDir, "auth");
|
|
561
|
+
fs.mkdirSync(authDir, { recursive: true });
|
|
562
|
+
fs.writeFileSync(path.join(authDir, "jwt_helper.py"), (0, auth_generator_1.generateJwtHelperPython)(), "utf-8");
|
|
563
|
+
console.log(` Created: functions/auth/jwt_helper.py`);
|
|
564
|
+
// __init__.py
|
|
565
|
+
fs.writeFileSync(path.join(authDir, "__init__.py"), "", "utf-8");
|
|
566
|
+
// Register auth blueprint in function_app.py
|
|
567
|
+
const functionAppPath = path.join(functionsDir, "function_app.py");
|
|
568
|
+
if (fs.existsSync(functionAppPath)) {
|
|
569
|
+
const content = fs.readFileSync(functionAppPath, "utf-8");
|
|
570
|
+
const authImport = "from blueprints.auth import bp as auth_bp";
|
|
571
|
+
const authRegister = "app.register_blueprint(auth_bp)";
|
|
572
|
+
if (!content.includes(authImport)) {
|
|
573
|
+
const marker = "# SwallowKit scaffold registrations";
|
|
574
|
+
if (content.includes(marker)) {
|
|
575
|
+
const updated = content.replace(marker, `${authImport}\n${authRegister}\n${marker}`);
|
|
576
|
+
fs.writeFileSync(functionAppPath, updated, "utf-8");
|
|
577
|
+
console.log(` Updated: functions/function_app.py (registered auth blueprint)`);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
function generateBFFAuth(cwd, projectName, sharedPackageName) {
|
|
584
|
+
const authApiDir = path.join(cwd, "app", "api", "auth");
|
|
585
|
+
// Login route
|
|
586
|
+
const loginDir = path.join(authApiDir, "login");
|
|
587
|
+
fs.mkdirSync(loginDir, { recursive: true });
|
|
588
|
+
fs.writeFileSync(path.join(loginDir, "route.ts"), (0, auth_generator_1.generateBFFAuthLoginRoute)(projectName, sharedPackageName), "utf-8");
|
|
589
|
+
console.log(` Created: app/api/auth/login/route.ts`);
|
|
590
|
+
// Logout route
|
|
591
|
+
const logoutDir = path.join(authApiDir, "logout");
|
|
592
|
+
fs.mkdirSync(logoutDir, { recursive: true });
|
|
593
|
+
fs.writeFileSync(path.join(logoutDir, "route.ts"), (0, auth_generator_1.generateBFFAuthLogoutRoute)(projectName), "utf-8");
|
|
594
|
+
console.log(` Created: app/api/auth/logout/route.ts`);
|
|
595
|
+
// Me route
|
|
596
|
+
const meDir = path.join(authApiDir, "me");
|
|
597
|
+
fs.mkdirSync(meDir, { recursive: true });
|
|
598
|
+
fs.writeFileSync(path.join(meDir, "route.ts"), (0, auth_generator_1.generateBFFAuthMeRoute)(), "utf-8");
|
|
599
|
+
console.log(` Created: app/api/auth/me/route.ts`);
|
|
600
|
+
}
|
|
601
|
+
function updateConfigWithAuth(cwd, provider, config) {
|
|
602
|
+
const configPath = path.join(cwd, "swallowkit.config.js");
|
|
603
|
+
if (!fs.existsSync(configPath)) {
|
|
604
|
+
console.warn(" swallowkit.config.js not found. Please add auth config manually.");
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
const content = fs.readFileSync(configPath, "utf-8");
|
|
608
|
+
if (content.includes("auth:") || content.includes("auth :")) {
|
|
609
|
+
console.log(" 'auth' section already exists in swallowkit.config.js");
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
// Find the last property before the closing of module.exports
|
|
613
|
+
const closingBraceIdx = content.lastIndexOf("}");
|
|
614
|
+
if (closingBraceIdx === -1) {
|
|
615
|
+
console.error(" Could not parse config file structure.");
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
const beforeClosing = content.substring(0, closingBraceIdx).trimEnd();
|
|
619
|
+
const needsComma = !beforeClosing.endsWith(",") && !beforeClosing.endsWith("{");
|
|
620
|
+
const providerSettings = provider === "custom-jwt" ? `
|
|
621
|
+
customJwt: {
|
|
622
|
+
userConnector: '${config.userConnector}',
|
|
623
|
+
userTable: '${config.userTable}',
|
|
624
|
+
loginIdColumn: '${config.loginIdColumn}',
|
|
625
|
+
passwordHashColumn: '${config.passwordHashColumn}',
|
|
626
|
+
rolesColumn: '${config.rolesColumn}',
|
|
627
|
+
jwtSecretEnv: '${config.jwtSecretEnv || "JWT_SECRET"}',
|
|
628
|
+
tokenExpiry: '${config.tokenExpiry || "24h"}',
|
|
629
|
+
},` : provider === "swa" ? `
|
|
630
|
+
swa: {
|
|
631
|
+
allowedProviders: ['aad'],
|
|
632
|
+
roleSource: 'swa-roles',
|
|
633
|
+
},` : "";
|
|
634
|
+
const authBlock = `${needsComma ? "," : ""}
|
|
635
|
+
// 認証認可設定
|
|
636
|
+
auth: {
|
|
637
|
+
provider: '${provider}',
|
|
638
|
+
${providerSettings}
|
|
639
|
+
authorization: {
|
|
640
|
+
defaultPolicy: 'authenticated',
|
|
641
|
+
},
|
|
642
|
+
},
|
|
643
|
+
`;
|
|
644
|
+
const newContent = content.substring(0, closingBraceIdx) + authBlock + content.substring(closingBraceIdx);
|
|
645
|
+
fs.writeFileSync(configPath, newContent, "utf-8");
|
|
646
|
+
console.log(` Updated: swallowkit.config.js`);
|
|
647
|
+
}
|
|
648
|
+
function updateEnvironmentFiles(cwd) {
|
|
649
|
+
// Update functions/local.settings.json
|
|
650
|
+
const localSettingsPath = path.join(cwd, "functions", "local.settings.json");
|
|
651
|
+
if (fs.existsSync(localSettingsPath)) {
|
|
652
|
+
const settings = JSON.parse(fs.readFileSync(localSettingsPath, "utf-8"));
|
|
653
|
+
if (!settings.Values)
|
|
654
|
+
settings.Values = {};
|
|
655
|
+
if (!settings.Values.JWT_SECRET) {
|
|
656
|
+
settings.Values.JWT_SECRET = "dev-jwt-secret-change-in-production-min-32-chars!!";
|
|
657
|
+
}
|
|
658
|
+
fs.writeFileSync(localSettingsPath, JSON.stringify(settings, null, 2), "utf-8");
|
|
659
|
+
console.log(` Updated: functions/local.settings.json`);
|
|
660
|
+
}
|
|
661
|
+
// Update .env.example
|
|
662
|
+
const envExamplePath = path.join(cwd, ".env.example");
|
|
663
|
+
if (fs.existsSync(envExamplePath)) {
|
|
664
|
+
let content = fs.readFileSync(envExamplePath, "utf-8");
|
|
665
|
+
if (!content.includes("JWT_SECRET")) {
|
|
666
|
+
content += "\n# Authentication\nJWT_SECRET=your-jwt-secret-key-at-least-32-chars\n";
|
|
667
|
+
fs.writeFileSync(envExamplePath, content, "utf-8");
|
|
668
|
+
console.log(` Updated: .env.example`);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
async function installAuthDependencies(cwd, backendLanguage, provider = "mysql") {
|
|
673
|
+
if (backendLanguage === "typescript") {
|
|
674
|
+
const funcPkgPath = path.join(cwd, "functions", "package.json");
|
|
675
|
+
if (fs.existsSync(funcPkgPath)) {
|
|
676
|
+
const funcPkg = JSON.parse(fs.readFileSync(funcPkgPath, "utf-8"));
|
|
677
|
+
if (!funcPkg.dependencies)
|
|
678
|
+
funcPkg.dependencies = {};
|
|
679
|
+
funcPkg.dependencies["jsonwebtoken"] = "^9.0.0";
|
|
680
|
+
funcPkg.dependencies["bcryptjs"] = "^2.4.3";
|
|
681
|
+
// RDB driver based on provider
|
|
682
|
+
if (provider === "mysql")
|
|
683
|
+
funcPkg.dependencies["mysql2"] = "^3.11.0";
|
|
684
|
+
else if (provider === "postgres")
|
|
685
|
+
funcPkg.dependencies["pg"] = "^8.13.0";
|
|
686
|
+
else
|
|
687
|
+
funcPkg.dependencies["mssql"] = "^11.0.0";
|
|
688
|
+
if (!funcPkg.devDependencies)
|
|
689
|
+
funcPkg.devDependencies = {};
|
|
690
|
+
funcPkg.devDependencies["@types/jsonwebtoken"] = "^9.0.0";
|
|
691
|
+
funcPkg.devDependencies["@types/bcryptjs"] = "^2.4.0";
|
|
692
|
+
if (provider === "postgres")
|
|
693
|
+
funcPkg.devDependencies["@types/pg"] = "^8.11.0";
|
|
694
|
+
fs.writeFileSync(funcPkgPath, JSON.stringify(funcPkg, null, 2), "utf-8");
|
|
695
|
+
console.log(` Updated: functions/package.json with auth dependencies (${provider})`);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
else if (backendLanguage === "csharp") {
|
|
699
|
+
// Add NuGet package references to .csproj
|
|
700
|
+
const functionsDir = path.join(cwd, "functions");
|
|
701
|
+
const csprojFiles = fs.readdirSync(functionsDir).filter((f) => f.endsWith(".csproj"));
|
|
702
|
+
if (csprojFiles.length > 0) {
|
|
703
|
+
const csprojPath = path.join(functionsDir, csprojFiles[0]);
|
|
704
|
+
let csprojContent = fs.readFileSync(csprojPath, "utf-8");
|
|
705
|
+
const nugetPackages = [
|
|
706
|
+
{ name: "System.IdentityModel.Tokens.Jwt", version: "7.0.0" },
|
|
707
|
+
{ name: "Microsoft.IdentityModel.Tokens", version: "7.0.0" },
|
|
708
|
+
{ name: "BCrypt.Net-Next", version: "4.0.3" },
|
|
709
|
+
];
|
|
710
|
+
// RDB driver based on provider
|
|
711
|
+
if (provider === "mysql")
|
|
712
|
+
nugetPackages.push({ name: "MySqlConnector", version: "2.3.0" });
|
|
713
|
+
else if (provider === "postgres")
|
|
714
|
+
nugetPackages.push({ name: "Npgsql", version: "8.0.0" });
|
|
715
|
+
else
|
|
716
|
+
nugetPackages.push({ name: "Microsoft.Data.SqlClient", version: "5.2.0" });
|
|
717
|
+
for (const pkg of nugetPackages) {
|
|
718
|
+
if (!csprojContent.includes(`"${pkg.name}"`)) {
|
|
719
|
+
const insertPoint = csprojContent.lastIndexOf("</ItemGroup>");
|
|
720
|
+
if (insertPoint >= 0) {
|
|
721
|
+
csprojContent =
|
|
722
|
+
csprojContent.slice(0, insertPoint) +
|
|
723
|
+
` <PackageReference Include="${pkg.name}" Version="${pkg.version}" />\n ` +
|
|
724
|
+
csprojContent.slice(insertPoint);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
fs.writeFileSync(csprojPath, csprojContent, "utf-8");
|
|
729
|
+
console.log(` Updated: ${csprojFiles[0]} with auth NuGet packages (${provider})`);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
else if (backendLanguage === "python") {
|
|
733
|
+
// Add Python dependencies to requirements.txt
|
|
734
|
+
const requirementsPath = path.join(cwd, "functions", "requirements.txt");
|
|
735
|
+
const baseDeps = ["PyJWT>=2.8.0", "bcrypt>=4.1.0"];
|
|
736
|
+
// RDB driver based on provider
|
|
737
|
+
if (provider === "mysql")
|
|
738
|
+
baseDeps.push("mysql-connector-python>=8.3.0");
|
|
739
|
+
else if (provider === "postgres")
|
|
740
|
+
baseDeps.push("psycopg2-binary>=2.9.0");
|
|
741
|
+
else
|
|
742
|
+
baseDeps.push("pymssql>=2.2.0");
|
|
743
|
+
if (fs.existsSync(requirementsPath)) {
|
|
744
|
+
let content = fs.readFileSync(requirementsPath, "utf-8");
|
|
745
|
+
for (const dep of baseDeps) {
|
|
746
|
+
const pkgName = dep.split(">=")[0].split("==")[0];
|
|
747
|
+
if (!content.includes(pkgName)) {
|
|
748
|
+
content += `${dep}\n`;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
fs.writeFileSync(requirementsPath, content, "utf-8");
|
|
752
|
+
}
|
|
753
|
+
else {
|
|
754
|
+
fs.writeFileSync(requirementsPath, baseDeps.join("\n") + "\n", "utf-8");
|
|
755
|
+
}
|
|
756
|
+
console.log(` Updated: functions/requirements.txt with auth dependencies`);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
//# sourceMappingURL=add-auth.js.map
|