-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDiffyneController.php
More file actions
476 lines (401 loc) · 15.8 KB
/
Copy pathDiffyneController.php
File metadata and controls
476 lines (401 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
<?php
namespace Diffyne\Http\Controllers;
use BadMethodCallException;
use Diffyne\DiffyneManager;
use Diffyne\Exceptions\RedirectException;
use Diffyne\FileUpload\FileUploadService;
use Diffyne\Security\StateSigner;
use Diffyne\State\ComponentHydrator;
use Diffyne\VirtualDOM\PatchSerializer;
use Diffyne\VirtualDOM\Renderer;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
class DiffyneController extends Controller
{
protected ComponentHydrator $hydrator;
protected Renderer $renderer;
protected PatchSerializer $serializer;
protected DiffyneManager $manager;
public function __construct(
ComponentHydrator $hydrator,
Renderer $renderer,
PatchSerializer $serializer,
DiffyneManager $manager
) {
$this->hydrator = $hydrator;
$this->renderer = $renderer;
$this->serializer = $serializer;
$this->manager = $manager;
}
/**
* Handle component updates.
*/
public function update(Request $request): JsonResponse
{
try {
$type = $request->input('type');
$componentId = $request->input('componentId');
$state = $request->input('state', []);
$fingerprint = $request->input('fingerprint');
$signature = $request->input('signature');
// Validate request
if (! $componentId || ! $state) {
return response()->json([
'success' => false,
'error' => 'Invalid request',
], 400);
}
$verifyMode = config('diffyne.security.verify_state', 'property-updates');
$shouldVerify = match ($verifyMode) {
'strict', true, 'true' => true,
'property-updates' => ($type === 'update'),
default => false,
};
if ($shouldVerify) {
if (! $signature) {
return response()->json([
'success' => false,
'error' => 'Missing state signature',
], 400);
}
$signatureValid = StateSigner::verify($state, $componentId, $signature);
if (! $signatureValid && $type === 'call' && config('diffyne.security.lenient_form_verification', true)) {
$reconstructedState = $state;
$reconstructedCount = 0;
foreach ($reconstructedState as $key => $value) {
if (is_string($value) && $value !== '') {
$reconstructedState[$key] = null;
$reconstructedCount++;
} elseif (is_int($value) && $value !== 0) {
$reconstructedState[$key] = 0;
$reconstructedCount++;
} elseif (is_bool($value) && $value === true) {
$reconstructedState[$key] = false;
$reconstructedCount++;
}
}
if ($reconstructedCount > 0 && $reconstructedCount <= 20) {
$reconstructedState = $this->normalizeStateForVerification($reconstructedState);
$signatureValid = StateSigner::verify($reconstructedState, $componentId, $signature);
}
}
if (! $signatureValid) {
Log::warning('Invalid state signature detected', [
'component_id' => $componentId,
'ip' => $request->ip(),
'type' => $type,
]);
return response()->json([
'success' => false,
'error' => 'Invalid state signature. State may have been tampered with.',
], 403);
}
}
// Get component class from state or registry
$componentClass = $this->resolveComponentClass($request);
if (! $componentClass) {
return response()->json([
'success' => false,
'error' => 'Component class not found',
], 404);
}
// Hydrate component from state
$component = $this->hydrator->hydrate($componentClass, $state, $componentId);
// Store initial snapshot for diffing
$this->renderer->snapshotComponent($component);
// Restore error bag if present
if ($request->has('errors')) {
$component->setErrorBag($request->input('errors', []));
}
// Handle different request types
switch ($type) {
case 'call':
$method = $request->input('method');
$params = $request->input('params', []);
if (! $method) {
return response()->json([
'success' => false,
'error' => 'Method not specified',
], 400);
}
$component->callMethod($method, $params);
break;
case 'update':
$property = $request->input('property');
$value = $request->input('value');
if (! $property) {
return response()->json([
'success' => false,
'error' => 'Property not specified',
], 400);
}
$component->updateProperty($property, $value);
break;
default:
return response()->json([
'success' => false,
'error' => 'Invalid request type',
], 400);
}
// Render updates and generate patches
$response = $this->renderer->renderUpdate($component);
// Optimize response
$serializedResponse = $this->serializer->toResponse($response, config('diffyne.performance.minify_patches', true));
return response()->json($serializedResponse)
->header('Content-Type', 'application/json; charset=utf-8');
} catch (RedirectException $e) {
$redirectData = $e->getRedirectData();
return response()->json([
's' => true,
'redirect' => $redirectData['redirect'],
]);
} catch (ValidationException $e) {
// Return validation errors
return response()->json([
's' => false,
'error' => 'Validation failed',
'type' => 'validation_error',
'errors' => $e->errors(),
], 422);
} catch (BadMethodCallException $e) {
return response()->json([
's' => false,
'error' => $e->getMessage(),
'type' => 'method_error',
], 400);
} catch (InvalidArgumentException $e) {
return response()->json([
's' => false,
'error' => $e->getMessage(),
'type' => 'property_error',
], 400);
} catch (Exception $e) {
Log::error('Diffyne Error: '.$e->getMessage(), [
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString(),
]);
if (config('diffyne.debug', false)) {
return response()->json([
's' => false,
'error' => $e->getMessage(),
'type' => 'exception',
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => explode("\n", $e->getTraceAsString()),
], 500);
}
return response()->json([
's' => false,
'error' => 'An error occurred while processing your request.',
'type' => 'server_error',
], 500);
}
}
/**
* @param array<string, mixed> $state
* @return array<string, mixed>
*/
protected function normalizeStateForVerification(array $state): array
{
foreach ($state as $key => $value) {
if ($value === '') {
$state[$key] = null;
} elseif (is_array($value)) {
$state[$key] = $this->normalizeStateForVerification($value);
}
}
ksort($state);
return $state;
}
/**
* Resolve component class from request.
*/
protected function resolveComponentClass(Request $request): ?string
{
// Try to get from request
$componentClass = $request->input('componentClass');
if ($componentClass && class_exists($componentClass)) {
return $componentClass;
}
// Try to get from component name
$componentName = $request->input('componentName');
if ($componentName) {
$defaultNamespace = config('diffyne.component_namespace', 'App\\Diffyne');
$componentName = str_replace('/', '\\', $componentName);
$fullClass = $defaultNamespace.'\\'.$componentName;
if (class_exists($fullClass)) {
return $fullClass;
}
}
return null;
}
/**
* Load a lazy component.
*/
public function loadLazy(Request $request): JsonResponse
{
try {
$componentClass = $request->input('componentClass');
$componentId = $request->input('componentId');
$params = $request->input('params', []);
$queryParams = $request->input('queryParams', []);
if (! $componentClass || ! class_exists($componentClass)) {
return response()->json([
'success' => false,
'error' => 'Invalid component class',
], 400);
}
// Merge query parameters with component params
// Query parameters take precedence for QueryString properties
$mergedParams = array_merge($params, $queryParams);
// Mount the component
$instance = $this->hydrator->mount($componentClass, $mergedParams);
$rendered = $this->renderer->renderInitial($instance);
// Return the rendered HTML and state
return response()->json([
'success' => true,
'id' => $rendered['id'],
'html' => $rendered['html'],
'state' => $rendered['state'],
'fingerprint' => $rendered['fingerprint'],
]);
} catch (Exception $e) {
Log::error('Lazy Load Error: '.$e->getMessage(), [
'exception' => get_class($e),
'file' => $e->getFile(),
'line' => $e->getLine(),
]);
return response()->json([
'success' => false,
'error' => 'Failed to load component: '.$e->getMessage(),
], 500);
}
}
/**
* Health check endpoint.
*/
public function health(): JsonResponse
{
return response()->json([
'status' => 'ok',
'version' => '1.0.0',
'transport' => config('diffyne.transport', 'ajax'),
]);
}
/**
* Handle file upload.
*/
public function upload(Request $request): JsonResponse
{
try {
$componentId = $request->input('componentId');
$property = $request->input('property');
if (! $request->hasFile('file')) {
return response()->json([
'success' => false,
'error' => 'No file uploaded',
], 400);
}
$file = $request->file('file');
if (is_array($file)) {
$file = $file[0] ?? null;
}
if (! $componentId || ! $property || ! $file instanceof UploadedFile) {
return response()->json([
'success' => false,
'error' => 'Missing required parameters',
'debug' => [
'has_componentId' => ! empty($componentId),
'has_property' => ! empty($property),
'has_file' => $file instanceof UploadedFile,
],
], 400);
}
if (! $file->isValid()) {
return response()->json([
'success' => false,
'error' => 'Invalid file upload',
'error_code' => $file->getError(),
], 400);
}
$maxSize = config('diffyne.file_upload.max_size', 12288);
if ($file->getSize() > $maxSize * 1024) {
return response()->json([
'success' => false,
'error' => 'File too large',
], 422);
}
$allowedMimes = config('diffyne.file_upload.allowed_mimes');
if ($allowedMimes !== null && is_array($allowedMimes) && count($allowedMimes) > 0) {
$mimeType = $file->getMimeType();
if (! in_array($mimeType, $allowedMimes, true)) {
return response()->json([
'success' => false,
'error' => 'File type not allowed',
'allowed_types' => $allowedMimes,
], 422);
}
}
$service = app(FileUploadService::class);
$identifier = $service->storeTemporary($file, $componentId);
return response()->json([
'success' => true,
'identifier' => $identifier,
'filename' => $file->getClientOriginalName(),
'size' => $file->getSize(),
]);
} catch (\Exception $e) {
Log::error('File upload error: '.$e->getMessage(), [
'exception' => get_class($e),
'trace' => $e->getTraceAsString(),
]);
return response()->json([
'success' => false,
'error' => 'Upload failed: '.$e->getMessage(),
], 500);
}
}
/**
* Preview temporary file.
*/
public function preview(Request $request): Response
{
$id = $request->query('id', '');
$identifier = is_string($id) ? urldecode($id) : '';
if (! $identifier) {
abort(404);
}
$service = app(FileUploadService::class);
$path = $service->getTemporaryPath($identifier);
if (! $path) {
abort(404);
}
$disk = config('diffyne.file_upload.disk', 'local');
$content = Storage::disk($disk)->get($path);
if (! $content) {
abort(404);
}
$extension = pathinfo($path, PATHINFO_EXTENSION);
$mimeType = match(strtolower($extension)) {
'jpg', 'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
default => 'application/octet-stream',
};
return response($content, 200)
->header('Content-Type', $mimeType)
->header('Cache-Control', 'private, max-age=3600');
}
}