seoActionFormMiddleware function

Middleware seoActionFormMiddleware({
  1. required String publicOrigin,
  2. required List<SeoActionFormRegistration> registrations,
  3. int maxBodyBytes = 32768,
  4. SeoActionFormErrorHandler? onError,
})

Handles the package-owned POST endpoint for registered action forms.

Place this middleware before seoBotMiddleware. Requests outside the fixed action-form namespace are passed through unchanged. The application handler receives only bounded, decoded and schema-validated values.

Implementation

Middleware seoActionFormMiddleware({
  required String publicOrigin,
  required List<SeoActionFormRegistration> registrations,
  int maxBodyBytes = 32768,
  SeoActionFormErrorHandler? onError,
}) {
  final expectedOrigin = _canonicalOrigin(publicOrigin, siteUrl: true);
  if (expectedOrigin == null) {
    throw ArgumentError.value(
      publicOrigin,
      'publicOrigin',
      'must be an absolute HTTP(S) origin or site URL',
    );
  }
  if (maxBodyBytes < 1024 || maxBodyBytes > 1024 * 1024) {
    throw RangeError.range(maxBodyBytes, 1024, 1024 * 1024, 'maxBodyBytes');
  }
  final byPath = <String, SeoActionFormRegistration>{};
  for (final registration in registrations) {
    if (byPath.containsKey(registration.plan.endpointPath)) {
      throw ArgumentError.value(
        registration.plan.actionId,
        'registrations',
        'contains a duplicate action id',
      );
    }
    byPath[registration.plan.endpointPath] = registration;
  }
  final frozen = Map<String, SeoActionFormRegistration>.unmodifiable(byPath);

  return (innerHandler) {
    return (request) async {
      final path = '/${request.url.path}';
      if (!path.startsWith(internalSeoActionFormEndpointPrefix)) {
        return innerHandler(request);
      }
      final registration = frozen[path];
      if (registration == null) {
        return _plainResponse(404, 'Not found.');
      }
      if (request.method != 'POST') {
        return _plainResponse(405, 'Method not allowed.', extraHeaders: {
          'allow': 'POST',
        });
      }
      if (_canonicalOrigin(request.headers['origin']) != expectedOrigin) {
        return _resultResponse(
          request,
          registration,
          403,
          registration._preparedMessages.forbiddenRequest,
        );
      }
      if (!_validFormContentType(request.headers['content-type'])) {
        return _resultResponse(
          request,
          registration,
          415,
          registration._preparedMessages.malformedRequest,
        );
      }
      final contentEncoding = request.headers['content-encoding'];
      if (contentEncoding != null &&
          contentEncoding.trim().toLowerCase() != 'identity') {
        return _resultResponse(
          request,
          registration,
          415,
          registration._preparedMessages.malformedRequest,
        );
      }
      final declared = request.headers['content-length'];
      final declaredLength = declared == null ? null : int.tryParse(declared);
      if (declared != null && (declaredLength == null || declaredLength < 0)) {
        return _resultResponse(
          request,
          registration,
          400,
          registration._preparedMessages.malformedRequest,
        );
      }
      if (declaredLength != null && declaredLength > maxBodyBytes) {
        return _resultResponse(
          request,
          registration,
          413,
          registration._preparedMessages.malformedRequest,
        );
      }

      Map<String, String>? rawValues;
      try {
        final bytes = <int>[];
        await for (final chunk in request.read()) {
          if (bytes.length + chunk.length > maxBodyBytes) {
            return _resultResponse(
              request,
              registration,
              413,
              registration._preparedMessages.malformedRequest,
            );
          }
          bytes.addAll(chunk);
        }
        rawValues = _decodeForm(bytes);
      } on FormatException {
        rawValues = null;
      } on ArgumentError {
        rawValues = null;
      }
      if (rawValues == null) {
        return _resultResponse(
          request,
          registration,
          400,
          registration._preparedMessages.malformedRequest,
        );
      }

      final validation = registration.flowPlan == null
          ? validateSeoActionFormValues(registration.plan, rawValues)
          : validateSeoActionFlowValues(registration.flowPlan!, rawValues);
      if (validation.malformed) {
        return _resultResponse(
          request,
          registration,
          400,
          registration._preparedMessages.malformedRequest,
        );
      }
      if (!validation.isValid) {
        return _resultResponse(
          request,
          registration,
          422,
          registration._preparedMessages.invalidSubmission,
          fieldErrors: validation.errors,
        );
      }

      try {
        final rawResult = await registration.handler(validation.values!);
        final result = canonicalizeSeoActionFormResult(
          registration.plan,
          rawResult,
          allowedFieldNames: registration.flowPlan == null
              ? null
              : validation.values!.values.keys.toSet(),
        );
        if (result == null) {
          throw const FormatException('Invalid action-form handler result');
        }
        return _resultResponse(
          request,
          registration,
          result.outcome == SeoActionFormOutcome.success ? 200 : 422,
          result.message,
          fieldErrors: result.fieldErrors,
          success: result.outcome == SeoActionFormOutcome.success,
        );
      } catch (error, stackTrace) {
        try {
          onError?.call(error, stackTrace);
        } catch (_) {
          // Diagnostics must not turn a contained application failure into an
          // unhandled request failure.
        }
        return _resultResponse(
          request,
          registration,
          500,
          registration._preparedMessages.internalError,
        );
      }
    };
  };
}