Base.pm 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package Trog::Renderer::Base;
  2. use v5.36;
  3. use re '/aa';
  4. use Encode qw{encode_utf8};
  5. use IO::Compress::Gzip;
  6. use Text::Xslate;
  7. use Trog::Themes;
  8. use Trog::Config;
  9. use Time::HiRes qw{tv_interval};
  10. =head1 Trog::Renderer::Base
  11. Basic rendering structure, subclass me.
  12. Sets up the methods which must be present for all templates, e.g. render_it for rendering dynamic template strings coming from a post.
  13. =cut
  14. our %renderers;
  15. =head2 render(%options)
  16. Render a template and build the PSGI response around it.
  17. Recognized options:
  18. template => the template's filename, relative to the template dir. Required.
  19. contenttype => what we're rendering, e.g. 'text/html'. Picks the template dir.
  20. component => render a component rather than a whole page. Returns just the
  21. body string, with no headers and no compression.
  22. data => the variables handed to the template.
  23. code => HTTP status for the response.
  24. headers => extra headers, merged over the computed ones.
  25. deflate => gzip the body and set Content-Encoding.
  26. post_processor => CODEREF run over the body before headers are computed, for
  27. things like minifiers.
  28. child_processor / child_renderer => override how post bodies are rendered by
  29. the render_it() template function. Built for you if omitted.
  30. Dies unless Xslate can resolve and render the template. Returns the body
  31. string for components, and a PSGI arrayref of [ code, headers, body ] otherwise.
  32. =cut
  33. sub render (%options) {
  34. die "Templated renders require a template to be passed" unless $options{template};
  35. # Xslate resolves includes against every dir in path, first match winning,
  36. # so handing it both lets a theme override individual templates without
  37. # having to fork the ones next to them. With no theme configured this is
  38. # just the stock dir, exactly as it was.
  39. my @template_dirs = Trog::Themes::template_dirs( $options{contenttype}, $options{component} );
  40. #TODO make this work with posts all the time
  41. $options{child_processor} //= Text::Xslate->new( path => \@template_dirs );
  42. my $child_processor = $options{child_processor};
  43. $options{child_renderer} //= sub {
  44. my ( $template_string, $options ) = @_;
  45. # If it fails to render, it must be something else
  46. my $out = eval { $child_processor->render_string( $template_string, $options ) };
  47. return $out ? $out : $template_string;
  48. };
  49. # Keyed on the whole search path, not just the winning dir: two different
  50. # paths that happen to start with the same dir are not the same renderer.
  51. my $renderer_key = join( ':', @template_dirs );
  52. $renderers{$renderer_key} //= Text::Xslate->new(
  53. path => \@template_dirs,
  54. function => {
  55. render_it => $options{child_renderer},
  56. },
  57. );
  58. my $code = $options{code};
  59. # Xslate resolves the template itself, against the same @template_dirs it
  60. # will actually use. There used to be a pre-flight test here, and it was
  61. # wrong twice over: it resolved through template_dir(), which returns one
  62. # winning directory rather than the search path, so it could pass on a file
  63. # Xslate would not use and name a nonexistent stock path in its error while
  64. # a good theme template existed. And the condition itself, -f $t || -s $t,
  65. # short-circuited on -f, so an empty file passed, while a *directory* passed
  66. # on -s returning its size.
  67. my $body = eval { encode_utf8( $renderers{$renderer_key}->render( $options{template}, $options{data} ) ) };
  68. die "Could not render template '$options{template}' (searched @template_dirs): $@" unless defined $body;
  69. # Users can supply a post_processor to futz with the output (such as with minifiers) if they wish.
  70. $body = $options{post_processor}->($body) if $options{post_processor} && ref $options{post_processor} eq 'CODE';
  71. # Users can supply custom headers as part of the data in options.
  72. my %headers = headers( \%options, $body );
  73. return $body if $options{component};
  74. return [ $code, [%headers], [$body] ] unless $options{deflate};
  75. $headers{"Content-Encoding"} = "gzip";
  76. my $dfh;
  77. IO::Compress::Gzip::gzip( \$body => \$dfh );
  78. print $IO::Compress::Gzip::GzipError if $IO::Compress::Gzip::GzipError;
  79. $headers{"Content-Length"} = length($dfh);
  80. return [ $code, [%headers], [$dfh] ];
  81. }
  82. =head2 headers($options, $body) = %headers
  83. The response headers for a rendered body: content type and length, caching,
  84. Server-Timing, and the security headers (CSP, X-Frame-Options, HSTS when we're
  85. on https, nosniff). Anything in $options->{headers} is merged over the top.
  86. ETags are only set for logged in users, as everyone else is served out of the
  87. static render cache.
  88. =cut
  89. sub headers ( $options, $body ) {
  90. my $query = $options->{data};
  91. my $uh = ref $options->{headers} eq 'HASH' ? $options->{headers} : {};
  92. my $ct = $options->{contenttype} eq 'text/html' ? "text/html; charset=UTF-8" : "$options->{contenttype};";
  93. my %headers = (
  94. 'Content-Type' => $ct,
  95. 'Content-Length' => length($body),
  96. 'Cache-Control' => $query->{cachecontrol} // $Trog::Vars::cache_control{revalidate},
  97. 'X-Content-Type-Options' => 'nosniff',
  98. 'Vary' => 'Accept-Encoding',
  99. 'Server-Timing' => "render;dur=" . ( tv_interval( $query->{start} ) * 1000 ),
  100. %$uh,
  101. );
  102. #Disallow framing UNLESS we are in embed mode
  103. my $ancestor = $query->{domain} || 'none';
  104. $headers{"Content-Security-Policy"} = qq{frame-ancestors $ancestor} unless $query->{embed};
  105. $headers{'X-Frame-Options'} = 'DENY' unless $query->{embed};
  106. $headers{'Referrer-Policy'} = 'no-referrer-when-downgrade';
  107. #CSP. Yet another layer of 'no mixed content' plus whitelisted execution of remote resources.
  108. # Component renders (posts.tx, the bars) get a data hash built by the route
  109. # rather than the request, and it carries no scheme.
  110. my $scheme = ( $query->{scheme} // '' ) eq 'https' ? "$query->{scheme}:" : '';
  111. my $conf = Trog::Config::get();
  112. my $sites = $conf->param('security.allow_embeds_from') // '';
  113. $headers{'Content-Security-Policy'} .= ";default-src $scheme 'self' data: 'unsafe-eval' 'unsafe-inline' $sites";
  114. $headers{'Content-Security-Policy'} .= ";object-src 'none'";
  115. # Force https if we are https
  116. $headers{'Strict-Transport-Security'} = 'max-age=63072000' if ( $query->{scheme} // '' ) eq 'https';
  117. # We only set etags when users are logged in, cause we don't use statics
  118. $headers{'ETag'} = $query->{etag} if $query->{etag} && $query->{user};
  119. return %headers;
  120. }
  121. 1;