Skip to content

Commit 681378b

Browse files
alistair3149claude
andcommitted
Send the login code as a formatted mail
The code arrived as five lines of unstyled text, with nothing in it to say which wiki had sent it or that the eight digits in the middle were the point. It read like something to be deleted unread, which is a poor start for the one message standing between a member and their account. Send it as a formatted part with a plain-text alternative: the wiki's name, the code set apart in a panel of its own, how long it lasts, and what to do if it was not you. The plain part carries the same code and the same warning rather than a note that the mail is better read elsewhere, since for many wikis it is the only part that ships. The formatted part is a Mustache template, so what it looks like is changed by editing markup rather than by concatenating strings in PHP. It is table layout and inline styles throughout, because a mail client is not a browser and the classic Outlook still in use across the companies this extension serves lays out with Word's engine. Every string reaches it already localised, and Mustache escapes what it interpolates, so a wiki's site name cannot carry markup into the mail. Nothing in it is fetched from the network. No link, since a login mail that trains its reader to click one is a phishing template with a head start, and no image, since clients block remote ones by default and would show a broken box where a logo went. MediaWiki keeps the formatted part only where $wgAllowHTMLEmail is on, which it is not by default. That setting governs every mail a wiki sends, so it is recommended in the README rather than set here, which is what Echo does with it too. The code is shown in groups of four so it can be held in the head between the mail and the form. That is a display alone: a member who copies the spaces along with the digits is no longer refused their own code. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 0c08453 commit 681378b

11 files changed

Lines changed: 233 additions & 14 deletions

File tree

‎README.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,17 @@ $wgMemberAccessCodeLogin = 'allowlisted';
214214
Loading alone admits nobody: the second line turns on the code login route, held to the allowlist.
215215
See [Login routes](#login-routes) for what each route setting admits.
216216

217+
The login code arrives as a formatted mail with a plain-text alternative. MediaWiki keeps the
218+
formatted part only where the wiki allows formatted mail at all, which it does not by default:
219+
220+
```php
221+
$wgAllowHTMLEmail = true;
222+
```
223+
224+
Recommended, and left to the wiki rather than set here, since it governs every mail the wiki sends.
225+
The same setting decides whether [Echo] offers its notifications formatted. Without it the code
226+
still arrives, as the plain-text part alone.
227+
217228
Run `php maintenance/run.php update --quick` to create the extension's tables. Until it has run, the
218229
code login route is not offered and the management API answers `schema_missing`, with a warning on
219230
the `MemberAccess` log channel. Accounts in the reader group are refused a password meanwhile, and
@@ -338,6 +349,8 @@ Initial version for MediaWiki 1.43+ with these features:
338349

339350
* Login with an eight-digit code mailed to the member's address, valid for ten minutes and usable
340351
once, requested from the login form's username field
352+
* The code mailed as a formatted message naming the wiki, with a plain-text alternative carrying the
353+
same code and the same warning
341354
* An allowlist of email addresses and domains, organized into named groups, decides who is admitted
342355
* Accounts create themselves at first login, into a reader group that may read and nothing else
343356
* Single sign-on logins through [PluggableAuth] can be held to the same allowlist, with staff
@@ -364,3 +377,4 @@ Initial version for MediaWiki 1.43+ with these features:
364377
[PHP]: https://www.php.net
365378
[PluggableAuth]: https://www.mediawiki.org/wiki/Extension:PluggableAuth
366379
[Lockdown]: https://www.mediawiki.org/wiki/Extension:Lockdown
380+
[Echo]: https://www.mediawiki.org/wiki/Extension:Echo

‎i18n/en.json‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@
66
},
77
"memberaccess-description": "Members-only wiki access with email one-time-code login and an allowlist of addresses and domains",
88
"memberaccess-code-email-subject": "Your login code for {{SITENAME}}",
9-
"memberaccess-code-email-body": "Your login code for {{SITENAME}} is:\n\n$1\n\nThe code is valid for $2 {{PLURAL:$2|minute|minutes}} and can be used once.\n\nIf you did not request a login code, you can ignore this message.",
9+
"memberaccess-code-email-site": "{{SITENAME}}",
10+
"memberaccess-code-email-intro": "Here is your login code.",
11+
"memberaccess-code-email-validity": "It works once, and stops working in $1 {{PLURAL:$1|minute|minutes}}.",
12+
"memberaccess-code-email-disclaimer": "If you did not ask to log in to {{SITENAME}}, nothing has happened and you can ignore this message.",
13+
"memberaccess-code-email-body": "Here is your login code for {{SITENAME}}:\n\n $1\n\nIt works once, and stops working in $2 {{PLURAL:$2|minute|minutes}}.\n\nIf you did not ask to log in to {{SITENAME}}, nothing has happened and you can ignore this message.",
1014
"memberaccess-auth-button-label": "Email me a login code",
1115
"memberaccess-auth-button-help": "We send a one-time code to your email address. Nothing beyond your email address is requested.",
1216
"memberaccess-auth-email-label": "Email address",

‎i18n/qqq.json‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@
66
},
77
"memberaccess-description": "{{desc|name=MemberAccess|url=https://professional.wiki}}",
88
"memberaccess-code-email-subject": "Subject line of the email carrying a one-time login code.",
9-
"memberaccess-code-email-body": "Plain text body of the email carrying a one-time login code.\n\nParameters:\n* $1 - the login code\n* $2 - the number of minutes the code stays valid",
9+
"memberaccess-code-email-site": "The name of the wiki, shown at the top of the email carrying a login code. Its own message so that a wiki can put something other than {{msg-mw|Sitename}} on its mail.",
10+
"memberaccess-code-email-intro": "First line of the email carrying a login code, above the code itself.",
11+
"memberaccess-code-email-validity": "Line below the login code saying how long it lasts. Parameters:\n* $1 - the number of minutes the code stays valid",
12+
"memberaccess-code-email-disclaimer": "Closing line of the email carrying a login code, for someone who did not ask for one.",
13+
"memberaccess-code-email-body": "Plain text alternative of the email carrying a one-time login code, shown by mail clients that do not display the formatted part. Parameters:\n* $1 - the login code, in groups of four digits\n* $2 - the number of minutes the code stays valid",
1014
"memberaccess-auth-button-label": "Label of the button on the login form that asks for a login code to be mailed.",
1115
"memberaccess-auth-button-help": "Help text below the button that asks for a login code to be mailed. \"Nothing beyond your email address is requested\" is a commitment: keep the meaning \"asked for\", and do not turn it into \"stored\".",
1216
"memberaccess-auth-email-label": "Label of the email address field.",

‎src/Application/DisplayedCode.php‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
declare( strict_types = 1 );
4+
5+
namespace ProfessionalWiki\MemberAccess\Application;
6+
7+
/**
8+
* A code as it is shown to the member: in groups, so that it can be held in the head between the
9+
* mail and the form.
10+
*
11+
* The grouping is shown and never checked. What a member types is put back the way it was issued
12+
* before it is verified, so copying the spaces along with the digits is not a wrong answer.
13+
* {@see \ProfessionalWiki\MemberAccess\Application\VerifyCodeUseCase}
14+
*/
15+
class DisplayedCode {
16+
17+
private const int GROUP_SIZE = 4;
18+
19+
public static function of( string $code ): string {
20+
return implode( ' ', str_split( $code, self::GROUP_SIZE ) );
21+
}
22+
23+
/**
24+
* The digits alone, whichever way they were grouped on the way back.
25+
*/
26+
public static function withoutGrouping( string $code ): string {
27+
return (string)preg_replace( '/\s+/u', '', $code );
28+
}
29+
30+
}

‎src/EntryPoints/Auth/MemberAuthenticationProvider.php‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use ProfessionalWiki\MemberAccess\Application\CodeLoginMode;
2020
use ProfessionalWiki\MemberAccess\Application\CodeRequestOutcome;
2121
use ProfessionalWiki\MemberAccess\Application\CodeVerificationOutcome;
22+
use ProfessionalWiki\MemberAccess\Application\DisplayedCode;
2223
use ProfessionalWiki\MemberAccess\Application\Member;
2324
use ProfessionalWiki\MemberAccess\Application\MemberGroup;
2425
use ProfessionalWiki\MemberAccess\Application\MemberRepository;
@@ -146,7 +147,11 @@ public function continuePrimaryAuthentication( array $reqs ) {
146147
return $this->refuse( 'Code entry continued without a code request in the session' );
147148
}
148149

149-
$result = $this->codeVerification->verify( $handle, trim( $request->memberaccessCode ) );
150+
// Shown in groups in the mail, so a member who copied it brings the spaces along.
151+
$result = $this->codeVerification->verify(
152+
$handle,
153+
DisplayedCode::withoutGrouping( $request->memberaccessCode )
154+
);
150155

151156
return match ( $result->outcome ) {
152157
CodeVerificationOutcome::Pass => $this->admit( (string)$result->email ),

‎src/MemberAccessExtension.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use MailAddress;
88
use MediaWiki\Context\RequestContext;
99
use MediaWiki\Logger\LoggerFactory;
10+
use MediaWiki\Html\TemplateParser;
1011
use MediaWiki\MediaWikiServices;
1112
use MediaWiki\Session\CsrfTokenSet;
1213
use ProfessionalWiki\MemberAccess\Application\AddEntriesUseCase;
@@ -432,6 +433,7 @@ private function newCodeMailer(): CodeMailer {
432433
mailer: new MediaWikiCodeMailer(
433434
emailer: MediaWikiServices::getInstance()->getEmailer(),
434435
sender: $this->getSenderAddress(),
436+
templates: new TemplateParser( __DIR__ . '/../templates' ),
435437
logger: $this->newLogger()
436438
)
437439
);

‎src/Persistence/MediaWikiCodeMailer.php‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,29 +5,45 @@
55
namespace ProfessionalWiki\MemberAccess\Persistence;
66

77
use MailAddress;
8+
use MediaWiki\Html\TemplateParser;
89
use MediaWiki\Mail\IEmailer;
910
use ProfessionalWiki\MemberAccess\Application\CodeMailer;
11+
use ProfessionalWiki\MemberAccess\Application\DisplayedCode;
1012
use ProfessionalWiki\MemberAccess\Application\NormalizedEmail;
1113
use Psr\Log\LoggerInterface;
1214

1315
class MediaWikiCodeMailer implements CodeMailer {
1416

17+
private const string TEMPLATE = 'CodeEmail';
18+
1519
public function __construct(
1620
private readonly IEmailer $emailer,
1721
private readonly MailAddress $sender,
22+
private readonly TemplateParser $templates,
1823
private readonly LoggerInterface $logger
1924
) {
2025
}
2126

27+
/**
28+
* Sent as both a formatted part and a plain one. Which of them a member sees is their mail
29+
* client's to decide, and some of them will only ever show the second, so it carries the same
30+
* code and the same warning rather than a note that the mail is best read elsewhere.
31+
*/
2232
public function sendCode( NormalizedEmail $email, string $code, int $expiryInMinutes ): void {
33+
$displayed = DisplayedCode::of( $code );
34+
2335
$status = $this->emailer->send(
2436
to: new MailAddress( $email->value ),
2537
from: $this->sender,
26-
subject: wfMessage( 'memberaccess-code-email-subject' )->inContentLanguage()->text(),
27-
bodyText: wfMessage( 'memberaccess-code-email-body' )
28-
->params( $code, $expiryInMinutes )
29-
->inContentLanguage()
30-
->text()
38+
subject: $this->text( 'memberaccess-code-email-subject' ),
39+
bodyText: $this->text( 'memberaccess-code-email-body', $displayed, $expiryInMinutes ),
40+
bodyHtml: $this->templates->processTemplate( self::TEMPLATE, [
41+
'siteName' => $this->text( 'memberaccess-code-email-site' ),
42+
'intro' => $this->text( 'memberaccess-code-email-intro' ),
43+
'code' => $displayed,
44+
'validity' => $this->text( 'memberaccess-code-email-validity', $expiryInMinutes ),
45+
'disclaimer' => $this->text( 'memberaccess-code-email-disclaimer' )
46+
] )
3147
);
3248

3349
if ( !$status->isGood() ) {
@@ -38,4 +54,12 @@ public function sendCode( NormalizedEmail $email, string $code, int $expiryInMin
3854
}
3955
}
4056

57+
/**
58+
* In the wiki's own language, since who the mail is going to is exactly what has not been
59+
* established yet.
60+
*/
61+
private function text( string $key, string|int ...$params ): string {
62+
return wfMessage( $key )->params( ...$params )->inContentLanguage()->text();
63+
}
64+
4165
}

‎templates/CodeEmail.mustache‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
{{!
2+
The HTML part of the mail carrying a login code.
3+
4+
Table layout and inline styles throughout, because a mail client is not a browser: the classic
5+
Outlook still in use across the companies this extension serves lays out with Word's engine,
6+
which has no flex, no grid, and no stylesheet to read. What is used here it does support, but
7+
for border-radius, which it ignores into square corners.
8+
9+
Nothing is fetched from the network. There is no link, since a login mail that trains its reader
10+
to click one is a phishing template with a head start, and no image, since clients block remote
11+
ones by default and would show a broken box where a logo went.
12+
13+
Every string arrives localised. Mustache escapes what it interpolates, so none of it can carry
14+
markup out of a wiki's site name.
15+
}}
16+
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="border-collapse:collapse;background:#ffffff;">
17+
<tr>
18+
<td align="center" style="padding:24px 12px;">
19+
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="border-collapse:collapse;max-width:480px;background:#ffffff;border:1px solid #c8ccd1;border-radius:2px;">
20+
<tr>
21+
<td style="border-top:3px solid #3366cc;padding:20px 24px 0;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:15px;font-weight:bold;color:#202122;">
22+
{{siteName}}
23+
</td>
24+
</tr>
25+
<tr>
26+
<td style="padding:12px 24px 0;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:16px;line-height:24px;color:#202122;">
27+
{{intro}}
28+
</td>
29+
</tr>
30+
<tr>
31+
<td style="padding:16px 24px 0;">
32+
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="border-collapse:collapse;background:#f8f9fa;border:1px solid #c8ccd1;">
33+
<tr>
34+
<td align="center" style="padding:16px;font-family:'SFMono-Regular',Consolas,'Liberation Mono',Menlo,monospace;font-size:30px;font-weight:bold;letter-spacing:6px;color:#202122;">
35+
{{code}}
36+
</td>
37+
</tr>
38+
</table>
39+
</td>
40+
</tr>
41+
<tr>
42+
<td style="padding:14px 24px 0;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:14px;line-height:22px;color:#54595d;">
43+
{{validity}}
44+
</td>
45+
</tr>
46+
<tr>
47+
<td style="padding:18px 24px 20px;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:13px;line-height:20px;color:#72777d;">
48+
{{disclaimer}}
49+
</td>
50+
</tr>
51+
</table>
52+
</td>
53+
</tr>
54+
</table>

‎tests/phpunit/Integration/Auth/MemberAuthenticationProviderTest.php‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use Wikimedia\Rdbms\IDBAccessObject;
1616
use MediaWikiIntegrationTestCase;
1717
use ProfessionalWiki\MemberAccess\Application\AllowlistValue;
18+
use ProfessionalWiki\MemberAccess\Application\DisplayedCode;
1819
use ProfessionalWiki\MemberAccess\Application\Member;
1920
use ProfessionalWiki\MemberAccess\Application\ReadConsistency;
2021
use ProfessionalWiki\MemberAccess\EntryPoints\Auth\EnterCodeRequest;
@@ -74,7 +75,23 @@ public function testAdmittedAddressIsMailedACodeAndTheCodeScreenIsShown(): void
7475

7576
$this->assertSame( AuthenticationResponse::UI, $response->status );
7677
$this->assertCount( 1, $this->emailer->getSentMails() );
77-
$this->assertStringContainsString( self::CODE, $this->emailer->getSentMails()[0]['bodyText'] );
78+
$this->assertStringContainsString(
79+
DisplayedCode::of( self::CODE ),
80+
$this->emailer->getSentMails()[0]['bodyText']
81+
);
82+
}
83+
84+
/**
85+
* The mail shows the code in groups, so a member copying it brings the spaces along. Refusing
86+
* that would be refusing the code exactly as it was given to them.
87+
*/
88+
public function testCodeIsAcceptedAsItWasShownInTheMail(): void {
89+
$this->allow( 'jane@example.com' );
90+
$this->requestCode( 'jane@example.com' );
91+
92+
$response = $this->enterCode( DisplayedCode::of( self::CODE ) );
93+
94+
$this->assertSame( AuthenticationResponse::PASS, $response->status );
7895
}
7996

8097
public function testCorrectCodeLogsTheMemberInAndCreatesTheAccount(): void {

‎tests/phpunit/Integration/MediaWikiCodeMailerTest.php‎

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
namespace ProfessionalWiki\MemberAccess\Tests\Integration;
66

77
use MailAddress;
8+
use MediaWiki\Html\TemplateParser;
9+
use MediaWiki\MainConfigNames;
810
use MediaWikiIntegrationTestCase;
911
use ProfessionalWiki\MemberAccess\Application\NormalizedEmail;
1012
use ProfessionalWiki\MemberAccess\Persistence\MediaWikiCodeMailer;
@@ -13,12 +15,14 @@
1315

1416
/**
1517
* @covers \ProfessionalWiki\MemberAccess\Persistence\MediaWikiCodeMailer
18+
* @covers \ProfessionalWiki\MemberAccess\Application\DisplayedCode
1619
*/
1720
class MediaWikiCodeMailerTest extends MediaWikiIntegrationTestCase {
1821

1922
private const string SENDER = 'no-reply@example.com';
2023
private const string RECIPIENT = 'jane@example.com';
2124
private const string CODE = '12345678';
25+
private const string GROUPED_CODE = '1234 5678';
2226

2327
private SpyLogger $logger;
2428

@@ -40,10 +44,65 @@ public function testMailComesFromTheConfiguredSender(): void {
4044
$this->assertSame( self::SENDER, $emailer->getSentMails()[0]['from'] );
4145
}
4246

43-
public function testBodyCarriesTheCode(): void {
47+
public function testEachPartCarriesTheCode(): void {
4448
$emailer = $this->sendCode();
4549

46-
$this->assertStringContainsString( self::CODE, $emailer->getSentMails()[0]['bodyText'] );
50+
$this->assertStringContainsString( self::GROUPED_CODE, $emailer->getSentMails()[0]['bodyText'] );
51+
$this->assertStringContainsString( self::GROUPED_CODE, $this->htmlPart( $emailer ) );
52+
}
53+
54+
/**
55+
* A client that shows only the plain part shows the same code and the same warning, rather than
56+
* a note that the mail is better read elsewhere.
57+
*/
58+
public function testAFormattedPartIsSentAlongsideThePlainOne(): void {
59+
$emailer = $this->sendCode();
60+
61+
$this->assertStringContainsString( '<table', $this->htmlPart( $emailer ) );
62+
$this->assertStringNotContainsString( '<table', $emailer->getSentMails()[0]['bodyText'] );
63+
}
64+
65+
public function testEachPartNamesTheWiki(): void {
66+
$this->overrideConfigValue( MainConfigNames::Sitename, 'Acme Handbook' );
67+
68+
$emailer = $this->sendCode();
69+
70+
$this->assertStringContainsString( 'Acme Handbook', $emailer->getSentMails()[0]['bodyText'] );
71+
$this->assertStringContainsString( 'Acme Handbook', $this->htmlPart( $emailer ) );
72+
}
73+
74+
/**
75+
* Nothing is fetched when the mail is opened: no remote image for a client to block, and no
76+
* link to train its reader into clicking one in a mail about logging in.
77+
*/
78+
public function testTheMailAsksForNothingFromTheNetwork(): void {
79+
$html = $this->htmlPart( $this->sendCode() );
80+
81+
$this->assertStringNotContainsString( '<a ', $html );
82+
$this->assertStringNotContainsString( '<img', $html );
83+
$this->assertStringNotContainsString( 'http', $html );
84+
}
85+
86+
/**
87+
* The site name is a wiki's to set, so it reaches the formatted part as text and not as markup.
88+
*/
89+
public function testMarkupInTheSiteNameIsNotMarkupInTheMail(): void {
90+
$this->overrideConfigValue( MainConfigNames::Sitename, '<script>alert(1)</script>' );
91+
92+
$html = $this->htmlPart( $this->sendCode() );
93+
94+
$this->assertStringNotContainsString( '<script>', $html );
95+
$this->assertStringContainsString( '&lt;script&gt;', $html );
96+
}
97+
98+
/**
99+
* Grouped for reading, and only for reading: what is verified is still the digits as issued.
100+
* {@see \ProfessionalWiki\MemberAccess\Application\DisplayedCode}
101+
*/
102+
public function testTheCodeIsShownInGroups(): void {
103+
$emailer = $this->sendCode();
104+
105+
$this->assertStringNotContainsString( self::CODE, $this->htmlPart( $emailer ) );
47106
}
48107

49108
public function testBodyCarriesHowLongTheCodeLasts(): void {
@@ -94,10 +153,15 @@ private function sendCode( int $expiryInMinutes = 10, bool $sendSucceeds = true
94153
( new MediaWikiCodeMailer(
95154
emailer: $emailer,
96155
sender: new MailAddress( self::SENDER ),
156+
templates: new TemplateParser( __DIR__ . '/../../../templates' ),
97157
logger: $this->logger
98158
) )->sendCode( $email, self::CODE, $expiryInMinutes );
99159

100160
return $emailer;
101161
}
102162

163+
private function htmlPart( SpyEmailer $emailer ): string {
164+
return (string)( $emailer->getSentMails()[0]['bodyHtml'] ?? '' );
165+
}
166+
103167
}

0 commit comments

Comments
 (0)