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