domma-cms 1.28.4 → 1.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/admin/js/lib/contacts-arrange.js +1 -1
- package/docs/DommaFeatures.md +5 -3
- package/package.json +4 -1
- package/plugins/_lib/admin/mail/body-menu.js +2 -0
- package/plugins/_lib/admin/mail/cms-host.js +22 -0
- package/plugins/_lib/admin/mail/compose-window.js +1027 -1021
- package/plugins/_lib/admin/mail/contacts.js +10 -8
- package/plugins/_lib/admin/mail/diagnostics-section.js +2 -0
- package/plugins/_lib/admin/mail/drag-drop.js +46 -0
- package/plugins/_lib/admin/mail/folder-tree.js +2 -0
- package/plugins/_lib/admin/mail/font-controls.js +6 -4
- package/plugins/_lib/admin/mail/fonts.js +1 -1
- package/plugins/_lib/admin/mail/host-context.js +87 -0
- package/plugins/_lib/admin/mail/identity.js +2 -0
- package/plugins/_lib/admin/mail/image-senders-section.js +2 -0
- package/plugins/_lib/admin/mail/keyboard.js +2 -0
- package/plugins/_lib/admin/mail/mail.css +1 -1
- package/plugins/_lib/admin/mail/mail.html +4 -0
- package/plugins/_lib/admin/mail/message-actions.js +2 -0
- package/plugins/_lib/admin/mail/oauth-panel.js +2 -0
- package/plugins/_lib/admin/mail/panes.js +2 -0
- package/plugins/_lib/admin/mail/reader-kit.js +2 -0
- package/plugins/_lib/admin/mail/reader-runtime.js +6534 -0
- package/plugins/_lib/admin/mail/reader-view.js +9 -6380
- package/plugins/_lib/admin/mail/resizable.js +2 -0
- package/plugins/_lib/admin/mail/restore-spam.js +13 -0
- package/plugins/_lib/admin/mail/rules.js +14 -0
- package/plugins/_lib/admin/mail/scheduling.js +4 -1
- package/plugins/_lib/admin/mail/section-kit.js +4 -1
- package/plugins/_lib/admin/mail/security-note.js +2 -0
- package/plugins/_lib/admin/mail/settings-section.js +11 -10
- package/plugins/_lib/admin/mail/templates.js +5 -2
- package/plugins/_lib/admin/mail/threads.js +2 -0
- package/plugins/_lib/admin/mail/vacation.js +16 -2
- package/plugins/_lib/admin/mail/when-closed.js +24 -2
- package/plugins/_lib/admin/ui/dates.js +2 -0
- package/plugins/_lib/admin/ui/resizable.js +7 -5
- package/plugins/_lib/contacts/mailContact.js +69 -0
- package/plugins/_lib/contacts/model.js +199 -0
- package/plugins/_lib/domma-mail-contacts.lock.json +10 -0
- package/plugins/_lib/domma-mail.lock.json +85 -0
- package/plugins/_lib/mail/accountFileStore.js +66 -0
- package/plugins/_lib/mail/accountRepository.js +617 -0
- package/plugins/_lib/mail/accountRoutes.js +130 -0
- package/plugins/_lib/mail/accounts.js +66 -940
- package/plugins/_lib/mail/automationLock.js +10 -0
- package/plugins/_lib/mail/bodyTokenProvider.js +36 -0
- package/plugins/_lib/mail/bodyTokens.js +5 -99
- package/plugins/_lib/mail/compose.js +5 -3
- package/plugins/_lib/mail/defaults.js +2 -0
- package/plugins/_lib/mail/envelope.js +3 -1
- package/plugins/_lib/mail/folderActions.js +83 -0
- package/plugins/_lib/mail/folderRuntime.js +109 -0
- package/plugins/_lib/mail/folders.js +4 -9
- package/plugins/_lib/mail/imapPool.js +11 -389
- package/plugins/_lib/mail/imapPoolRuntime.js +396 -0
- package/plugins/_lib/mail/mbox.js +2 -0
- package/plugins/_lib/mail/message-action.js +2 -0
- package/plugins/_lib/mail/messageSecurity.js +4 -111
- package/plugins/_lib/mail/messageSecurityProvider.js +116 -0
- package/plugins/_lib/mail/networkAddresses.js +77 -0
- package/plugins/_lib/mail/networkPolicy.js +62 -0
- package/plugins/_lib/mail/oauth.js +3 -451
- package/plugins/_lib/mail/oauthAccounts.js +178 -0
- package/plugins/_lib/mail/oauthRouteRuntime.js +282 -0
- package/plugins/_lib/mail/oauthRoutes.js +7 -289
- package/plugins/_lib/mail/oauthRuntime.js +456 -0
- package/plugins/_lib/mail/pollSchedule.js +2 -0
- package/plugins/_lib/mail/poller.js +4 -136
- package/plugins/_lib/mail/pollerRuntime.js +150 -0
- package/plugins/_lib/mail/priority.js +2 -0
- package/plugins/_lib/mail/publicMailbox.js +27 -0
- package/plugins/_lib/mail/readRoutes.js +14 -827
- package/plugins/_lib/mail/readRuntime.js +701 -0
- package/plugins/_lib/mail/render.js +2 -0
- package/plugins/_lib/mail/ruleRunner.js +27 -10
- package/plugins/_lib/mail/scheduler.js +11 -279
- package/plugins/_lib/mail/schedulerRuntime.js +259 -0
- package/plugins/_lib/mail/secretProvider.js +112 -0
- package/plugins/_lib/mail/secretbox.js +12 -225
- package/plugins/_lib/mail/send.js +21 -537
- package/plugins/_lib/mail/sieve.js +211 -0
- package/plugins/_lib/mail/sieveHost.js +24 -0
- package/plugins/_lib/mail/smtpService.js +553 -0
- package/plugins/_lib/mail/snoozeRuntime.js +60 -0
- package/plugins/_lib/mail/store.js +122 -64
- package/plugins/_lib/mail/subscriptions.js +11 -0
- package/plugins/_lib/mail/sync.js +64 -290
- package/plugins/_lib/mail/syncPlan.js +2 -0
- package/plugins/_lib/mail/syncRuntime.js +255 -0
- package/plugins/_lib/mail/syncSelection.js +2 -0
- package/plugins/_lib/mail/unreadBadge.js +2 -0
- package/plugins/_lib/mail/unsubscribe.js +2 -0
- package/plugins/_lib/mail/vacationRunner.js +3 -116
- package/plugins/_lib/mail/vacationRuntime.js +70 -0
- package/plugins/_lib/mail/write.js +44 -13
- package/server/routes/api/contacts.js +2 -196
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// Source: @domma-mail/core 0.18.0, packages/core/src/mail/oauthAccounts.js.
|
|
2
|
+
// Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
import {MailKeyError} from './secretProvider.js';
|
|
5
|
+
|
|
6
|
+
export class OAuthReconnectError extends MailKeyError {
|
|
7
|
+
constructor(message = 'This mailbox\'s sign-in has expired or was withdrawn. Reconnect it under Mail Settings > Mailboxes.') {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'OAuthReconnectError';
|
|
10
|
+
this.needsReconnect = true;
|
|
11
|
+
this.statusCode = 409;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Is this mailbox signed in with a provider (OAuth2) rather than a password?
|
|
17
|
+
*
|
|
18
|
+
* @param {object|null} account
|
|
19
|
+
* @returns {boolean}
|
|
20
|
+
*/
|
|
21
|
+
export function isOAuth(account) {
|
|
22
|
+
return account?.auth === 'oauth' && !!account.oauth;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Does this mailbox need its owner to sign in again?
|
|
27
|
+
*
|
|
28
|
+
* @param {object|null} account
|
|
29
|
+
* @returns {boolean}
|
|
30
|
+
*/
|
|
31
|
+
export function needsReconnect(account) {
|
|
32
|
+
return isOAuth(account) && account.oauth.status !== 'ok';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
export function createOAuthAccounts({store, secrets, refresherFor, OAuthError = OAuthReconnectError}) {
|
|
37
|
+
const {readAll, writeAll, withStoreLock} = store;
|
|
38
|
+
const {open, seal} = secrets;
|
|
39
|
+
async function saveOAuthAccount(userId, accountId, f) {
|
|
40
|
+
return withStoreLock(async () => {
|
|
41
|
+
const all = await readAll();
|
|
42
|
+
const now = new Date().toISOString();
|
|
43
|
+
const previous = accountId ? all.find(a => a.id === accountId && a.userId === userId) : null;
|
|
44
|
+
const oauth = {
|
|
45
|
+
// A new sign-in is a new generation: a renewal that started under the
|
|
46
|
+
// old one must not write its tokens over this (see updateOAuth).
|
|
47
|
+
gen: (Number(previous?.oauth?.gen) || 0) + 1,
|
|
48
|
+
provider: f.provider,
|
|
49
|
+
clientId: f.clientId,
|
|
50
|
+
tenant: f.tenant ?? null,
|
|
51
|
+
clientSecretSealed: seal(f.clientSecret),
|
|
52
|
+
refreshTokenSealed: seal(f.refreshToken),
|
|
53
|
+
accessTokenSealed: seal(f.accessToken),
|
|
54
|
+
expiresAt: f.expiresAt,
|
|
55
|
+
scope: f.scope ?? '',
|
|
56
|
+
status: 'ok',
|
|
57
|
+
error: null,
|
|
58
|
+
connectedAt: now,
|
|
59
|
+
refreshedAt: now
|
|
60
|
+
};
|
|
61
|
+
const fields = {
|
|
62
|
+
auth: 'oauth',
|
|
63
|
+
host: f.imap.host,
|
|
64
|
+
port: f.imap.port,
|
|
65
|
+
secure: f.imap.secure,
|
|
66
|
+
username: f.username,
|
|
67
|
+
oauth
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
if (accountId) {
|
|
71
|
+
const index = all.findIndex(a => a.id === accountId && a.userId === userId);
|
|
72
|
+
if (index === -1) return null;
|
|
73
|
+
const {passwordSealed, ...existing} = all[index];
|
|
74
|
+
const keepSmtp = existing.smtp ?? {};
|
|
75
|
+
all[index] = {
|
|
76
|
+
...existing,
|
|
77
|
+
...fields,
|
|
78
|
+
label: f.label || existing.label,
|
|
79
|
+
smtp: {
|
|
80
|
+
...keepSmtp,
|
|
81
|
+
host: f.smtp.host, port: f.smtp.port, secure: f.smtp.secure,
|
|
82
|
+
username: f.username, passwordSealed: null,
|
|
83
|
+
from: keepSmtp.from || f.username,
|
|
84
|
+
sentFolder: keepSmtp.sentFolder ?? null
|
|
85
|
+
},
|
|
86
|
+
updatedAt: now
|
|
87
|
+
};
|
|
88
|
+
await writeAll(all);
|
|
89
|
+
return all[index];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const record = {
|
|
93
|
+
id: randomUUID(),
|
|
94
|
+
userId,
|
|
95
|
+
label: f.label || f.username,
|
|
96
|
+
...fields,
|
|
97
|
+
smtp: {host: f.smtp.host, port: f.smtp.port, secure: f.smtp.secure, username: f.username,
|
|
98
|
+
passwordSealed: null, from: f.username, sentFolder: null},
|
|
99
|
+
createdAt: now,
|
|
100
|
+
updatedAt: now
|
|
101
|
+
};
|
|
102
|
+
all.push(record);
|
|
103
|
+
await writeAll(all);
|
|
104
|
+
return record;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Change part of a mailbox's stored sign-in: a renewed token, a rotated
|
|
110
|
+
* refresh token, "needs reconnecting", or a disconnect.
|
|
111
|
+
*
|
|
112
|
+
* Does NOT touch `updatedAt`: that stamp means "the person changed the
|
|
113
|
+
* settings", and the free reader's unread badge keys its failure back-off on
|
|
114
|
+
* it - an hourly token renewal would otherwise reset the back-off every hour.
|
|
115
|
+
*
|
|
116
|
+
* `expectGen`: apply only if the stored sign-in is still that generation.
|
|
117
|
+
* `requireOk`: apply only if it is still working. `bumpGen`: this patch IS a
|
|
118
|
+
* new state (Disconnect) that older in-flight work must not overwrite.
|
|
119
|
+
* Returns null when the patch was dropped (or the mailbox is gone).
|
|
120
|
+
*
|
|
121
|
+
* @param {string} userId
|
|
122
|
+
* @param {string} accountId
|
|
123
|
+
* @param {object} patch
|
|
124
|
+
* @param {{expectGen?: number, requireOk?: boolean, bumpGen?: boolean}} [options]
|
|
125
|
+
* @returns {Promise<object|null>}
|
|
126
|
+
*/
|
|
127
|
+
async function updateOAuth(userId, accountId, patch, {expectGen, requireOk = false, bumpGen = false} = {}) {
|
|
128
|
+
return withStoreLock(async () => {
|
|
129
|
+
const all = await readAll();
|
|
130
|
+
const index = all.findIndex(a => a.id === accountId && a.userId === userId);
|
|
131
|
+
if (index === -1 || !all[index].oauth) return null;
|
|
132
|
+
const current = all[index].oauth;
|
|
133
|
+
// The sign-in this patch was worked out against is no longer the stored
|
|
134
|
+
// one (a Reconnect or Disconnect happened meanwhile): drop it rather than
|
|
135
|
+
// undo the newer state.
|
|
136
|
+
if (expectGen !== undefined && (Number(current.gen) || 0) !== expectGen) return null;
|
|
137
|
+
// A renewal only ever lands on a working sign-in, never revives a dead one.
|
|
138
|
+
if (requireOk && current.status !== 'ok') return null;
|
|
139
|
+
const next = {...current, ...patch};
|
|
140
|
+
if (bumpGen) next.gen = (Number(current.gen) || 0) + 1;
|
|
141
|
+
all[index] = {...all[index], oauth: next};
|
|
142
|
+
await writeAll(all);
|
|
143
|
+
return all[index];
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function storedAccess(account) {
|
|
148
|
+
if (needsReconnect(account)) throw new OAuthError(account.oauth.error || undefined);
|
|
149
|
+
let accessToken = '';
|
|
150
|
+
try {
|
|
151
|
+
accessToken = account.oauth.accessTokenSealed ? open(account.oauth.accessTokenSealed) : '';
|
|
152
|
+
} catch {
|
|
153
|
+
// Unreadable (the key moved): treat as expired, the refresh decides.
|
|
154
|
+
}
|
|
155
|
+
return {accessToken, expiresAt: accessToken ? Number(account.oauth.expiresAt) || 0 : 0};
|
|
156
|
+
}
|
|
157
|
+
function oauthToPublic(oauth) {
|
|
158
|
+
return {
|
|
159
|
+
provider: oauth.provider,
|
|
160
|
+
clientId: oauth.clientId,
|
|
161
|
+
tenant: oauth.tenant ?? null,
|
|
162
|
+
status: oauth.status ?? 'reconnect',
|
|
163
|
+
error: oauth.error ?? null,
|
|
164
|
+
connectedAt: oauth.connectedAt ?? null,
|
|
165
|
+
refreshedAt: oauth.refreshedAt ?? null,
|
|
166
|
+
hasClientSecret: typeof oauth.clientSecretSealed === 'string' && oauth.clientSecretSealed.length > 0
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function oauthConnection(account) {
|
|
171
|
+
const {accessToken, expiresAt} = storedAccess(account);
|
|
172
|
+
return {
|
|
173
|
+
host: account.host, port: account.port, secure: account.secure,
|
|
174
|
+
auth: {user: account.username, accessToken}, expiresAt, refresh: refresherFor(account)
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
return {saveOAuthAccount, updateOAuth, isOAuth, needsReconnect, oauthConnection, oauthToPublic};
|
|
178
|
+
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// Source: @domma-mail/core 0.18.0, packages/core/src/mail/oauthRouteRuntime.js.
|
|
2
|
+
// Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
|
|
3
|
+
/**
|
|
4
|
+
* The OAuth2 sign-in routes for mailboxes: Connect, the provider's callback,
|
|
5
|
+
* Disconnect and Test. Registered by Email Pro (which feature-detects this
|
|
6
|
+
* file - an engine without it simply offers no sign-in); the free reader does
|
|
7
|
+
* not register them, but reads a signed-in mailbox all the same.
|
|
8
|
+
*
|
|
9
|
+
* Each customer registers THEIR OWN app with Microsoft or Google - the Docs
|
|
10
|
+
* Pro cloud-copies design. The admin form shows this site's exact redirect
|
|
11
|
+
* URI with a guide; the client secret goes in sealed and never comes out.
|
|
12
|
+
*
|
|
13
|
+
* The callback is the one route without a session. Its `state` is a one-time
|
|
14
|
+
* ticket, ten minutes long, naming the person who pressed Connect, and the
|
|
15
|
+
* callback refuses a browser signed in to this site as somebody else.
|
|
16
|
+
*
|
|
17
|
+
* @module _lib/mail/oauthRoutes
|
|
18
|
+
*/
|
|
19
|
+
import {createHash, randomBytes, timingSafeEqual} from 'node:crypto';
|
|
20
|
+
|
|
21
|
+
const STATE_TTL = 10 * 60 * 1000;
|
|
22
|
+
/** Pending sign-ins kept at once - a ceiling on what a busy (or hostile) admin can pile up. */
|
|
23
|
+
const MAX_PENDING = 200;
|
|
24
|
+
/** Pending sign-ins per person: a new one beyond this replaces their oldest. */
|
|
25
|
+
const MAX_PENDING_PER_USER = 5;
|
|
26
|
+
|
|
27
|
+
const sha256 = (v) => createHash('sha256').update(String(v)).digest();
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The browser-binding cookie's name for one sign-in. Per state, so two
|
|
31
|
+
* Connects in two tabs do not overwrite each other's cookie.
|
|
32
|
+
*
|
|
33
|
+
* @param {string} state
|
|
34
|
+
* @returns {string}
|
|
35
|
+
*/
|
|
36
|
+
export function bindCookieName(state) {
|
|
37
|
+
return `dm_mail_oauth_${sha256(state).toString('hex').slice(0, 16)}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* One cookie's value from a raw Cookie header (no cookie plugin assumed).
|
|
42
|
+
*
|
|
43
|
+
* @param {string|undefined} header
|
|
44
|
+
* @param {string} name
|
|
45
|
+
* @returns {string}
|
|
46
|
+
*/
|
|
47
|
+
export function readCookie(header, name) {
|
|
48
|
+
for (const part of String(header ?? '').split(';')) {
|
|
49
|
+
const at = part.indexOf('=');
|
|
50
|
+
if (at !== -1 && part.slice(0, at).trim() === name) return part.slice(at + 1).trim();
|
|
51
|
+
}
|
|
52
|
+
return '';
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const text = (v, max = 300) => String(v ?? '').trim().slice(0, max);
|
|
56
|
+
// JSON inside a <script>: nothing in it can close the element early.
|
|
57
|
+
const js = (v) => JSON.stringify(v).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
|
|
58
|
+
const esc = (s) => String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* @param {object} fastify
|
|
62
|
+
* @param {{authenticate: Function, pool: object, pluginName: string, config?: object,
|
|
63
|
+
* onNeedsReconnect?: Function, onConnected?: Function, fetch?: Function}} options
|
|
64
|
+
*/
|
|
65
|
+
export function registerOAuthRuntime(fastify, {authenticate, pool, pluginName, config = {}, onNeedsReconnect, onConnected, fetch, accounts, secrets, MailKeyError, verifySmtp, oauth, redirectUriFor, resolveViewer, requireViewer = false}) {
|
|
66
|
+
const {open, seal} = secrets;
|
|
67
|
+
const {announceConnected, authorizeUrl, cleanTenant, configureOAuth, describeProviders, exchangeCode, mailboxFor, pkcePair, PROVIDERS, revokeAccount} = oauth;
|
|
68
|
+
configureOAuth({fetch, onNeedsReconnect: onNeedsReconnect ?? null, onConnected: onConnected ?? null});
|
|
69
|
+
|
|
70
|
+
/** state -> {userId, accountId, provider, clientId, clientSecretSealed, tenant, label, username, verifier, redirectUri, expires} */
|
|
71
|
+
const pending = new Map();
|
|
72
|
+
const userId = (request) => request.user?.id ?? request.user?.sub ?? null;
|
|
73
|
+
|
|
74
|
+
function sweep() {
|
|
75
|
+
const now = Date.now();
|
|
76
|
+
for (const [k, v] of pending) if (v.expires < now) pending.delete(k);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** GET /oauth/status - providers and the redirect URI, for the form's guide. */
|
|
80
|
+
fastify.get('/oauth/status', {preHandler: [authenticate]}, async (request) => {
|
|
81
|
+
const redirectUri = await redirectUriFor(request);
|
|
82
|
+
return {available: true, redirectUri, https: redirectUri.startsWith('https://'), providers: describeProviders()};
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* POST /oauth/start - where to send the person to sign in.
|
|
87
|
+
* Body: {accountId?, provider, clientId, clientSecret (blank = keep the saved one), tenant?, label?, username?}
|
|
88
|
+
*/
|
|
89
|
+
fastify.post('/oauth/start', {preHandler: [authenticate], config: {rateLimit: {max: 20, timeWindow: '1 minute'}}}, async (request, reply) => {
|
|
90
|
+
const uid = userId(request);
|
|
91
|
+
if (!uid) return reply.code(401).send({error: 'Authentication required.'});
|
|
92
|
+
const body = request.body ?? {};
|
|
93
|
+
const provider = text(body.provider, 20);
|
|
94
|
+
if (!PROVIDERS[provider]) return reply.code(400).send({error: 'Choose Microsoft or Google.'});
|
|
95
|
+
|
|
96
|
+
const accountId = body.accountId ? text(body.accountId, 80) : null;
|
|
97
|
+
const existing = accountId ? await accounts.getAccount(uid, accountId) : null;
|
|
98
|
+
if (accountId && !existing) return reply.code(404).send({error: 'That mailbox does not exist.'});
|
|
99
|
+
|
|
100
|
+
const clientId = text(body.clientId, 200);
|
|
101
|
+
if (!clientId) return reply.code(400).send({error: PROVIDERS[provider].id === 'microsoft' ? 'The Application (client) ID is needed.' : 'The Client ID is needed.'});
|
|
102
|
+
|
|
103
|
+
// Blank secret = the one already saved, but only for the same app.
|
|
104
|
+
let clientSecret = text(body.clientSecret, 2000);
|
|
105
|
+
if (!clientSecret) {
|
|
106
|
+
const o = existing?.oauth;
|
|
107
|
+
if (o?.clientSecretSealed && o.provider === provider && o.clientId === clientId) {
|
|
108
|
+
try {
|
|
109
|
+
clientSecret = open(o.clientSecretSealed);
|
|
110
|
+
} catch (err) {
|
|
111
|
+
if (err instanceof MailKeyError) return reply.code(409).send({error: 'The saved client secret can no longer be read - type it again.'});
|
|
112
|
+
throw err;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (!clientSecret) return reply.code(400).send({error: 'The client secret is needed.'});
|
|
117
|
+
|
|
118
|
+
const username = text(body.username, 254).toLowerCase();
|
|
119
|
+
if (username && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(username)) return reply.code(400).send({error: 'That is not an email address.'});
|
|
120
|
+
|
|
121
|
+
sweep();
|
|
122
|
+
// Per person first: their oldest waiting sign-in makes room. Then the
|
|
123
|
+
// site-wide ceiling, which only many people at once can reach.
|
|
124
|
+
const mine = [...pending.entries()].filter(([, v]) => v.userId === uid).sort((a, b) => a[1].expires - b[1].expires);
|
|
125
|
+
while (mine.length >= MAX_PENDING_PER_USER) pending.delete(mine.shift()[0]);
|
|
126
|
+
if (pending.size >= MAX_PENDING) return reply.code(429).send({error: 'Too many sign-ins are waiting. Try again in a few minutes.'});
|
|
127
|
+
|
|
128
|
+
const state = randomBytes(24).toString('base64url');
|
|
129
|
+
const {verifier, challenge} = pkcePair();
|
|
130
|
+
const redirectUri = await redirectUriFor(request);
|
|
131
|
+
const tenant = PROVIDERS[provider].needsTenant ? cleanTenant(body.tenant) : null;
|
|
132
|
+
// Binds the sign-in to THIS browser: the callback refuses one that does
|
|
133
|
+
// not bring the cookie back. Without it, an anonymous browser could
|
|
134
|
+
// finish a sign-in someone else started (send a colleague the
|
|
135
|
+
// provider link, and their mailbox lands under your account).
|
|
136
|
+
// HttpOnly, SameSite=Lax (sent on the provider's top-level redirect
|
|
137
|
+
// back), scoped to the callback path, gone in ten minutes.
|
|
138
|
+
const bind = randomBytes(24).toString('base64url');
|
|
139
|
+
const callbackPath = new URL(redirectUri).pathname;
|
|
140
|
+
reply.header('Set-Cookie', `${bindCookieName(state)}=${bind}; Path=${callbackPath}; Max-Age=${STATE_TTL / 1000}; HttpOnly; SameSite=Lax`
|
|
141
|
+
+ (redirectUri.startsWith('https://') ? '; Secure' : ''));
|
|
142
|
+
pending.set(state, {
|
|
143
|
+
userId: uid, accountId, provider, clientId, clientSecretSealed: seal(clientSecret), tenant,
|
|
144
|
+
label: text(body.label, 80), username, verifier, redirectUri, bindHash: sha256(bind), expires: Date.now() + STATE_TTL
|
|
145
|
+
});
|
|
146
|
+
return {
|
|
147
|
+
url: authorizeUrl({provider, clientId, tenant, redirectUri, state, codeChallenge: challenge,
|
|
148
|
+
loginHint: username || existing?.username || ''}),
|
|
149
|
+
redirectUri
|
|
150
|
+
};
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* GET /oauth/callback - the provider sends the person back here. Answers a
|
|
155
|
+
* small page that tells the mail screen (its opener) and closes itself.
|
|
156
|
+
*/
|
|
157
|
+
fastify.get('/oauth/callback', {config: {rateLimit: {max: 30, timeWindow: '1 minute'}}}, async (request, reply) => {
|
|
158
|
+
const q = request.query ?? {};
|
|
159
|
+
const key = String(q.state ?? '');
|
|
160
|
+
const ticket = pending.get(key);
|
|
161
|
+
pending.delete(key);
|
|
162
|
+
|
|
163
|
+
const page = (ok, message, origin, accountId = null) => reply
|
|
164
|
+
.type('text/html; charset=utf-8')
|
|
165
|
+
.header('Cache-Control', 'no-store')
|
|
166
|
+
.header('Referrer-Policy', 'no-referrer')
|
|
167
|
+
.header('X-Robots-Tag', 'noindex')
|
|
168
|
+
.send(`<!doctype html><meta charset="utf-8"><meta name="robots" content="noindex"><title>${ok ? 'Mailbox connected' : 'Not connected'}</title>`
|
|
169
|
+
+ `<body style="font-family:system-ui,sans-serif;display:grid;place-items:center;min-height:90vh;margin:0"><main style="max-width:30rem;text-align:center;padding:1rem">`
|
|
170
|
+
+ `<h1 style="font-size:1.3rem">${ok ? 'Mailbox connected' : 'Not connected'}</h1><p>${esc(message)}</p><p>You can close this window.</p></main>`
|
|
171
|
+
+ `<script>try{window.opener&&window.opener.postMessage(${js({type: 'domma-mail-oauth', ok, message, accountId})},${js(origin || '')});}catch(e){}${ok ? 'setTimeout(function(){window.close();},1200);' : ''}</script>`);
|
|
172
|
+
|
|
173
|
+
if (!ticket || ticket.expires < Date.now()) {
|
|
174
|
+
return page(false, 'This sign-in link has expired or was already used. Go back to Email and press Connect again.', null);
|
|
175
|
+
}
|
|
176
|
+
const origin = new URL(ticket.redirectUri).origin;
|
|
177
|
+
// Used up either way; clear it.
|
|
178
|
+
const cookieName = bindCookieName(key);
|
|
179
|
+
reply.header('Set-Cookie', `${cookieName}=; Path=${new URL(ticket.redirectUri).pathname}; Max-Age=0; HttpOnly; SameSite=Lax`);
|
|
180
|
+
if (q.error) return page(false, `The sign-in was not completed: ${text(q.error_description || q.error, 200)}`, origin);
|
|
181
|
+
|
|
182
|
+
// The browser that pressed Connect, and no other.
|
|
183
|
+
const bound = readCookie(request.headers.cookie, cookieName);
|
|
184
|
+
if (!bound || !timingSafeEqual(sha256(bound), ticket.bindHash)) {
|
|
185
|
+
return page(false, `This sign-in has to be finished in the browser that pressed Connect, with the admin open at ${origin}. Press Connect again there.`, origin);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Signed in to this site as somebody else: refuse - whoever pressed
|
|
189
|
+
// Connect must be the one who finishes it.
|
|
190
|
+
const viewer = await resolveViewer(request).catch(() => null);
|
|
191
|
+
if ((requireViewer && !viewer?.id) || (viewer?.id && viewer.id !== ticket.userId)) {
|
|
192
|
+
return page(false, 'This sign-in was started by someone else. Press Connect yourself.', origin);
|
|
193
|
+
}
|
|
194
|
+
if (ticket.accountId && !(await accounts.getAccount(ticket.userId, ticket.accountId))) {
|
|
195
|
+
return page(false, 'That mailbox no longer exists.', origin);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
try {
|
|
199
|
+
const clientSecret = open(ticket.clientSecretSealed);
|
|
200
|
+
const got = await exchangeCode({
|
|
201
|
+
provider: ticket.provider, clientId: ticket.clientId, clientSecret, tenant: ticket.tenant,
|
|
202
|
+
code: text(q.code, 4000), redirectUri: ticket.redirectUri, codeVerifier: ticket.verifier
|
|
203
|
+
});
|
|
204
|
+
const box = mailboxFor(ticket.provider, got.claims);
|
|
205
|
+
// Typed wins: a Microsoft 365 shared mailbox is signed in to by a
|
|
206
|
+
// person but addressed as itself (XOAUTH2 user = the shared address).
|
|
207
|
+
const username = ticket.username || box.email;
|
|
208
|
+
if (!username) {
|
|
209
|
+
return page(false, 'The provider did not say which mailbox was signed in to. Type the email address in the form and Connect again.', origin);
|
|
210
|
+
}
|
|
211
|
+
const p = PROVIDERS[ticket.provider];
|
|
212
|
+
const saved = await accounts.saveOAuthAccount(ticket.userId, ticket.accountId, {
|
|
213
|
+
label: ticket.label || username,
|
|
214
|
+
username,
|
|
215
|
+
provider: ticket.provider,
|
|
216
|
+
clientId: ticket.clientId,
|
|
217
|
+
tenant: ticket.tenant,
|
|
218
|
+
clientSecret,
|
|
219
|
+
refreshToken: got.refreshToken,
|
|
220
|
+
accessToken: got.accessToken,
|
|
221
|
+
expiresAt: got.expiresAt,
|
|
222
|
+
scope: got.scope,
|
|
223
|
+
imap: p.imap,
|
|
224
|
+
smtp: box.smtp
|
|
225
|
+
});
|
|
226
|
+
if (!saved) return page(false, 'That mailbox no longer exists.', origin);
|
|
227
|
+
// A connection opened with the old details must not be reused.
|
|
228
|
+
pool.release(`${ticket.userId}:${saved.id}`);
|
|
229
|
+
announceConnected(saved);
|
|
230
|
+
return page(true, `${username} is connected through ${p.short}.`, origin, saved.id);
|
|
231
|
+
} catch (err) {
|
|
232
|
+
fastify.log.warn(`[${pluginName}] mailbox sign-in failed: ${err.message}`);
|
|
233
|
+
return page(false, text(err.message, 300), origin);
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
/** POST /oauth/:id/disconnect - hand the sign-in back (where the provider allows) and forget it. */
|
|
238
|
+
fastify.post('/oauth/:id/disconnect', {preHandler: [authenticate]}, async (request, reply) => {
|
|
239
|
+
const uid = userId(request);
|
|
240
|
+
if (!uid) return reply.code(401).send({error: 'Authentication required.'});
|
|
241
|
+
const account = await accounts.getAccount(uid, request.params.id);
|
|
242
|
+
if (!account) return reply.code(404).send({error: 'That mailbox does not exist.'});
|
|
243
|
+
if (!accounts.isOAuth(account)) return reply.code(400).send({error: 'This mailbox uses a password, not a sign-in.'});
|
|
244
|
+
|
|
245
|
+
const result = await revokeAccount(account);
|
|
246
|
+
pool.release(`${uid}:${account.id}`);
|
|
247
|
+
// A new generation: a renewal already on the wire must not write a
|
|
248
|
+
// working token back over the disconnect (see accounts.updateOAuth).
|
|
249
|
+
const saved = await accounts.updateOAuth(uid, account.id, {
|
|
250
|
+
status: 'disconnected',
|
|
251
|
+
error: 'Disconnected. Reconnect to use this mailbox again.',
|
|
252
|
+
refreshTokenSealed: null,
|
|
253
|
+
accessTokenSealed: null,
|
|
254
|
+
expiresAt: 0
|
|
255
|
+
}, {bumpGen: true});
|
|
256
|
+
return {account: accounts.toPublic(saved), revoked: result.revoked, revokeSupported: result.supported};
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
/** POST /oauth/:id/test - sign in to both servers with the stored sign-in. */
|
|
260
|
+
fastify.post('/oauth/:id/test', {preHandler: [authenticate], config: {rateLimit: {max: 10, timeWindow: '1 minute'}}}, async (request, reply) => {
|
|
261
|
+
const uid = userId(request);
|
|
262
|
+
if (!uid) return reply.code(401).send({error: 'Authentication required.'});
|
|
263
|
+
const account = await accounts.getAccount(uid, request.params.id);
|
|
264
|
+
if (!account) return reply.code(404).send({error: 'That mailbox does not exist.'});
|
|
265
|
+
if (!accounts.isOAuth(account)) return reply.code(400).send({error: 'This mailbox uses a password, not a sign-in.'});
|
|
266
|
+
|
|
267
|
+
let imap;
|
|
268
|
+
let smtp;
|
|
269
|
+
try {
|
|
270
|
+
imap = await pool.test(accounts.toConnection(account));
|
|
271
|
+
} catch (err) {
|
|
272
|
+
imap = {ok: false, error: err.message};
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
const out = accounts.toSmtpConnection(account);
|
|
276
|
+
smtp = out ? await verifySmtp(out.transport, config.allowInsecureTLS === true) : {ok: false, error: 'No outgoing server.'};
|
|
277
|
+
} catch (err) {
|
|
278
|
+
smtp = {ok: false, error: err.message};
|
|
279
|
+
}
|
|
280
|
+
return {ok: imap.ok && smtp.ok, imap, smtp};
|
|
281
|
+
});
|
|
282
|
+
}
|