Skip to content

Commit e56d3bb

Browse files
alistair3149claude
andauthored
Send the login code as a formatted mail (#20)
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 is rewritten to say the same, since a wiki that has not turned formatted mail on sends only that one. The formatted part is a Mustache template, so what it looks like is changed by editing markup rather than by concatenating strings in PHP. What a mail client will and will not lay out is written down there rather than here. 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 the README says to set it rather than the extension setting it, 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 e56d3bb

12 files changed

Lines changed: 370 additions & 19 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,12 @@ $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+
To send the login code as rich email rather than plain text, set:
218+
219+
```php
220+
$wgAllowHTMLEmail = true;
221+
```
222+
217223
Run `php maintenance/run.php update --quick` to create the extension's tables. Until it has run, the
218224
code login route is not offered and the management API answers `schema_missing`, with a warning on
219225
the `MemberAccess` log channel. Accounts in the reader group are refused a password meanwhile, and
@@ -338,6 +344,8 @@ Initial version for MediaWiki 1.43+ with these features:
338344

339345
* Login with an eight-digit code mailed to the member's address, valid for ten minutes and usable
340346
once, requested from the login form's username field
347+
* The code mailed as a formatted message naming the wiki, with a plain-text alternative carrying the
348+
same code and the same warning
341349
* An allowlist of email addresses and domains, organized into named groups, decides who is admitted
342350
* Accounts create themselves at first login, into a reader group that may read and nothing else
343351
* Single sign-on logins through [PluggableAuth] can be held to the same allowlist, with staff

‎i18n/en.json‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
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-intro": "Here is your login code.",
10+
"memberaccess-code-email-validity": "It works once, and stops working in $1 {{PLURAL:$1|minute|minutes}}.",
11+
"memberaccess-code-email-disclaimer": "If you did not ask to log in to {{SITENAME}}, nothing has happened and you can ignore this message.",
12+
"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.",
1013
"memberaccess-auth-button-label": "Email me a login code",
1114
"memberaccess-auth-button-help": "We send a one-time code to your email address. Nothing beyond your email address is requested.",
1215
"memberaccess-auth-email-label": "Email address",

‎i18n/qqq.json‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
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-intro": "First line of the email carrying a login code, above the code itself.",
10+
"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",
11+
"memberaccess-code-email-disclaimer": "Closing line of the email carrying a login code, for someone who did not ask for one.",
12+
"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",
1013
"memberaccess-auth-button-label": "Label of the button on the login form that asks for a login code to be mailed.",
1114
"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\".",
1215
"memberaccess-auth-email-label": "Label of the email address field.",

‎src/Application/DisplayedCode.php‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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, and as it comes back.
9+
*
10+
* Shown in groups, so that it can be held in the head between the mail and the form. The grouping is
11+
* never checked: what a member types is put back the way it was issued before it is verified, so
12+
* copying the spaces along with the digits is not a wrong answer.
13+
* {@see \ProfessionalWiki\MemberAccess\Application\VerifyCodeUseCase}
14+
*/
15+
final class DisplayedCode {
16+
17+
private const int GROUP_SIZE = 4;
18+
19+
private function __construct() {
20+
}
21+
22+
/**
23+
* A code whose length is not a whole number of groups keeps the remainder as a shorter last
24+
* group, since a code is a code however long the wiki's generator makes them.
25+
*/
26+
public static function grouped( string $code ): string {
27+
return $code === '' ? '' : implode( ' ', str_split( $code, self::GROUP_SIZE ) );
28+
}
29+
30+
/**
31+
* The digits alone, whichever way they came back grouped. Every kind of space is taken out, not
32+
* only the one that was put in, since what a mail client hands to a clipboard is its own affair.
33+
*/
34+
public static function ungrouped( string $code ): string {
35+
return preg_replace( '/\s+/u', '', $code ) ?? $code;
36+
}
37+
38+
}

‎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::ungrouped( $request->memberaccessCode )
154+
);
150155

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

‎src/MemberAccessExtension.php‎

Lines changed: 4 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,9 @@ private function newCodeMailer(): CodeMailer {
432433
mailer: new MediaWikiCodeMailer(
433434
emailer: MediaWikiServices::getInstance()->getEmailer(),
434435
sender: $this->getSenderAddress(),
436+
templates: new TemplateParser( __DIR__ . '/../templates' ),
437+
contentLanguage: MediaWikiServices::getInstance()->getContentLanguage(),
438+
siteName: $this->getStringConfig( 'Sitename' ),
435439
logger: $this->newLogger()
436440
)
437441
);

‎src/Persistence/MediaWikiCodeMailer.php‎

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

77
use MailAddress;
8+
use MediaWiki\Html\TemplateParser;
9+
use MediaWiki\Language\Language;
810
use MediaWiki\Mail\IEmailer;
911
use ProfessionalWiki\MemberAccess\Application\CodeMailer;
12+
use ProfessionalWiki\MemberAccess\Application\DisplayedCode;
1013
use ProfessionalWiki\MemberAccess\Application\NormalizedEmail;
1114
use Psr\Log\LoggerInterface;
1215

1316
class MediaWikiCodeMailer implements CodeMailer {
1417

18+
private const string TEMPLATE = 'CodeEmail';
19+
1520
public function __construct(
1621
private readonly IEmailer $emailer,
1722
private readonly MailAddress $sender,
23+
private readonly TemplateParser $templates,
24+
private readonly Language $contentLanguage,
25+
private readonly string $siteName,
1826
private readonly LoggerInterface $logger
1927
) {
2028
}
2129

30+
/**
31+
* Sent as both a formatted part and a plain one. Which of them a member sees is their mail
32+
* client's to decide, and a wiki that has not turned formatted mail on sends only the second, so
33+
* it carries the same code and the same warning rather than a note to read the mail elsewhere.
34+
*/
2235
public function sendCode( NormalizedEmail $email, string $code, int $expiryInMinutes ): void {
36+
$displayed = DisplayedCode::grouped( $code );
37+
2338
$status = $this->emailer->send(
2439
to: new MailAddress( $email->value ),
2540
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()
41+
subject: $this->text( 'memberaccess-code-email-subject' ),
42+
bodyText: $this->text( 'memberaccess-code-email-body', $displayed, $expiryInMinutes ),
43+
bodyHtml: $this->templates->processTemplate( self::TEMPLATE, [
44+
// The same name the plain part gets from {{SITENAME}}, so the two cannot disagree.
45+
'siteName' => $this->siteName,
46+
'intro' => $this->text( 'memberaccess-code-email-intro' ),
47+
'code' => $displayed,
48+
'validity' => $this->text( 'memberaccess-code-email-validity', $expiryInMinutes ),
49+
'disclaimer' => $this->text( 'memberaccess-code-email-disclaimer' ),
50+
'lang' => $this->contentLanguage->getHtmlCode(),
51+
'dir' => $this->contentLanguage->getDir()
52+
] )
3153
);
3254

3355
if ( !$status->isGood() ) {
@@ -38,4 +60,28 @@ public function sendCode( NormalizedEmail $email, string $code, int $expiryInMin
3860
}
3961
}
4062

63+
/**
64+
* In the wiki's own language, since who the mail is going to is exactly what has not been
65+
* established yet.
66+
*
67+
* A message is preprocessed as wikitext before it is put together, so anything substituted into
68+
* one as an ordinary parameter is preprocessed with it. Only a count is passed that way, because
69+
* PLURAL has to be able to read it; everything else goes in afterwards, out of the preprocessor's
70+
* reach. Nothing given here is a visitor's to write, and this is what keeps it that way should
71+
* something one day be. {@see \MediaWiki\Message\Message::transformText}
72+
*/
73+
private function text( string $key, string|int ...$params ): string {
74+
$message = wfMessage( $key );
75+
76+
foreach ( $params as $param ) {
77+
if ( is_int( $param ) ) {
78+
$message->numParams( $param );
79+
} else {
80+
$message->plaintextParams( $param );
81+
}
82+
}
83+
84+
return $message->inContentLanguage()->text();
85+
}
86+
4187
}

‎templates/CodeEmail.mustache‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
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. Nor does it honour max-width, so the width
7+
the card is held to is given to it again in a table only that engine sees. Colours are given as
8+
bgcolor beside the style carrying them, for the webmail clients that drop the shorthand. The
9+
rounded corners it will not do either way.
10+
11+
Colours, spacing and type sizes are Codex's, spelled out rather than referred to: a mail carries
12+
no stylesheet, so there is nothing for a custom property to resolve against and no compiler to
13+
resolve a LESS variable. Each is named in a comment beside its value. The line heights and the
14+
size of the code itself are set to suit a message read at arm's length, and are nobody's tokens.
15+
16+
Nothing is fetched from the network. There is no link, since a login mail that trains its reader
17+
to click one is a phishing template with a head start, and no image, since clients block remote
18+
ones by default and would show a broken box where a logo went. A code in groups reads as a phone
19+
number to a client that hunts for them, which would make a link of it unasked, so they are asked
20+
not to.
21+
22+
Every string arrives localised, in the wiki's own language, which is why the direction to read it
23+
in is given here too. The code keeps its own direction, being digits either way. Mustache escapes
24+
what it interpolates, so none of it can carry markup out of a wiki's site name.
25+
}}
26+
<!DOCTYPE html>
27+
<html dir="{{dir}}" lang="{{lang}}">
28+
<head>
29+
<meta charset="UTF-8">
30+
<meta name="format-detection" content="telephone=no">
31+
<title>{{siteName}}</title>
32+
</head>
33+
{{! background-color-neutral }}
34+
<body style="margin:0;padding:0;background-color:#eaecf0;">
35+
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" bgcolor="#eaecf0" style="border-collapse:collapse;background-color:#eaecf0;">
36+
<tr>
37+
{{! spacing-150, spacing-75 }}
38+
<td align="center" style="padding:24px 12px;">
39+
<!--[if mso]><table role="presentation" cellpadding="0" cellspacing="0" border="0" width="480" align="center"><tr><td><![endif]-->
40+
{{! background-color-base, border-color-subtle, border-radius-base }}
41+
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" bgcolor="#ffffff" style="border-collapse:collapse;max-width:480px;background-color:#ffffff;border:1px solid #c8ccd1;border-radius:2px;">
42+
<tr>
43+
{{! font-size-x-large, font-weight-bold, color-base, spacing-150 }}
44+
<td align="center" style="padding:24px 24px 0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Inter,Helvetica,Arial,sans-serif;font-size:20px;font-weight:700;line-height:28px;color:#202122;text-align:center;">
45+
{{siteName}}
46+
</td>
47+
</tr>
48+
<tr>
49+
{{! font-size-medium, color-base, spacing-25 }}
50+
<td align="center" style="padding:4px 24px 0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Inter,Helvetica,Arial,sans-serif;font-size:16px;line-height:26px;color:#202122;text-align:center;">
51+
{{intro}}
52+
</td>
53+
</tr>
54+
<tr>
55+
{{! spacing-100, spacing-150 }}
56+
<td align="center" style="padding:16px 24px 0;">
57+
{{! background-color-neutral-subtle, border-color-subtle }}
58+
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" bgcolor="#f8f9fa" style="border-collapse:collapse;background-color:#f8f9fa;border:1px solid #c8ccd1;">
59+
<tr>
60+
{{! font-family-monospace, font-weight-bold, color-base, spacing-100 }}
61+
<td align="center" dir="ltr" style="padding:16px;font-family:Menlo,Consolas,'Liberation Mono','Fira Code','Courier New',monospace;font-size:30px;font-weight:700;letter-spacing:6px;color:#202122;text-align:center;">
62+
{{code}}
63+
</td>
64+
</tr>
65+
</table>
66+
</td>
67+
</tr>
68+
<tr>
69+
{{! font-size-small, color-subtle, spacing-150 }}
70+
<td align="center" style="padding:14px 24px 0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Inter,Helvetica,Arial,sans-serif;font-size:14px;line-height:22px;color:#54595d;text-align:center;">
71+
{{validity}}
72+
</td>
73+
</tr>
74+
<tr>
75+
{{! font-size-x-small, color-subtle, spacing-100, spacing-150 }}
76+
<td align="center" style="padding:16px 24px 24px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Inter,Helvetica,Arial,sans-serif;font-size:12px;line-height:19px;color:#54595d;text-align:center;">
77+
{{disclaimer}}
78+
</td>
79+
</tr>
80+
</table>
81+
<!--[if mso]></td></tr></table><![endif]-->
82+
</td>
83+
</tr>
84+
</table>
85+
</body>
86+
</html>
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php
2+
3+
declare( strict_types = 1 );
4+
5+
namespace ProfessionalWiki\MemberAccess\Tests\Application;
6+
7+
use PHPUnit\Framework\TestCase;
8+
use ProfessionalWiki\MemberAccess\Application\DisplayedCode;
9+
10+
/**
11+
* @covers \ProfessionalWiki\MemberAccess\Application\DisplayedCode
12+
*/
13+
class DisplayedCodeTest extends TestCase {
14+
15+
public function testCodeIsShownInGroupsOfFour(): void {
16+
$this->assertSame( '4063 2370', DisplayedCode::grouped( '40632370' ) );
17+
}
18+
19+
/**
20+
* The length is the wiki's generator's to choose, so a code that does not divide into whole
21+
* groups is shown with a shorter last one rather than not shown at all.
22+
*/
23+
public function testCodeThatDoesNotFillItsLastGroupKeepsTheRemainder(): void {
24+
$this->assertSame( '1234 56', DisplayedCode::grouped( '123456' ) );
25+
}
26+
27+
public function testEmptyCodeIsShownAsNothing(): void {
28+
$this->assertSame( '', DisplayedCode::grouped( '' ) );
29+
}
30+
31+
public function testGroupingIsTakenBackOff(): void {
32+
$this->assertSame( '40632370', DisplayedCode::ungrouped( '4063 2370' ) );
33+
}
34+
35+
public function testACodeTypedWithoutTheGroupingIsLeftAsItIs(): void {
36+
$this->assertSame( '40632370', DisplayedCode::ungrouped( '40632370' ) );
37+
}
38+
39+
/**
40+
* What a mail client hands to a clipboard is its own affair, and a member pasting from one is
41+
* not to be refused their own code over it.
42+
*/
43+
public function testEverySortOfSpaceIsTakenBackOff(): void {
44+
$this->assertSame( '40632370', DisplayedCode::ungrouped( " 4063\t2370\u{00A0}" ) );
45+
}
46+
47+
public function testShowingACodeAndTakingItBackReturnsWhatWasIssued(): void {
48+
$this->assertSame( '40632370', DisplayedCode::ungrouped( DisplayedCode::grouped( '40632370' ) ) );
49+
}
50+
51+
}

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

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ class MemberAuthenticationProviderTest extends MediaWikiIntegrationTestCase {
4040
use AuthenticationProviderTestTrait;
4141

4242
private const CODE = '12345678';
43+
private const GROUPED_CODE = '1234 5678';
4344
private const RETURN_TO_URL = 'https://wiki.example.com/return';
4445
private const SSO_USERNAME = 'Jane of Acme';
4546

@@ -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+
self::GROUPED_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( self::GROUPED_CODE );
93+
94+
$this->assertSame( AuthenticationResponse::PASS, $response->status );
7895
}
7996

8097
public function testCorrectCodeLogsTheMemberInAndCreatesTheAccount(): void {

0 commit comments

Comments
 (0)