-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
756 lines (675 loc) · 33 KB
/
Copy pathindex.php
File metadata and controls
756 lines (675 loc) · 33 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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
<?php
declare(strict_types=1);
/**
* eeID embedded widget demo — full loop (Phase 2).
*
* Three halves, and the split is the whole point of the design:
*
* SERVER-SIDE create (this file, below): the integrator authenticates with its OAuth2 client
* credentials and asks eeID-login for a widget session. The client secret never reaches the
* browser. eeID-login drives Hydra's /oauth2/auth itself and hands back an opaque
* session_token.
*
* BROWSER (the HTML further down): loads the self-hosted SDK (<eeid-widget>), which frames
* /embed/<session_token> and relays the widget's postMessage events. No cookie is involved
* anywhere — the token IS the session, which is what makes this work in Safari with
* third-party cookies blocked. On success the widget hands the parent a single-use
* result_token — never the OAuth2 code.
*
* SERVER-SIDE redeem (the POST branch at the top): the browser posts the result_token back
* here; this backend redeems it for the OAuth2 code (client-authenticated) and exchanges the
* code at Hydra's token endpoint for the ID token. Again, no secret in the browser.
*/
$clientId = getenv('EEID_CLIENT_ID') ?: '';
$clientSecret = getenv('EEID_CLIENT_SECRET') ?: '';
$redirectUri = getenv('EEID_REDIRECT_URI') ?: '';
$verifyTls = (getenv('EEID_VERIFY_TLS') ?: '1') === '1';
/**
* The eeID stacks this demo may talk to, most likely first, as
* [['login' => <login-server origin>, 'hydra' => <Hydra base or null>], ...]
*
* A Service lives in exactly ONE stack: eeID-manager registers its OAuth2 client in the Hydra
* matching the service's environment and deletes it from the other. So the environment never
* has to be configured — whichever stack authenticates these credentials IS the one the service
* is registered in, and flipping the environment in eeID-manager is picked up on the next page
* load with no .env edit.
*
* Configure the pairs once, comma-separated, "<login origin>|<hydra base>":
*
* EEID_ENVIRONMENTS=https://test-auth.eeid.ee,https://auth.eeid.ee
*
* The Hydra base is where that stack publishes /.well-known/openid-configuration — its own host
* on some deployments, a path prefix on others. Omit it and the login origin is tried with the
* /hydra-public prefix — which is what eeID itself uses (https://auth.eeid.ee/hydra-public), so
* for eeID the second half never has to be given.
*
* EEID_LOGIN_PUBLIC_URL pins a single stack and skips the probing entirely. Use it when you have
* one eeID to talk to, or when Hydra sits on its own host (a local development stack).
*
* There is no built-in default: set one of the two, whichever matches your deployment.
*/
function eeid_environments(): array
{
$pinned = getenv('EEID_LOGIN_PUBLIC_URL');
if ($pinned) {
return [['login' => rtrim($pinned, '/'), 'hydra' => null]];
}
$raw = getenv('EEID_ENVIRONMENTS') ?: '';
$environments = [];
foreach (explode(',', $raw) as $entry) {
$entry = trim($entry);
if ($entry === '') {
continue;
}
[$login, $hydra] = array_pad(explode('|', $entry, 2), 2, null);
$login = rtrim(trim((string) $login), '/');
$hydra = $hydra === null ? null : rtrim(trim($hydra), '/');
if ($login !== '') {
$environments[] = ['login' => $login, 'hydra' => $hydra ?: null];
}
}
return $environments;
}
/** Just the login origins, for validating what the browser reports back to us. */
function eeid_login_origins(): array
{
return array_column(eeid_environments(), 'login');
}
/**
* Server-side base for the API calls to a given stack. Only set EEID_LOGIN_INTERNAL_URL when
* those calls have a PRIVATE address the browser cannot use — e.g. http://eeid-login:3000 on a
* shared Docker network. A normal deployment has no such address, so it defaults to the public
* origin. It applies only to a pinned single stack; when several are probed, each is called on
* its own public origin.
*/
function eeid_internal_url(string $publicOrigin): string
{
$internal = getenv('EEID_LOGIN_INTERNAL_URL');
if ($internal && getenv('EEID_LOGIN_PUBLIC_URL')) {
return rtrim($internal, '/');
}
return $publicOrigin;
}
/**
* Hydra's token endpoint for a stack, read from that stack's own discovery document so it
* follows the environment automatically. EEID_HYDRA_TOKEN_URL overrides it outright, for a
* deployment that publishes no discovery document under the login origin.
*/
function eeid_token_url(string $loginOrigin, bool $verifyTls): array
{
$explicit = getenv('EEID_HYDRA_TOKEN_URL');
if ($explicit) {
return [rtrim($explicit, '/'), null];
}
$hydra = null;
foreach (eeid_environments() as $environment) {
if ($environment['login'] === $loginOrigin) {
$hydra = $environment['hydra'] ?: $loginOrigin . '/hydra-public';
break;
}
}
if ($hydra === null) {
return [null, 'No Hydra configured for ' . $loginOrigin . ' — add it to EEID_ENVIRONMENTS.'];
}
$discovery = $hydra . '/.well-known/openid-configuration';
[$status, $body] = eeid_http($discovery, [
CURLOPT_HTTPHEADER => ['Accept: application/json'],
CURLOPT_SSL_VERIFYPEER => $verifyTls,
]);
if ($status === 200 && !empty($body['token_endpoint'])) {
return [$body['token_endpoint'], null];
}
return [null, 'Could not discover the token endpoint at ' . $discovery . ' (HTTP ' . $status . '). '
. 'Check the Hydra base in EEID_ENVIRONMENTS, or set EEID_HYDRA_TOKEN_URL.'];
}
/**
* Blends #rrggbb toward $toward by $ratio (0..1) and returns #rrggbb. Used to derive the hover
* shade and the tint from whatever brand colour is in play, so the row controls compose with
* ?primary= rather than hard-coding one palette.
*/
function eeid_mix(string $hex, string $toward, float $ratio): string
{
$parse = static function (string $value): array {
$value = ltrim(trim($value), '#');
if (strlen($value) === 3) {
$value = $value[0] . $value[0] . $value[1] . $value[1] . $value[2] . $value[2];
}
if (!preg_match('/^[0-9a-f]{6}$/i', $value)) {
return [124, 58, 237]; // the default violet, for anything unparseable
}
return [hexdec(substr($value, 0, 2)), hexdec(substr($value, 2, 2)), hexdec(substr($value, 4, 2))];
};
[$r1, $g1, $b1] = $parse($hex);
[$r2, $g2, $b2] = $parse($toward);
$ratio = max(0.0, min(1.0, $ratio));
return sprintf(
'#%02x%02x%02x',
(int) round($r1 + ($r2 - $r1) * $ratio),
(int) round($g1 + ($g2 - $g1) * $ratio),
(int) round($b1 + ($b2 - $b1) * $ratio)
);
}
/**
* Small cURL helper returning [httpStatus, decodedJsonOrNull, rawBody, curlError].
*/
function eeid_http(string $url, array $opts): array
{
$ch = curl_init($url);
curl_setopt_array($ch, $opts + [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
]);
$raw = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
$json = is_string($raw) ? json_decode($raw, true) : null;
return [$status, $json, $raw, $err];
}
/**
* Mints a fresh embedded session. Used both for the first page render and for "log out",
* which starts a whole new session rather than reusing the spent one.
*
* Returns [sessionToken, errorMessage] — exactly one of the two is non-null.
*/
function eeid_create_session(array $cfg, string $locale, array $theme, string $returnUrl): array
{
if ($cfg['clientId'] === '' || $cfg['clientSecret'] === '') {
return [null, null, 'EEID_CLIENT_ID / EEID_CLIENT_SECRET are not set. Copy .env.example to .env and fill them in.'];
}
if ($cfg['redirectUri'] === '') {
return [null, null, 'EEID_REDIRECT_URI is not set. Use one of the redirect URIs registered on your eeID service.'];
}
if ($cfg['environments'] === []) {
return [null, null, 'No eeID server configured. Set EEID_LOGIN_PUBLIC_URL to your eeID login server, '
. 'or EEID_ENVIRONMENTS if you want the demo to probe several.'];
}
$failures = [];
// A 401 means "this client does not live in this stack's Hydra" — the ONLY signal we need
// to move on to the next candidate. Any other failure is reported as-is, since retrying a
// stack that is down or misconfigured against another one just hides the real problem.
foreach ($cfg['environments'] as $environment) {
$origin = $environment['login'];
$base = eeid_internal_url($origin);
// return_url carries the stack it belongs to, so a top-level OIDC round-trip comes back
// knowing which one to resume against. Adding a query param keeps the ORIGIN identical,
// which is what eeID-login allowlists.
$payload = json_encode([
'redirect_uri' => $cfg['redirectUri'],
'scope' => getenv('EEID_SCOPE') ?: 'openid',
'locale' => $locale,
'state' => bin2hex(random_bytes(16)),
'nonce' => bin2hex(random_bytes(16)),
'return_url' => $returnUrl . (str_contains($returnUrl, '?') ? '&' : '?')
. 'eeid_origin=' . rawurlencode($origin),
'theme' => $theme,
], JSON_THROW_ON_ERROR);
[$status, $body, $raw, $curlError] = eeid_http($base . '/api/embedded/sessions', [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Accept: application/json'],
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $cfg['clientId'] . ':' . $cfg['clientSecret'],
// The dev stack uses a private CA; do not copy this into production.
CURLOPT_SSL_VERIFYPEER => $cfg['verifyTls'],
]);
if ($status === 201 && isset($body['session_token'])) {
return [$body['session_token'], $origin, null];
}
if ($raw === false) {
$failures[] = $origin . ' — unreachable (' . $curlError . ')';
continue;
}
$failures[] = $origin . ' — HTTP ' . $status
. ($body['error'] ?? null ? ': ' . $body['error'] : '');
}
$hint = count($cfg['environments']) > 1
? ' The client was not accepted by any known eeID environment. Check EEID_CLIENT_ID / '
. 'EEID_CLIENT_SECRET, and that the service is approved in eeID-manager.'
: '';
return [null, null, 'Session creation failed. Tried: ' . implode('; ', $failures) . '.' . $hint];
}
$eeidConfig = [
'environments' => eeid_environments(),
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'redirectUri' => $redirectUri,
'verifyTls' => $verifyTls,
];
// ---------------------------------------------------------------------------
// POST branch: redeem the result_token and exchange the code for tokens.
// ---------------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input') ?: '{}', true) ?: [];
$resultToken = (string) ($input['result_token'] ?? '');
// "Log out": there is no eeID session for this page to end — the embedded flow is
// cookieless, and Hydra's own login cookies live in a per-session SERVER-SIDE jar that is
// discarded with the session. So logging out is simply dropping the tokens we hold and
// minting a brand-new embedded session, which authenticates from scratch.
if (($input['action'] ?? '') === 'new_session') {
[$token, $origin, $err] = eeid_create_session(
$eeidConfig,
(string) ($input['locale'] ?? 'en'),
is_array($input['theme'] ?? null) ? $input['theme'] : [],
(string) ($input['return_url'] ?? 'http://localhost:8081/')
);
if ($token === null) {
http_response_code(502);
echo json_encode(['error' => $err]);
exit;
}
// The stack may have changed since the page was rendered (someone flipped the service's
// environment in eeID-manager), so the browser is told where to load the widget from.
echo json_encode(['session_token' => $token, 'login_origin' => $origin]);
exit;
}
if ($resultToken === '') {
http_response_code(400);
echo json_encode(['error' => 'result_token is required']);
exit;
}
// The session lives on ONE stack, so the redeem and the token exchange must both address
// that same one. The browser reports which it was; it is only ever honoured when it is one
// of our own configured candidates, because this request carries the client secret and must
// never be steered at a host of the caller's choosing.
$origin = rtrim((string) ($input['login_origin'] ?? ''), '/');
$candidates = eeid_login_origins();
if (!in_array($origin, $candidates, true)) {
$origin = $candidates[0] ?? '';
}
$internalUrl = eeid_internal_url($origin);
[$tokenUrl, $tokenUrlError] = eeid_token_url($origin, $verifyTls);
if ($tokenUrl === null) {
http_response_code(502);
echo json_encode(['error' => $tokenUrlError]);
exit;
}
// 1) Redeem the single-use result_token for the OAuth2 code (client-authenticated).
[$rStatus, $rBody] = eeid_http(
$internalUrl . '/api/embedded/sessions/' . rawurlencode($resultToken) . '/redeem',
[
CURLOPT_POST => true,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $clientId . ':' . $clientSecret,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
CURLOPT_SSL_VERIFYPEER => $verifyTls,
]
);
if ($rStatus !== 200 || !isset($rBody['code'])) {
http_response_code(502);
echo json_encode([
'error' => 'redeem failed (HTTP ' . $rStatus . ')',
'detail' => $rBody['error'] ?? null,
]);
exit;
}
// 2) Exchange the code at Hydra's token endpoint for the ID token (standard OIDC).
[$tStatus, $tBody, $tRaw] = eeid_http($tokenUrl, [
CURLOPT_POST => true,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $clientId . ':' . $clientSecret,
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'authorization_code',
'code' => $rBody['code'],
'redirect_uri' => $redirectUri,
]),
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
CURLOPT_SSL_VERIFYPEER => $verifyTls,
]);
if ($tStatus !== 200 || !isset($tBody['id_token'])) {
http_response_code(502);
echo json_encode([
'error' => 'token exchange failed (HTTP ' . $tStatus . ')',
'detail' => $tBody['error_description'] ?? $tBody['error'] ?? substr((string) $tRaw, 0, 300),
]);
exit;
}
// Decode the ID token payload for display (a real integrator MUST verify the signature).
$parts = explode('.', (string) $tBody['id_token']);
$claims = isset($parts[1])
? json_decode(base64_decode(strtr($parts[1], '-_', '+/')) ?: '{}', true)
: null;
echo json_encode([
'state' => $rBody['state'] ?? null,
'claims' => $claims,
]);
exit;
}
// ---------------------------------------------------------------------------
// GET branch: create a widget session and render the page.
// ---------------------------------------------------------------------------
$locale = $_GET['locale'] ?? (getenv('EEID_LOCALE') ?: 'en');
/**
* Theme sent per-session; merged over the client's default theme by eeID-login.
*
* No colour unless ?primary= asks for one. eeID's own palette already matches the classic
* redirect flow, so a demo that quietly recoloured the buttons would misrepresent what an
* integrator gets out of the box — and send people looking for the bug that turned their
* Continue button purple.
*/
$primary = $_GET['primary'] ?? null;
$theme = [
'colorScheme' => $_GET['scheme'] ?? 'light',
'shape' => ['radius' => 12],
];
if ($primary !== null) {
$theme['color'] = ['primary' => $primary];
}
// Base for the ?rows= mixes below when no ?primary= was given: eeID's own blue, so the tinted
// rows stay in the palette the widget is already using.
$rowsBase = $primary ?? '#118bcd';
// ?density=compact — sent as EXPLICIT TOKENS rather than the `density` switch, deliberately.
//
// The switch is styled by [data-eeid-widget][data-eeid-density="compact"], which is more
// specific than the block ThemeResolver emits, so on a login server that predates the
// specificity-ladder fix the switch wins and these values cannot be corrected from a theme.
// Worse, that build ships --eeid-method-row-height: 46px under "compact" — ABOVE the 44px
// comfortable base — so the method list, the tallest thing on the first screen, grows and the
// whole mode reads as doing nothing.
//
// Setting the tokens directly and leaving density at its default sidesteps the rule entirely:
// it never matches, so these apply. Works on old and new builds alike. Once every login server
// the demo targets carries the ladder fix, this can go back to ['density' => 'compact'].
if (($_GET['density'] ?? null) === 'compact') {
$theme['spacing']['unit'] = 3;
$theme['components']['button']['height'] = 38;
$theme['components']['input']['height'] = 38;
$theme['components']['methodList']['rowHeight'] = 40;
}
// ?rows=tint|solid — brand the METHOD LIST, which is the first screen the widget shows.
// color.primary alone paints only the submit button (.accept-btn), so on the method screen it
// looks like nothing happened; these are the tokens that actually colour that screen.
//
// The row text is --eeid-color-on-secondary, so "solid" has to move it to white with the
// background or the grey default becomes unreadable on a saturated brand colour.
$rows = $_GET['rows'] ?? null;
// Merged, not assigned: ?density=compact may already have put rowHeight here, and a plain
// assignment would silently drop it when both controls are combined.
if ($rows === 'tint') {
$theme['components']['methodList'] = ($theme['components']['methodList'] ?? []) + [
'rowBackground' => eeid_mix($rowsBase, '#ffffff', 0.90),
'rowHoverBackground' => eeid_mix($rowsBase, '#ffffff', 0.82),
];
} elseif ($rows === 'solid') {
$theme['components']['methodList'] = ($theme['components']['methodList'] ?? []) + [
'rowBackground' => $rowsBase,
'rowHoverBackground' => eeid_mix($rowsBase, '#000000', 0.18),
];
$theme['color'] = ($theme['color'] ?? []) + ['onSecondary' => '#ffffff'];
}
$sessionToken = isset($_GET['eeid_session_token']) ? (string) $_GET['eeid_session_token'] : null;
$error = null;
$resolvedOrigin = null;
if ($sessionToken !== null && $sessionToken !== '') {
// Re-entry after top-level OIDC callback: reuse the existing embedded session so the iframe
// can resume and finish via the normal eeid:success postMessage bridge. The session belongs
// to one stack, which the return_url we handed eeID-login names back to us here.
$claimed = rtrim((string) ($_GET['eeid_origin'] ?? ''), '/');
$resolvedOrigin = in_array($claimed, eeid_login_origins(), true) ? $claimed : null;
} else {
[$sessionToken, $resolvedOrigin, $error] = eeid_create_session($eeidConfig, $locale, $theme, current_page_url());
}
// Whichever stack accepted the credentials is the one the browser must load the widget from.
$publicUrl = $resolvedOrigin ?? (eeid_login_origins()[0] ?? '');
$loginOrigin = parse_url($publicUrl, PHP_URL_SCHEME) . '://' . parse_url($publicUrl, PHP_URL_HOST)
. (parse_url($publicUrl, PHP_URL_PORT) ? ':' . parse_url($publicUrl, PHP_URL_PORT) : '');
function current_page_url(): string
{
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$uri = $_SERVER['REQUEST_URI'] ?? '/';
$parts = parse_url($uri);
parse_str($parts['query'] ?? '', $query);
unset($query['eeid_session_token'], $query['eeid_origin']);
$path = $parts['path'] ?? '/';
$queryString = http_build_query($query);
return $scheme . '://' . $host . $path . ($queryString !== '' ? '?' . $queryString : '');
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>eeID Embedded Widget Demo</title>
<?php if ($sessionToken): ?>
<script src="<?= htmlspecialchars($publicUrl, ENT_QUOTES) ?>/widget/eeid-widget.js" defer></script>
<?php endif; ?>
<style>
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
body {
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
margin: 0; padding: 32px 20px; background: #f5f5f7; color: #111827;
}
.wrap { max-width: 900px; margin: 0 auto; display: grid; gap: 20px;
grid-template-columns: minmax(0, 420px) minmax(0, 1fr); align-items: start; }
@media (max-width: 820px) { .wrap { grid-template-columns: 1fr; } }
.card { background: #fff; border: 1px solid #e5e7eb; border-radius: 16px;
box-shadow: 0 1px 3px rgba(0,0,0,.08); overflow: hidden; }
.card h1 { font-size: 18px; margin: 0; padding: 18px 20px; border-bottom: 1px solid #e5e7eb; }
.card .body { padding: 20px; }
p.lede { color: #6b7280; font-size: 14px; margin: 0 0 16px; }
eeid-widget { display: block; }
.error { background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c;
padding: 14px 16px; border-radius: 10px; font-size: 14px; line-height: 1.5; }
.error code { background: rgba(0,0,0,.05); padding: 1px 4px; border-radius: 4px; }
#log { font: 12px/1.6 ui-monospace, SFMono-Regular, Menlo, monospace;
background: #0b1020; color: #cbd5e1; border-radius: 10px; padding: 14px;
max-height: 240px; overflow: auto; margin: 0 0 14px; white-space: pre-wrap; }
.muted { color: #6b7280; font-size: 12px; margin-top: 12px; }
.controls { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 16px; }
.controls a { font-size: 12px; text-decoration: none; color: #374151;
border: 1px solid #d1d5db; border-radius: 999px; padding: 5px 12px; background: #fff; }
.controls a:hover { background: #f9fafb; }
dl { margin: 0; font-size: 13px; }
dt { color: #6b7280; margin-top: 8px; }
dd { margin: 2px 0 0; font-family: ui-monospace, monospace; word-break: break-all; }
#result { display: none; margin-top: 4px; }
#result.show { display: block; }
.result-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
#logout { font: inherit; font-size: 12px; cursor: pointer; color: #374151;
border: 1px solid #d1d5db; border-radius: 999px; padding: 5px 12px; background: #fff; }
#logout:hover { background: #f9fafb; }
#logout[disabled] { opacity: .5; cursor: default; }
#signed-in-note { color: #6b7280; font-size: 13px; line-height: 1.5; margin: 0; }
#result table { width: 100%; border-collapse: collapse; font-size: 13px; }
#result th, #result td { text-align: left; padding: 6px 8px; border-bottom: 1px solid #eef2f7; vertical-align: top; }
#result th { color: #6b7280; font-weight: 600; white-space: nowrap; }
</style>
</head>
<body>
<div class="wrap">
<main class="card">
<h1>Sign in</h1>
<div class="body">
<p class="lede">The form below is served by eeID and rendered inside this page via the self-hosted SDK.</p>
<div class="controls">
<a href="?scheme=light">light</a>
<a href="?scheme=dark">dark</a>
<a href="?density=compact">compact</a>
<a href="?primary=%23e1261c">red brand (submit button only)</a>
<a href="?primary=%23e1261c&rows=tint">red + tinted rows</a>
<a href="?primary=%23e1261c&rows=solid">red + solid rows</a>
<a href="?primary=%23059669&scheme=dark">green + dark</a>
<a href="?locale=et">et</a>
<a href="?locale=ru">ru</a>
<a href="?">reset</a>
</div>
<?php if ($error): ?>
<div class="error"><strong>Could not start a widget session.</strong><br><?= htmlspecialchars($error, ENT_QUOTES) ?></div>
<?php else: ?>
<div id="widget-mount">
<eeid-widget
base-url="<?= htmlspecialchars($publicUrl, ENT_QUOTES) ?>"
session-token="<?= htmlspecialchars($sessionToken, ENT_QUOTES) ?>"
height="420px"></eeid-widget>
</div>
<p id="signed-in-note" hidden>
Signed in. The widget was taken down because its terminal page has already
handed over the result token and never navigates again.
</p>
<?php endif; ?>
</div>
</main>
<aside class="card">
<h1>What the widget is telling us</h1>
<div class="body">
<pre id="log">waiting for the widget…</pre>
<div id="result">
<div class="result-head">
<strong style="font-size:14px">Signed in ✓</strong>
<button type="button" id="logout">Log out</button>
</div>
<table id="claims"></table>
</div>
<dl>
<dt>parent origin (must be allowlisted on the client)</dt>
<dd id="parent-origin"></dd>
<dt>widget origin <span class="muted">(resolved from the credentials)</span></dt>
<dd id="widget-origin"><?= htmlspecialchars($loginOrigin, ENT_QUOTES) ?></dd>
<dt>session token</dt>
<dd id="session-token"><?= $sessionToken ? htmlspecialchars(substr($sessionToken, 0, 12), ENT_QUOTES) . '…' : '—' ?></dd>
</dl>
<p class="muted">
Full loop: create → widget → <code>eeid:success</code> → redeem → token exchange.
The browser only ever sees the single-use <code>result_token</code>; the OAuth2
code and the ID token are obtained server-side.
</p>
</div>
</aside>
</div>
<script>
const logEl = document.getElementById('log');
document.getElementById('parent-origin').textContent = window.location.origin;
let lines = [];
function log(message) {
lines.push(new Date().toLocaleTimeString() + ' ' + message);
logEl.textContent = lines.slice(-40).join('\n');
logEl.scrollTop = logEl.scrollHeight;
}
// The session parameters this page was rendered with, so a re-login after "log out" keeps
// the same theme/locale instead of silently falling back to the defaults.
const SESSION_PARAMS = <?= json_encode([
'locale' => $locale,
'theme' => $theme,
'return_url' => current_page_url(),
], JSON_THROW_ON_ERROR | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
// The stack this session lives on. Not a constant: "log out" re-resolves it from the
// credentials, so flipping the service's environment in eeID-manager is picked up here.
let baseUrl = <?= json_encode($publicUrl, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
const mount = document.getElementById('widget-mount');
const signedInNote = document.getElementById('signed-in-note');
const logoutBtn = document.getElementById('logout');
const tokenEl = document.getElementById('session-token');
const originEl = document.getElementById('widget-origin');
// The SDK verifies message origin/source and re-emits as DOM events; we just listen.
function wire(widget) {
widget.addEventListener('eeid:ready', () => log('← ready'));
widget.addEventListener('eeid:resize', (e) => log('← resize ' + e.detail.height + 'px'));
widget.addEventListener('eeid:error', (e) => log('← error ' + JSON.stringify(e.detail)));
widget.addEventListener('eeid:cancel', () => log('← cancel'));
widget.addEventListener('eeid:success', onSuccess);
return widget;
}
function teardownWidget() {
// The widget's terminal page postMessages the result token and then deliberately stops
// — it never navigates — so it sits on "Signing you in…" forever. Take the iframe down,
// or a finished flow looks hung. (eeID-manager does the same in
// embedded_sign_in_controller.js#onSuccess.)
if (mount) mount.replaceChildren();
if (signedInNote) signedInNote.hidden = false;
}
function mountWidget(sessionToken) {
if (!mount) return;
const widget = document.createElement('eeid-widget');
widget.setAttribute('base-url', baseUrl);
widget.setAttribute('session-token', sessionToken);
widget.setAttribute('height', '420px');
mount.replaceChildren(wire(widget));
if (signedInNote) signedInNote.hidden = true;
if (tokenEl) tokenEl.textContent = sessionToken.slice(0, 12) + '…';
}
async function onSuccess(e) {
log('← success, result_token ' + String(e.detail.resultToken).slice(0, 10) + '…');
teardownWidget();
log('→ redeeming server-side…');
try {
const res = await fetch('', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
// Tells the backend which stack to redeem against; it only honours an origin
// that is one of its own configured candidates.
body: JSON.stringify({ result_token: e.detail.resultToken, login_origin: baseUrl }),
});
const data = await res.json();
if (!res.ok) {
log('✗ ' + (data.error || res.status) + (data.detail ? ' — ' + data.detail : ''));
return;
}
log('✓ token exchange complete');
renderClaims(data.claims || {});
if (logoutBtn) logoutBtn.disabled = false;
} catch (err) {
log('✗ redeem request failed: ' + err.message);
}
}
// "Log out" — there is no eeID session in this browser to end: the embedded flow is
// cookieless and Hydra's login cookies live in a per-session SERVER-SIDE jar that dies with
// the session. So we drop the claims we hold and mint a brand-new embedded session, which
// authenticates from scratch.
async function logout() {
if (!logoutBtn) return;
logoutBtn.disabled = true;
document.getElementById('result').classList.remove('show');
document.getElementById('claims').innerHTML = '';
log('→ logging out, requesting a fresh session…');
try {
const res = await fetch('', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'new_session', ...SESSION_PARAMS }),
});
const data = await res.json();
if (!res.ok || !data.session_token) {
log('✗ ' + (data.error || 'could not create a new session (HTTP ' + res.status + ')'));
return;
}
if (data.login_origin && data.login_origin !== baseUrl) {
log('↻ environment changed — now on ' + data.login_origin);
baseUrl = data.login_origin;
originEl.textContent = baseUrl;
}
log('✓ new session ' + data.session_token.slice(0, 10) + '… — sign in again');
mountWidget(data.session_token);
} catch (err) {
log('✗ new session request failed: ' + err.message);
}
}
if (logoutBtn) {
logoutBtn.disabled = true;
logoutBtn.addEventListener('click', logout);
}
const initialWidget = document.querySelector('eeid-widget');
if (initialWidget) {
wire(initialWidget);
log('SDK attached, waiting for the widget…');
}
function renderClaims(claims) {
const table = document.getElementById('claims');
const interesting = ['sub', 'name', 'given_name', 'family_name', 'birthdate', 'email', 'amr', 'acr'];
const keys = interesting.filter((k) => k in claims).concat(
Object.keys(claims).filter((k) => !interesting.includes(k))
);
table.innerHTML = keys.map((k) =>
'<tr><th>' + k + '</th><td>' + escapeHtml(JSON.stringify(claims[k])) + '</td></tr>'
).join('');
document.getElementById('result').classList.add('show');
}
function escapeHtml(s) {
return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
}
</script>
</body>
</html>