@empire-builder-kit/nx 1.0.0-rc.45 → 1.0.0-rc.47

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 (187) hide show
  1. package/generators.json +11 -1
  2. package/package.json +3 -3
  3. package/src/aws-authority/stage-authority.d.ts +30 -2
  4. package/src/aws-authority/stage-authority.js +220 -25
  5. package/src/developer-agent/generator-planning.js +109 -9
  6. package/src/developer-agent/model.d.ts +7 -3
  7. package/src/developer-agent/model.js +1 -0
  8. package/src/developer-agent/operation-registry.d.ts +1 -0
  9. package/src/developer-agent/operation-registry.js +44 -3
  10. package/src/developer-agent/planning.js +5 -2
  11. package/src/developer-agent/preview-changes.js +10 -0
  12. package/src/developer-agent/validation.js +7 -3
  13. package/src/developer-agent/workspace-inspection.js +51 -4
  14. package/src/executors/deployment-plan/deployment-plan.js +3 -0
  15. package/src/executors/dev-doctor/dev-doctor.d.ts +25 -3
  16. package/src/executors/dev-doctor/dev-doctor.js +136 -49
  17. package/src/executors/dev-setup/dev-setup.d.ts +18 -1
  18. package/src/executors/dev-setup/dev-setup.js +320 -196
  19. package/src/executors/foundation-preflight/foundation-preflight.js +9 -1
  20. package/src/executors/foundation-remove-preflight/foundation-remove-preflight.js +2 -2
  21. package/src/executors/github-bootstrap/github-bootstrap.d.ts +3 -0
  22. package/src/executors/github-bootstrap/github-bootstrap.js +28 -0
  23. package/src/executors/github-bootstrap/schema.json +14 -0
  24. package/src/executors/infrastructure-plan/infrastructure-plan.js +10 -3
  25. package/src/executors/local-deploy/local-deploy.d.ts +15 -0
  26. package/src/executors/local-deploy/local-deploy.js +96 -14
  27. package/src/executors/sst-lifecycle/logging-preflight.js +12 -1
  28. package/src/executors/sst-lifecycle/run-sst-command.js +51 -5
  29. package/src/foundation/cost-estimate.js +1 -1
  30. package/src/foundation/identity-domain-parent-ready.d.ts +91 -0
  31. package/src/foundation/identity-domain-parent-ready.js +333 -0
  32. package/src/foundation/identity-domain.d.ts +94 -0
  33. package/src/foundation/identity-domain.js +115 -0
  34. package/src/foundation/index.d.ts +2 -0
  35. package/src/foundation/index.js +7 -0
  36. package/src/foundation/preflight.js +17 -1
  37. package/src/foundation/root-site-readiness.d.ts +27 -0
  38. package/src/foundation/root-site-readiness.js +78 -0
  39. package/src/foundation/root-site.d.ts +81 -0
  40. package/src/foundation/root-site.js +268 -0
  41. package/src/generators/framework-prerequisites.d.ts +2 -0
  42. package/src/generators/framework-prerequisites.js +34 -0
  43. package/src/generators/function/function-registration.d.ts +24 -0
  44. package/src/generators/function/function-registration.js +66 -0
  45. package/src/generators/function/function.d.ts +16 -1
  46. package/src/generators/function/function.js +101 -18
  47. package/src/generators/function/schema.d.ts +1 -0
  48. package/src/generators/function/schema.json +6 -0
  49. package/src/generators/function-access/function-access.d.ts +14 -0
  50. package/src/generators/function-access/function-access.js +141 -0
  51. package/src/generators/function-access/schema.d.ts +6 -0
  52. package/src/generators/function-access/schema.json +25 -0
  53. package/src/generators/post-generation-install.d.ts +1 -1
  54. package/src/generators/post-generation-install.js +1 -1
  55. package/src/generators/preset/dependency-overrides.d.ts +1 -1
  56. package/src/generators/preset/dependency-overrides.js +1 -1
  57. package/src/generators/preset/workspace-files-adopter-skills.js +14 -0
  58. package/src/generators/preset/workspace-files-developer-agent.js +17 -11
  59. package/src/generators/preset/workspace-files-stage-authority.js +58 -1
  60. package/src/generators/preset/workspace-files-thin-deploy.d.ts +11 -0
  61. package/src/generators/preset/workspace-files-thin-deploy.js +52 -5
  62. package/src/generators/preset/workspace-files-thin-docs.js +33 -5
  63. package/src/generators/preset/workspace-files.js +238 -41
  64. package/src/generators/repository-policy/repository-policy.js +2 -1
  65. package/src/generators/repository-policy/schema.d.ts +2 -0
  66. package/src/generators/repository-policy/schema.json +7 -2
  67. package/src/generators/site/built-in-site-documentation-files.d.ts +2 -0
  68. package/src/generators/site/built-in-site-documentation-files.js +92 -0
  69. package/src/generators/site/built-in-site-files.d.ts +8 -0
  70. package/src/generators/site/built-in-site-files.js +40 -0
  71. package/src/generators/site/built-in-site-infrastructure-files.d.ts +2 -0
  72. package/src/generators/site/built-in-site-infrastructure-files.js +275 -0
  73. package/src/generators/site/built-in-site-plan.d.ts +19 -0
  74. package/src/generators/site/built-in-site-plan.js +65 -0
  75. package/src/generators/site/built-in-site-project-files.d.ts +3 -0
  76. package/src/generators/site/built-in-site-project-files.js +258 -0
  77. package/src/generators/site/built-in-site-script-files.d.ts +2 -0
  78. package/src/generators/site/built-in-site-script-files.js +306 -0
  79. package/src/generators/site/built-in-site-shared.d.ts +9 -0
  80. package/src/generators/site/built-in-site-shared.js +21 -0
  81. package/src/generators/site/built-in-site-smoke-files.d.ts +2 -0
  82. package/src/generators/site/built-in-site-smoke-files.js +37 -0
  83. package/src/generators/site/built-in-site-sst-config-files.d.ts +2 -0
  84. package/src/generators/site/built-in-site-sst-config-files.js +39 -0
  85. package/src/generators/site/built-in-site-web-files.d.ts +2 -0
  86. package/src/generators/site/built-in-site-web-files.js +284 -0
  87. package/src/generators/site/schema.d.ts +4 -0
  88. package/src/generators/site/schema.json +20 -0
  89. package/src/generators/site/site.d.ts +13 -0
  90. package/src/generators/site/site.js +221 -0
  91. package/src/generators/slice/built-in-plan-alarm-identity.d.ts +9 -0
  92. package/src/generators/slice/built-in-plan-alarm-identity.js +8 -1
  93. package/src/generators/slice/built-in-plan-api-contract-files.js +18 -0
  94. package/src/generators/slice/built-in-plan-async-work-files.js +18 -0
  95. package/src/generators/slice/built-in-plan-data-files.js +126 -14
  96. package/src/generators/slice/built-in-plan-foundation-files.d.ts +12 -0
  97. package/src/generators/slice/built-in-plan-foundation-files.js +114 -5
  98. package/src/generators/slice/built-in-plan-frontend-files.js +2 -271
  99. package/src/generators/slice/built-in-plan-frontend-header-proof.d.ts +6 -0
  100. package/src/generators/slice/built-in-plan-frontend-header-proof.js +282 -0
  101. package/src/generators/slice/built-in-plan-infrastructure-files.js +151 -237
  102. package/src/generators/slice/built-in-plan-key-value-cleanup.js +4 -3
  103. package/src/generators/slice/built-in-plan-log-group-helpers.d.ts +29 -0
  104. package/src/generators/slice/built-in-plan-log-group-helpers.js +130 -0
  105. package/src/generators/slice/built-in-plan-metadata-files.js +25 -5
  106. package/src/generators/slice/built-in-plan-next-build-authority.d.ts +5 -0
  107. package/src/generators/slice/built-in-plan-next-build-authority.js +124 -0
  108. package/src/generators/slice/built-in-plan-operations-files.d.ts +6 -0
  109. package/src/generators/slice/built-in-plan-operations-files.js +107 -219
  110. package/src/generators/slice/built-in-plan-performance-files.js +6 -1
  111. package/src/generators/slice/built-in-plan-release-files.js +0 -1
  112. package/src/generators/slice/built-in-plan-reliability-files.js +12 -8
  113. package/src/generators/slice/built-in-plan-shared.d.ts +1 -1
  114. package/src/generators/slice/built-in-plan-shared.js +1 -1
  115. package/src/generators/slice/built-in-plan-sst-config.d.ts +49 -0
  116. package/src/generators/slice/built-in-plan-sst-config.js +160 -0
  117. package/src/generators/slice/built-in-plan-testing-files.js +92 -49
  118. package/src/generators/slice/built-in-plan-verification-files.js +15 -5
  119. package/src/generators/slice/built-in-plan-web-files.js +69 -5
  120. package/src/generators/slice/built-in-plan.js +1 -2
  121. package/src/generators/slice/deployed-smoke-diagnostics.d.ts +35 -0
  122. package/src/generators/slice/deployed-smoke-diagnostics.js +189 -0
  123. package/src/generators/slice/deployed-smoke-readiness.d.ts +7 -0
  124. package/src/generators/slice/deployed-smoke-readiness.js +118 -23
  125. package/src/generators/slice/persistence-contract.js +2 -2
  126. package/src/generators/slice/pnpm-launch-script.d.ts +13 -0
  127. package/src/generators/slice/pnpm-launch-script.js +28 -0
  128. package/src/generators/slice/slice.js +27 -0
  129. package/src/generators/upgrade/custom-domain-notice.d.ts +19 -0
  130. package/src/generators/upgrade/custom-domain-notice.js +38 -0
  131. package/src/generators/upgrade/external-blueprint-compositions.d.ts +84 -0
  132. package/src/generators/upgrade/external-blueprint-compositions.js +478 -0
  133. package/src/generators/upgrade/framework-package-upgrade.d.ts +58 -0
  134. package/src/generators/upgrade/framework-package-upgrade.js +78 -0
  135. package/src/generators/upgrade/function-authentication-notice.d.ts +29 -0
  136. package/src/generators/upgrade/function-authentication-notice.js +74 -0
  137. package/src/generators/upgrade/schema.json +2 -2
  138. package/src/generators/upgrade/upgrade-plan.d.ts +52 -0
  139. package/src/generators/upgrade/upgrade-plan.js +406 -0
  140. package/src/generators/upgrade/upgrade.d.ts +1 -35
  141. package/src/generators/upgrade/upgrade.js +347 -595
  142. package/src/generators/workload/reliability-registration.d.ts +1 -1
  143. package/src/generators/workload/reliability-registration.js +9 -9
  144. package/src/generators/workload/workload.d.ts +1 -1
  145. package/src/generators/workload/workload.js +87 -13
  146. package/src/git-policy/github-bootstrap.d.ts +24 -5
  147. package/src/git-policy/github-bootstrap.js +105 -10
  148. package/src/local-dev/fleet-process.d.ts +9 -2
  149. package/src/local-dev/fleet-process.js +27 -7
  150. package/src/local-dev/fleet-session.js +41 -4
  151. package/src/local-dev/fleet-supervisor-daemon.js +1 -5
  152. package/src/local-dev/fleet-supervisor.d.ts +1 -0
  153. package/src/local-dev/fleet-supervisor.js +34 -11
  154. package/src/local-dev/gateway-daemon.d.ts +1 -1
  155. package/src/local-dev/gateway-daemon.js +6 -4
  156. package/src/local-dev/portless.d.ts +5 -0
  157. package/src/local-dev/portless.js +5 -0
  158. package/src/local-dev/process-group.d.ts +10 -0
  159. package/src/local-dev/process-group.js +33 -0
  160. package/src/local-dev/tls.js +31 -2
  161. package/src/local-dev/trust-store.d.ts +42 -0
  162. package/src/local-dev/trust-store.js +87 -0
  163. package/src/ownership/composition.d.ts +7 -0
  164. package/src/ownership/composition.js +64 -56
  165. package/src/ownership/index.d.ts +1 -0
  166. package/src/ownership/index.js +1 -0
  167. package/src/ownership/record.d.ts +19 -0
  168. package/src/ownership/record.js +26 -2
  169. package/src/ownership/site-record.d.ts +18 -0
  170. package/src/ownership/site-record.js +105 -0
  171. package/src/repository-policy/deployment-plan.d.ts +3 -0
  172. package/src/repository-policy/deployment-plan.js +33 -4
  173. package/src/repository-policy/index.d.ts +1 -0
  174. package/src/repository-policy/index.js +1 -0
  175. package/src/repository-policy/policy.d.ts +13 -1
  176. package/src/repository-policy/policy.js +55 -1
  177. package/src/repository-policy/public-dns.d.ts +65 -0
  178. package/src/repository-policy/public-dns.js +168 -0
  179. package/src/schemas/generated-ownership-v2.json +6 -0
  180. package/src/schemas/repository-policy-v1.json +67 -1
  181. package/src/supply-chain/blueprint-trust-git.js +24 -0
  182. package/src/supply-chain/blueprint-verification-authority.js +42 -3
  183. package/src/supply-chain/generated-blueprint-trust-command.js +15 -0
  184. package/src/supply-chain/sbom.js +74 -12
  185. package/src/work-markers/work-markers.js +4 -1
  186. package/src/workspace-deployment/ownership.d.ts +15 -0
  187. package/src/workspace-deployment/ownership.js +19 -3
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.renderConsumerSstConfig = renderConsumerSstConfig;
4
+ /** The managed sst.config.ts of a Next.js Foundation consumer. */
5
+ function renderConsumerSstConfig(input) {
6
+ const requiredKeys = input.requiredBuildKeys === undefined
7
+ ? 'ebkNextBuildEnvironmentKeys'
8
+ : 'ebkRequiredNextBuildEnvironmentKeys';
9
+ const identityCheck = input.nameSourceIdentities
10
+ ? ` const sourceCommit = resolved.EBK_SOURCE_COMMIT.trim();
11
+ const sourceTree = resolved.EBK_LOCAL_SOURCE_TREE.trim();
12
+ if (
13
+ !ebkSourceCommitPattern.test(sourceCommit) ||
14
+ !ebkSourceTreePattern.test(sourceTree)
15
+ ) {
16
+ `
17
+ : ` if (
18
+ !ebkSourceCommitPattern.test(resolved.EBK_SOURCE_COMMIT.trim()) ||
19
+ !ebkSourceTreePattern.test(resolved.EBK_LOCAL_SOURCE_TREE.trim())
20
+ ) {
21
+ `;
22
+ return `const ebkNextBuildEnvironmentKeys = new Set(${input.buildKeys});
23
+
24
+ ${input.requiredBuildKeys === undefined
25
+ ? ''
26
+ : `const ebkRequiredNextBuildEnvironmentKeys = ${input.requiredBuildKeys} as const;
27
+
28
+ `}\
29
+ const ebkLocalCommandResource = {
30
+ __pulumiType: 'command:local:Command',
31
+ } as unknown as new (
32
+ name: string,
33
+ args: { environment?: unknown; triggers?: unknown },
34
+ options?: unknown,
35
+ ) => unknown;
36
+
37
+ const ebkSourceCommitPattern = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
38
+ const ebkSourceTreePattern = /^[a-f0-9]{64}$/;
39
+
40
+ function exactNextBuildEnvironment(value: unknown): Record<string, string> {
41
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
42
+ throw new Error('The Next build environment must resolve to one object.');
43
+ }
44
+ const environment = value as Record<string, unknown>;
45
+ const retained = Object.fromEntries(
46
+ Object.entries(environment)
47
+ .filter(([key]) => ebkNextBuildEnvironmentKeys.has(key))
48
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)),
49
+ );
50
+ for (const key of ${requiredKeys}) {
51
+ if (typeof retained[key] !== 'string') {
52
+ throw new Error('The Next build environment omitted ' + key + '.');
53
+ }
54
+ }
55
+ return retained as Record<string, string>;
56
+ }
57
+
58
+ // SST 4.17.1 installs its transform globals only while evaluating $config.run.
59
+ // Register there, before infrastructure construction, rather than at module
60
+ // load. The explicit ${input.buildCommandNoun} separately routes diff/refresh invokes
61
+ // through the wrapper.
62
+ function registerExactNextBuildEnvironmentTransform(): void {
63
+ $transform(
64
+ ebkLocalCommandResource,
65
+ (
66
+ args: { environment?: unknown; triggers?: unknown },
67
+ _options: unknown,
68
+ resourceName: string,
69
+ ) => {
70
+ if (resourceName !== '${input.builderLogicalName}') return;
71
+ const unresolvedEnvironment = args.environment as Record<
72
+ string,
73
+ unknown
74
+ >;
75
+ const resolveEnvironment = (environment: Record<string, unknown>) => {
76
+ const resolved = exactNextBuildEnvironment({
77
+ ...environment,
78
+ CI: 'true',
79
+ NEXT_TELEMETRY_DISABLED: '1',
80
+ });
81
+ ${identityCheck}\
82
+ throw new Error(
83
+ 'The Next builder requires exact EBK commit and working-tree identities.',
84
+ );
85
+ }
86
+ return resolved;
87
+ };
88
+ args.environment = $output(unresolvedEnvironment).apply(
89
+ resolveEnvironment,
90
+ );
91
+ // Preserve SST's native per-invocation build trigger.${input.buildTriggerNote}
92
+ },
93
+ );
94
+ }
95
+
96
+ export default $config({
97
+ app(input: { stage?: string } | undefined) {
98
+ const stage = input?.stage ?? 'development';
99
+ const production = input?.stage === 'production';
100
+ return {
101
+ name: '${input.appName}',
102
+ removal: production ? 'retain' : 'remove',
103
+ protect: production,
104
+ home: 'aws',
105
+ providers: {
106
+ aws: {
107
+ defaultTags: {
108
+ // SST contributes sst:app and sst:stage. Keep the provider baseline
109
+ // at eight tags so generated S3 asset objects remain within AWS's
110
+ // hard ten-tag object limit.${input.tagBaselineNote}
111
+ tags: {
112
+ 'ebk:cost-allocation': 'unallocated',
113
+ 'ebk:cost-scope': '${input.workspace}/${input.appName}/' + stage,
114
+ 'ebk:framework-version': '${input.frameworkVersion}',
115
+ 'ebk:managed-by': 'empire-builder-kit',
116
+ 'ebk:owner': '${input.appName}-product',
117
+ 'ebk:slice': '${input.appName}',
118
+ 'ebk:stage': stage,
119
+ 'ebk:workspace': '${input.workspace}',
120
+ },
121
+ },
122
+ region: process.env.AWS_REGION ?? 'us-east-1',
123
+ },
124
+ },
125
+ };
126
+ },
127
+ async run() {
128
+ ${input.stageGuard}\
129
+ const {
130
+ installLambdaPolicyWriteOrdering,
131
+ installStageIamBoundaryTransforms,
132
+ } = await import('@empire-builder-kit/nx/aws-authority');
133
+ registerExactNextBuildEnvironmentTransform();
134
+ const accountId = process.env.AWS_EXPECTED_ACCOUNT_ID?.trim() ?? '';
135
+ if (!/^[0-9]{12}$/.test(accountId)) {
136
+ throw new Error(
137
+ '${input.boundarySubject} IAM boundary injection requires AWS_EXPECTED_ACCOUNT_ID.',
138
+ );
139
+ }
140
+ installStageIamBoundaryTransforms({
141
+ accountId,
142
+ instanceProfileResource: aws.iam.InstanceProfile,
143
+ registerTransform: $transform,
144
+ roleResource: aws.iam.Role,
145
+ resourceStage: $app.stage,
146
+ stage: ${input.boundaryStage},
147
+ });
148
+ // Order Function URL and Lambda permission policy writes before any
149
+ // resource registers; the pinned providers otherwise race them.
150
+ installLambdaPolicyWriteOrdering({
151
+ mergeOptions: $util.mergeOptions,
152
+ registerStackTransformation: $util.runtime.registerStackTransformation,
153
+ });
154
+ const { app } = await import('./infra/index.js');
155
+ return ${input.runEntry};
156
+ },
157
+ });
158
+ `;
159
+ }
160
+ //# sourceMappingURL=built-in-plan-sst-config.js.map
@@ -5,6 +5,8 @@ const built_in_plan_shared_js_1 = require("./built-in-plan-shared.js");
5
5
  const local_source_identity_js_1 = require("./local-source-identity.js");
6
6
  const built_in_plan_testing_persistence_files_js_1 = require("./built-in-plan-testing-persistence-files.js");
7
7
  const deployed_smoke_readiness_js_1 = require("./deployed-smoke-readiness.js");
8
+ const deployed_smoke_diagnostics_js_1 = require("./deployed-smoke-diagnostics.js");
9
+ const pnpm_launch_script_js_1 = require("./pnpm-launch-script.js");
8
10
  /** @internal */
9
11
  function renderProductTestingFiles(name, pascalName, sql = false) {
10
12
  return {
@@ -74,8 +76,12 @@ The runner creates one run-scoped synthetic customer in the Slice's narrow
74
76
  \`<slice>-admin\`. It never grants the customer administrator authority, strips
75
77
  AWS credentials from the browser child, observes the published event only from
76
78
  the credential-bearing parent, removes both principals and all raw browser and
77
- log state, and retains only allowlisted sanitized evidence. A failed smoke ends
78
- the lifecycle immediately and no successful deployment receipt is written.
79
+ log state, and retains only allowlisted sanitized evidence. A failed browser
80
+ run also keeps the last 4 KiB of its output, with every synthetic credential
81
+ and email replaced, as private local
82
+ \`.ebk/evidence/playwright-smoke-output-<attempt>.txt\`; the hosted workflow
83
+ does not upload it. A failed smoke ends the lifecycle immediately and no
84
+ successful deployment receipt is written.
79
85
 
80
86
  One optional evidence-level retry replays the complete, identical browser or
81
87
  live-integration proof. Consequently \`counts.retried\` is always zero or one.
@@ -1311,9 +1317,12 @@ import {
1311
1317
  import { spawnSync } from 'node:child_process';
1312
1318
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
1313
1319
  import {
1320
+ closeSync,
1314
1321
  existsSync,
1315
1322
  mkdirSync,
1323
+ openSync,
1316
1324
  readFileSync,
1325
+ readSync,
1317
1326
  rmSync,
1318
1327
  statSync,
1319
1328
  writeFileSync,
@@ -1419,6 +1428,11 @@ const rawPath = (attempt) =>
1419
1428
  join(rawRoot, 'playwright-smoke-' + attempt + '.json');
1420
1429
  const dataCleanupPath = (attempt) =>
1421
1430
  join(rawRoot, 'data-cleanup-' + attempt + '.json');
1431
+ const playwrightOutputTailPath = (attempt) =>
1432
+ join(evidenceRoot, 'playwright-smoke-output-' + attempt + '.txt');
1433
+ for (const attempt of [1, 2]) {
1434
+ rmSync(playwrightOutputTailPath(attempt), { force: true });
1435
+ }
1422
1436
  const source = {
1423
1437
  blueprintCandidates: [
1424
1438
  ownership.blueprint.name + '@' + ownership.blueprint.version,
@@ -1558,6 +1572,8 @@ function permissionFailure(error, operation, authority = 'Cognito principal') {
1558
1572
  };
1559
1573
  }
1560
1574
 
1575
+ ${deployed_smoke_diagnostics_js_1.deployedSmokeOwnershipFindingFunctions}
1576
+ ${deployed_smoke_diagnostics_js_1.playwrightOutputTailFunctions}
1561
1577
  function isCognitoUserAbsent(error) {
1562
1578
  return (
1563
1579
  error &&
@@ -1725,6 +1741,7 @@ function requiresScheduledDeliveryObservation(stage) {
1725
1741
  return ['development', 'staging', 'production'].includes(stage);
1726
1742
  }
1727
1743
 
1744
+ ${pnpm_launch_script_js_1.pnpmLaunchFunction}
1728
1745
  // A successful browser journey may have deleted its synthetic record, while
1729
1746
  // its mutation receipt remains. Replaying that same journey/run scope cannot
1730
1747
  // recreate the record, even when the first cleanup completed successfully.
@@ -1857,7 +1874,8 @@ if (
1857
1874
  !url ||
1858
1875
  !apiUrl ||
1859
1876
  normalizedProductPath !== expectedProductPath ||
1860
- apiUrl.pathname !== '/' ||
1877
+ // A bound Slice API is mapped under /<slice> on the Foundation's api.<root>.
1878
+ !['/', expectedProductPath].includes(apiUrl.pathname.replace(/\\/$/, '') || '/') ||
1861
1879
  !validIdentity ||
1862
1880
  !validSourceCommit ||
1863
1881
  !validRunId ||
@@ -1873,6 +1891,7 @@ if (
1873
1891
  );
1874
1892
  }
1875
1893
  if (process.exitCode === undefined) {
1894
+ let ownershipFailure;
1876
1895
  try {
1877
1896
  const ownership = await assertWorkspaceStageOwnershipForWorkspace(workspaceRoot, stage, {
1878
1897
  ...(process.env.AWS_PROFILE ? { profile: process.env.AWS_PROFILE } : {}),
@@ -1881,14 +1900,12 @@ if (process.exitCode === undefined) {
1881
1900
  ? { credentialsFilepath: process.env.AWS_SHARED_CREDENTIALS_FILE }
1882
1901
  : {}),
1883
1902
  });
1884
- if (process.env.AWS_REGION !== ownership.region) {
1885
- throw new Error('Deployed smoke Region differs from its exact workspace owner tuple.');
1886
- }
1887
- } catch {
1888
- failPreflight(
1889
- 'authorization-denied',
1890
- 'Deployed smoke requires this workspace to own the exact account, Region, and canonical stage tuple.',
1891
- );
1903
+ ownershipFailure = ownershipRegionFinding(ownership, process.env.AWS_REGION);
1904
+ } catch (error) {
1905
+ ownershipFailure = ownershipErrorFinding(error);
1906
+ }
1907
+ if (ownershipFailure) {
1908
+ failPreflight(ownershipFailure.classification, ownershipFailure.summary);
1892
1909
  }
1893
1910
  }
1894
1911
  if (process.exitCode === undefined) {
@@ -2085,8 +2102,12 @@ if (process.exitCode === undefined) {
2085
2102
  if (process.exitCode !== undefined) {
2086
2103
  rmSync(rawRoot, { force: true, recursive: true });
2087
2104
  } else {
2088
- const executable =
2089
- process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm';
2105
+ const playwright = pnpmLaunch([
2106
+ 'exec',
2107
+ 'playwright',
2108
+ 'test',
2109
+ '--reporter=json',
2110
+ ]);
2090
2111
  const executeAttempt = async (attempt) => {
2091
2112
  const attemptStartedAt = new Date().toISOString();
2092
2113
  const path = rawPath(attempt);
@@ -2095,6 +2116,7 @@ if (process.exitCode === undefined) {
2095
2116
  'event-observation-' + attempt + '.json',
2096
2117
  );
2097
2118
  const cleanupPath = dataCleanupPath(attempt);
2119
+ const outputPath = join(rawRoot, 'playwright-output-' + attempt + '.log');
2098
2120
  rmSync(observationPath, { force: true });
2099
2121
  rmSync(cleanupPath, { force: true });
2100
2122
  let dataCleanup = {
@@ -2135,34 +2157,41 @@ if (process.exitCode === undefined) {
2135
2157
  typeof value === 'string',
2136
2158
  ),
2137
2159
  );
2138
- execution = spawnSync(
2139
- executable,
2140
- ['exec', 'playwright', 'test', '--reporter=json'],
2141
- {
2142
- cwd: projectRoot,
2143
- encoding: 'utf8',
2144
- env: {
2145
- ...childEnvironment,
2146
- EBK_SOURCE_COMMIT: deployedSourceCommit,
2147
- EBK_STAGE: stage,
2148
- EBK_SMOKE_API_URL: apiUrl.href,
2149
- EBK_SMOKE_DATA_CLEANUP_PATH: cleanupPath,
2150
- EBK_SMOKE_EMAIL: principalEmail,
2151
- EBK_FRONTEND_SECURITY_PROFILE: 'deployed-https',
2152
- EBK_SMOKE_PASSWORD: principalPassword,
2153
- EBK_SMOKE_REVIEWER_EMAIL: reviewerEmail,
2154
- EBK_SMOKE_REVIEWER_PASSWORD: reviewerPassword,
2155
- EBK_SMOKE_OBSERVATION_PATH: observationPath,
2156
- EBK_SMOKE_URL: url.href,
2157
- EBK_TEST_RUN_ID: runId,
2158
- EBK_TEST_SEED: seed,
2159
- PLAYWRIGHT_JSON_OUTPUT_NAME: path,
2160
+ // Output goes to a private raw file, not a pipe, so its size can
2161
+ // never stop the run; only a failed run keeps its scrubbed tail.
2162
+ const output = openSync(outputPath, 'w', 0o600);
2163
+ try {
2164
+ execution = spawnSync(
2165
+ playwright.command,
2166
+ playwright.args,
2167
+ {
2168
+ cwd: projectRoot,
2169
+ encoding: 'utf8',
2170
+ env: {
2171
+ ...childEnvironment,
2172
+ EBK_SOURCE_COMMIT: deployedSourceCommit,
2173
+ EBK_STAGE: stage,
2174
+ EBK_SMOKE_API_URL: apiUrl.href,
2175
+ EBK_SMOKE_DATA_CLEANUP_PATH: cleanupPath,
2176
+ EBK_SMOKE_EMAIL: principalEmail,
2177
+ EBK_FRONTEND_SECURITY_PROFILE: 'deployed-https',
2178
+ EBK_SMOKE_PASSWORD: principalPassword,
2179
+ EBK_SMOKE_REVIEWER_EMAIL: reviewerEmail,
2180
+ EBK_SMOKE_REVIEWER_PASSWORD: reviewerPassword,
2181
+ EBK_SMOKE_OBSERVATION_PATH: observationPath,
2182
+ EBK_SMOKE_URL: url.href,
2183
+ EBK_TEST_RUN_ID: runId,
2184
+ EBK_TEST_SEED: seed,
2185
+ PLAYWRIGHT_JSON_OUTPUT_NAME: path,
2186
+ },
2187
+ shell: false,
2188
+ stdio: ['ignore', output, output],
2189
+ windowsHide: true,
2160
2190
  },
2161
- shell: false,
2162
- stdio: ['ignore', 'ignore', 'ignore'],
2163
- windowsHide: true,
2164
- },
2165
- );
2191
+ );
2192
+ } finally {
2193
+ closeSync(output);
2194
+ }
2166
2195
  if (existsSync(path)) {
2167
2196
  try {
2168
2197
  const reportContents = readBoundedUtf8(
@@ -2261,20 +2290,34 @@ if (process.exitCode === undefined) {
2261
2290
  observationFinding ? 1 : 0,
2262
2291
  reportPolicyFinding ? 1 : 0,
2263
2292
  );
2293
+ const outputTailKept =
2294
+ runnerFailed > 0 &&
2295
+ retainPlaywrightOutputTail(outputPath, playwrightOutputTailPath(attempt), [
2296
+ principalPassword,
2297
+ reviewerPassword,
2298
+ principalEmail,
2299
+ reviewerEmail,
2300
+ ]);
2301
+ rmSync(outputPath, { force: true });
2264
2302
  return {
2265
2303
  attempt,
2266
2304
  completedAt: new Date().toISOString(),
2267
2305
  dataCleanup,
2268
2306
  diagnostic:
2269
- (reportInvalid
2270
- ? 'Playwright emitted malformed machine-readable output.'
2271
- : undefined) ||
2272
- (reportCredentialLeak
2273
- ? 'Playwright output contained the synthetic principal credential and was removed.'
2274
- : undefined) ||
2275
- (execution?.error
2276
- ? 'The Playwright process could not start.'
2277
- : playwrightFailureDiagnostic(report)),
2307
+ [
2308
+ (reportInvalid
2309
+ ? 'Playwright emitted malformed machine-readable output.'
2310
+ : undefined) ||
2311
+ (reportCredentialLeak
2312
+ ? 'Playwright output contained the synthetic principal credential and was removed.'
2313
+ : undefined) ||
2314
+ (execution?.error
2315
+ ? 'The Playwright process could not start.'
2316
+ : playwrightFailureDiagnostic(report)),
2317
+ outputTailKept ? playwrightOutputTailNote : undefined,
2318
+ ]
2319
+ .filter(Boolean)
2320
+ .join(' ') || undefined,
2278
2321
  failed,
2279
2322
  artifactSensitive: reportCredentialLeak,
2280
2323
  observationFindings: observationFinding
@@ -79,7 +79,11 @@ test('proves the deployed product, auth, database, and event journey', async ({
79
79
  );
80
80
  writeDataCleanupOutcome(dataCleanupPath, 'not-required');
81
81
 
82
- const publicHealth = await page.request.get(new URL('/health', apiUrl).href);
82
+ // A bound Slice API is mapped under /<slice> on api.<root>: join each
83
+ // operation path onto apiUrl, never resolve an absolute path against it.
84
+ const publicHealth = await page.request.get(
85
+ productEndpoint(apiUrl, '/health'),
86
+ );
83
87
  expect(publicHealth.status()).toBe(200);
84
88
  await expect(publicHealth.json()).resolves.toMatchObject({
85
89
  data: {
@@ -121,8 +125,13 @@ test('proves the deployed product, auth, database, and event journey', async ({
121
125
  data: { message: 'Authenticated request accepted.' },
122
126
  });
123
127
 
128
+ // Generated auth routes accept only JSON from their own origin.
129
+ const sameOriginJson = {
130
+ headers: { 'content-type': 'application/json', origin: productUrl.origin },
131
+ };
124
132
  const refreshResponse = await page.request.post(
125
133
  productEndpoint(productUrl, '/api/auth/refresh'),
134
+ sameOriginJson,
126
135
  );
127
136
  expect(refreshResponse.status()).toBe(200);
128
137
  await expect(refreshResponse.json()).resolves.toEqual({ ok: true });
@@ -145,7 +154,7 @@ test('proves the deployed product, auth, database, and event journey', async ({
145
154
  };
146
155
 
147
156
  const databaseResponse = await page.request.get(
148
- new URL('/database-health', apiUrl).href,
157
+ productEndpoint(apiUrl, '/database-health'),
149
158
  { headers: authenticatedHeaders },
150
159
  );
151
160
  expect(databaseResponse.status()).toBe(200);
@@ -154,7 +163,7 @@ test('proves the deployed product, auth, database, and event journey', async ({
154
163
  });
155
164
 
156
165
  const recordId = runRecordId(runScope);
157
- const recordUrl = new URL('/records/' + recordId, apiUrl).href;
166
+ const recordUrl = productEndpoint(apiUrl, '/records/' + recordId);
158
167
  const testExpiresAt = new Date(Date.now() + 24 * 60 * 60 * 1_000)
159
168
  .toISOString();
160
169
  let recordCleanupRequired = false;
@@ -216,6 +225,7 @@ test('proves the deployed product, auth, database, and event journey', async ({
216
225
 
217
226
  await page.request.post(
218
227
  productEndpoint(productUrl, '/api/auth/sign-out'),
228
+ sameOriginJson,
219
229
  );
220
230
  await page.goto(productUrl.href);
221
231
  await page.getByRole('link', { name: 'Sign in' }).click();
@@ -256,7 +266,7 @@ test('proves the deployed product, auth, database, and event journey', async ({
256
266
  });
257
267
 
258
268
  const eventResponse = await page.request.post(
259
- new URL('/events/example', apiUrl).href,
269
+ productEndpoint(apiUrl, '/events/example'),
260
270
  { headers: authenticatedHeaders },
261
271
  );
262
272
  expect(eventResponse.status()).toBe(200);
@@ -344,6 +354,7 @@ test('proves the deployed product, auth, database, and event journey', async ({
344
354
 
345
355
  const signOutResponse = await page.request.post(
346
356
  productEndpoint(productUrl, '/api/auth/sign-out'),
357
+ sameOriginJson,
347
358
  );
348
359
  expect(signOutResponse.status()).toBe(200);
349
360
  await expect(signOutResponse.json()).resolves.toEqual({ ok: true });
@@ -416,7 +427,6 @@ test('renders the Slice through its exact task HTTPS origin', async ({ page }) =
416
427
  expect(response?.status()).toBe(200);
417
428
  expect(response?.headers()['x-ebk-upstream']).toBe('local');
418
429
  expect(new URL(page.url()).origin).toBe(target.origin);
419
- await expect(page.getByRole('heading', { name: '${pascalName}', exact: true })).toBeVisible();
420
430
  });
421
431
  `,
422
432
  'playwright.config.ts': `import { defineConfig } from '@playwright/test';
@@ -2,11 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.renderProductWebFiles = renderProductWebFiles;
4
4
  const built_in_plan_shared_js_1 = require("./built-in-plan-shared.js");
5
- const sst_environment_source_format_js_1 = require("../../sst-environment-source-format.js");
6
5
  /** @internal */
7
6
  function renderProductWebFiles(name, pascalName, workspace, sql = false) {
8
7
  return {
9
- 'web/next-env.d.ts': (0, sst_environment_source_format_js_1.generatedNextEnvironmentSource)(),
10
8
  'web/tsconfig.json': (0, built_in_plan_shared_js_1.json)({
11
9
  extends: '../tsconfig.json',
12
10
  compilerOptions: {
@@ -18,9 +16,10 @@ function renderProductWebFiles(name, pascalName, workspace, sql = false) {
18
16
  incremental: true,
19
17
  plugins: [{ name: 'next' }],
20
18
  },
21
- // Next 16.3 regenerates next-env.d.ts and rewrites tsconfig.json when
22
- // these entries are missing; the generated files match its output so
23
- // a build leaves the tracked workspace unchanged.
19
+ // Next rewrites tsconfig.json when these entries are missing, so the
20
+ // generated include matches its output. Next writes the gitignored
21
+ // next-env.d.ts itself on dev, build, and typegen; EBK does not
22
+ // generate or track it.
24
23
  include: [
25
24
  'next-env.d.ts',
26
25
  '.next/types/**/*.ts',
@@ -321,12 +320,66 @@ export default function PasswordReset() {
321
320
  <button type="submit">Send reset code</button></form><p role="status">{message}</p>
322
321
  </div></main>;
323
322
  }
323
+ `,
324
+ 'web/src/lib/same-origin-request.ts': `import 'server-only';
325
+
326
+ // State-changing auth routes accept only same-origin JSON. application/json is
327
+ // not a CORS-safelisted type, so a browser cannot send it cross-origin without
328
+ // a preflight that these routes never approve. Fetch Metadata, or Origin when
329
+ // a browser omits it, then binds the request to this exact origin, which also
330
+ // refuses sibling hosts that share the site and its SameSite=Strict cookies.
331
+
332
+ const noStore = { 'cache-control': 'no-store' };
333
+
334
+ function refusal(status: 403 | 415, code: string, message: string): Response {
335
+ return Response.json({ ok: false, error: { code, message } }, { status, headers: noStore });
336
+ }
337
+
338
+ // The public origin of this request. The EBK Router and the local Fleet proxy
339
+ // overwrite x-forwarded-host with the viewer's Host; the Host header behind
340
+ // the Router names the server's own URL. Secure-cookie stages are HTTPS-only.
341
+ function requestOrigin(request: Request): string | null {
342
+ const host = request.headers.get('x-forwarded-host')?.toLowerCase();
343
+ if (!host || host.includes(',')) return null;
344
+ const forwardedProto = request.headers.get('x-forwarded-proto');
345
+ const secure = process.env.EBK_SECURE_COOKIES === 'true' || process.env.NODE_ENV === 'production';
346
+ const scheme = secure ? 'https'
347
+ : forwardedProto === 'http' || forwardedProto === 'https' ? forwardedProto : null;
348
+ if (!scheme) return null;
349
+ try {
350
+ const origin = new URL(scheme + '://' + host);
351
+ return origin.host === host ? origin.origin : null;
352
+ } catch {
353
+ return null;
354
+ }
355
+ }
356
+
357
+ /** Returns the refusal for a request that is not same-origin JSON, else null. */
358
+ export function refuseUnlessSameOriginJson(request: Request): Response | null {
359
+ const mediaType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase();
360
+ if (mediaType !== 'application/json')
361
+ return refusal(415, 'unsupported_media_type', 'Content-Type application/json is required.');
362
+ const fetchSite = request.headers.get('sec-fetch-site');
363
+ if (fetchSite !== null) {
364
+ return fetchSite === 'same-origin'
365
+ ? null
366
+ : refusal(403, 'cross_origin_refused', 'Only same-origin requests are accepted.');
367
+ }
368
+ const origin = request.headers.get('origin');
369
+ if (origin !== null && origin !== requestOrigin(request))
370
+ return refusal(403, 'cross_origin_refused', 'Only same-origin requests are accepted.');
371
+ // Neither header: a non-browser client. Every browser that can send this
372
+ // JSON request cross-origin sends Origin with it; other clients can forge
373
+ // both headers and carry no ambient session cookies.
374
+ return null;
375
+ }
324
376
  `,
325
377
  'web/src/app/api/auth/sign-in/route.ts': `import 'server-only';
326
378
  import { InitiateAuthCommand, CognitoIdentityProviderClient } from '@aws-sdk/client-cognito-identity-provider';
327
379
  import { createSessionTokenCookiePlan } from '@empire-builder-kit/runtime/auth-session';
328
380
  import { cookies } from 'next/headers';
329
381
  import { NextResponse } from 'next/server';
382
+ import { refuseUnlessSameOriginJson } from '../../../../lib/same-origin-request';
330
383
  import { observeNextOperation } from '../../../../lib/server-logging';
331
384
 
332
385
  const cognito = new CognitoIdentityProviderClient({});
@@ -337,6 +390,8 @@ export async function POST(request: Request) {
337
390
  operation: 'sign-in',
338
391
  request,
339
392
  async handle() {
393
+ const refused = refuseUnlessSameOriginJson(request);
394
+ if (refused) return refused;
340
395
  const body = await request.json() as { email?: string; password?: string };
341
396
  if (!body.email || !body.password) return NextResponse.json({ ok: false }, { status: 400 });
342
397
  const result = await cognito.send(new InitiateAuthCommand({
@@ -363,6 +418,7 @@ import { InitiateAuthCommand, CognitoIdentityProviderClient } from '@aws-sdk/cli
363
418
  import { createSessionTokenCookiePlan, getSessionTokenCookieNames } from '@empire-builder-kit/runtime/auth-session';
364
419
  import { cookies } from 'next/headers';
365
420
  import { NextResponse } from 'next/server';
421
+ import { refuseUnlessSameOriginJson } from '../../../../lib/same-origin-request';
366
422
  import { observeNextOperation } from '../../../../lib/server-logging';
367
423
 
368
424
  const cognito = new CognitoIdentityProviderClient({});
@@ -373,6 +429,8 @@ export async function POST(request: Request) {
373
429
  operation: 'refresh-session',
374
430
  request,
375
431
  async handle() {
432
+ const refused = refuseUnlessSameOriginJson(request);
433
+ if (refused) return refused;
376
434
  const store = await cookies();
377
435
  const secure = process.env.EBK_SECURE_COOKIES === 'true' || process.env.NODE_ENV === 'production';
378
436
  const names = getSessionTokenCookieNames({ namespace: '${name}', secure });
@@ -398,6 +456,7 @@ export async function POST(request: Request) {
398
456
  import { createSessionTokenCookieDeletionPlan } from '@empire-builder-kit/runtime/auth-session';
399
457
  import { cookies } from 'next/headers';
400
458
  import { NextResponse } from 'next/server';
459
+ import { refuseUnlessSameOriginJson } from '../../../../lib/same-origin-request';
401
460
  import { observeNextOperation } from '../../../../lib/server-logging';
402
461
 
403
462
  export async function POST(request: Request) {
@@ -406,6 +465,8 @@ export async function POST(request: Request) {
406
465
  operation: 'sign-out',
407
466
  request,
408
467
  async handle() {
468
+ const refused = refuseUnlessSameOriginJson(request);
469
+ if (refused) return refused;
409
470
  const store = await cookies();
410
471
  const secure = process.env.EBK_SECURE_COOKIES === 'true' || process.env.NODE_ENV === 'production';
411
472
  for (const { name, value, ...options } of createSessionTokenCookieDeletionPlan({
@@ -420,6 +481,7 @@ export async function POST(request: Request) {
420
481
  'web/src/app/api/auth/password-reset/route.ts': `import 'server-only';
421
482
  import { ForgotPasswordCommand, CognitoIdentityProviderClient } from '@aws-sdk/client-cognito-identity-provider';
422
483
  import { NextResponse } from 'next/server';
484
+ import { refuseUnlessSameOriginJson } from '../../../../lib/same-origin-request';
423
485
  import { observeNextOperation } from '../../../../lib/server-logging';
424
486
 
425
487
  const cognito = new CognitoIdentityProviderClient({});
@@ -429,6 +491,8 @@ export async function POST(request: Request) {
429
491
  operation: 'password-reset',
430
492
  request,
431
493
  async handle() {
494
+ const refused = refuseUnlessSameOriginJson(request);
495
+ if (refused) return refused;
432
496
  const body = await request.json() as { email?: string };
433
497
  if (body.email) await cognito.send(new ForgotPasswordCommand({
434
498
  ClientId: process.env.AUTH_CLIENT_ID, Username: body.email,
@@ -48,7 +48,6 @@ const FORMAT_SENSITIVE_BUILT_IN_PATHS = new Set([
48
48
  'api/generated/baseline.json',
49
49
  'api/generated/contract.json',
50
50
  'api/generated/openapi.json',
51
- 'web/next-env.d.ts',
52
51
  ]);
53
52
  function isBuiltInSliceFormatSensitivePath(path) {
54
53
  return (path.startsWith('database/migrations/') ||
@@ -257,7 +256,7 @@ function classifyPaths(files, sql) {
257
256
  ]);
258
257
  for (const path of built_in_plan_performance_files_js_1.PRODUCT_PERFORMANCE_SEEDED_PATHS)
259
258
  seededPaths.add(path);
260
- const toolOwnedPaths = new Set(['sst-env.d.ts', 'web/next-env.d.ts']);
259
+ const toolOwnedPaths = new Set(['sst-env.d.ts']);
261
260
  return Object.entries(files)
262
261
  .filter(([path]) => path !== '.ebk/ownership.json' && !toolOwnedPaths.has(path))
263
262
  .map(([path, contents]) => {