main.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { NestFactory } from '@nestjs/core';
  2. import { AppModule } from './app.module';
  3. import { serverConfig } from './config/config';
  4. import { join } from 'path';
  5. import * as fs from 'fs';
  6. import { NestExpressApplication } from '@nestjs/platform-express';
  7. import session from 'express-session';
  8. import { ValidationPipe } from '@nestjs/common';
  9. async function bootstrap() {
  10. const certsDir = join(__dirname, '..', 'certs');
  11. const httpsOptions = {
  12. key: fs.readFileSync(join(certsDir, 'myapp.local-key.pem')),
  13. cert: fs.readFileSync(join(certsDir, 'myapp.local.pem')),
  14. };
  15. // Use HTTPS if needed:
  16. const app = await NestFactory.create<NestExpressApplication>(AppModule, {
  17. httpsOptions,
  18. });
  19. // HTTP version for LAN testing:
  20. // const app = await NestFactory.create<NestExpressApplication>(AppModule);
  21. app.useGlobalPipes(
  22. new ValidationPipe({
  23. whitelist: true,
  24. forbidNonWhitelisted: true,
  25. transform: true,
  26. }),
  27. );
  28. // app.enableCors({
  29. // origin: [
  30. // 'http://localhost:4200', // browser dev
  31. // 'capacitor://localhost', // Capacitor WebView
  32. // 'http://192.168.100.80:4200', // optional LAN Angular dev
  33. // ],
  34. // credentials: true,
  35. // });
  36. app.enableCors({
  37. origin: (origin, callback) => {
  38. // console.log('CORS origin:', origin); // check what the WebView sends
  39. callback(null, true); // allow all origins dynamically
  40. },
  41. credentials: true,
  42. });
  43. app.setGlobalPrefix('api');
  44. const angularDistPath = join(
  45. __dirname,
  46. '..',
  47. '..',
  48. 'web-app',
  49. 'dist',
  50. 'mobile-auth-web-app',
  51. 'browser',
  52. );
  53. const indexPath = join(angularDistPath, 'index.html');
  54. app.useStaticAssets(angularDistPath);
  55. app.setBaseViewsDir(angularDistPath);
  56. app.setViewEngine('html');
  57. app.use(
  58. session({
  59. secret: 'your-secret',
  60. resave: false,
  61. saveUninitialized: false,
  62. cookie: {
  63. httpOnly: true,
  64. secure: false, // set to true when using HTTPS
  65. sameSite: 'lax',
  66. maxAge: 24 * 60 * 60 * 1000,
  67. },
  68. }),
  69. );
  70. app.use((req, res, next) => {
  71. const isStaticAsset = req.url.includes('.');
  72. const isApiCall = req.url.startsWith('/api') || req.method !== 'GET';
  73. if (isStaticAsset || isApiCall) return next();
  74. res.sendFile(indexPath);
  75. });
  76. // Listen on all interfaces so LAN devices can reach it
  77. await app.listen(4000, '0.0.0.0');
  78. console.log(`🚀 HTTP server running at ${serverConfig.exposedUrl}`);
  79. }
  80. bootstrap();