Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/domain.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export function domain(store, baseCatalog, origin) {
publishedAt: published?.publishedAt || nowISO(), revision
});
// Queue an approval email. The address is looked up from Auth at send time, never stored here.
if (decision === 'publish') tx.set('mailOutbox', id + '-r' + revision, {kind: 'tool-approved', toolId: id, name: row.data.name,
if (decision === 'publish') tx.set('mailOutbox', id + '-r' + revision, {kind: 'tool-approved', toolId: id, name: row.data.name, author: row.author,
ownerUid: row.ownerUid, url: origin + '/tools/' + id + '/', update: Boolean(published), status: 'pending', createdAt: nowISO()});
return row;
});
Expand Down
75 changes: 75 additions & 0 deletions backend/mailer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Sends queued approval emails through Microsoft Graph (app-only, Mail.Send limited to one mailbox).
// Each record is claimed in a transaction first, so parallel instances never send the same mail twice.
import { nowISO } from './domain.js';

export function approvalMessage({name, url, author, update}) {
const subject = update ? `Your ToolIndex listing update is live: ${name}` : `Your tool is live on ToolIndex: ${name}`;
const opening = update ? `Your update to ${name} has been reviewed and is now live on ToolIndex:` : `Good news: ${name} has been reviewed and is now listed on ToolIndex:`;
const body = [
`Hi ${author || 'there'},`, '', opening, url, '',
'Thank you for sharing it. People and their agents can now find it, see how to set it up, and go straight to your source.', '',
'If the tool changes, you can edit the listing from your account at https://toolindex.org/account/. Edits are reviewed again, and the current version stays visible in the meantime.', '',
'Thanks,', 'ToolIndex', 'https://toolindex.org'
].join('\n');
return {subject, body};
}

export function mailer({store, auth, env = process.env, fetchImpl = fetch, log = console}) {
const config = {tenant: env.MAIL_TENANT_ID, client: env.MAIL_CLIENT_ID, secret: env.MAIL_CLIENT_SECRET, sender: env.MAIL_SENDER};
const enabled = Boolean(config.tenant && config.client && config.secret && config.sender);
let token = null;

async function accessToken() {
if (token && token.expires > Date.now() + 60000) return token.value;
const res = await fetchImpl(`https://login.microsoftonline.com/${encodeURIComponent(config.tenant)}/oauth2/v2.0/token`, {
method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({client_id: config.client, client_secret: config.secret, scope: 'https://graph.microsoft.com/.default', grant_type: 'client_credentials'})
});
if (!res.ok) throw new Error('Mail sign-in failed: ' + res.status);
const data = await res.json();
token = {value: data.access_token, expires: Date.now() + (data.expires_in || 3600) * 1000};
return token.value;
}

async function send(to, {subject, body}) {
const res = await fetchImpl(`https://graph.microsoft.com/v1.0/users/${encodeURIComponent(config.sender)}/sendMail`, {
method: 'POST', headers: {Authorization: 'Bearer ' + await accessToken(), 'Content-Type': 'application/json'},
body: JSON.stringify({message: {subject, body: {contentType: 'Text', content: body}, toRecipients: [{emailAddress: {address: to}}]}, saveToSentItems: true})
});
if (!res.ok) throw new Error('Mail send failed: ' + res.status);
}

async function claim(key) {
return store.atomic(async tx => {
const row = await tx.get('mailOutbox', key);
if (!row || row.status !== 'pending') return null;
tx.set('mailOutbox', key, {...row, status: 'sending', claimedAt: nowISO()});
return row;
});
}
const finish = (key, row, fields) => store.atomic(async tx => tx.set('mailOutbox', key, {...row, ...fields}));

return {
enabled,
// Sends up to `limit` pending approval emails. Never throws; failures stay visible on the record.
async flush(limit = 20) {
if (!enabled) return {sent: 0, skipped: 'not configured'};
let sent = 0;
for (const {_key} of await store.list('mailOutbox', {filters: [['status', 'pending']], limit})) {
const row = await claim(_key);
if (!row) continue;
try {
const user = await auth.getUser(row.ownerUid);
if (!user.email || !user.emailVerified) { await finish(_key, row, {status: 'skipped', note: 'No verified email', finishedAt: nowISO()}); continue; }
await send(user.email, approvalMessage(row));
await finish(_key, row, {status: 'sent', sentAt: nowISO()}); sent++;
} catch (err) {
const attempts = (row.attempts || 0) + 1;
await finish(_key, row, {status: attempts >= 5 ? 'failed' : 'pending', attempts, lastError: String(err.message).slice(0, 200), lastTriedAt: nowISO()});
log.error('Approval mail failed', _key, String(err.message).slice(0, 200));
}
}
return {sent};
}
};
}
1 change: 1 addition & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"express": "5.3.0",
"express-rate-limit": "8.7.1",
"firebase-admin": "14.5.0",
"google-auth-library": "11.3.2",
"zod": "^4.0.0"
}
}
29 changes: 24 additions & 5 deletions backend/server.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

75 changes: 75 additions & 0 deletions backend/test/mail.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { MemoryStore } from '../store.js';
import { domain } from '../domain.js';
import { mailer, approvalMessage } from '../mailer.js';
import { createApp } from '../server.js';

const origin = 'https://toolindex.example';
const alice = {uid: 'alice', email: 'alice@example.test', email_verified: true, admin: false};
const admin = {uid: 'admin', email: 'reviewer@example.test', email_verified: true, admin: true};
const profile = {handle: 'alice-tools', displayName: 'Alice', bio: '', website: '', avatar: '', discoverable: true};
const tool = {name: 'Example tool', summary: 'A focused example for agents.', type: 'CLI', category: 'Coding', repository: 'https://example.org/docs', version: '1.0', license: 'MIT', installation: 'Install the complete package.'};
const env = {MAIL_TENANT_ID: 'tenant', MAIL_CLIENT_ID: 'client', MAIL_CLIENT_SECRET: 'secret', MAIL_SENDER: 'hello@toolindex.example'};

async function publishedTool(store) {
const api = domain(store, {listings: []}, origin);
await api.saveProfile(alice, profile);
const d = await api.saveTool(alice, tool); await api.submit(alice, d.id, d.revision);
await api.review(admin, d.id, d.revision, 'publish', 'Reviewed package scope');
return d;
}
function fakeGraph({failSend = false} = {}) {
const sent = [];
const fetchImpl = async (url, init) => {
if (url.includes('/oauth2/v2.0/token')) return {ok: true, json: async () => ({access_token: 'token', expires_in: 3600})};
if (failSend) return {ok: false, status: 503};
sent.push({url, message: JSON.parse(init.body).message}); return {ok: true};
};
return {sent, fetchImpl};
}
const auth = {getUser: async uid => uid === 'alice' ? {uid, email: alice.email, emailVerified: true} : {uid, email: '', emailVerified: false}};

test('approval email goes once to the verified submitter, from the configured mailbox', async () => {
const store = new MemoryStore(); await publishedTool(store);
const graph = fakeGraph(), m = mailer({store, auth, env, fetchImpl: graph.fetchImpl, log: {error() {}}});
assert.deepEqual(await m.flush(), {sent: 1});
assert.deepEqual(await m.flush(), {sent: 0});
assert.equal(graph.sent.length, 1);
assert.ok(graph.sent[0].url.endsWith('/users/hello%40toolindex.example/sendMail'));
assert.equal(graph.sent[0].message.toRecipients[0].emailAddress.address, alice.email);
assert.match(graph.sent[0].message.subject, /Example tool/);
assert.match(graph.sent[0].message.body.content, /https:\/\/toolindex\.example\/tools\//);
const [row] = await store.list('mailOutbox'); assert.equal(row.status, 'sent'); assert.ok(!JSON.stringify(row).includes(alice.email));
});

test('mail stays queued when not configured or when sending fails', async () => {
const store = new MemoryStore(); await publishedTool(store);
assert.equal((await mailer({store, auth, env: {}}).flush()).skipped, 'not configured');
const m = mailer({store, auth, env, fetchImpl: fakeGraph({failSend: true}).fetchImpl, log: {error() {}}});
await m.flush();
const [row] = await store.list('mailOutbox'); assert.equal(row.status, 'pending'); assert.equal(row.attempts, 1);
});

test('approval text has no placeholders or em dashes', () => {
for (const update of [false, true]) {
const {subject, body} = approvalMessage({name: 'Tool', url: 'https://toolindex.org/tools/tool/', author: 'alice', update});
assert.ok(!/[—\[\]]/.test(subject + body));
}
});

test('review queue endpoint only answers the one automation service account', async t => {
const store = new MemoryStore(); const api = domain(store, {listings: []}, origin);
await api.saveProfile(alice, profile); const d = await api.saveTool(alice, tool); await api.submit(alice, d.id, d.revision);
const tokens = {good: {email: 'digest@project.iam.gserviceaccount.com', email_verified: true}, other: {email: 'someone@example.test', email_verified: true}};
const {app} = await createApp({store, auth: {}, origin, catalog: {listings: []}, automationAccount: 'digest@project.iam.gserviceaccount.com',
verifyAutomation: async token => { if (!tokens[token]) throw Error('bad'); return tokens[token]; }});
const server = app.listen(0, '127.0.0.1'); await once(server, 'listening'); t.after(() => new Promise(r => server.close(r)));
const url = 'http://127.0.0.1:' + server.address().port + '/api/automation/review-queue';
for (const token of [null, 'bad', 'other']) assert.equal((await fetch(url, token ? {headers: {Authorization: 'Bearer ' + token}} : {})).status, 401);
const res = await fetch(url, {headers: {Authorization: 'Bearer good'}}); assert.equal(res.status, 200);
const body = await res.json(); assert.equal(body.submissions.length, 1); assert.equal(body.submissions[0].id, d.id);
assert.ok(!JSON.stringify(body).includes('alice@') && !body.submissions[0].ownerUid);
assert.match(res.headers.get('cache-control'), /no-store/); assert.match(res.headers.get('x-robots-tag'), /noindex/);
});
2 changes: 1 addition & 1 deletion scripts/stage_cloudrun.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def stage(root=ROOT):
for filename in ('Dockerfile',):
shutil.copy2(root / 'deploy/cloudrun' / filename, target / filename)
(target / 'backend').mkdir()
for filename in ('package.json', 'package-lock.json', 'store.js', 'domain.js', 'oauth.js', 'render.js', 'server.js'):
for filename in ('package.json', 'package-lock.json', 'store.js', 'domain.js', 'oauth.js', 'render.js', 'server.js', 'mailer.js'):
shutil.copy2(root / 'backend' / filename, target / 'backend' / filename)
shutil.copy2(root / 'site/layout.html', target / 'layout.html')
# A fresh build prevents unrelated files left in a previous dist from shipping.
Expand Down