swallowkit 1.0.0-beta.5 → 1.0.0-beta.51

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 +73 -0
  33. package/dist/cli/commands/init.d.ts.map +1 -1
  34. package/dist/cli/commands/init.js +3089 -1779
  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 +356 -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,1760 @@
1
+ /**
2
+ * SwallowKit 認証・認可コード生成
3
+ * add-auth コマンドおよび scaffold ロールガード挿入で使用するテンプレート群
4
+ */
5
+
6
+ import { AuthProvider, CustomJwtConfig, ModelAuthPolicy, NormalizedAuthConfig, RdbConnectorConfig } from "../../types";
7
+
8
+ type RdbProvider = RdbConnectorConfig["provider"]; // "mysql" | "postgres" | "sqlserver"
9
+
10
+ export function generateNamedAuthRouterTS(config: NormalizedAuthConfig): string {
11
+ const external = Object.entries(config.schemes).filter(([, s]) => s.provider === "external-token");
12
+ const custom = Object.entries(config.schemes).filter(([, s]) => s.provider === "custom-jwt");
13
+ const imports = external.map(([name]) => {
14
+ const slug = name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
15
+ const id = safeIdentifier(name);
16
+ return `import { verifyExternalToken as verify_${id}, ExternalTokenVerificationError as Error_${id} } from './schemes/${slug}/verifier';`;
17
+ }).concat(custom.map(([name]) => {
18
+ const slug = name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
19
+ return `import { requireAuth as verify_${safeIdentifier(name)} } from './schemes/${slug}/jwt-helper';`;
20
+ })).join("\n");
21
+ const verifiers = external.map(([name]) => { const id = safeIdentifier(name); return `${JSON.stringify(name)}: async (token: string) => { try { return await verify_${id}(token); } catch (e) { if (e instanceof Error_${id}) throw new AuthError(e.status, e.message); throw e; } }`; }).join(",\n ");
22
+ return `import type { HttpRequest, HttpResponseInit } from '@azure/functions';
23
+ ${imports}
24
+ export type AuthPrincipal = { subject: string; scheme: string; issuer: string; roles: string[]; claims: Record<string, unknown>; /** @deprecated */ userId?: string; /** @deprecated */ userDetails?: string };
25
+ export class AuthError extends Error { constructor(public status: 401 | 403 | 503, message: string) { super(message); } }
26
+ const schemes = ${JSON.stringify(Object.fromEntries(Object.entries(config.schemes).map(([n,s]) => [n,{provider:s.provider,allowedProviders:s.swa?.allowedProviders??[]}])))} as const;
27
+ const policies = ${JSON.stringify(config.authorization.policies)} as Record<string, { schemes: string[]; roles?: string[] }>;
28
+ const externalVerifiers: Record<string, (token: string) => Promise<any>> = { ${verifiers} };
29
+ const customVerifiers: Record<string, (request: HttpRequest) => any> = { ${custom.map(([name]) => `${JSON.stringify(name)}: verify_${safeIdentifier(name)}`).join(", ")} };
30
+ function swa(request: HttpRequest, scheme: string): AuthPrincipal {
31
+ const encoded = request.headers.get('x-ms-client-principal');
32
+ if (!encoded) throw new AuthError(401, 'Authentication required');
33
+ try { const value = JSON.parse(Buffer.from(encoded, 'base64').toString('utf8')) as Record<string, unknown>;
34
+ const roles = Array.isArray(value.userRoles) ? value.userRoles.filter((r): r is string => typeof r === 'string') : [];
35
+ if (typeof value.userId !== 'string' || !value.userId || !roles.includes('authenticated')) throw new Error();
36
+ const allowed = (schemes as any)[scheme]?.allowedProviders as string[] | undefined;
37
+ if (allowed?.length && (typeof value.identityProvider !== 'string' || !allowed.includes(value.identityProvider))) throw new Error();
38
+ return { subject: value.userId, scheme, issuer: typeof value.identityProvider === 'string' ? 'swa:' + value.identityProvider : 'swa', roles, claims: value, userId: value.userId, userDetails: typeof value.userDetails === 'string' ? value.userDetails : undefined };
39
+ } catch (e) { if (e instanceof AuthError) throw e; throw new AuthError(401, 'Invalid SWA client principal'); }
40
+ }
41
+ export async function requireAuth(request: HttpRequest, policyName: string): Promise<AuthPrincipal> {
42
+ const policy = policies[policyName]; if (!policy) throw new AuthError(401, 'Undefined authorization policy');
43
+ const bearer = request.headers.get('authorization'); const hasSwa = Boolean(request.headers.get('x-ms-client-principal'));
44
+ const candidates = policy.schemes.filter(name => { const p=(schemes as any)[name]?.provider; return p === 'swa' ? hasSwa : (p === 'external-token' || p === 'custom-jwt') ? Boolean(bearer?.startsWith('Bearer ')) : false; });
45
+ if (candidates.length !== 1) throw new AuthError(401, candidates.length ? 'Ambiguous credentials' : 'Authentication required');
46
+ const scheme = candidates[0]; const provider = (schemes as any)[scheme]?.provider; let principal: AuthPrincipal;
47
+ if (provider === 'swa') principal = swa(request, scheme);
48
+ else if (provider === 'external-token') { const token=bearer!.slice(7); try { const p=await externalVerifiers[scheme](token); const subject=p?.subject ?? p?.userId; if (typeof subject !== 'string' || !subject || !Array.isArray(p.roles)) throw new AuthError(401,'Invalid external principal'); principal={subject,scheme,issuer:typeof p.issuer==='string'?p.issuer:scheme,roles:p.roles,claims:p.claims && typeof p.claims==='object'?p.claims:p,userId:subject,userDetails:p.userDetails}; } catch(e) { if(e instanceof AuthError) throw e; throw new AuthError(503,'Identity provider unavailable'); } }
49
+ else if (provider === 'custom-jwt') { try { const p=customVerifiers[scheme](request); const subject=p?.sub ?? p?.userId; if(typeof subject !== 'string' || !subject || !Array.isArray(p.roles)) throw new Error(); principal={subject,scheme,issuer:scheme,roles:p.roles,claims:p,userId:subject,userDetails:p.loginId}; } catch { throw new AuthError(401,'Invalid or expired token'); } }
50
+ else throw new AuthError(401, 'Authentication adapter is not configured');
51
+ requireRoles(principal, policy.roles || []); return principal;
52
+ }
53
+ export function requireRoles(principal: AuthPrincipal, roles: string[]): void { if (roles.length && !roles.some(r => principal.roles.includes(r))) throw new AuthError(403, 'Insufficient permissions'); }
54
+ export function identityKey(principal: AuthPrincipal): string { return principal.scheme + ':' + principal.subject; }
55
+ export function handleAuthError(error: unknown): HttpResponseInit | null { return error instanceof AuthError ? { status:error.status, jsonBody:{error:error.message} } : null; }
56
+ `;
57
+ }
58
+
59
+ function safeIdentifier(name: string): string {
60
+ return name.replace(/[^A-Za-z0-9_]/g, "_");
61
+ }
62
+
63
+ function schemeSlug(name: string): string {
64
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/_/g, "-").toLowerCase();
65
+ }
66
+
67
+ export function generateNamedExternalTokenVerifierCSharp(scheme: string): string {
68
+ const id = safeIdentifier(scheme);
69
+ return `namespace Functions.Auth.Schemes;
70
+ public record ExternalPrincipal_${id}(string Subject, string Issuer, string[] Roles, IReadOnlyDictionary<string, object?> Claims);
71
+ public sealed class ExternalTokenVerificationException_${id} : Exception
72
+ {
73
+ public bool IsIdentityProviderUnavailable { get; }
74
+ public ExternalTokenVerificationException_${id}(string message, bool unavailable = false) : base(message) => IsIdentityProviderUnavailable = unavailable;
75
+ }
76
+ public static class ExternalTokenVerifier_${id}
77
+ {
78
+ // Validate signature, issuer, audience and expiry. This stub deliberately fails closed.
79
+ public static Task<ExternalPrincipal_${id}> VerifyAsync(string token) => throw new InvalidOperationException("External token verifier for ${scheme} is not configured");
80
+ }
81
+ `;
82
+ }
83
+
84
+ export function generateNamedExternalTokenVerifierPython(scheme: string): string {
85
+ return `class ExternalTokenVerificationError(Exception):
86
+ def __init__(self, message: str, identity_provider_unavailable: bool = False):
87
+ super().__init__(message)
88
+ self.identity_provider_unavailable = identity_provider_unavailable
89
+
90
+ def verify_external_token(token: str) -> dict:
91
+ # Validate signature, issuer, audience and expiry. This stub deliberately fails closed.
92
+ raise RuntimeError("External token verifier for ${scheme} is not configured")
93
+ `;
94
+ }
95
+
96
+ export function generateNamedAuthRouterCSharp(config: NormalizedAuthConfig): string {
97
+ const externalCases = Object.entries(config.schemes).filter(([,s]) => s.provider === "external-token").map(([name]) => {
98
+ const id = safeIdentifier(name);
99
+ return ` case "${name}":
100
+ try
101
+ {
102
+ var external = await ExternalTokenVerifier_${id}.VerifyAsync(bearer!);
103
+ principal = new AuthPrincipal(external.Subject, "${name}", external.Issuer, external.Roles, external.Claims);
104
+ }
105
+ catch (ExternalTokenVerificationException_${id} ex) when (ex.IsIdentityProviderUnavailable) { return (null, await Error(request, HttpStatusCode.ServiceUnavailable, "Identity provider unavailable")); }
106
+ catch (ExternalTokenVerificationException_${id}) { return (null, await Error(request, HttpStatusCode.Unauthorized, "Invalid token")); }
107
+ catch { return (null, await Error(request, HttpStatusCode.ServiceUnavailable, "External token verifier unavailable")); }
108
+ break;`;
109
+ }).join("\n");
110
+ return `using System.Net;
111
+ using System.Text;
112
+ using System.Text.Json;
113
+ using Microsoft.Azure.Functions.Worker.Http;
114
+ using Functions.Auth.Schemes;
115
+ namespace Functions.Auth;
116
+ public record AuthPrincipal(string Subject, string Scheme, string Issuer, string[] Roles, IReadOnlyDictionary<string, object?> Claims)
117
+ {
118
+ [Obsolete("Use Subject")] public string UserId => Subject;
119
+ public string IdentityKey => $"{Scheme}:{Subject}";
120
+ }
121
+ public static class AuthRouter
122
+ {
123
+ private static readonly Dictionary<string, (string[] Schemes, string[] Roles)> Policies = new()
124
+ {
125
+ ${Object.entries(config.authorization.policies).map(([n,p]) => ` ["${n}"] = (new[] { ${p.schemes.map(s=>`"${s}"`).join(", ")} }, new[] { ${(p.roles??[]).map(r=>`"${r}"`).join(", ")} }),`).join("\n")}
126
+ };
127
+ private static readonly Dictionary<string,string> Providers = new() { ${Object.entries(config.schemes).map(([n,s])=>`["${n}"]="${s.provider}"`).join(", ")} };
128
+ private static readonly Dictionary<string,string[]> AllowedProviders = new() { ${Object.entries(config.schemes).map(([n,s])=>`["${n}"]=new[] { ${(s.swa?.allowedProviders??[]).map(p=>`"${p}"`).join(", ")} }`).join(", ")} };
129
+ public static async Task<(AuthPrincipal? Principal, HttpResponseData? ErrorResponse)> Authorize(HttpRequestData request, string policyName)
130
+ {
131
+ if (!Policies.TryGetValue(policyName, out var policy)) return (null, await Error(request, HttpStatusCode.Unauthorized, "Undefined authorization policy"));
132
+ var bearerHeader = request.Headers.TryGetValues("Authorization", out var authValues) ? authValues.FirstOrDefault() : null;
133
+ var bearer = bearerHeader?.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) == true ? bearerHeader[7..] : null;
134
+ var swa = request.Headers.TryGetValues("x-ms-client-principal", out var swaValues) ? swaValues.FirstOrDefault() : null;
135
+ var candidates = policy.Schemes.Where(s => Providers[s] == "swa" ? swa != null : Providers[s] is "external-token" or "custom-jwt" ? bearer != null : false).ToArray();
136
+ if (candidates.Length != 1) return (null, await Error(request, HttpStatusCode.Unauthorized, candidates.Length == 0 ? "Authentication required" : "Ambiguous credentials"));
137
+ var scheme = candidates[0]; AuthPrincipal principal;
138
+ switch (scheme)
139
+ {
140
+ ${externalCases}
141
+ default:
142
+ if (Providers[scheme] != "swa") return (null, await Error(request, HttpStatusCode.Unauthorized, "Authentication adapter is not configured"));
143
+ try
144
+ {
145
+ using var doc = JsonDocument.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(swa!)));
146
+ var root = doc.RootElement; var subject = root.GetProperty("userId").GetString();
147
+ var roles = root.TryGetProperty("userRoles", out var rv) ? rv.EnumerateArray().Where(v=>v.ValueKind==JsonValueKind.String).Select(v=>v.GetString()!).ToArray() : Array.Empty<string>();
148
+ if (string.IsNullOrEmpty(subject) || !roles.Contains("authenticated")) throw new InvalidOperationException();
149
+ var identityProvider = root.TryGetProperty("identityProvider", out var iv) ? iv.GetString() : null;
150
+ if (AllowedProviders[scheme].Length > 0 && (identityProvider == null || !AllowedProviders[scheme].Contains(identityProvider))) throw new InvalidOperationException();
151
+ var issuer = identityProvider == null ? "swa" : "swa:" + identityProvider;
152
+ principal = new AuthPrincipal(subject!, scheme, issuer, roles, new Dictionary<string,object?> { ["clientPrincipal"] = root.Clone() });
153
+ }
154
+ catch { return (null, await Error(request, HttpStatusCode.Unauthorized, "Invalid SWA client principal")); }
155
+ break;
156
+ }
157
+ if (policy.Roles.Length > 0 && !policy.Roles.Any(principal.Roles.Contains)) return (null, await Error(request, HttpStatusCode.Forbidden, "Insufficient permissions"));
158
+ return (principal, null);
159
+ }
160
+ private static async Task<HttpResponseData> Error(HttpRequestData request, HttpStatusCode status, string message) { var response=request.CreateResponse(status); await response.WriteAsJsonAsync(new { error=message }); return response; }
161
+ }
162
+ `;
163
+ }
164
+
165
+ export function generateNamedAuthRouterPython(config: NormalizedAuthConfig): string {
166
+ const external = Object.entries(config.schemes).filter(([,s])=>s.provider === "external-token");
167
+ const imports = external.map(([n])=>`from auth.schemes.${schemeSlug(n).replace(/-/g,"_")}.verifier import verify_external_token as verify_${safeIdentifier(n)}, ExternalTokenVerificationError as Error_${safeIdentifier(n)}`).join("\n");
168
+ const cases = external.map(([n], index)=>` ${index === 0 ? "if" : "elif"} scheme == ${JSON.stringify(n)}:
169
+ try:
170
+ value = verify_${safeIdentifier(n)}(bearer)
171
+ except Error_${safeIdentifier(n)} as exc:
172
+ raise AuthError(503 if exc.identity_provider_unavailable else 401, "Identity provider unavailable" if exc.identity_provider_unavailable else "Invalid token")
173
+ except Exception:
174
+ raise AuthError(503, "External token verifier unavailable")
175
+ if not value.get("subject") or not isinstance(value.get("roles"), list): raise AuthError(401, "Invalid external principal")
176
+ principal = {"subject": value["subject"], "scheme": scheme, "issuer": value.get("issuer", scheme), "roles": value["roles"], "claims": value.get("claims", {}), "userId": value["subject"]}`).join("\n");
177
+ return `import base64
178
+ import json
179
+ import azure.functions as func
180
+ ${imports}
181
+ POLICIES = ${JSON.stringify(config.authorization.policies)}
182
+ PROVIDERS = ${JSON.stringify(Object.fromEntries(Object.entries(config.schemes).map(([n,s])=>[n,s.provider])))}
183
+ ALLOWED_PROVIDERS = ${JSON.stringify(Object.fromEntries(Object.entries(config.schemes).map(([n,s])=>[n,s.swa?.allowedProviders??[]])))}
184
+ class AuthError(Exception):
185
+ def __init__(self, status, message): self.status, self.message = status, message
186
+ def require_auth(req: func.HttpRequest, policy_name: str):
187
+ policy = POLICIES.get(policy_name)
188
+ if not policy: raise AuthError(401, "Undefined authorization policy")
189
+ header = req.headers.get("authorization", "")
190
+ bearer = header[7:] if header.lower().startswith("bearer ") else None
191
+ swa = req.headers.get("x-ms-client-principal")
192
+ candidates = [s for s in policy["schemes"] if (PROVIDERS[s] == "swa" and swa) or (PROVIDERS[s] in ("external-token", "custom-jwt") and bearer)]
193
+ if len(candidates) != 1: raise AuthError(401, "Authentication required" if not candidates else "Ambiguous credentials")
194
+ scheme = candidates[0]
195
+ ${cases}
196
+ ${external.length ? "elif" : "if"} PROVIDERS[scheme] == "swa":
197
+ try:
198
+ value=json.loads(base64.b64decode(swa).decode("utf-8")); roles=[r for r in value.get("userRoles",[]) if isinstance(r,str)]
199
+ if not value.get("userId") or "authenticated" not in roles: raise ValueError()
200
+ if ALLOWED_PROVIDERS[scheme] and value.get("identityProvider") not in ALLOWED_PROVIDERS[scheme]: raise ValueError()
201
+ principal={"subject":value["userId"],"scheme":scheme,"issuer":"swa:"+value.get("identityProvider", "unknown"),"roles":roles,"claims":value,"userId":value["userId"]}
202
+ except Exception: raise AuthError(401,"Invalid SWA client principal")
203
+ else: raise AuthError(401,"Authentication adapter is not configured")
204
+ require_roles(principal, policy.get("roles", [])); return principal
205
+ def require_roles(principal, roles):
206
+ if roles and not any(role in principal.get("roles",[]) for role in roles): raise AuthError(403,"Insufficient permissions")
207
+ def identity_key(principal): return principal["scheme"] + ":" + principal["subject"]
208
+ def handle_auth_error(error): return func.HttpResponse(json.dumps({"error":error.message}),status_code=error.status,mimetype="application/json") if isinstance(error,AuthError) else None
209
+ `;
210
+ }
211
+
212
+ // ============================================================
213
+ // 1. shared/models/auth.ts(Zod スキーマ)
214
+ // ============================================================
215
+
216
+ export function generateAuthModels(): string {
217
+ return `import { z } from 'zod/v4';
218
+
219
+ // ログインリクエスト
220
+ export const LoginRequest = z.object({
221
+ loginId: z.string().min(1),
222
+ password: z.string().min(1),
223
+ });
224
+ export type LoginRequest = z.infer<typeof LoginRequest>;
225
+
226
+ // 認証済みユーザー情報(JWT claims 相当、機密情報なし)
227
+ export const AuthUser = z.object({
228
+ id: z.string(),
229
+ loginId: z.string(),
230
+ name: z.string(),
231
+ email: z.string().email(),
232
+ roles: z.array(z.string()),
233
+ });
234
+ export type AuthUser = z.infer<typeof AuthUser>;
235
+
236
+ // ログインレスポンス
237
+ export const LoginResponse = z.object({
238
+ user: AuthUser,
239
+ token: z.string(),
240
+ expiresAt: z.string(),
241
+ });
242
+ export type LoginResponse = z.infer<typeof LoginResponse>;
243
+
244
+ export const displayName = 'Auth';
245
+ `;
246
+ }
247
+
248
+ // ============================================================
249
+ // 2. TypeScript Functions テンプレート
250
+ // ============================================================
251
+
252
+ export function generateAuthFunctionsTS(
253
+ sharedPackageName: string,
254
+ config: CustomJwtConfig,
255
+ provider: RdbProvider,
256
+ ): string {
257
+ const envVar = `${config.userConnector.toUpperCase()}_CONNECTION_STRING`;
258
+
259
+ const driverImport = provider === "mysql"
260
+ ? `import mysql from 'mysql2/promise';`
261
+ : provider === "postgres"
262
+ ? `import pg from 'pg';`
263
+ : `import sql from 'mssql';`;
264
+
265
+ const getConnection = provider === "mysql"
266
+ ? `function getConnection() {
267
+ return mysql.createConnection(process.env.${envVar} || '');
268
+ }`
269
+ : provider === "postgres"
270
+ ? `async function getConnection() {
271
+ const client = new pg.Client(process.env.${envVar} || '');
272
+ await client.connect();
273
+ return client;
274
+ }`
275
+ : `async function getConnection() {
276
+ return sql.connect(process.env.${envVar} || '');
277
+ }`;
278
+
279
+ const connVar = provider === "mysql" ? "conn" : provider === "postgres" ? "client" : "pool";
280
+
281
+ const queryExec = provider === "mysql"
282
+ ? `const [rows] = await ${connVar}.query(
283
+ 'SELECT * FROM ${config.userTable} WHERE ${config.loginIdColumn} = ?',
284
+ [body.loginId]
285
+ );
286
+ const users = rows as any[];`
287
+ : provider === "postgres"
288
+ ? `const result = await ${connVar}.query(
289
+ 'SELECT * FROM ${config.userTable} WHERE ${config.loginIdColumn} = $1',
290
+ [body.loginId]
291
+ );
292
+ const users = result.rows;`
293
+ : `const result = await ${connVar}.request()
294
+ .input('loginId', body.loginId)
295
+ .query('SELECT * FROM ${config.userTable} WHERE ${config.loginIdColumn} = @loginId');
296
+ const users = result.recordset;`;
297
+
298
+ const cleanup = provider === "mysql"
299
+ ? `await ${connVar}.end();`
300
+ : provider === "postgres"
301
+ ? `await ${connVar}.end();`
302
+ : `await ${connVar}.close();`;
303
+
304
+ return `import { app, HttpRequest, HttpResponseInit, InvocationContext } from '@azure/functions';
305
+ import { LoginRequest, LoginResponse, AuthUser } from '${sharedPackageName}';
306
+ import { requireAuth, generateToken, handleAuthError } from './auth/jwt-helper';
307
+ import bcrypt from 'bcryptjs';
308
+ ${driverImport}
309
+
310
+ ${getConnection}
311
+
312
+ // POST /api/auth/login - ログイン
313
+ app.http('auth-login', {
314
+ methods: ['POST'],
315
+ route: 'auth/login',
316
+ authLevel: 'function',
317
+ handler: async (request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> => {
318
+ try {
319
+ const body = LoginRequest.parse(await request.json());
320
+
321
+ const ${connVar} = await getConnection();
322
+ try {
323
+ ${queryExec}
324
+
325
+ if (users.length === 0) {
326
+ return { status: 401, jsonBody: { error: 'Invalid credentials' } };
327
+ }
328
+
329
+ const user = users[0];
330
+ const valid = await bcrypt.compare(body.password, user.${config.passwordHashColumn});
331
+ if (!valid) {
332
+ return { status: 401, jsonBody: { error: 'Invalid credentials' } };
333
+ }
334
+
335
+ // ロール取得(JSON配列 or カンマ区切り)
336
+ let roles: string[] = [];
337
+ if (typeof user.${config.rolesColumn} === 'string') {
338
+ try {
339
+ roles = JSON.parse(user.${config.rolesColumn});
340
+ } catch {
341
+ roles = user.${config.rolesColumn}.split(',').map((r: string) => r.trim());
342
+ }
343
+ } else if (Array.isArray(user.${config.rolesColumn})) {
344
+ roles = user.${config.rolesColumn};
345
+ }
346
+
347
+ const authUser: AuthUser = {
348
+ id: String(user.id),
349
+ loginId: user.${config.loginIdColumn},
350
+ name: user.name || user.${config.loginIdColumn},
351
+ email: user.email || '',
352
+ roles,
353
+ };
354
+
355
+ const token = generateToken(authUser);
356
+ const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();
357
+
358
+ const response: LoginResponse = { user: authUser, token, expiresAt };
359
+ return { status: 200, jsonBody: response };
360
+ } finally {
361
+ ${cleanup}
362
+ }
363
+ } catch (error: any) {
364
+ context.error('Login error:', error);
365
+ return { status: 500, jsonBody: { error: 'Login failed' } };
366
+ }
367
+ },
368
+ });
369
+
370
+ // GET /api/auth/me - 現在のユーザー情報取得
371
+ app.http('auth-me', {
372
+ methods: ['GET'],
373
+ route: 'auth/me',
374
+ authLevel: 'function',
375
+ handler: async (request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> => {
376
+ try {
377
+ const user = requireAuth(request);
378
+ return { status: 200, jsonBody: user };
379
+ } catch (error) {
380
+ const authErr = handleAuthError(error);
381
+ if (authErr) return authErr;
382
+ context.error('Auth/me error:', error);
383
+ return { status: 500, jsonBody: { error: 'Internal server error' } };
384
+ }
385
+ },
386
+ });
387
+
388
+ // POST /api/auth/logout - ログアウト(ステートレスJWTのためサーバー側処理なし)
389
+ app.http('auth-logout', {
390
+ methods: ['POST'],
391
+ route: 'auth/logout',
392
+ authLevel: 'function',
393
+ handler: async (request: HttpRequest): Promise<HttpResponseInit> => {
394
+ return { status: 200, jsonBody: { message: 'Logged out' } };
395
+ },
396
+ });
397
+ `;
398
+ }
399
+
400
+ // ============================================================
401
+ // 3. TypeScript JWT Helper
402
+ // ============================================================
403
+
404
+ export function generateJwtHelperTS(): string {
405
+ return `import jwt from 'jsonwebtoken';
406
+ import { HttpRequest, HttpResponseInit } from '@azure/functions';
407
+
408
+ export interface JwtPayload {
409
+ sub: string;
410
+ loginId: string;
411
+ name: string;
412
+ email: string;
413
+ roles: string[];
414
+ }
415
+
416
+ const JWT_SECRET = process.env.JWT_SECRET || '';
417
+
418
+ /**
419
+ * JWT 検証。無効な場合は AuthError をスロー。
420
+ */
421
+ export function requireAuth(request: HttpRequest): JwtPayload {
422
+ const authHeader = request.headers.get('authorization');
423
+ if (!authHeader?.startsWith('Bearer ')) {
424
+ throw new AuthError(401, 'Missing or invalid Authorization header');
425
+ }
426
+ const token = authHeader.slice(7);
427
+ try {
428
+ const payload = jwt.verify(token, JWT_SECRET) as JwtPayload;
429
+ return payload;
430
+ } catch {
431
+ throw new AuthError(401, 'Invalid or expired token');
432
+ }
433
+ }
434
+
435
+ /**
436
+ * ロール確認。必要なロールを持たない場合は AuthError をスロー。
437
+ */
438
+ export function requireRoles(user: JwtPayload, requiredRoles: string[]): void {
439
+ const hasRole = requiredRoles.some(role => user.roles.includes(role));
440
+ if (!hasRole) {
441
+ throw new AuthError(403, \`Requires one of roles: \${requiredRoles.join(', ')}\`);
442
+ }
443
+ }
444
+
445
+ /**
446
+ * JWT 生成
447
+ */
448
+ export function generateToken(payload: { id: string; loginId: string; name: string; email: string; roles: string[] }): string {
449
+ return jwt.sign(
450
+ { sub: payload.id, loginId: payload.loginId, name: payload.name, email: payload.email, roles: payload.roles },
451
+ JWT_SECRET,
452
+ { expiresIn: process.env.JWT_EXPIRY || '24h' } as jwt.SignOptions
453
+ );
454
+ }
455
+
456
+ /**
457
+ * 認証エラー
458
+ */
459
+ export class AuthError extends Error {
460
+ constructor(public statusCode: number, message: string) {
461
+ super(message);
462
+ this.name = 'AuthError';
463
+ }
464
+ }
465
+
466
+ /**
467
+ * AuthError を HTTP レスポンスに変換
468
+ */
469
+ export function handleAuthError(error: unknown): HttpResponseInit | null {
470
+ if (error instanceof AuthError) {
471
+ return { status: error.statusCode, jsonBody: { error: error.message } };
472
+ }
473
+ return null;
474
+ }
475
+ `;
476
+ }
477
+
478
+ // ============================================================
479
+ // 4. C# Auth Functions テンプレート
480
+ // ============================================================
481
+
482
+ export function generateAuthFunctionsCSharp(
483
+ config: CustomJwtConfig,
484
+ provider: RdbProvider,
485
+ ): string {
486
+ const usingStatement = provider === "mysql"
487
+ ? `using MySqlConnector;`
488
+ : provider === "postgres"
489
+ ? `using Npgsql;`
490
+ : `using Microsoft.Data.SqlClient;`;
491
+
492
+ const connType = provider === "mysql"
493
+ ? "MySqlConnection"
494
+ : provider === "postgres"
495
+ ? "NpgsqlConnection"
496
+ : "SqlConnection";
497
+
498
+ const cmdType = provider === "mysql"
499
+ ? "MySqlCommand"
500
+ : provider === "postgres"
501
+ ? "NpgsqlCommand"
502
+ : "SqlCommand";
503
+
504
+ return `using System;
505
+ using System.Text.Json;
506
+ using Microsoft.Azure.Functions.Worker;
507
+ using Microsoft.Azure.Functions.Worker.Http;
508
+ ${usingStatement}
509
+ using BCrypt.Net;
510
+
511
+ namespace Functions.Auth
512
+ {
513
+ public class AuthFunctions
514
+ {
515
+ [Function("auth-login")]
516
+ public async Task<HttpResponseData> Login(
517
+ [HttpTrigger(AuthorizationLevel.Function, "post", Route = "auth/login")] HttpRequestData request)
518
+ {
519
+ var body = await JsonSerializer.DeserializeAsync<LoginRequest>(request.Body);
520
+ if (body == null || string.IsNullOrEmpty(body.LoginId) || string.IsNullOrEmpty(body.Password))
521
+ {
522
+ var badReq = request.CreateResponse(System.Net.HttpStatusCode.BadRequest);
523
+ await badReq.WriteAsJsonAsync(new { error = "loginId and password are required" });
524
+ return badReq;
525
+ }
526
+
527
+ await using var conn = new ${connType}(
528
+ Environment.GetEnvironmentVariable("${config.userConnector.toUpperCase()}_CONNECTION_STRING"));
529
+ await conn.OpenAsync();
530
+
531
+ await using var cmd = new ${cmdType}(
532
+ "SELECT * FROM ${config.userTable} WHERE ${config.loginIdColumn} = @loginId", conn);
533
+ cmd.Parameters.AddWithValue("@loginId", body.LoginId);
534
+
535
+ await using var reader = await cmd.ExecuteReaderAsync();
536
+ if (!await reader.ReadAsync())
537
+ {
538
+ var unauthorized = request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
539
+ await unauthorized.WriteAsJsonAsync(new { error = "Invalid credentials" });
540
+ return unauthorized;
541
+ }
542
+
543
+ var passwordHash = reader["${config.passwordHashColumn}"].ToString()!;
544
+ if (!BCrypt.Net.BCrypt.Verify(body.Password, passwordHash))
545
+ {
546
+ var unauthorized = request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
547
+ await unauthorized.WriteAsJsonAsync(new { error = "Invalid credentials" });
548
+ return unauthorized;
549
+ }
550
+
551
+ var rolesStr = reader["${config.rolesColumn}"].ToString() ?? "[]";
552
+ string[] roles;
553
+ try { roles = JsonSerializer.Deserialize<string[]>(rolesStr) ?? Array.Empty<string>(); }
554
+ catch { roles = rolesStr.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); }
555
+
556
+ var userId = reader["id"].ToString()!;
557
+ var loginId = reader["${config.loginIdColumn}"].ToString()!;
558
+ var name = reader["name"]?.ToString() ?? loginId;
559
+ var email = reader["email"]?.ToString() ?? "";
560
+
561
+ var token = JwtHelper.GenerateToken(userId, loginId, name, email, roles);
562
+ var expiresAt = DateTime.UtcNow.AddHours(24).ToString("o");
563
+
564
+ var response = request.CreateResponse(System.Net.HttpStatusCode.OK);
565
+ await response.WriteAsJsonAsync(new
566
+ {
567
+ user = new { id = userId, loginId, name, email, roles },
568
+ token,
569
+ expiresAt
570
+ });
571
+ return response;
572
+ }
573
+
574
+ [Function("auth-me")]
575
+ public async Task<HttpResponseData> Me(
576
+ [HttpTrigger(AuthorizationLevel.Function, "get", Route = "auth/me")] HttpRequestData request)
577
+ {
578
+ var (principal, errorResponse) = await JwtHelper.Authorize(request);
579
+ if (errorResponse != null) return errorResponse;
580
+
581
+ var response = request.CreateResponse(System.Net.HttpStatusCode.OK);
582
+ await response.WriteAsJsonAsync(new
583
+ {
584
+ sub = principal!.Sub,
585
+ loginId = principal.LoginId,
586
+ name = principal.Name,
587
+ email = principal.Email,
588
+ roles = principal.Roles
589
+ });
590
+ return response;
591
+ }
592
+
593
+ [Function("auth-logout")]
594
+ public async Task<HttpResponseData> Logout(
595
+ [HttpTrigger(AuthorizationLevel.Function, "post", Route = "auth/logout")] HttpRequestData request)
596
+ {
597
+ var response = request.CreateResponse(System.Net.HttpStatusCode.OK);
598
+ await response.WriteAsJsonAsync(new { message = "Logged out" });
599
+ return response;
600
+ }
601
+ }
602
+
603
+ public class LoginRequest
604
+ {
605
+ [System.Text.Json.Serialization.JsonPropertyName("loginId")]
606
+ public string LoginId { get; set; } = "";
607
+ [System.Text.Json.Serialization.JsonPropertyName("password")]
608
+ public string Password { get; set; } = "";
609
+ }
610
+ }
611
+ `;
612
+ }
613
+
614
+ // ============================================================
615
+ // 5. C# JWT Helper
616
+ // ============================================================
617
+
618
+ export function generateJwtHelperCSharp(): string {
619
+ return `using System;
620
+ using System.IdentityModel.Tokens.Jwt;
621
+ using System.Security.Claims;
622
+ using System.Text;
623
+ using System.Text.Json;
624
+ using System.Threading.Tasks;
625
+ using Microsoft.Azure.Functions.Worker.Http;
626
+ using Microsoft.IdentityModel.Tokens;
627
+
628
+ namespace Functions.Auth
629
+ {
630
+ public class JwtPayload
631
+ {
632
+ public string Sub { get; set; } = "";
633
+ public string LoginId { get; set; } = "";
634
+ public string Name { get; set; } = "";
635
+ public string Email { get; set; } = "";
636
+ public string[] Roles { get; set; } = Array.Empty<string>();
637
+ }
638
+
639
+ public static class JwtHelper
640
+ {
641
+ private static string JwtSecret => Environment.GetEnvironmentVariable("JWT_SECRET") ?? "";
642
+
643
+ public static string GenerateToken(string userId, string loginId, string name, string email, string[] roles)
644
+ {
645
+ var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSecret));
646
+ var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
647
+
648
+ var claims = new List<Claim>
649
+ {
650
+ new(JwtRegisteredClaimNames.Sub, userId),
651
+ new("loginId", loginId),
652
+ new("name", name),
653
+ new("email", email),
654
+ };
655
+ foreach (var role in roles)
656
+ {
657
+ claims.Add(new Claim("roles", role));
658
+ }
659
+
660
+ var token = new JwtSecurityToken(
661
+ expires: DateTime.UtcNow.AddHours(24),
662
+ claims: claims,
663
+ signingCredentials: creds
664
+ );
665
+
666
+ return new JwtSecurityTokenHandler().WriteToken(token);
667
+ }
668
+
669
+ public static JwtPayload? ValidateToken(HttpRequestData request)
670
+ {
671
+ var authHeader = request.Headers.TryGetValues("Authorization", out var values)
672
+ ? values.FirstOrDefault() : null;
673
+
674
+ if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer "))
675
+ return null;
676
+
677
+ var token = authHeader["Bearer ".Length..];
678
+ var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSecret));
679
+
680
+ try
681
+ {
682
+ var handler = new JwtSecurityTokenHandler();
683
+ var principal = handler.ValidateToken(token, new TokenValidationParameters
684
+ {
685
+ ValidateIssuer = false,
686
+ ValidateAudience = false,
687
+ ValidateLifetime = true,
688
+ IssuerSigningKey = key,
689
+ }, out _);
690
+
691
+ return new JwtPayload
692
+ {
693
+ Sub = principal.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "",
694
+ LoginId = principal.FindFirst("loginId")?.Value ?? "",
695
+ Name = principal.FindFirst("name")?.Value ?? "",
696
+ Email = principal.FindFirst("email")?.Value ?? "",
697
+ Roles = principal.FindAll("roles").Select(c => c.Value).ToArray(),
698
+ };
699
+ }
700
+ catch
701
+ {
702
+ return null;
703
+ }
704
+ }
705
+
706
+ public static async Task<(JwtPayload?, HttpResponseData?)> Authorize(
707
+ HttpRequestData request, params string[] requiredRoles)
708
+ {
709
+ var payload = ValidateToken(request);
710
+ if (payload == null)
711
+ {
712
+ var unauthorized = request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
713
+ await unauthorized.WriteAsJsonAsync(new { error = "Unauthorized" });
714
+ return (null, unauthorized);
715
+ }
716
+
717
+ if (requiredRoles.Length > 0 && !requiredRoles.Any(r => payload.Roles.Contains(r)))
718
+ {
719
+ var forbidden = request.CreateResponse(System.Net.HttpStatusCode.Forbidden);
720
+ await forbidden.WriteAsJsonAsync(new { error = "Forbidden" });
721
+ return (null, forbidden);
722
+ }
723
+
724
+ return (payload, null);
725
+ }
726
+ }
727
+ }
728
+ `;
729
+ }
730
+
731
+ // ============================================================
732
+ // 6. Python Auth Functions テンプレート
733
+ // ============================================================
734
+
735
+ export function generateAuthFunctionsPython(
736
+ config: CustomJwtConfig,
737
+ provider: RdbProvider,
738
+ ): string {
739
+ const envPrefix = config.userConnector.toUpperCase();
740
+
741
+ const driverImport = provider === "mysql"
742
+ ? `import mysql.connector`
743
+ : provider === "postgres"
744
+ ? `import psycopg2\nimport psycopg2.extras`
745
+ : `import pymssql`;
746
+
747
+ const getConnection = provider === "mysql"
748
+ ? `def get_connection():
749
+ return mysql.connector.connect(
750
+ host=os.environ.get("${envPrefix}_HOST", "localhost"),
751
+ user=os.environ.get("${envPrefix}_USER", "root"),
752
+ password=os.environ.get("${envPrefix}_PASSWORD", ""),
753
+ database=os.environ.get("${envPrefix}_DATABASE", ""),
754
+ )`
755
+ : provider === "postgres"
756
+ ? `def get_connection():
757
+ return psycopg2.connect(os.environ.get("${envPrefix}_CONNECTION_STRING", ""))`
758
+ : `def get_connection():
759
+ return pymssql.connect(
760
+ server=os.environ.get("${envPrefix}_SERVER", "localhost"),
761
+ user=os.environ.get("${envPrefix}_USER", ""),
762
+ password=os.environ.get("${envPrefix}_PASSWORD", ""),
763
+ database=os.environ.get("${envPrefix}_DATABASE", ""),
764
+ )`;
765
+
766
+ const cursorCreate = provider === "mysql"
767
+ ? `cursor = conn.cursor(dictionary=True)`
768
+ : provider === "postgres"
769
+ ? `cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)`
770
+ : `cursor = conn.cursor(as_dict=True)`;
771
+
772
+ return `import json
773
+ import os
774
+ import logging
775
+ import azure.functions as func
776
+ import jwt
777
+ import bcrypt
778
+ ${driverImport}
779
+
780
+ auth_bp = func.Blueprint()
781
+
782
+ ${getConnection}
783
+
784
+
785
+ @auth_bp.route(route="auth/login", methods=["POST"], auth_level=func.AuthLevel.FUNCTION)
786
+ def auth_login(req: func.HttpRequest) -> func.HttpResponse:
787
+ try:
788
+ body = req.get_json()
789
+ login_id = body.get("loginId", "")
790
+ password = body.get("password", "")
791
+
792
+ if not login_id or not password:
793
+ return func.HttpResponse(
794
+ json.dumps({"error": "loginId and password are required"}),
795
+ status_code=400, mimetype="application/json"
796
+ )
797
+
798
+ conn = get_connection()
799
+ ${cursorCreate}
800
+ cursor.execute(
801
+ "SELECT * FROM ${config.userTable} WHERE ${config.loginIdColumn} = %s",
802
+ (login_id,)
803
+ )
804
+ user = cursor.fetchone()
805
+ cursor.close()
806
+ conn.close()
807
+
808
+ if not user:
809
+ return func.HttpResponse(
810
+ json.dumps({"error": "Invalid credentials"}),
811
+ status_code=401, mimetype="application/json"
812
+ )
813
+
814
+ if not bcrypt.checkpw(
815
+ password.encode("utf-8"),
816
+ user["${config.passwordHashColumn}"].encode("utf-8")
817
+ ):
818
+ return func.HttpResponse(
819
+ json.dumps({"error": "Invalid credentials"}),
820
+ status_code=401, mimetype="application/json"
821
+ )
822
+
823
+ roles_raw = user.get("${config.rolesColumn}", "[]")
824
+ try:
825
+ roles = json.loads(roles_raw) if isinstance(roles_raw, str) else list(roles_raw)
826
+ except (json.JSONDecodeError, TypeError):
827
+ roles = [r.strip() for r in str(roles_raw).split(",")]
828
+
829
+ from auth.jwt_helper import generate_token
830
+ import datetime
831
+
832
+ auth_user = {
833
+ "id": str(user["id"]),
834
+ "loginId": user["${config.loginIdColumn}"],
835
+ "name": user.get("name", user["${config.loginIdColumn}"]),
836
+ "email": user.get("email", ""),
837
+ "roles": roles,
838
+ }
839
+
840
+ token = generate_token(auth_user)
841
+ expires_at = (
842
+ datetime.datetime.utcnow() + datetime.timedelta(hours=24)
843
+ ).isoformat() + "Z"
844
+
845
+ return func.HttpResponse(
846
+ json.dumps({"user": auth_user, "token": token, "expiresAt": expires_at}),
847
+ status_code=200, mimetype="application/json"
848
+ )
849
+ except Exception as e:
850
+ logging.error(f"Login error: {e}")
851
+ return func.HttpResponse(
852
+ json.dumps({"error": "Login failed"}),
853
+ status_code=500, mimetype="application/json"
854
+ )
855
+
856
+
857
+ @auth_bp.route(route="auth/me", methods=["GET"], auth_level=func.AuthLevel.FUNCTION)
858
+ def auth_me(req: func.HttpRequest) -> func.HttpResponse:
859
+ from auth.jwt_helper import require_auth, handle_auth_error
860
+
861
+ try:
862
+ user = require_auth(req)
863
+ return func.HttpResponse(
864
+ json.dumps(user), status_code=200, mimetype="application/json"
865
+ )
866
+ except Exception as e:
867
+ err = handle_auth_error(e)
868
+ if err:
869
+ return err
870
+ return func.HttpResponse(
871
+ json.dumps({"error": "Internal server error"}),
872
+ status_code=500, mimetype="application/json"
873
+ )
874
+
875
+
876
+ @auth_bp.route(route="auth/logout", methods=["POST"], auth_level=func.AuthLevel.FUNCTION)
877
+ def auth_logout(req: func.HttpRequest) -> func.HttpResponse:
878
+ return func.HttpResponse(
879
+ json.dumps({"message": "Logged out"}),
880
+ status_code=200, mimetype="application/json"
881
+ )
882
+ `;
883
+ }
884
+
885
+ // ============================================================
886
+ // 7. Python JWT Helper
887
+ // ============================================================
888
+
889
+ export function generateJwtHelperPython(): string {
890
+ return `import os
891
+ import json
892
+ import jwt
893
+ import azure.functions as func
894
+
895
+
896
+ JWT_SECRET = os.environ.get("JWT_SECRET", "")
897
+
898
+
899
+ def require_auth(req: func.HttpRequest) -> dict:
900
+ """JWT 検証。無効な場合は AuthError を raise。"""
901
+ auth_header = req.headers.get("authorization", "")
902
+ if not auth_header.startswith("Bearer "):
903
+ raise AuthError(401, "Missing or invalid Authorization header")
904
+
905
+ token = auth_header[7:]
906
+ try:
907
+ payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
908
+ return {
909
+ "sub": payload.get("sub", ""),
910
+ "loginId": payload.get("loginId", ""),
911
+ "name": payload.get("name", ""),
912
+ "email": payload.get("email", ""),
913
+ "roles": payload.get("roles", []),
914
+ }
915
+ except jwt.ExpiredSignatureError:
916
+ raise AuthError(401, "Token expired")
917
+ except jwt.InvalidTokenError:
918
+ raise AuthError(401, "Invalid token")
919
+
920
+
921
+ def require_roles(user: dict, required_roles: list[str]) -> None:
922
+ """ロール確認。必要なロールを持たない場合は AuthError を raise。"""
923
+ user_roles = user.get("roles", [])
924
+ if not any(role in user_roles for role in required_roles):
925
+ raise AuthError(403, f"Requires one of roles: {', '.join(required_roles)}")
926
+
927
+
928
+ def generate_token(payload: dict) -> str:
929
+ """JWT 生成"""
930
+ import datetime
931
+
932
+ return jwt.encode(
933
+ {
934
+ "sub": payload["id"],
935
+ "loginId": payload["loginId"],
936
+ "name": payload["name"],
937
+ "email": payload["email"],
938
+ "roles": payload["roles"],
939
+ "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=24),
940
+ },
941
+ JWT_SECRET,
942
+ algorithm="HS256",
943
+ )
944
+
945
+
946
+ class AuthError(Exception):
947
+ def __init__(self, status_code: int, message: str):
948
+ super().__init__(message)
949
+ self.status_code = status_code
950
+
951
+
952
+ def handle_auth_error(error: Exception) -> func.HttpResponse | None:
953
+ """AuthError を HTTP レスポンスに変換"""
954
+ if isinstance(error, AuthError):
955
+ return func.HttpResponse(
956
+ json.dumps({"error": str(error)}),
957
+ status_code=error.status_code,
958
+ mimetype="application/json",
959
+ )
960
+ return None
961
+ `;
962
+ }
963
+
964
+ // ============================================================
965
+ // 8. BFF Auth Routes(Next.js API Routes)
966
+ // ============================================================
967
+
968
+ export function generateBFFAuthLoginRoute(projectName: string, sharedPackageName: string): string {
969
+ const cookieName = projectName.replace(/^@[^/]+\//, '').replace(/[^a-z0-9-]/g, '-') + '-auth-token';
970
+ return `import { NextRequest, NextResponse } from 'next/server';
971
+ import { LoginRequest, LoginResponse } from '${sharedPackageName}';
972
+
973
+ export async function POST(request: NextRequest) {
974
+ const FUNCTIONS_BASE_URL = process.env.BACKEND_FUNCTIONS_BASE_URL || process.env.FUNCTIONS_BASE_URL || 'http://localhost:7071';
975
+ try {
976
+ const body = await request.json();
977
+ const validated = LoginRequest.parse(body);
978
+
979
+ const result = await fetch(\`\${FUNCTIONS_BASE_URL}/api/auth/login\`, {
980
+ method: 'POST',
981
+ headers: { 'Content-Type': 'application/json' },
982
+ body: JSON.stringify(validated),
983
+ });
984
+
985
+ if (!result.ok) {
986
+ const error = await result.json().catch(() => ({ error: 'Authentication failed' }));
987
+ return NextResponse.json(error, { status: result.status });
988
+ }
989
+
990
+ const data = LoginResponse.parse(await result.json());
991
+
992
+ const response = NextResponse.json({ user: data.user });
993
+ response.cookies.set('${cookieName}', data.token, {
994
+ httpOnly: true,
995
+ secure: process.env.NODE_ENV === 'production',
996
+ sameSite: 'lax',
997
+ path: '/',
998
+ maxAge: 86400,
999
+ });
1000
+ return response;
1001
+ } catch (error: any) {
1002
+ console.error('[BFF] Login error:', error);
1003
+ return NextResponse.json({ error: 'Login failed' }, { status: 500 });
1004
+ }
1005
+ }
1006
+ `;
1007
+ }
1008
+
1009
+ export function generateBFFAuthLogoutRoute(projectName: string): string {
1010
+ const cookieName = projectName.replace(/^@[^/]+\//, '').replace(/[^a-z0-9-]/g, '-') + '-auth-token';
1011
+ return `import { NextResponse } from 'next/server';
1012
+
1013
+ export async function POST() {
1014
+ const response = NextResponse.json({ message: 'Logged out' });
1015
+ response.cookies.delete('${cookieName}');
1016
+ return response;
1017
+ }
1018
+ `;
1019
+ }
1020
+
1021
+ export function generateBFFAuthMeRoute(_sharedPackageName?: string): string {
1022
+ void _sharedPackageName;
1023
+ return `import { NextResponse } from 'next/server';
1024
+ import { headers } from 'next/headers';
1025
+
1026
+ export async function GET() {
1027
+ const FUNCTIONS_BASE_URL = process.env.BACKEND_FUNCTIONS_BASE_URL || process.env.FUNCTIONS_BASE_URL || 'http://localhost:7071';
1028
+ try {
1029
+ const reqHeaders = await headers();
1030
+ const authorization = reqHeaders.get('authorization');
1031
+
1032
+ if (!authorization) {
1033
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
1034
+ }
1035
+
1036
+ const result = await fetch(\`\${FUNCTIONS_BASE_URL}/api/auth/me\`, {
1037
+ headers: { Authorization: authorization },
1038
+ });
1039
+
1040
+ if (!result.ok) {
1041
+ return NextResponse.json({ error: 'Unauthorized' }, { status: result.status });
1042
+ }
1043
+
1044
+ const data = await result.json();
1045
+ return NextResponse.json(data);
1046
+ } catch (error: any) {
1047
+ console.error('[BFF] Auth/me error:', error);
1048
+ return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
1049
+ }
1050
+ }
1051
+ `;
1052
+ }
1053
+
1054
+ // ============================================================
1055
+ // 9. Next.js Proxy (formerly Middleware)
1056
+ // ============================================================
1057
+
1058
+ export function generateProxy(projectName: string): string {
1059
+ const cookieName = projectName.replace(/^@[^/]+\//, '').replace(/[^a-z0-9-]/g, '-') + '-auth-token';
1060
+ return `import { NextResponse } from 'next/server';
1061
+ import type { NextRequest } from 'next/server';
1062
+
1063
+ const AUTH_COOKIE_NAME = '${cookieName}';
1064
+ const PUBLIC_PATHS = ['/login', '/api/auth/login', '/api/auth/logout'];
1065
+
1066
+ export function proxy(request: NextRequest) {
1067
+ const { pathname } = request.nextUrl;
1068
+
1069
+ // 公開パス・静的アセットはスキップ
1070
+ if (PUBLIC_PATHS.some(p => pathname.startsWith(p))) return NextResponse.next();
1071
+ if (pathname.startsWith('/_next') || pathname.match(/\\.(ico|png|jpg|svg|css|js)$/)) {
1072
+ return NextResponse.next();
1073
+ }
1074
+
1075
+ const token = request.cookies.get(AUTH_COOKIE_NAME)?.value;
1076
+
1077
+ if (!token) {
1078
+ if (pathname.startsWith('/api/')) {
1079
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
1080
+ }
1081
+ return NextResponse.redirect(new URL('/login', request.url));
1082
+ }
1083
+
1084
+ // JWT 有効期限の簡易チェック(署名検証なし)
1085
+ try {
1086
+ const payload = JSON.parse(atob(token.split('.')[1]));
1087
+ if (payload.exp && payload.exp * 1000 < Date.now()) {
1088
+ const response = pathname.startsWith('/api/')
1089
+ ? NextResponse.json({ error: 'Token expired' }, { status: 401 })
1090
+ : NextResponse.redirect(new URL('/login', request.url));
1091
+ response.cookies.delete(AUTH_COOKIE_NAME);
1092
+ return response;
1093
+ }
1094
+ } catch {
1095
+ const response = pathname.startsWith('/api/')
1096
+ ? NextResponse.json({ error: 'Invalid token' }, { status: 401 })
1097
+ : NextResponse.redirect(new URL('/login', request.url));
1098
+ response.cookies.delete(AUTH_COOKIE_NAME);
1099
+ return response;
1100
+ }
1101
+
1102
+ // Authorization ヘッダーを注入(BFF callFunction が自動転送できるように)
1103
+ const requestHeaders = new Headers(request.headers);
1104
+ requestHeaders.set('Authorization', \`Bearer \${token}\`);
1105
+ return NextResponse.next({
1106
+ request: { headers: requestHeaders },
1107
+ });
1108
+ }
1109
+ `;
1110
+ }
1111
+
1112
+ // ============================================================
1113
+ // 10. ログインページ
1114
+ // ============================================================
1115
+
1116
+ export function generateLoginPage(): string {
1117
+ return `'use client';
1118
+
1119
+ import { useState } from 'react';
1120
+ import { useRouter } from 'next/navigation';
1121
+
1122
+ export default function LoginPage() {
1123
+ const [loginId, setLoginId] = useState('');
1124
+ const [password, setPassword] = useState('');
1125
+ const [error, setError] = useState('');
1126
+ const [loading, setLoading] = useState(false);
1127
+ const router = useRouter();
1128
+
1129
+ const handleSubmit = async (e: React.FormEvent) => {
1130
+ e.preventDefault();
1131
+ setError('');
1132
+ setLoading(true);
1133
+
1134
+ try {
1135
+ const res = await fetch('/api/auth/login', {
1136
+ method: 'POST',
1137
+ headers: { 'Content-Type': 'application/json' },
1138
+ body: JSON.stringify({ loginId, password }),
1139
+ });
1140
+
1141
+ if (!res.ok) {
1142
+ const data = await res.json().catch(() => ({}));
1143
+ setError(data.error || 'ログインに失敗しました');
1144
+ return;
1145
+ }
1146
+
1147
+ router.push('/');
1148
+ router.refresh();
1149
+ } catch {
1150
+ setError('通信エラーが発生しました');
1151
+ } finally {
1152
+ setLoading(false);
1153
+ }
1154
+ };
1155
+
1156
+ return (
1157
+ <div className="min-h-screen flex items-center justify-center bg-gray-50">
1158
+ <div className="w-full max-w-md p-8 bg-white rounded-lg shadow-md">
1159
+ <h1 className="text-2xl font-bold text-center mb-6">ログイン</h1>
1160
+ {error && (
1161
+ <div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded text-sm">
1162
+ {error}
1163
+ </div>
1164
+ )}
1165
+ <form onSubmit={handleSubmit} className="space-y-4">
1166
+ <div>
1167
+ <label htmlFor="loginId" className="block text-sm font-medium text-gray-700 mb-1">
1168
+ ログインID
1169
+ </label>
1170
+ <input
1171
+ id="loginId"
1172
+ type="text"
1173
+ value={loginId}
1174
+ onChange={(e) => setLoginId(e.target.value)}
1175
+ className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
1176
+ required
1177
+ autoFocus
1178
+ />
1179
+ </div>
1180
+ <div>
1181
+ <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
1182
+ パスワード
1183
+ </label>
1184
+ <input
1185
+ id="password"
1186
+ type="password"
1187
+ value={password}
1188
+ onChange={(e) => setPassword(e.target.value)}
1189
+ className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
1190
+ required
1191
+ />
1192
+ </div>
1193
+ <button
1194
+ type="submit"
1195
+ disabled={loading}
1196
+ className="w-full py-2 px-4 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
1197
+ >
1198
+ {loading ? 'ログイン中...' : 'ログイン'}
1199
+ </button>
1200
+ </form>
1201
+ </div>
1202
+ </div>
1203
+ );
1204
+ }
1205
+ `;
1206
+ }
1207
+
1208
+ // ============================================================
1209
+ // 11. React Auth Context
1210
+ // ============================================================
1211
+
1212
+ export function generateAuthContext(): string {
1213
+ return `'use client';
1214
+
1215
+ import { createContext, useContext, useEffect, useState, useCallback, ReactNode } from 'react';
1216
+ import { useRouter } from 'next/navigation';
1217
+
1218
+ interface AuthUser {
1219
+ id: string;
1220
+ loginId: string;
1221
+ name: string;
1222
+ email: string;
1223
+ roles: string[];
1224
+ }
1225
+
1226
+ interface AuthContextType {
1227
+ user: AuthUser | null;
1228
+ loading: boolean;
1229
+ login: (loginId: string, password: string) => Promise<{ success: boolean; error?: string }>;
1230
+ logout: () => Promise<void>;
1231
+ hasRole: (role: string) => boolean;
1232
+ hasAnyRole: (roles: string[]) => boolean;
1233
+ }
1234
+
1235
+ const AuthContext = createContext<AuthContextType | undefined>(undefined);
1236
+
1237
+ export function AuthProvider({ children }: { children: ReactNode }) {
1238
+ const [user, setUser] = useState<AuthUser | null>(null);
1239
+ const [loading, setLoading] = useState(true);
1240
+ const router = useRouter();
1241
+
1242
+ const fetchUser = useCallback(async () => {
1243
+ try {
1244
+ const res = await fetch('/api/auth/me');
1245
+ if (res.ok) {
1246
+ const data = await res.json();
1247
+ setUser(data);
1248
+ } else {
1249
+ setUser(null);
1250
+ }
1251
+ } catch {
1252
+ setUser(null);
1253
+ } finally {
1254
+ setLoading(false);
1255
+ }
1256
+ }, []);
1257
+
1258
+ useEffect(() => {
1259
+ fetchUser();
1260
+ }, [fetchUser]);
1261
+
1262
+ const login = async (loginId: string, password: string) => {
1263
+ try {
1264
+ const res = await fetch('/api/auth/login', {
1265
+ method: 'POST',
1266
+ headers: { 'Content-Type': 'application/json' },
1267
+ body: JSON.stringify({ loginId, password }),
1268
+ });
1269
+
1270
+ if (!res.ok) {
1271
+ const data = await res.json().catch(() => ({}));
1272
+ return { success: false, error: data.error || 'Login failed' };
1273
+ }
1274
+
1275
+ const data = await res.json();
1276
+ setUser(data.user);
1277
+ return { success: true };
1278
+ } catch {
1279
+ return { success: false, error: 'Network error' };
1280
+ }
1281
+ };
1282
+
1283
+ const logout = async () => {
1284
+ await fetch('/api/auth/logout', { method: 'POST' });
1285
+ setUser(null);
1286
+ router.push('/login');
1287
+ };
1288
+
1289
+ const hasRole = (role: string) => user?.roles?.includes(role) ?? false;
1290
+ const hasAnyRole = (roles: string[]) => roles.some(r => hasRole(r));
1291
+
1292
+ return (
1293
+ <AuthContext.Provider value={{ user, loading, login, logout, hasRole, hasAnyRole }}>
1294
+ {children}
1295
+ </AuthContext.Provider>
1296
+ );
1297
+ }
1298
+
1299
+ export function useAuth() {
1300
+ const context = useContext(AuthContext);
1301
+ if (!context) {
1302
+ throw new Error('useAuth must be used within an AuthProvider');
1303
+ }
1304
+ return context;
1305
+ }
1306
+ `;
1307
+ }
1308
+
1309
+ // ============================================================
1310
+ // 12. callFunction 認証対応版
1311
+ // ============================================================
1312
+
1313
+ export function generateBFFCallFunctionWithAuth(): string {
1314
+ return `import { NextRequest, NextResponse } from 'next/server';
1315
+ import { headers } from 'next/headers';
1316
+ import { z } from 'zod/v4';
1317
+
1318
+ /**
1319
+ * SwallowKit BFF Call Function Helper (Auth-enabled)
1320
+ * Azure Functions を呼び出す汎用ヘルパー(Authorization ヘッダー自動転送対応)
1321
+ */
1322
+
1323
+ function getFunctionsBaseUrl(): string {
1324
+ return process.env.BACKEND_FUNCTIONS_BASE_URL || process.env.FUNCTIONS_BASE_URL || 'http://localhost:7071';
1325
+ }
1326
+
1327
+ function isLocalFunctionsUrl(url: string): boolean {
1328
+ return url.startsWith('http://localhost:') || url.startsWith('http://127.0.0.1:');
1329
+ }
1330
+
1331
+ function getFunctionsKeyHeaders(functionsBaseUrl: string): Record<string, string> {
1332
+ const key = process.env.BACKEND_FUNCTIONS_KEY;
1333
+ if (key) return { 'x-functions-key': key };
1334
+ if (isLocalFunctionsUrl(functionsBaseUrl)) return {};
1335
+ throw new Error('BACKEND_FUNCTIONS_KEY is required for non-local Functions calls');
1336
+ }
1337
+
1338
+ interface CallFunctionConfig<TInput = any, TOutput = any> {
1339
+ /** HTTP メソッド */
1340
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
1341
+ /** Azure Functions のパス (例: '/api/todo', '/api/todo/123') */
1342
+ path: string;
1343
+ /** リクエストボディ (POST/PUT 用) */
1344
+ body?: any;
1345
+ /** 入力バリデーション用 Zod スキーマ (省略時はバリデーションなし) */
1346
+ inputSchema?: z.ZodSchema<TInput>;
1347
+ /** 出力バリデーション用 Zod スキーマ (省略時はそのまま返す) */
1348
+ responseSchema?: z.ZodSchema<TOutput>;
1349
+ /** 成功時の HTTP ステータスコード (デフォルト: 200) */
1350
+ successStatus?: number;
1351
+ }
1352
+
1353
+ export async function callFunction<TInput = any, TOutput = any>(
1354
+ config: CallFunctionConfig<TInput, TOutput>
1355
+ ): Promise<NextResponse> {
1356
+ const { method, path, body, inputSchema, responseSchema, successStatus = 200 } = config;
1357
+
1358
+ try {
1359
+ // 入力バリデーション
1360
+ let validatedBody = body;
1361
+ if (inputSchema && body !== undefined) {
1362
+ const result = inputSchema.safeParse(body);
1363
+ if (!result.success) {
1364
+ console.error('[BFF] Validation failed:', result.error.issues);
1365
+ return NextResponse.json(
1366
+ { error: 'Validation failed', details: result.error.issues },
1367
+ { status: 400 }
1368
+ );
1369
+ }
1370
+ validatedBody = result.data;
1371
+ }
1372
+
1373
+ // Azure Functions を呼び出し
1374
+ const functionsBaseUrl = getFunctionsBaseUrl();
1375
+ const url = functionsBaseUrl + path;
1376
+ const keyHeaders = getFunctionsKeyHeaders(functionsBaseUrl);
1377
+ console.log(\`[BFF] \${method} \${url}\`);
1378
+
1379
+ // Authorization ヘッダーの転送(Proxy が cookie → Authorization に変換済み)
1380
+ const fetchHeaders: Record<string, string> = {
1381
+ 'Content-Type': 'application/json',
1382
+ ...keyHeaders,
1383
+ };
1384
+ try {
1385
+ const reqHeaders = await headers();
1386
+ const authorization = reqHeaders.get('authorization');
1387
+ if (authorization) {
1388
+ fetchHeaders['Authorization'] = authorization;
1389
+ }
1390
+ } catch {
1391
+ // headers() が使えないコンテキスト(ISR 等)では無視
1392
+ }
1393
+
1394
+ const response = await fetch(url, {
1395
+ method,
1396
+ headers: fetchHeaders,
1397
+ body: validatedBody !== undefined ? JSON.stringify(validatedBody) : undefined,
1398
+ });
1399
+
1400
+ console.log('[BFF] Functions response status:', response.status);
1401
+
1402
+ // エラーレスポンスの転送
1403
+ if (!response.ok) {
1404
+ const text = await response.text();
1405
+ console.error('[BFF] Functions error:', { status: response.status, body: text });
1406
+
1407
+ let errorMessage = 'Request failed';
1408
+ try {
1409
+ const error = JSON.parse(text);
1410
+ errorMessage = error.error || errorMessage;
1411
+ } catch {
1412
+ errorMessage = text || errorMessage;
1413
+ }
1414
+ return NextResponse.json({ error: errorMessage }, { status: response.status });
1415
+ }
1416
+
1417
+ // DELETE 204 の場合はボディなし
1418
+ if (response.status === 204 || method === 'DELETE') {
1419
+ return new NextResponse(null, { status: 204 });
1420
+ }
1421
+
1422
+ // レスポンスの取得と出力バリデーション
1423
+ const data = await response.json();
1424
+
1425
+ if (responseSchema) {
1426
+ const validated = responseSchema.parse(data);
1427
+ return NextResponse.json(validated, { status: successStatus });
1428
+ }
1429
+
1430
+ return NextResponse.json(data, { status: successStatus });
1431
+ } catch (error: any) {
1432
+ console.error(\`[BFF] Error:\`, error);
1433
+ return NextResponse.json(
1434
+ { error: error.message || 'Internal server error' },
1435
+ { status: 500 }
1436
+ );
1437
+ }
1438
+ }
1439
+ `;
1440
+ }
1441
+
1442
+ /** SWA built-in auth variant: forward only a platform-derived client principal. */
1443
+ export function generateBFFCallFunctionWithSwaAuth(): string {
1444
+ return generateBFFCallFunctionWithAuth()
1445
+ .replace(
1446
+ ` // Authorization ヘッダーの転送(Proxy が cookie → Authorization に変換済み)`,
1447
+ ` // SWA client principal is accepted only from the platform request context.`
1448
+ )
1449
+ .replace(
1450
+ ` const authorization = reqHeaders.get('authorization');
1451
+ if (authorization) {
1452
+ fetchHeaders['Authorization'] = authorization;
1453
+ }`,
1454
+ ` // Never forward a browser-supplied principal header. Resolve it from the SWA session endpoint.
1455
+ let principal: string | null = null;
1456
+ {
1457
+ const cookie = reqHeaders.get('cookie');
1458
+ const host = reqHeaders.get('host');
1459
+ if (cookie && host) {
1460
+ const proto = reqHeaders.get('x-forwarded-proto') || 'https';
1461
+ const meResponse = await fetch(\`\${proto}://\${host}/.auth/me\`, {
1462
+ headers: { cookie },
1463
+ cache: 'no-store',
1464
+ });
1465
+ if (meResponse.ok) {
1466
+ const payload = await meResponse.json() as { clientPrincipal?: unknown };
1467
+ if (payload.clientPrincipal) {
1468
+ principal = Buffer.from(JSON.stringify(payload.clientPrincipal), 'utf8').toString('base64');
1469
+ }
1470
+ }
1471
+ }
1472
+ }
1473
+ if (principal) {
1474
+ const parsed = JSON.parse(Buffer.from(principal, 'base64').toString('utf8'));
1475
+ const normalized = {
1476
+ identityProvider: String(parsed.identityProvider || ''),
1477
+ userId: String(parsed.userId || ''),
1478
+ userDetails: String(parsed.userDetails || ''),
1479
+ userRoles: Array.isArray(parsed.userRoles) ? parsed.userRoles.filter((role: unknown) => typeof role === 'string') : [],
1480
+ };
1481
+ if (normalized.userId && normalized.userRoles.includes('authenticated')) {
1482
+ fetchHeaders['x-ms-client-principal'] = Buffer.from(JSON.stringify(normalized), 'utf8').toString('base64');
1483
+ }
1484
+ }`
1485
+ );
1486
+ }
1487
+
1488
+ /** Combined transport for named schemes. Functions still performs all verification. */
1489
+ export function generateBFFCallFunctionWithMultipleAuth(): string {
1490
+ return generateBFFCallFunctionWithSwaAuth().replace(
1491
+ ` // Never forward a browser-supplied principal header. Resolve it from the SWA session endpoint.`,
1492
+ ` const authorization = reqHeaders.get('authorization');
1493
+ if (authorization?.startsWith('Bearer ')) fetchHeaders['Authorization'] = authorization;
1494
+ // Never forward a browser-supplied principal header. Resolve it from the SWA session endpoint.`
1495
+ );
1496
+ }
1497
+
1498
+ export function generateSwaAuthHelperTS(): string {
1499
+ return `import { HttpRequest, HttpResponseInit } from '@azure/functions';
1500
+
1501
+ export interface AuthUser { id: string; loginId: string; roles: string[]; }
1502
+ export class AuthError extends Error { constructor(public status: number, message: string) { super(message); } }
1503
+
1504
+ export function requireAuth(request: HttpRequest): AuthUser {
1505
+ const encoded = request.headers.get('x-ms-client-principal');
1506
+ if (!encoded) throw new AuthError(401, 'Authentication required');
1507
+ try {
1508
+ const value = JSON.parse(Buffer.from(encoded, 'base64').toString('utf8'));
1509
+ const roles = Array.isArray(value.userRoles) ? value.userRoles.filter((r: unknown) => typeof r === 'string') : [];
1510
+ if (typeof value.userId !== 'string' || !value.userId || !roles.includes('authenticated')) throw new Error();
1511
+ return { id: value.userId, loginId: typeof value.userDetails === 'string' ? value.userDetails : '', roles };
1512
+ } catch { throw new AuthError(401, 'Invalid client principal'); }
1513
+ }
1514
+ export function requireRoles(user: AuthUser, roles: string[]): void {
1515
+ if (roles.length && !roles.some(role => user.roles.includes(role))) throw new AuthError(403, 'Insufficient permissions');
1516
+ }
1517
+ export function handleAuthError(error: unknown): HttpResponseInit | null {
1518
+ return error instanceof AuthError ? { status: error.status, jsonBody: { error: error.message } } : null;
1519
+ }
1520
+ `;
1521
+ }
1522
+
1523
+ // ============================================================
1524
+ // External token authentication
1525
+ // ============================================================
1526
+
1527
+ export function generateExternalTokenAdapter(): string {
1528
+ return `/** Replace these functions with your external IdP SDK integration. */
1529
+ export async function getToken(): Promise<string | null> { return null; }
1530
+ export async function login(): Promise<void> { throw new Error('External token login adapter is not configured'); }
1531
+ export async function logout(): Promise<void> { throw new Error('External token logout adapter is not configured'); }
1532
+ `;
1533
+ }
1534
+
1535
+ export function generateAuthenticatedFetch(): string {
1536
+ return `import { getToken } from './external-token-adapter';
1537
+
1538
+ export async function authenticatedFetch(input: RequestInfo | URL, init: RequestInit = {}): Promise<Response> {
1539
+ const token = await getToken();
1540
+ if (!token) return new Response(JSON.stringify({ error: 'Authentication required' }), { status: 401, headers: { 'content-type': 'application/json' } });
1541
+ const headers = new Headers(init.headers);
1542
+ headers.set('Authorization', \`Bearer \${token}\`);
1543
+ return fetch(input, { ...init, headers });
1544
+ }
1545
+ `;
1546
+ }
1547
+
1548
+ export function generateExternalTokenBFFMeRoute(): string {
1549
+ return `import { callFunction } from '@/lib/api/call-function';
1550
+ export async function GET() { return callFunction({ method: 'GET', path: '/api/auth/me' }); }
1551
+ `;
1552
+ }
1553
+
1554
+ export function generateExternalTokenAuthContext(): string {
1555
+ return `'use client';
1556
+ import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
1557
+ import { authenticatedFetch } from './authenticated-fetch';
1558
+ import * as adapter from './external-token-adapter';
1559
+ export interface AuthUser { id: string; loginId: string; name: string; email: string; roles: string[]; }
1560
+ interface Value { user: AuthUser | null; loading: boolean; login: () => Promise<void>; logout: () => Promise<void>; hasRole: (role: string) => boolean; hasAnyRole: (roles: string[]) => boolean; }
1561
+ const Context = createContext<Value | null>(null);
1562
+ export function AuthProvider({ children }: { children: ReactNode }) {
1563
+ const [user, setUser] = useState<AuthUser | null>(null); const [loading, setLoading] = useState(true);
1564
+ useEffect(() => { authenticatedFetch('/api/auth/me').then(async r => {
1565
+ if (!r.ok || !(r.headers.get('content-type') || '').includes('application/json')) return null;
1566
+ return r.json() as Promise<AuthUser>;
1567
+ }).then(setUser).catch(() => setUser(null)).finally(() => setLoading(false)); }, []);
1568
+ const hasRole = (role: string) => user?.roles.includes(role) ?? false;
1569
+ const logout = async () => { await adapter.logout(); setUser(null); };
1570
+ return <Context.Provider value={{ user, loading, login: adapter.login, logout, hasRole, hasAnyRole: roles => roles.some(hasRole) }}>{children}</Context.Provider>;
1571
+ }
1572
+ export function useAuth() { const value = useContext(Context); if (!value) throw new Error('useAuth must be used within an AuthProvider'); return value; }
1573
+ `;
1574
+ }
1575
+
1576
+ export function generateExternalTokenVerifierTS(): string {
1577
+ return `export interface ExternalAuthPrincipal { userId: string; userDetails: string; roles: string[]; }
1578
+ export class ExternalTokenVerificationError extends Error { constructor(public status: 401 | 503, message: string) { super(message); } }
1579
+ /** Implement IdP verification here. Never decode and trust a token without verification. */
1580
+ export async function verifyExternalToken(_token: string): Promise<ExternalAuthPrincipal> {
1581
+ throw new Error('External token verifier is not configured');
1582
+ }
1583
+ `;
1584
+ }
1585
+
1586
+ export function generateExternalTokenHelperTS(): string {
1587
+ return `import { HttpRequest, HttpResponseInit } from '@azure/functions';
1588
+ import { verifyExternalToken, ExternalTokenVerificationError, type ExternalAuthPrincipal } from './external-token-verifier';
1589
+ export class AuthError extends Error { constructor(public status: number, message: string) { super(message); } }
1590
+ export async function requireAuth(request: HttpRequest): Promise<ExternalAuthPrincipal> {
1591
+ const header = request.headers.get('authorization') || '';
1592
+ if (!header.startsWith('Bearer ') || !header.slice(7)) throw new AuthError(401, 'Missing or invalid Authorization header');
1593
+ try { const principal = await verifyExternalToken(header.slice(7));
1594
+ if (!principal?.userId || !Array.isArray(principal.roles)) throw new AuthError(401, 'Invalid external principal');
1595
+ return principal;
1596
+ } catch (error) { if (error instanceof AuthError) throw error; if (error instanceof ExternalTokenVerificationError) throw new AuthError(error.status, error.message); throw new AuthError(500, 'External token verifier is not configured'); }
1597
+ }
1598
+ export function requireRoles(user: ExternalAuthPrincipal, roles: string[]) { if (!roles.some(role => user.roles.includes(role))) throw new AuthError(403, 'Insufficient permissions'); }
1599
+ export function handleAuthError(error: unknown): HttpResponseInit | null { return error instanceof AuthError ? { status: error.status, jsonBody: { error: error.message } } : null; }
1600
+ `;
1601
+ }
1602
+
1603
+ export function generateExternalAuthMeTS(): string {
1604
+ return `import { app, HttpRequest, HttpResponseInit } from '@azure/functions';
1605
+ import { requireAuth, handleAuthError } from './auth/jwt-helper';
1606
+ app.http('external-auth-me', { methods: ['GET'], route: 'auth/me', authLevel: 'function', handler: async (request: HttpRequest): Promise<HttpResponseInit> => {
1607
+ try { const p = await requireAuth(request); return { status: 200, jsonBody: { id: p.userId, loginId: p.userDetails, name: p.userDetails, email: '', roles: p.roles } }; }
1608
+ catch (error) { return handleAuthError(error) || { status: 500, jsonBody: { error: 'Authentication failed' } }; }
1609
+ } });
1610
+ `;
1611
+ }
1612
+
1613
+ export function generateExternalTokenVerifierCSharp(): string { return `namespace Functions.Auth;\npublic record ExternalAuthPrincipal(string UserId, string UserDetails, string[] Roles);\npublic static class ExternalTokenVerifier { public static Task<ExternalAuthPrincipal> VerifyExternalToken(string token) => throw new InvalidOperationException("External token verifier is not configured"); }\n`; }
1614
+ export function generateExternalTokenHelperCSharp(): string { return `using Microsoft.Azure.Functions.Worker.Http;\nnamespace Functions.Auth;\npublic static class JwtHelper { public static async Task<(ExternalAuthPrincipal? Principal, HttpResponseData? ErrorResponse)> Authorize(HttpRequestData request, params string[] roles) { if (!request.Headers.TryGetValues("Authorization", out var values) || !values.FirstOrDefault()!.StartsWith("Bearer ")) { var r=request.CreateResponse(System.Net.HttpStatusCode.Unauthorized); await r.WriteAsJsonAsync(new { error="Authentication required" }); return (null,r); } try { var p=await ExternalTokenVerifier.VerifyExternalToken(values.First()[7..]); if (roles.Length>0 && !roles.Any(p.Roles.Contains)) { var r=request.CreateResponse(System.Net.HttpStatusCode.Forbidden); await r.WriteAsJsonAsync(new { error="Insufficient permissions" }); return (null,r); } return (p,null); } catch (HttpRequestException) { var r=request.CreateResponse(System.Net.HttpStatusCode.ServiceUnavailable); await r.WriteAsJsonAsync(new { error="Identity provider unavailable" }); return (null,r); } catch { var r=request.CreateResponse(System.Net.HttpStatusCode.Unauthorized); await r.WriteAsJsonAsync(new { error="Authentication failed" }); return (null,r); } } }\n`; }
1615
+ export function generateExternalAuthMeCSharp(): string { return `using Microsoft.Azure.Functions.Worker;\nusing Microsoft.Azure.Functions.Worker.Http;\nnamespace Functions.Auth;\npublic class ExternalAuthMe { [Function("external-auth-me")] public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function,"get",Route="auth/me")] HttpRequestData req) { var (p,e)=await JwtHelper.Authorize(req); if(e!=null)return e; var r=req.CreateResponse(System.Net.HttpStatusCode.OK); await r.WriteAsJsonAsync(new { id=p!.UserId, loginId=p.UserDetails, name=p.UserDetails, email="", roles=p.Roles }); return r; } }\n`; }
1616
+ export function generateExternalTokenVerifierPython(): string { return `class ExternalTokenVerificationError(Exception):\n def __init__(self, status: int, message: str): self.status, self.message = status, message\n\ndef verify_external_token(token: str) -> dict:\n raise RuntimeError("External token verifier is not configured")\n`; }
1617
+ export function generateExternalTokenHelperPython(): string { return `import azure.functions as func\nfrom .external_token_verifier import verify_external_token, ExternalTokenVerificationError\nclass AuthError(Exception):\n def __init__(self,status,message): self.status,self.message=status,message\ndef require_auth(req: func.HttpRequest):\n header=req.headers.get("authorization","")\n if not header.startswith("Bearer "): raise AuthError(401,"Authentication required")\n try:\n p=verify_external_token(header[7:])\n if not p.get("userId") or not isinstance(p.get("roles"),list): raise AuthError(401,"Invalid external principal")\n return p\n except ExternalTokenVerificationError as e: raise AuthError(e.status,e.message)\n except AuthError: raise\n except RuntimeError: raise AuthError(500,"External token verifier is not configured")\ndef require_roles(user,roles):\n if not any(r in user.get("roles",[]) for r in roles): raise AuthError(403,"Insufficient permissions")\ndef handle_auth_error(error):\n return func.HttpResponse('{"error":"%s"}' % error.message,status_code=error.status,mimetype="application/json") if isinstance(error,AuthError) else None\n`; }
1618
+ export function generateExternalAuthMePython(): string { return `import json\nimport azure.functions as func\nfrom auth.jwt_helper import require_auth, handle_auth_error\nbp=func.Blueprint()\n@bp.route(route="auth/me",methods=["GET"],auth_level=func.AuthLevel.FUNCTION)\ndef auth_me(req: func.HttpRequest):\n try:\n p=require_auth(req); return func.HttpResponse(json.dumps({"id":p["userId"],"loginId":p.get("userDetails",""),"name":p.get("userDetails",""),"email":"","roles":p["roles"]}),mimetype="application/json")\n except Exception as e:\n return handle_auth_error(e) or func.HttpResponse('{"error":"Authentication failed"}',status_code=500,mimetype="application/json")\n`; }
1619
+ export function generateSwaAuthHelperPython(): string {
1620
+ return `import base64
1621
+ import json
1622
+ import azure.functions as func
1623
+
1624
+ class AuthError(Exception):
1625
+ def __init__(self, status, message): self.status, self.message = status, message
1626
+
1627
+ def require_auth(req):
1628
+ encoded = req.headers.get("x-ms-client-principal")
1629
+ if not encoded: raise AuthError(401, "Authentication required")
1630
+ try:
1631
+ value = json.loads(base64.b64decode(encoded).decode("utf-8"))
1632
+ roles = [r for r in value.get("userRoles", []) if isinstance(r, str)]
1633
+ if not value.get("userId") or "authenticated" not in roles: raise ValueError()
1634
+ return {"id": value["userId"], "loginId": value.get("userDetails", ""), "roles": roles}
1635
+ except Exception: raise AuthError(401, "Invalid client principal")
1636
+
1637
+ def require_roles(user, roles):
1638
+ if roles and not any(role in user["roles"] for role in roles): raise AuthError(403, "Insufficient permissions")
1639
+
1640
+ def handle_auth_error(error):
1641
+ return func.HttpResponse(json.dumps({"error": error.message}), status_code=error.status, mimetype="application/json") if isinstance(error, AuthError) else None
1642
+ `;
1643
+ }
1644
+
1645
+ export function generateSwaAuthHelperCSharp(): string {
1646
+ return `using System.Text;
1647
+ using System.Text.Json;
1648
+ using Microsoft.Azure.Functions.Worker.Http;
1649
+
1650
+ namespace Functions.Auth;
1651
+
1652
+ public class JwtPayload
1653
+ {
1654
+ public string Sub { get; set; } = "";
1655
+ public string LoginId { get; set; } = "";
1656
+ public string[] Roles { get; set; } = Array.Empty<string>();
1657
+ }
1658
+
1659
+ public static class JwtHelper
1660
+ {
1661
+ public static async Task<(JwtPayload?, HttpResponseData?)> Authorize(HttpRequestData request, params string[] requiredRoles)
1662
+ {
1663
+ try
1664
+ {
1665
+ var encoded = request.Headers.TryGetValues("x-ms-client-principal", out var values) ? values.FirstOrDefault() : null;
1666
+ if (string.IsNullOrWhiteSpace(encoded)) throw new InvalidOperationException();
1667
+ using var document = JsonDocument.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(encoded)));
1668
+ var root = document.RootElement;
1669
+ var userId = root.GetProperty("userId").GetString() ?? "";
1670
+ var details = root.TryGetProperty("userDetails", out var detailValue) ? detailValue.GetString() ?? "" : "";
1671
+ var roles = root.TryGetProperty("userRoles", out var roleValue) && roleValue.ValueKind == JsonValueKind.Array
1672
+ ? roleValue.EnumerateArray().Where(v => v.ValueKind == JsonValueKind.String).Select(v => v.GetString()!).ToArray()
1673
+ : Array.Empty<string>();
1674
+ if (string.IsNullOrEmpty(userId) || !roles.Contains("authenticated")) throw new InvalidOperationException();
1675
+ if (requiredRoles.Length > 0 && !requiredRoles.Any(roles.Contains))
1676
+ {
1677
+ var forbidden = request.CreateResponse(System.Net.HttpStatusCode.Forbidden);
1678
+ await forbidden.WriteAsJsonAsync(new { error = "Forbidden" });
1679
+ return (null, forbidden);
1680
+ }
1681
+ return (new JwtPayload { Sub = userId, LoginId = details, Roles = roles }, null);
1682
+ }
1683
+ catch
1684
+ {
1685
+ var unauthorized = request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
1686
+ await unauthorized.WriteAsJsonAsync(new { error = "Unauthorized" });
1687
+ return (null, unauthorized);
1688
+ }
1689
+ }
1690
+ }
1691
+ `;
1692
+ }
1693
+
1694
+ // ============================================================
1695
+ // 13. scaffold 用ロールガード挿入ヘルパー
1696
+ // ============================================================
1697
+
1698
+ /**
1699
+ * TypeScript Functions のハンドラーにロールガードを挿入するためのインポート文を生成
1700
+ */
1701
+ export function generateAuthImportTS(namedPolicy = false): string {
1702
+ return `import { requireAuth, requireRoles, handleAuthError } from './auth/${namedPolicy ? "auth-router" : "jwt-helper"}';`;
1703
+ }
1704
+
1705
+ /**
1706
+ * TypeScript Functions のハンドラー先頭に挿入する認証チェックコードを生成
1707
+ */
1708
+ export function generateAuthGuardTS(policy: ModelAuthPolicy, operation: 'read' | 'write', provider?: AuthProvider): string {
1709
+ const selected = operation === 'read' ? policy.read : policy.write;
1710
+ if (typeof selected === 'string' || policy.policy) {
1711
+ const name = typeof selected === 'string' ? selected : policy.policy!;
1712
+ return ` const authUser = await requireAuth(request, ${JSON.stringify(name)});`;
1713
+ }
1714
+ const roles = selected || policy.roles || [];
1715
+
1716
+ if (roles.length > 0) {
1717
+ return ` const authUser = ${provider === 'external-token' ? 'await ' : ''}requireAuth(request);
1718
+ requireRoles(authUser, ${JSON.stringify(roles)});`;
1719
+ }
1720
+ return ` const authUser = ${provider === 'external-token' ? 'await ' : ''}requireAuth(request);`;
1721
+ }
1722
+
1723
+ /**
1724
+ * C# Functions のハンドラーに挿入するロールガードコードを生成
1725
+ */
1726
+ export function generateAuthGuardCSharp(policy: ModelAuthPolicy, operation: 'read' | 'write'): string {
1727
+ const selected = operation === 'read' ? policy.read : policy.write;
1728
+ if (typeof selected === 'string' || policy.policy) {
1729
+ const name = typeof selected === 'string' ? selected : policy.policy!;
1730
+ return ` var (principal, errorResponse) = await AuthRouter.Authorize(request, ${JSON.stringify(name)});\n if (errorResponse != null) return errorResponse;`;
1731
+ }
1732
+ const roles = selected || policy.roles || [];
1733
+
1734
+ if (roles.length > 0) {
1735
+ const rolesStr = roles.map(r => `"${r}"`).join(', ');
1736
+ return ` var (principal, errorResponse) = await JwtHelper.Authorize(request, ${rolesStr});
1737
+ if (errorResponse != null) return errorResponse;`;
1738
+ }
1739
+ return ` var (principal, errorResponse) = await JwtHelper.Authorize(request);
1740
+ if (errorResponse != null) return errorResponse;`;
1741
+ }
1742
+
1743
+ /**
1744
+ * Python Functions のハンドラーに挿入するロールガードコードを生成
1745
+ */
1746
+ export function generateAuthGuardPython(policy: ModelAuthPolicy, operation: 'read' | 'write'): string {
1747
+ const selected = operation === 'read' ? policy.read : policy.write;
1748
+ if (typeof selected === 'string' || policy.policy) {
1749
+ const name = typeof selected === 'string' ? selected : policy.policy!;
1750
+ return ` user = require_auth(req, ${JSON.stringify(name)})`;
1751
+ }
1752
+ const roles = selected || policy.roles || [];
1753
+
1754
+ if (roles.length > 0) {
1755
+ const rolesStr = roles.map(r => `"${r}"`).join(', ');
1756
+ return ` user = require_auth(req)
1757
+ require_roles(user, [${rolesStr}])`;
1758
+ }
1759
+ return ` user = require_auth(req)`;
1760
+ }