swallowkit 1.0.0-beta.53 ā 1.0.0-beta.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/commands/scaffold.d.ts +6 -0
- package/dist/cli/commands/scaffold.d.ts.map +1 -1
- package/dist/cli/commands/scaffold.js +9 -0
- package/dist/cli/commands/scaffold.js.map +1 -1
- package/dist/core/scaffold/auth-generator.d.ts +1 -1
- package/dist/core/scaffold/auth-generator.d.ts.map +1 -1
- package/dist/core/scaffold/auth-generator.js +84 -25
- package/dist/core/scaffold/auth-generator.js.map +1 -1
- package/dist/core/scaffold/ui-generator.d.ts +4 -0
- package/dist/core/scaffold/ui-generator.d.ts.map +1 -1
- package/dist/core/scaffold/ui-generator.js +20 -0
- package/dist/core/scaffold/ui-generator.js.map +1 -1
- package/package.json +1 -1
- package/src/__tests__/bff-swa-auth.test.ts +275 -0
- package/src/__tests__/multi-auth.test.ts +18 -3
- package/src/__tests__/scaffold.test.ts +112 -1
- package/src/__tests__/ui-generator.test.ts +36 -0
- package/src/cli/commands/scaffold.ts +10 -2
- package/src/core/scaffold/auth-generator.ts +95 -33
- package/src/core/scaffold/ui-generator.ts +21 -0
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import {
|
|
3
|
+
generateBFFCallFunctionWithMultipleAuth,
|
|
4
|
+
generateBFFCallFunctionWithSwaAuth,
|
|
5
|
+
} from "../core/scaffold/auth-generator";
|
|
6
|
+
|
|
7
|
+
type GeneratedModule = {
|
|
8
|
+
callFunction(config: { method: "GET"; path: string }): Promise<unknown>;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
type FetchCall = {
|
|
12
|
+
url: string;
|
|
13
|
+
init: RequestInit | undefined;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const originalFetch = global.fetch;
|
|
17
|
+
const originalBaseUrl = process.env.BACKEND_FUNCTIONS_BASE_URL;
|
|
18
|
+
const originalFunctionsKey = process.env.BACKEND_FUNCTIONS_KEY;
|
|
19
|
+
|
|
20
|
+
function encodePrincipal(value: unknown): string {
|
|
21
|
+
return Buffer.from(JSON.stringify(value), "utf8").toString("base64");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function decodeForwardedPrincipal(call: FetchCall): Record<string, unknown> | undefined {
|
|
25
|
+
const value = (call.init?.headers as Record<string, string>)["x-ms-client-principal"];
|
|
26
|
+
return value
|
|
27
|
+
? JSON.parse(Buffer.from(value, "base64").toString("utf8"))
|
|
28
|
+
: undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function loadGeneratedModule(
|
|
32
|
+
code: string,
|
|
33
|
+
requestHeaders: Record<string, string>,
|
|
34
|
+
): GeneratedModule {
|
|
35
|
+
const output = ts.transpileModule(code, {
|
|
36
|
+
compilerOptions: {
|
|
37
|
+
esModuleInterop: true,
|
|
38
|
+
module: ts.ModuleKind.CommonJS,
|
|
39
|
+
target: ts.ScriptTarget.ES2020,
|
|
40
|
+
},
|
|
41
|
+
reportDiagnostics: true,
|
|
42
|
+
});
|
|
43
|
+
expect(output.diagnostics).toEqual([]);
|
|
44
|
+
|
|
45
|
+
class MockNextResponse {
|
|
46
|
+
static json(body: unknown, init?: { status?: number }) {
|
|
47
|
+
return { body, status: init?.status ?? 200 };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
constructor(
|
|
51
|
+
public body: unknown,
|
|
52
|
+
public init?: { status?: number },
|
|
53
|
+
) {}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const generatedModule = { exports: {} as GeneratedModule };
|
|
57
|
+
const mockRequire = (id: string): unknown => {
|
|
58
|
+
if (id === "next/server") return { NextResponse: MockNextResponse };
|
|
59
|
+
if (id === "next/headers") {
|
|
60
|
+
return { headers: async () => new Headers(requestHeaders) };
|
|
61
|
+
}
|
|
62
|
+
if (id === "zod/v4") return require("zod/v4");
|
|
63
|
+
throw new Error(`Unexpected generated import: ${id}`);
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
new Function("require", "module", "exports", output.outputText)(
|
|
67
|
+
mockRequire,
|
|
68
|
+
generatedModule,
|
|
69
|
+
generatedModule.exports,
|
|
70
|
+
);
|
|
71
|
+
return generatedModule.exports;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function runGeneratedCall(options: {
|
|
75
|
+
code: string;
|
|
76
|
+
requestHeaders: Record<string, string>;
|
|
77
|
+
mePrincipal?: unknown;
|
|
78
|
+
functionsBaseUrl?: string;
|
|
79
|
+
}): Promise<FetchCall[]> {
|
|
80
|
+
process.env.BACKEND_FUNCTIONS_BASE_URL =
|
|
81
|
+
options.functionsBaseUrl ?? "https://functions.example.test";
|
|
82
|
+
process.env.BACKEND_FUNCTIONS_KEY = "functions-key-secret";
|
|
83
|
+
|
|
84
|
+
const calls: FetchCall[] = [];
|
|
85
|
+
global.fetch = jest.fn(async (input: string | URL | Request, init?: RequestInit) => {
|
|
86
|
+
const url = input.toString();
|
|
87
|
+
calls.push({ url, init });
|
|
88
|
+
if (url.endsWith("/.auth/me")) {
|
|
89
|
+
return {
|
|
90
|
+
ok: true,
|
|
91
|
+
status: 200,
|
|
92
|
+
json: async () => ({ clientPrincipal: options.mePrincipal }),
|
|
93
|
+
} as Response;
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
ok: true,
|
|
97
|
+
status: 200,
|
|
98
|
+
json: async () => ({ ok: true }),
|
|
99
|
+
text: async () => "",
|
|
100
|
+
} as Response;
|
|
101
|
+
}) as typeof fetch;
|
|
102
|
+
|
|
103
|
+
const generated = loadGeneratedModule(options.code, options.requestHeaders);
|
|
104
|
+
await generated.callFunction({ method: "GET", path: "/api/resource" });
|
|
105
|
+
return calls;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function functionsCall(calls: FetchCall[]): FetchCall {
|
|
109
|
+
const call = calls.find(({ url }) => url.endsWith("/api/resource"));
|
|
110
|
+
expect(call).toBeDefined();
|
|
111
|
+
return call!;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
afterEach(() => {
|
|
115
|
+
global.fetch = originalFetch;
|
|
116
|
+
if (originalBaseUrl === undefined) delete process.env.BACKEND_FUNCTIONS_BASE_URL;
|
|
117
|
+
else process.env.BACKEND_FUNCTIONS_BASE_URL = originalBaseUrl;
|
|
118
|
+
if (originalFunctionsKey === undefined) delete process.env.BACKEND_FUNCTIONS_KEY;
|
|
119
|
+
else process.env.BACKEND_FUNCTIONS_KEY = originalFunctionsKey;
|
|
120
|
+
jest.restoreAllMocks();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe("generated BFF SWA credential forwarding", () => {
|
|
124
|
+
const validPrincipal = {
|
|
125
|
+
identityProvider: "github",
|
|
126
|
+
userId: "user-123",
|
|
127
|
+
userDetails: "octocat",
|
|
128
|
+
userRoles: ["anonymous", "authenticated", 123],
|
|
129
|
+
untrustedExtra: "must-not-be-forwarded",
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
it("normalizes an incoming principal and does not call /.auth/me", async () => {
|
|
133
|
+
const calls = await runGeneratedCall({
|
|
134
|
+
code: generateBFFCallFunctionWithSwaAuth(),
|
|
135
|
+
requestHeaders: {
|
|
136
|
+
cookie: "session=cookie-secret",
|
|
137
|
+
host: "app.example.test",
|
|
138
|
+
"x-ms-client-principal": encodePrincipal(validPrincipal),
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
expect(calls.map(({ url }) => url)).not.toContain("https://app.example.test/.auth/me");
|
|
143
|
+
expect(decodeForwardedPrincipal(functionsCall(calls))).toEqual({
|
|
144
|
+
identityProvider: "github",
|
|
145
|
+
userId: "user-123",
|
|
146
|
+
userDetails: "octocat",
|
|
147
|
+
userRoles: ["anonymous", "authenticated"],
|
|
148
|
+
});
|
|
149
|
+
expect(
|
|
150
|
+
(functionsCall(calls).init?.headers as Record<string, string>)[
|
|
151
|
+
"x-functions-key"
|
|
152
|
+
],
|
|
153
|
+
).toBe("functions-key-secret");
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("uses x-forwarded-host for the /.auth/me fallback", async () => {
|
|
157
|
+
const calls = await runGeneratedCall({
|
|
158
|
+
code: generateBFFCallFunctionWithSwaAuth(),
|
|
159
|
+
requestHeaders: {
|
|
160
|
+
cookie: "session=valid",
|
|
161
|
+
host: "internal.example.test",
|
|
162
|
+
"x-forwarded-host": "public.example.test",
|
|
163
|
+
},
|
|
164
|
+
mePrincipal: validPrincipal,
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
expect(calls[0].url).toBe("https://public.example.test/.auth/me");
|
|
168
|
+
expect(decodeForwardedPrincipal(functionsCall(calls))).toEqual({
|
|
169
|
+
identityProvider: "github",
|
|
170
|
+
userId: "user-123",
|
|
171
|
+
userDetails: "octocat",
|
|
172
|
+
userRoles: ["anonymous", "authenticated"],
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("falls back to host when x-forwarded-host is absent", async () => {
|
|
177
|
+
const calls = await runGeneratedCall({
|
|
178
|
+
code: generateBFFCallFunctionWithSwaAuth(),
|
|
179
|
+
requestHeaders: { cookie: "session=valid", host: "app.example.test" },
|
|
180
|
+
mePrincipal: validPrincipal,
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
expect(calls[0].url).toBe("https://app.example.test/.auth/me");
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it("uses the first comma-separated forwarded host and protocol", async () => {
|
|
187
|
+
const calls = await runGeneratedCall({
|
|
188
|
+
code: generateBFFCallFunctionWithSwaAuth(),
|
|
189
|
+
requestHeaders: {
|
|
190
|
+
cookie: "session=valid",
|
|
191
|
+
host: "internal.example.test",
|
|
192
|
+
"x-forwarded-host": "public.example.test, proxy.example.test",
|
|
193
|
+
"x-forwarded-proto": "http, https",
|
|
194
|
+
},
|
|
195
|
+
mePrincipal: validPrincipal,
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
expect(calls[0].url).toBe("http://public.example.test/.auth/me");
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it.each([
|
|
202
|
+
["a missing userId", { ...validPrincipal, userId: undefined }],
|
|
203
|
+
["a missing authenticated role", { ...validPrincipal, userRoles: ["anonymous"] }],
|
|
204
|
+
["a missing identityProvider", { ...validPrincipal, identityProvider: "" }],
|
|
205
|
+
])("does not forward a principal with %s", async (_case, principal) => {
|
|
206
|
+
const calls = await runGeneratedCall({
|
|
207
|
+
code: generateBFFCallFunctionWithSwaAuth(),
|
|
208
|
+
requestHeaders: { "x-ms-client-principal": encodePrincipal(principal) },
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
expect(decodeForwardedPrincipal(functionsCall(calls))).toBeUndefined();
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it.each([
|
|
215
|
+
"not-base64!",
|
|
216
|
+
`${encodePrincipal(validPrincipal)}!`,
|
|
217
|
+
Buffer.from("not-json", "utf8").toString("base64"),
|
|
218
|
+
])(
|
|
219
|
+
"fails closed without logging credentials for malformed principal %s",
|
|
220
|
+
async (principal) => {
|
|
221
|
+
const error = jest.spyOn(console, "error").mockImplementation(() => undefined);
|
|
222
|
+
const cookie = "session=highly-sensitive-cookie";
|
|
223
|
+
const calls = await runGeneratedCall({
|
|
224
|
+
code: generateBFFCallFunctionWithSwaAuth(),
|
|
225
|
+
requestHeaders: { cookie, "x-ms-client-principal": principal },
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
expect(decodeForwardedPrincipal(functionsCall(calls))).toBeUndefined();
|
|
229
|
+
const logged = JSON.stringify(error.mock.calls);
|
|
230
|
+
expect(logged).not.toContain(cookie);
|
|
231
|
+
expect(logged).not.toContain(principal);
|
|
232
|
+
},
|
|
233
|
+
);
|
|
234
|
+
|
|
235
|
+
it("preserves Bearer and applies the same SWA rules for multiple auth", async () => {
|
|
236
|
+
const calls = await runGeneratedCall({
|
|
237
|
+
code: generateBFFCallFunctionWithMultipleAuth(),
|
|
238
|
+
requestHeaders: {
|
|
239
|
+
authorization: "Bearer line-token-secret",
|
|
240
|
+
"x-ms-client-principal": encodePrincipal(validPrincipal),
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
const headers = functionsCall(calls).init?.headers as Record<string, string>;
|
|
244
|
+
|
|
245
|
+
expect(headers.Authorization).toBe("Bearer line-token-secret");
|
|
246
|
+
expect(decodeForwardedPrincipal(functionsCall(calls))?.userId).toBe("user-123");
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it("does not add Bearer forwarding to the SWA-only variant", async () => {
|
|
250
|
+
const code = generateBFFCallFunctionWithSwaAuth();
|
|
251
|
+
const calls = await runGeneratedCall({
|
|
252
|
+
code,
|
|
253
|
+
requestHeaders: {
|
|
254
|
+
authorization: "Bearer must-not-be-forwarded",
|
|
255
|
+
"x-ms-client-principal": encodePrincipal(validPrincipal),
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
const headers = functionsCall(calls).init?.headers as Record<string, string>;
|
|
259
|
+
|
|
260
|
+
expect(headers.Authorization).toBeUndefined();
|
|
261
|
+
expect(code).not.toContain("reqHeaders.get('authorization')");
|
|
262
|
+
expect(decodeForwardedPrincipal(functionsCall(calls))?.userId).toBe("user-123");
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
it("defaults /.auth/me to http for local Functions development", async () => {
|
|
266
|
+
const calls = await runGeneratedCall({
|
|
267
|
+
code: generateBFFCallFunctionWithSwaAuth(),
|
|
268
|
+
requestHeaders: { cookie: "session=valid", host: "localhost:3000" },
|
|
269
|
+
mePrincipal: validPrincipal,
|
|
270
|
+
functionsBaseUrl: "http://localhost:7071",
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
expect(calls[0].url).toBe("http://localhost:3000/.auth/me");
|
|
274
|
+
});
|
|
275
|
+
});
|
|
@@ -2,6 +2,7 @@ import * as fs from "fs";
|
|
|
2
2
|
import * as os from "os";
|
|
3
3
|
import * as path from "path";
|
|
4
4
|
import { addAuthCommand } from "../cli/commands/add-auth";
|
|
5
|
+
import { createUIAuthOptions } from "../cli/commands/scaffold";
|
|
5
6
|
import {
|
|
6
7
|
generateBFFCallFunctionWithMultipleAuth,
|
|
7
8
|
generateNamedAuthRouterCSharp,
|
|
@@ -12,8 +13,10 @@ import { normalizeAuthConfig } from "../core/config";
|
|
|
12
13
|
import { parseAuthPolicy } from "../core/scaffold/model-parser";
|
|
13
14
|
import { createBasicModelInfo } from "./fixtures";
|
|
14
15
|
import { generateCSharpAzureFunctionsCRUD, generateCompactAzureFunctionsCRUD, generatePythonAzureFunctionsCRUD } from "../core/scaffold/functions-generator";
|
|
16
|
+
import { generateAuthLayout, generateNewPage } from "../core/scaffold/ui-generator";
|
|
17
|
+
import { AuthConfig } from "../types";
|
|
15
18
|
|
|
16
|
-
const
|
|
19
|
+
const namedAuthConfig: AuthConfig = {
|
|
17
20
|
schemes: {
|
|
18
21
|
admin: { provider: "swa" },
|
|
19
22
|
lineUser: { provider: "external-token" },
|
|
@@ -25,7 +28,8 @@ const auth = normalizeAuthConfig({
|
|
|
25
28
|
lineUserOnly: { schemes: ["lineUser"], roles: ["authenticated"] },
|
|
26
29
|
},
|
|
27
30
|
},
|
|
28
|
-
}
|
|
31
|
+
};
|
|
32
|
+
const auth = normalizeAuthConfig(namedAuthConfig)!;
|
|
29
33
|
|
|
30
34
|
describe("named authentication routers", () => {
|
|
31
35
|
it("generates deterministic TypeScript policy routing and normalized principals", () => {
|
|
@@ -77,7 +81,7 @@ describe("named authentication routers", () => {
|
|
|
77
81
|
|
|
78
82
|
it("forwards both credential sources and the Functions host key", () => {
|
|
79
83
|
const code = generateBFFCallFunctionWithMultipleAuth();
|
|
80
|
-
expect(code).toContain("fetchHeaders
|
|
84
|
+
expect(code).toContain("fetchHeaders.Authorization");
|
|
81
85
|
expect(code).toContain("fetchHeaders['x-ms-client-principal']");
|
|
82
86
|
expect(code).toContain("'x-functions-key'");
|
|
83
87
|
expect(code).not.toMatch(/console\.log\([^\n]*(authorization|principal|cookie)/i);
|
|
@@ -89,6 +93,17 @@ describe("named authentication routers", () => {
|
|
|
89
93
|
expect(parseAuthPolicy("export const authPolicy = { read: 'adminOnly', write: 'lineUserOnly' };"))
|
|
90
94
|
.toEqual({ read: "adminOnly", write: "lineUserOnly" });
|
|
91
95
|
});
|
|
96
|
+
|
|
97
|
+
it("resolves the same named auth context for the model layout and CRUD pages", () => {
|
|
98
|
+
const model = createBasicModelInfo({ name: "Product", authPolicy: { policy: "adminOnly" } });
|
|
99
|
+
const options = createUIAuthOptions(model.authPolicy!, namedAuthConfig);
|
|
100
|
+
const layout = generateAuthLayout(model, options);
|
|
101
|
+
const page = generateNewPage(model, options);
|
|
102
|
+
|
|
103
|
+
expect(options.authContextImport).toBe("@/lib/auth/schemes/admin/auth-context");
|
|
104
|
+
expect(layout).toContain("AuthProvider } from '@/lib/auth/schemes/admin/auth-context'");
|
|
105
|
+
expect(page).toContain("useAuth } from '@/lib/auth/schemes/admin/auth-context'");
|
|
106
|
+
});
|
|
92
107
|
});
|
|
93
108
|
|
|
94
109
|
describe("add-auth named scheme CLI", () => {
|
|
@@ -3,7 +3,7 @@ import * as fs from "fs";
|
|
|
3
3
|
import * as os from "os";
|
|
4
4
|
import { EventEmitter } from "events";
|
|
5
5
|
import * as childProcess from "child_process";
|
|
6
|
-
import { generateCosmosContainer } from "../cli/commands/scaffold";
|
|
6
|
+
import { generateCosmosContainer, generateUIComponents } from "../cli/commands/scaffold";
|
|
7
7
|
import {
|
|
8
8
|
NSWAG_CONSOLECORE_VERSION,
|
|
9
9
|
buildCSharpCodegenToolManifestSource,
|
|
@@ -17,6 +17,117 @@ import {
|
|
|
17
17
|
} from "../core/scaffold/native-schema-generator";
|
|
18
18
|
import { createBasicModelInfo } from "./fixtures";
|
|
19
19
|
|
|
20
|
+
describe("authenticated UI scaffold layouts", () => {
|
|
21
|
+
const originalCwd = process.cwd();
|
|
22
|
+
let tempDir: string;
|
|
23
|
+
const authOptions = {
|
|
24
|
+
authPolicy: { policy: "staffOnly" },
|
|
25
|
+
writeRoles: ["authenticated"],
|
|
26
|
+
authContextImport: "@/lib/auth/schemes/staff/auth-context",
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
beforeEach(() => {
|
|
30
|
+
tempDir = fs.mkdtempSync(path.join(originalCwd, ".tmp-auth-layout-"));
|
|
31
|
+
process.chdir(tempDir);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
afterEach(() => {
|
|
35
|
+
process.chdir(originalCwd);
|
|
36
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("writes a model-scoped provider layout and regenerates it stably", async () => {
|
|
40
|
+
const model = createBasicModelInfo({ name: "Product", schemaName: "productSchema" });
|
|
41
|
+
|
|
42
|
+
await generateUIComponents(model, "@fixture/shared", authOptions);
|
|
43
|
+
const layoutPath = path.join(tempDir, "app", "product", "layout.tsx");
|
|
44
|
+
const first = fs.readFileSync(layoutPath, "utf-8");
|
|
45
|
+
await generateUIComponents(model, "@fixture/shared", authOptions);
|
|
46
|
+
const second = fs.readFileSync(layoutPath, "utf-8");
|
|
47
|
+
|
|
48
|
+
expect(second).toBe(first);
|
|
49
|
+
expect(second).toContain("from '@/lib/auth/schemes/staff/auth-context'");
|
|
50
|
+
expect(second.match(/import \{ AuthProvider \}/g)).toHaveLength(1);
|
|
51
|
+
expect(second.match(/<AuthProvider>/g)).toHaveLength(1);
|
|
52
|
+
expect(fs.readFileSync(path.join(tempDir, "app", "product", "page.tsx"), "utf-8"))
|
|
53
|
+
.toContain("from '@/lib/auth/schemes/staff/auth-context'");
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("does not create an auth layout for an unauthenticated model or affect another route", async () => {
|
|
57
|
+
await generateUIComponents(createBasicModelInfo({ name: "Product", schemaName: "productSchema" }), "@fixture/shared");
|
|
58
|
+
await generateUIComponents(createBasicModelInfo({ name: "Line", schemaName: "lineSchema" }), "@fixture/shared");
|
|
59
|
+
|
|
60
|
+
expect(fs.existsSync(path.join(tempDir, "app", "product", "layout.tsx"))).toBe(false);
|
|
61
|
+
expect(fs.existsSync(path.join(tempDir, "app", "line", "layout.tsx"))).toBe(false);
|
|
62
|
+
expect(fs.readFileSync(path.join(tempDir, "app", "line", "page.tsx"), "utf-8"))
|
|
63
|
+
.not.toContain("schemes/staff/auth-context");
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("builds the generated authenticated CRUD routes with Next.js", async () => {
|
|
67
|
+
const model = createBasicModelInfo({ name: "Product", schemaName: "productSchema" });
|
|
68
|
+
await generateUIComponents(model, "@fixture/shared", authOptions);
|
|
69
|
+
|
|
70
|
+
writeFile(path.join(tempDir, "app", "layout.tsx"), `export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
71
|
+
return <html><body>{children}</body></html>;
|
|
72
|
+
}
|
|
73
|
+
`);
|
|
74
|
+
writeFile(path.join(tempDir, "lib", "auth", "schemes", "staff", "auth-context.tsx"), `'use client';
|
|
75
|
+
import { createContext, useContext } from 'react';
|
|
76
|
+
const AuthContext = createContext<{ user: { id: string }; loading: boolean; hasAnyRole: (roles: string[]) => boolean } | null>(null);
|
|
77
|
+
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|
78
|
+
return <AuthContext.Provider value={{ user: { id: 'test' }, loading: false, hasAnyRole: () => true }}>{children}</AuthContext.Provider>;
|
|
79
|
+
}
|
|
80
|
+
export function useAuth() {
|
|
81
|
+
const value = useContext(AuthContext);
|
|
82
|
+
if (!value) throw new Error('useAuth must be used within an AuthProvider');
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
`);
|
|
86
|
+
writeFile(path.join(tempDir, "shared.ts"), `import { z } from 'zod/v4';
|
|
87
|
+
export const productSchema = z.object({
|
|
88
|
+
id: z.string(),
|
|
89
|
+
title: z.string(),
|
|
90
|
+
description: z.string().optional(),
|
|
91
|
+
completed: z.boolean(),
|
|
92
|
+
createdAt: z.string(),
|
|
93
|
+
updatedAt: z.string(),
|
|
94
|
+
});
|
|
95
|
+
`);
|
|
96
|
+
writeFile(path.join(tempDir, "package.json"), JSON.stringify({
|
|
97
|
+
private: true,
|
|
98
|
+
scripts: { build: "next build" },
|
|
99
|
+
}, null, 2));
|
|
100
|
+
writeFile(path.join(tempDir, "tsconfig.json"), JSON.stringify({
|
|
101
|
+
compilerOptions: {
|
|
102
|
+
target: "ES2020",
|
|
103
|
+
lib: ["dom", "dom.iterable", "esnext"],
|
|
104
|
+
strict: true,
|
|
105
|
+
noEmit: true,
|
|
106
|
+
esModuleInterop: true,
|
|
107
|
+
module: "esnext",
|
|
108
|
+
moduleResolution: "bundler",
|
|
109
|
+
resolveJsonModule: true,
|
|
110
|
+
isolatedModules: true,
|
|
111
|
+
jsx: "preserve",
|
|
112
|
+
baseUrl: ".",
|
|
113
|
+
paths: { "@/*": ["./*"], "@fixture/shared": ["./shared.ts"] },
|
|
114
|
+
},
|
|
115
|
+
include: ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
|
116
|
+
exclude: ["node_modules"],
|
|
117
|
+
}, null, 2));
|
|
118
|
+
|
|
119
|
+
const npmCommand = process.platform === "win32"
|
|
120
|
+
? { file: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", "npm run build"] }
|
|
121
|
+
: { file: "npm", args: ["run", "build"] };
|
|
122
|
+
expect(() => childProcess.execFileSync(npmCommand.file, npmCommand.args, {
|
|
123
|
+
cwd: tempDir,
|
|
124
|
+
env: { ...process.env, NEXT_TELEMETRY_DISABLED: "1" },
|
|
125
|
+
stdio: "pipe",
|
|
126
|
+
timeout: 120_000,
|
|
127
|
+
})).not.toThrow();
|
|
128
|
+
}, 150_000);
|
|
129
|
+
});
|
|
130
|
+
|
|
20
131
|
jest.mock("child_process", () => {
|
|
21
132
|
const actual = jest.requireActual<typeof import("child_process")>("child_process");
|
|
22
133
|
return {
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
generateFormComponent,
|
|
8
8
|
generateNewPage,
|
|
9
9
|
generateEditPage,
|
|
10
|
+
generateAuthLayout,
|
|
10
11
|
} from "../core/scaffold/ui-generator";
|
|
11
12
|
import {
|
|
12
13
|
createBasicModelInfo,
|
|
@@ -15,6 +16,41 @@ import {
|
|
|
15
16
|
createModelInfoWithEnum,
|
|
16
17
|
} from "./fixtures";
|
|
17
18
|
|
|
19
|
+
const namedAuthOptions = {
|
|
20
|
+
authPolicy: { policy: "staffOnly" },
|
|
21
|
+
writeRoles: ["authenticated"],
|
|
22
|
+
authContextImport: "@/lib/auth/schemes/staff/auth-context",
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
describe("generateAuthLayout", () => {
|
|
26
|
+
it("uses the same resolved auth context as authenticated CRUD pages", () => {
|
|
27
|
+
const model = createBasicModelInfo({ name: "Product" });
|
|
28
|
+
const layout = generateAuthLayout(model, namedAuthOptions);
|
|
29
|
+
const listPage = generateListPage(model, "@myapp/shared", namedAuthOptions);
|
|
30
|
+
const newPage = generateNewPage(model, namedAuthOptions);
|
|
31
|
+
|
|
32
|
+
expect(layout).toContain("import { AuthProvider } from '@/lib/auth/schemes/staff/auth-context';");
|
|
33
|
+
expect(layout).toContain("<AuthProvider>{children}</AuthProvider>");
|
|
34
|
+
expect(layout).toContain("function ProductLayout");
|
|
35
|
+
expect(listPage).toContain("import { useAuth } from '@/lib/auth/schemes/staff/auth-context';");
|
|
36
|
+
expect(newPage).toContain("import { useAuth } from '@/lib/auth/schemes/staff/auth-context';");
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("does not generate an auth layout without auth options", () => {
|
|
40
|
+
expect(generateAuthLayout(createBasicModelInfo({ name: "Product" }))).toBeUndefined();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("is deterministic and does not duplicate providers or imports", () => {
|
|
44
|
+
const model = createBasicModelInfo({ name: "Product" });
|
|
45
|
+
const first = generateAuthLayout(model, namedAuthOptions);
|
|
46
|
+
const second = generateAuthLayout(model, namedAuthOptions);
|
|
47
|
+
|
|
48
|
+
expect(second).toBe(first);
|
|
49
|
+
expect(first?.match(/import \{ AuthProvider \}/g)).toHaveLength(1);
|
|
50
|
+
expect(first?.match(/<AuthProvider>/g)).toHaveLength(1);
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
18
54
|
describe("generateListPage", () => {
|
|
19
55
|
it("generates list page for basic model (snapshot)", () => {
|
|
20
56
|
const model = createBasicModelInfo();
|
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
generateFormComponent,
|
|
29
29
|
generateNewPage,
|
|
30
30
|
generateEditPage,
|
|
31
|
+
generateAuthLayout,
|
|
31
32
|
UIAuthOptions,
|
|
32
33
|
} from "../../core/scaffold/ui-generator";
|
|
33
34
|
import { generateLanguageSchemaArtifacts } from "../../core/scaffold/native-schema-generator";
|
|
@@ -440,7 +441,7 @@ async function generateFunctionsCode(
|
|
|
440
441
|
console.log(`ā
Created: ${blueprintPath}`);
|
|
441
442
|
}
|
|
442
443
|
|
|
443
|
-
function createUIAuthOptions(policy: ModelAuthPolicy, authConfig: AuthConfig): UIAuthOptions {
|
|
444
|
+
export function createUIAuthOptions(policy: ModelAuthPolicy, authConfig: AuthConfig): UIAuthOptions {
|
|
444
445
|
const normalized = normalizeAuthConfig(authConfig);
|
|
445
446
|
const readPolicyName = typeof policy.read === 'string' ? policy.read : policy.policy;
|
|
446
447
|
const writePolicyName = typeof policy.write === 'string' ? policy.write : policy.policy;
|
|
@@ -956,7 +957,7 @@ module ${containerModuleName} 'containers/${modelKebab}-container.bicep' = {
|
|
|
956
957
|
/**
|
|
957
958
|
* Generate UI components (list, detail, form, create, edit pages)
|
|
958
959
|
*/
|
|
959
|
-
async function generateUIComponents(modelInfo:
|
|
960
|
+
export async function generateUIComponents(modelInfo: ModelInfo, sharedPackageName: string, authOptions?: UIAuthOptions): Promise<void> {
|
|
960
961
|
console.log("\nšØ Generating UI components...");
|
|
961
962
|
|
|
962
963
|
const modelKebab = toKebabCase(modelInfo.name);
|
|
@@ -983,18 +984,25 @@ async function generateUIComponents(modelInfo: any, sharedPackageName: string, a
|
|
|
983
984
|
const formComponent = generateFormComponent(modelInfo, sharedPackageName);
|
|
984
985
|
const newPage = generateNewPage(modelInfo, authOptions);
|
|
985
986
|
const editPage = generateEditPage(modelInfo, sharedPackageName, authOptions);
|
|
987
|
+
const authLayout = generateAuthLayout(modelInfo, authOptions);
|
|
986
988
|
|
|
987
989
|
fs.writeFileSync(path.join(modelDir, "page.tsx"), listPage, "utf-8");
|
|
988
990
|
fs.writeFileSync(path.join(idDir, "page.tsx"), detailPage, "utf-8");
|
|
989
991
|
fs.writeFileSync(path.join(componentsDir, `${modelName}Form.tsx`), formComponent, "utf-8");
|
|
990
992
|
fs.writeFileSync(path.join(newDir, "page.tsx"), newPage, "utf-8");
|
|
991
993
|
fs.writeFileSync(path.join(editDir, "page.tsx"), editPage, "utf-8");
|
|
994
|
+
if (authLayout) {
|
|
995
|
+
fs.writeFileSync(path.join(modelDir, "layout.tsx"), authLayout, "utf-8");
|
|
996
|
+
}
|
|
992
997
|
|
|
993
998
|
console.log(`ā
Created: ${path.join(modelDir, "page.tsx")}`);
|
|
994
999
|
console.log(`ā
Created: ${path.join(idDir, "page.tsx")}`);
|
|
995
1000
|
console.log(`ā
Created: ${path.join(componentsDir, `${modelName}Form.tsx`)}`);
|
|
996
1001
|
console.log(`ā
Created: ${path.join(newDir, "page.tsx")}`);
|
|
997
1002
|
console.log(`ā
Created: ${path.join(editDir, "page.tsx")}`);
|
|
1003
|
+
if (authLayout) {
|
|
1004
|
+
console.log(`ā
Created: ${path.join(modelDir, "layout.tsx")}`);
|
|
1005
|
+
}
|
|
998
1006
|
}
|
|
999
1007
|
|
|
1000
1008
|
/**
|