@friggframework/devtools 2.0.0--canary.743.d13a976.0 → 2.0.0--canary.745.0209482d.0

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 (29) hide show
  1. package/frigg-cli/README.md +41 -1
  2. package/frigg-cli/generate-command/__tests__/generate-command.test.js +36 -0
  3. package/frigg-cli/generate-command/index.js +3 -1
  4. package/frigg-cli/generate-command/terraform-generator.js +48 -0
  5. package/frigg-cli/generate-iam-command.js +1 -0
  6. package/frigg-cli/index.js +8 -0
  7. package/frigg-cli/templates/backend/README.md +3 -2
  8. package/frigg-cli/tls-check-command/__tests__/check-post-quantum-tls.test.js +396 -0
  9. package/frigg-cli/tls-check-command/__tests__/tls-check-command.test.js +182 -0
  10. package/frigg-cli/tls-check-command/check-post-quantum-tls.js +194 -0
  11. package/frigg-cli/tls-check-command/index.js +136 -0
  12. package/frigg-cli/validate-command/__tests__/validate-app-definition.test.js +69 -0
  13. package/frigg-cli/validate-command/checks/config.js +59 -0
  14. package/infrastructure/app-definition-schema-contract.test.js +10 -0
  15. package/infrastructure/domains/edge/cloudfront-builder.js +237 -0
  16. package/infrastructure/domains/edge/cloudfront-builder.test.js +273 -0
  17. package/infrastructure/domains/integration/integration-builder.js +1 -34
  18. package/infrastructure/domains/integration/integration-builder.test.js +0 -86
  19. package/infrastructure/domains/security/iam-generator.js +45 -2
  20. package/infrastructure/domains/security/iam-generator.test.js +23 -0
  21. package/infrastructure/domains/security/templates/iam-policy-full.json +30 -1
  22. package/infrastructure/domains/shared/builder-orchestrator.js +6 -0
  23. package/infrastructure/domains/shared/builder-orchestrator.test.js +30 -0
  24. package/infrastructure/domains/shared/utilities/base-definition-factory.js +9 -2
  25. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +11 -0
  26. package/infrastructure/infrastructure-composer.js +8 -0
  27. package/infrastructure/infrastructure-composer.test.js +35 -0
  28. package/package.json +7 -7
  29. package/infrastructure/domains/integration/queue-worker-concurrency.js +0 -85
@@ -473,6 +473,45 @@ Next steps:
473
473
 
474
474
  ---
475
475
 
476
+ ### Post-Quantum TLS Check
477
+
478
+ #### `frigg tls-check <endpoint...> [options]`
479
+
480
+ Checks whether each endpoint accepts hybrid post-quantum TLS key exchange
481
+ (`X25519MLKEM768`, ML-KEM-768 with X25519). The command offers only that
482
+ group, over TLS 1.3. Use it on your deployed API, on the CloudFront URL of
483
+ the `cloudFront` option, on AWS endpoints, or on partner APIs.
484
+
485
+ **Usage:**
486
+ ```bash
487
+ frigg tls-check https://abc123.execute-api.us-east-1.amazonaws.com
488
+ frigg tls-check https://d111111abcdef8.cloudfront.net kms.us-east-1.amazonaws.com
489
+ frigg tls-check api.example.com:8443 --timeout 5000 --json
490
+ ```
491
+
492
+ **Options:**
493
+ - `-t, --timeout <ms>` - Handshake timeout (default: 10000)
494
+ - `--json` - Print the result as JSON
495
+
496
+ **Results:**
497
+ - `accepted` - The endpoint supports hybrid post-quantum key exchange. A
498
+ certificate warning can show (TLS 1.3 checks the certificate after the key
499
+ exchange).
500
+ - `refused` - The endpoint gives clients classical key exchange only (or has
501
+ no TLS 1.3).
502
+ - `unreachable` - No connection or no handshake within the timeout.
503
+ - `unsupported-client` - The local Node.js cannot offer the group. Use
504
+ Node.js 22.20 or later, or Node.js 24.5 or later (OpenSSL 3.5).
505
+
506
+ **Exit codes:** 0 all endpoints accept, 1 one or more do not, 2 the local
507
+ Node.js cannot offer the group.
508
+
509
+ The check connects directly and does not use `HTTPS_PROXY`. Behind a proxy
510
+ that intercepts TLS, it measures the proxy. See
511
+ [Post-Quantum Readiness](../../../docs/reference/post-quantum-readiness.md).
512
+
513
+ ---
514
+
476
515
  ### New Infrastructure Health Commands
477
516
 
478
517
  #### `frigg doctor [options]`
@@ -1057,7 +1096,8 @@ const orchestrator = new BuilderOrchestrator(
1057
1096
  **Encryption:**
1058
1097
  - `KMS_KEY_ARN` - AWS KMS key ARN (or auto-discovered)
1059
1098
  - `AES_KEY_ID` - AES key ID (if using AES encryption)
1060
- - `AES_KEY` - AES encryption key (32 characters)
1099
+ - `AES_KEY` - AES-256 encryption key: 32 random bytes as 64 hex characters (`openssl rand -hex 32`) or base64. A legacy 32-character key still works but `frigg validate` warns (`weak-encryption-key`)
1100
+ - `DEPRECATED_AES_KEY_ID` / `DEPRECATED_AES_KEY` - Previous AES key pair, kept readable during a key rotation
1061
1101
 
1062
1102
  **Optional:**
1063
1103
  - `STAGE` - Deployment stage (default: 'dev')
@@ -179,6 +179,42 @@ describe('Generate Command', () => {
179
179
  });
180
180
  });
181
181
 
182
+ describe('CloudFront edge (cloudFront.enable)', () => {
183
+ const { generateTerraformTemplate } = require('../terraform-generator');
184
+ const { generateIAMCloudFormation } = require('../../../infrastructure/domains/security/iam-generator');
185
+
186
+ it('detects cloudFront like frigg generate-iam does', () => {
187
+ expect(generateCommand.analyzeAppFeatures({ cloudFront: { enable: true } }).cloudFront).toBe(true);
188
+ expect(generateCommand.analyzeAppFeatures({}).cloudFront).toBe(false);
189
+ });
190
+
191
+ it('grants the CloudFront permissions in the CloudFormation template', () => {
192
+ const features = generateCommand.analyzeAppFeatures({ cloudFront: { enable: true } });
193
+ const yaml = generateIAMCloudFormation({ appName: 'test-app', features });
194
+
195
+ expect(yaml).toContain('cloudfront:CreateDistribution');
196
+ });
197
+
198
+ it('adds a CloudFront policy to the Terraform template only when enabled', async () => {
199
+ const withEdge = await generateTerraformTemplate({
200
+ appName: 'test-app',
201
+ features: { vpc: false, kms: false, ssm: false, websockets: false, cloudFront: true },
202
+ userPrefix: 'frigg-deployment-user',
203
+ });
204
+ const withoutEdge = await generateTerraformTemplate({
205
+ appName: 'test-app',
206
+ features: { vpc: false, kms: false, ssm: false, websockets: false, cloudFront: false },
207
+ userPrefix: 'frigg-deployment-user',
208
+ });
209
+
210
+ expect(withEdge).toContain('resource "aws_iam_policy" "frigg_cloudfront"');
211
+ expect(withEdge).toContain('"cloudfront:CreateDistribution"');
212
+ expect(withEdge).toContain('resource "aws_iam_user_policy_attachment" "frigg_cloudfront"');
213
+ expect((withEdge.match(/{/g) || []).length).toBe((withEdge.match(/}/g) || []).length);
214
+ expect(withoutEdge).not.toContain('cloudfront:');
215
+ });
216
+ });
217
+
182
218
  describe('AWS Terraform Generation', () => {
183
219
  it('should generate valid Terraform template with actual HCL syntax', async () => {
184
220
  await generateCommand({
@@ -233,6 +233,7 @@ function analyzeAppFeatures(appDefinition) {
233
233
  kms: appDefinition.encryption?.fieldLevelEncryptionMethod === 'kms',
234
234
  ssm: appDefinition.ssm?.enable === true,
235
235
  websockets: appDefinition.websockets?.enable === true,
236
+ cloudFront: appDefinition.cloudFront?.enable === true,
236
237
  // Add more feature detection as needed
237
238
  };
238
239
 
@@ -331,4 +332,5 @@ To use Terraform with GCP:
331
332
  `;
332
333
  }
333
334
 
334
- module.exports = generateCommand;
335
+ module.exports = generateCommand;
336
+ module.exports.analyzeAppFeatures = analyzeAppFeatures;
@@ -504,6 +504,54 @@ resource "aws_iam_user_policy_attachment" "frigg_kms" {
504
504
  `;
505
505
  }
506
506
 
507
+ if (features.cloudFront) {
508
+ template += `
509
+ # CloudFront edge (cloudFront.enable): distribution in front of the HTTP API
510
+ resource "aws_iam_policy" "frigg_cloudfront" {
511
+ name = "${userName}-cloudfront-policy"
512
+ description = "CloudFront distribution permissions for Frigg"
513
+
514
+ policy = jsonencode({
515
+ Version = "2012-10-17"
516
+ Statement = [
517
+ {
518
+ Sid = "FriggCloudFrontDistributions"
519
+ Effect = "Allow"
520
+ Action = [
521
+ "cloudfront:CreateDistribution",
522
+ "cloudfront:CreateDistributionWithTags",
523
+ "cloudfront:UpdateDistribution",
524
+ "cloudfront:DeleteDistribution",
525
+ "cloudfront:GetDistribution",
526
+ "cloudfront:GetDistributionConfig",
527
+ "cloudfront:TagResource",
528
+ "cloudfront:UntagResource",
529
+ "cloudfront:ListTagsForResource"
530
+ ]
531
+ Resource = "arn:aws:cloudfront::*:distribution/*"
532
+ },
533
+ {
534
+ Sid = "FriggCloudFrontReadPolicies"
535
+ Effect = "Allow"
536
+ Action = [
537
+ "cloudfront:GetCachePolicy",
538
+ "cloudfront:GetOriginRequestPolicy",
539
+ "acm:DescribeCertificate",
540
+ "acm:ListCertificates"
541
+ ]
542
+ Resource = "*"
543
+ }
544
+ ]
545
+ })
546
+ }
547
+
548
+ resource "aws_iam_user_policy_attachment" "frigg_cloudfront" {
549
+ user = aws_iam_user.frigg_deployment.name
550
+ policy_arn = aws_iam_policy.frigg_cloudfront.arn
551
+ }
552
+ `;
553
+ }
554
+
507
555
  if (features.ssm) {
508
556
  template += `
509
557
  resource "aws_iam_user_policy_attachment" "frigg_ssm" {
@@ -52,6 +52,7 @@ async function generateIamCommand(options = {}) {
52
52
  console.log(` ${summary.features.kms ? '✅' : '❌'} KMS encryption`);
53
53
  console.log(` ${summary.features.ssm ? '✅' : '❌'} SSM Parameter Store`);
54
54
  console.log(` ${summary.features.websockets ? '✅' : '❌'} WebSocket support`);
55
+ console.log(` ${summary.features.cloudFront ? '✅' : '❌'} CloudFront edge (post-quantum TLS)`);
55
56
 
56
57
  // Generate the CloudFormation template
57
58
  console.log('\\n🏗️ Generating IAM CloudFormation template...');
@@ -88,6 +88,7 @@ const { repairCommand } = require('./repair-command');
88
88
  const { authCommand } = require('./auth-command');
89
89
  const { ssmPushCommand } = require('./ssm-command');
90
90
  const { validateCommand } = require('./validate-command');
91
+ const { tlsCheckCommand } = require('./tls-check-command');
91
92
 
92
93
  const program = new Command();
93
94
 
@@ -176,6 +177,13 @@ program
176
177
  .option('-v, --verbose', 'enable verbose output')
177
178
  .action(doctorCommand);
178
179
 
180
+ program
181
+ .command('tls-check <endpoints...>')
182
+ .description('Check whether endpoints accept hybrid post-quantum TLS key exchange (X25519MLKEM768)')
183
+ .option('-t, --timeout <ms>', 'handshake timeout in milliseconds', '10000')
184
+ .option('--json', 'print the result as JSON')
185
+ .action(tlsCheckCommand);
186
+
179
187
  program
180
188
  .command('repair <stackName>')
181
189
  .description('Repair infrastructure issues (import orphaned resources, reconcile property drift)')
@@ -67,8 +67,9 @@ validate it.
67
67
  explicitly. Keep it: the schema lists `aes` as the default, but nothing applies
68
68
  that default, and without the field `frigg deploy` creates no KMS key. Use `aes`
69
69
  instead of `kms` only if you manage the key yourself; then add
70
- `AES_KEY_ID: true` and `AES_KEY: true` to `environment` and set both (a
71
- 32-character key) in the shell that runs `frigg deploy`. See
70
+ `AES_KEY_ID: true` and `AES_KEY: true` to `environment` and set both
71
+ (`AES_KEY=$(openssl rand -hex 32)`, a 256-bit key) in the shell that runs
72
+ `frigg deploy`. See
72
73
  [Field-level encryption](#field-level-encryption) for when encryption runs.
73
74
  - **Database** — PostgreSQL that you bring (`management: 'external'`). Locally the
74
75
  connection string comes from `DATABASE_URL` in `.env`. To use MongoDB instead,
@@ -0,0 +1,396 @@
1
+ const { EventEmitter } = require('events');
2
+ const fs = require('fs');
3
+ const os = require('os');
4
+ const path = require('path');
5
+ const tls = require('tls');
6
+ const { execFileSync } = require('child_process');
7
+ const {
8
+ checkPostQuantumTls,
9
+ parseEndpoint,
10
+ HYBRID_POST_QUANTUM_GROUP,
11
+ } = require('../check-post-quantum-tls');
12
+
13
+ /** A fake tls module whose socket emits one event on the next tick. */
14
+ function fakeTls({ event, error, protocol = 'TLSv1.3', supported = true }) {
15
+ const sockets = [];
16
+ return {
17
+ sockets,
18
+ createSecureContext: jest.fn(() => {
19
+ if (!supported) throw new Error('Failed to set ECDH curve');
20
+ return {};
21
+ }),
22
+ connect: jest.fn(() => {
23
+ const socket = new EventEmitter();
24
+ socket.getProtocol = () => protocol;
25
+ socket.setTimeout = jest.fn((ms, onTimeout) => {
26
+ socket.onTimeout = onTimeout;
27
+ });
28
+ socket.destroy = jest.fn();
29
+ sockets.push(socket);
30
+ process.nextTick(() => {
31
+ if (event === 'timeout') socket.onTimeout();
32
+ else if (event === 'error') socket.emit('error', error);
33
+ else socket.emit('secureConnect');
34
+ });
35
+ return socket;
36
+ }),
37
+ };
38
+ }
39
+
40
+ const codedError = (code, message = code) =>
41
+ Object.assign(new Error(message), { code });
42
+
43
+ describe('parseEndpoint', () => {
44
+ it('reads host and port from an https URL', () => {
45
+ expect(
46
+ parseEndpoint(
47
+ 'https://abc.execute-api.us-east-1.amazonaws.com/prod/health'
48
+ )
49
+ ).toEqual({
50
+ host: 'abc.execute-api.us-east-1.amazonaws.com',
51
+ port: 443,
52
+ });
53
+ });
54
+
55
+ it('accepts a bare host and a host with a port', () => {
56
+ expect(parseEndpoint('kms.us-east-1.amazonaws.com')).toEqual({
57
+ host: 'kms.us-east-1.amazonaws.com',
58
+ port: 443,
59
+ });
60
+ expect(parseEndpoint('example.com:8443')).toEqual({
61
+ host: 'example.com',
62
+ port: 8443,
63
+ });
64
+ });
65
+
66
+ it('accepts wss URLs (WebSocket APIs)', () => {
67
+ expect(parseEndpoint('wss://ws.example.com/dev')).toEqual({
68
+ host: 'ws.example.com',
69
+ port: 443,
70
+ });
71
+ });
72
+
73
+ it('reads an IPv6 address without the URL brackets', () => {
74
+ expect(parseEndpoint('https://[::1]:8443/x')).toEqual({
75
+ host: '::1',
76
+ port: 8443,
77
+ });
78
+ expect(parseEndpoint('[2001:db8::1]')).toEqual({
79
+ host: '2001:db8::1',
80
+ port: 443,
81
+ });
82
+ });
83
+
84
+ it('refuses plain http, because there is no TLS to check', () => {
85
+ expect(() => parseEndpoint('http://example.com')).toThrow(/https/);
86
+ });
87
+
88
+ it('refuses an empty value', () => {
89
+ expect(() => parseEndpoint('')).toThrow();
90
+ });
91
+ });
92
+
93
+ describe('checkPostQuantumTls', () => {
94
+ it('offers only the hybrid group, over TLS 1.3, with SNI', async () => {
95
+ const tlsModule = fakeTls({ event: 'secureConnect' });
96
+
97
+ await checkPostQuantumTls({
98
+ host: 'api.example.com',
99
+ port: 443,
100
+ tlsModule,
101
+ });
102
+
103
+ expect(HYBRID_POST_QUANTUM_GROUP).toBe('X25519MLKEM768');
104
+ expect(tlsModule.connect).toHaveBeenCalledWith(
105
+ expect.objectContaining({
106
+ host: 'api.example.com',
107
+ port: 443,
108
+ servername: 'api.example.com',
109
+ ecdhCurve: 'X25519MLKEM768',
110
+ minVersion: 'TLSv1.3',
111
+ })
112
+ );
113
+ expect(tlsModule.sockets[0].destroy).toHaveBeenCalled();
114
+ });
115
+
116
+ it('sends no SNI for an IP address (RFC 6066)', async () => {
117
+ const tlsModule = fakeTls({ event: 'secureConnect' });
118
+
119
+ await checkPostQuantumTls({ host: '127.0.0.1', port: 9443, tlsModule });
120
+
121
+ expect(tlsModule.connect.mock.calls[0][0]).not.toHaveProperty(
122
+ 'servername'
123
+ );
124
+ });
125
+
126
+ it('gives a short refusal reason, not the full OpenSSL error text', async () => {
127
+ const error = codedError(
128
+ 'ERR_SSL_SSL/TLS_ALERT_HANDSHAKE_FAILURE',
129
+ '80E8:error:0A000410:SSL routines:ssl3_read_bytes:ssl/tls alert handshake failure:../deps/openssl/ssl/record/rec_layer_s3.c:918:SSL alert number 40\n'
130
+ );
131
+ error.reason = 'ssl/tls alert handshake failure';
132
+
133
+ const result = await checkPostQuantumTls({
134
+ host: 'api.example.com',
135
+ port: 443,
136
+ tlsModule: fakeTls({ event: 'error', error }),
137
+ });
138
+
139
+ expect(result.detail).toBe(
140
+ 'The server refused X25519MLKEM768 over TLS 1.3, so clients get classical key exchange only ' +
141
+ '(ERR_SSL_SSL/TLS_ALERT_HANDSHAKE_FAILURE: ssl/tls alert handshake failure).'
142
+ );
143
+ });
144
+
145
+ it('reports accepted when the handshake completes', async () => {
146
+ const result = await checkPostQuantumTls({
147
+ host: 'api.example.com',
148
+ port: 443,
149
+ tlsModule: fakeTls({ event: 'secureConnect' }),
150
+ });
151
+
152
+ expect(result).toEqual({
153
+ host: 'api.example.com',
154
+ port: 443,
155
+ result: 'accepted',
156
+ tlsVersion: 'TLSv1.3',
157
+ });
158
+ });
159
+
160
+ it.each([
161
+ 'ERR_SSL_SSL/TLS_ALERT_HANDSHAKE_FAILURE', // OpenSSL 3.5
162
+ 'ERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILURE', // older OpenSSL
163
+ 'ERR_SSL_TLSV1_ALERT_PROTOCOL_VERSION', // server has no TLS 1.3
164
+ 'ERR_SSL_BAD_KEY_SHARE', // HelloRetryRequest for a classical group
165
+ ])('reports refused for the TLS alert %s', async (code) => {
166
+ const result = await checkPostQuantumTls({
167
+ host: 'api.example.com',
168
+ port: 443,
169
+ tlsModule: fakeTls({ event: 'error', error: codedError(code) }),
170
+ });
171
+
172
+ expect(result.result).toBe('refused');
173
+ expect(result.detail).toMatch(/classical/);
174
+ });
175
+
176
+ it('reports accepted with a certificate error, because TLS 1.3 checks the certificate after the key exchange', async () => {
177
+ const result = await checkPostQuantumTls({
178
+ host: 'api.example.com',
179
+ port: 443,
180
+ tlsModule: fakeTls({
181
+ event: 'error',
182
+ error: codedError(
183
+ 'DEPTH_ZERO_SELF_SIGNED_CERT',
184
+ 'self-signed certificate'
185
+ ),
186
+ }),
187
+ });
188
+
189
+ expect(result.result).toBe('accepted');
190
+ expect(result.certificateError).toBe(
191
+ 'DEPTH_ZERO_SELF_SIGNED_CERT: self-signed certificate'
192
+ );
193
+ });
194
+
195
+ it.each(['ENOTFOUND', 'ECONNREFUSED', 'ETIMEDOUT', 'EHOSTUNREACH'])(
196
+ 'reports unreachable for %s',
197
+ async (code) => {
198
+ const result = await checkPostQuantumTls({
199
+ host: 'api.example.com',
200
+ port: 443,
201
+ tlsModule: fakeTls({ event: 'error', error: codedError(code) }),
202
+ });
203
+
204
+ expect(result.result).toBe('unreachable');
205
+ expect(result.detail).toContain(code);
206
+ }
207
+ );
208
+
209
+ it('reports error, with a middlebox hint, when the connection closes during the handshake', async () => {
210
+ // ECONNRESET needs an open TCP connection (a refused one is ECONNREFUSED).
211
+ const tlsModule = fakeTls({
212
+ event: 'error',
213
+ error: codedError(
214
+ 'ECONNRESET',
215
+ 'Client network socket disconnected before secure TLS connection was established'
216
+ ),
217
+ });
218
+
219
+ const result = await checkPostQuantumTls({
220
+ host: 'api.example.com',
221
+ port: 443,
222
+ tlsModule,
223
+ });
224
+
225
+ expect(result.result).toBe('error');
226
+ expect(result.detail).toMatch(/during the TLS handshake/);
227
+ expect(result.detail).toMatch(/ClientHello/);
228
+ });
229
+
230
+ it('reports unreachable after the timeout and destroys the socket', async () => {
231
+ const tlsModule = fakeTls({ event: 'timeout' });
232
+
233
+ const result = await checkPostQuantumTls({
234
+ host: 'api.example.com',
235
+ port: 443,
236
+ timeoutMs: 1234,
237
+ tlsModule,
238
+ });
239
+
240
+ expect(tlsModule.sockets[0].setTimeout).toHaveBeenCalledWith(
241
+ 1234,
242
+ expect.any(Function)
243
+ );
244
+ expect(result.result).toBe('unreachable');
245
+ expect(result.detail).toMatch(/1234 ms/);
246
+ expect(tlsModule.sockets[0].destroy).toHaveBeenCalled();
247
+ });
248
+
249
+ it('reports error for any other failure', async () => {
250
+ const result = await checkPostQuantumTls({
251
+ host: 'api.example.com',
252
+ port: 443,
253
+ tlsModule: fakeTls({
254
+ event: 'error',
255
+ error: codedError('ERR_SOMETHING_ELSE', 'odd'),
256
+ }),
257
+ });
258
+
259
+ expect(result.result).toBe('error');
260
+ expect(result.detail).toBe('ERR_SOMETHING_ELSE: odd');
261
+ });
262
+
263
+ it('reports unsupported-client and does not connect when this Node.js cannot offer the group', async () => {
264
+ const tlsModule = fakeTls({ event: 'secureConnect', supported: false });
265
+
266
+ const result = await checkPostQuantumTls({
267
+ host: 'api.example.com',
268
+ port: 443,
269
+ tlsModule,
270
+ });
271
+
272
+ expect(result.result).toBe('unsupported-client');
273
+ expect(result.detail).toMatch(/OpenSSL 3\.5/);
274
+ expect(tlsModule.connect).not.toHaveBeenCalled();
275
+ });
276
+ });
277
+
278
+ /**
279
+ * Real handshakes against local servers. They need the openssl CLI (for a
280
+ * throwaway certificate) and a Node.js that knows the group.
281
+ */
282
+ function canRunRealHandshakes() {
283
+ try {
284
+ tls.createSecureContext({ ecdhCurve: 'X25519MLKEM768' });
285
+ execFileSync('openssl', ['version'], { stdio: 'ignore' });
286
+ return true;
287
+ } catch {
288
+ return false;
289
+ }
290
+ }
291
+
292
+ const describeReal = canRunRealHandshakes() ? describe : describe.skip;
293
+
294
+ describeReal('checkPostQuantumTls against real local TLS servers', () => {
295
+ let dir;
296
+ let key;
297
+ let cert;
298
+
299
+ beforeAll(() => {
300
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-tls-check-'));
301
+ execFileSync(
302
+ 'openssl',
303
+ [
304
+ 'req',
305
+ '-x509',
306
+ '-newkey',
307
+ 'ec',
308
+ '-pkeyopt',
309
+ 'ec_paramgen_curve:P-256',
310
+ '-nodes',
311
+ '-keyout',
312
+ path.join(dir, 'key.pem'),
313
+ '-out',
314
+ path.join(dir, 'cert.pem'),
315
+ '-days',
316
+ '1',
317
+ '-subj',
318
+ '/CN=localhost',
319
+ '-addext',
320
+ 'subjectAltName=DNS:localhost',
321
+ ],
322
+ { stdio: 'ignore' }
323
+ );
324
+ key = fs.readFileSync(path.join(dir, 'key.pem'));
325
+ cert = fs.readFileSync(path.join(dir, 'cert.pem'));
326
+ });
327
+
328
+ afterAll(() => {
329
+ fs.rmSync(dir, { recursive: true, force: true });
330
+ });
331
+
332
+ async function withServer(serverOptions, run) {
333
+ const server = tls.createServer(
334
+ { key, cert, ...serverOptions },
335
+ (socket) => socket.end()
336
+ );
337
+ server.on('tlsClientError', () => {});
338
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
339
+ try {
340
+ return await run(server.address().port);
341
+ } finally {
342
+ await new Promise((resolve) => server.close(resolve));
343
+ }
344
+ }
345
+
346
+ it('accepted: a server with the default OpenSSL 3.5 groups', async () => {
347
+ const result = await withServer({}, (port) =>
348
+ checkPostQuantumTls({
349
+ host: 'localhost',
350
+ port,
351
+ tlsOptions: { ca: cert },
352
+ })
353
+ );
354
+
355
+ expect(result).toEqual(
356
+ expect.objectContaining({
357
+ result: 'accepted',
358
+ tlsVersion: 'TLSv1.3',
359
+ })
360
+ );
361
+ expect(result).not.toHaveProperty('certificateError');
362
+ });
363
+
364
+ it('refused: a server that allows only classical groups', async () => {
365
+ const result = await withServer({ ecdhCurve: 'X25519:P-256' }, (port) =>
366
+ checkPostQuantumTls({
367
+ host: 'localhost',
368
+ port,
369
+ tlsOptions: { ca: cert },
370
+ })
371
+ );
372
+
373
+ expect(result.result).toBe('refused');
374
+ });
375
+
376
+ it('refused: a server without TLS 1.3', async () => {
377
+ const result = await withServer({ maxVersion: 'TLSv1.2' }, (port) =>
378
+ checkPostQuantumTls({
379
+ host: 'localhost',
380
+ port,
381
+ tlsOptions: { ca: cert },
382
+ })
383
+ );
384
+
385
+ expect(result.result).toBe('refused');
386
+ });
387
+
388
+ it('accepted with a certificate error: an untrusted certificate', async () => {
389
+ const result = await withServer({}, (port) =>
390
+ checkPostQuantumTls({ host: 'localhost', port })
391
+ );
392
+
393
+ expect(result.result).toBe('accepted');
394
+ expect(result.certificateError).toMatch(/self-signed/);
395
+ });
396
+ });