Base.pm 6.3 KB

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