Skip to content
Agentpost robot in sunglasses on a red circleAgentpost

Send security notices

Use this guide when your app should email a principal about changes to its account. IdentityHound records each change in its change feed, and your app decides which notices it sends, in what words, and to whom. IdentityHound sends the emails a principal needs to finish an action: sign-in codes, codes that prove an added address, and invitations.

@agentpost-tools/identityhound-sdk/notices builds four notices from feed events:

Notice Event Who is told by default
identity_linked identity.linked with reason added The principal, at every verified address but the new one
connection_created connection.created The principal
api_key_created api_key.created and api_key.rotated The principal that holds the key
accounts_merged principal.merged, except a guest’s merge Both accounts, each at the addresses its own account had

The helper builds each message. Run its code where your server already reads the feed, such as the loop in Sync records with the change feed, and send with the mail service your app already uses.

Before you start

This page's code continues the script of the pages above: run its blocks after theirs, in the same file. To run them as a script of their own, first copy each helper from the page that defines it, and set each other value, such as a key or an ID, to one you already have.

1. Turn on the notices you send

Turn on each notice you send by naming it in notices. Give true for the default wording, or your own subject, blocks, and footer, each as a value or a function of the notice. A function also receives the default message as defaults, so it can change only part of it:

import type { SecurityNoticeOptions } from '@agentpost-tools/identityhound-sdk/notices';

const noticeOptions: SecurityNoticeOptions = {
  productName: 'Acme',
  accountUrl: 'https://acme.example/account',
  notices: {
    identity_linked: true,
    connection_created: true,
    api_key_created: {
      subject: ({ facts }) =>
        `Key ${facts.prefix} was ${facts.rotated ? 'rotated' : 'created'}`,
    },
    accounts_merged: {
      footer: 'Questions? Reply to this email and our team will help.',
    },
  },
};

productName names your product in the default wording, and accountUrl adds a link to each default message.

Give a notice recipients to replace who it tells, the table’s last column by default. Each recipient names the principalId its message is for and its addresses: of, the principal whose verified email addresses to read, with only or except identity IDs to narrow them. A function receives the notice’s facts and the default recipients as defaults, so it can add to them. It runs synchronously, so read what it needs, such as a workspace’s owners, before you call securityNotice. This example tells the principal at the address it just added too, and tells the owners you pass about a key as well as the principal that holds it:

function withWorkspaceOwners(ownerIds: string[]): SecurityNoticeOptions {
  return {
    ...noticeOptions,
    notices: {
      ...noticeOptions.notices,
      identity_linked: {
        recipients: ({ facts }) => [
          {
            principalId: facts.principalId,
            addresses: { of: facts.principalId },
          },
        ],
      },
      api_key_created: {
        recipients: ({ defaults, facts }) => [
          ...defaults,
          ...ownerIds
            .filter((id) => id !== facts.principalId)
            .map((id) => ({ principalId: id, addresses: { of: id } })),
        ],
        blocks: ({ principalId, facts, defaults }) =>
          principalId === facts.principalId
            ? defaults.blocks
            : [
                {
                  kind: 'text',
                  text: `${facts.displayName ?? 'A member'} of your workspace has a new API key.`,
                },
              ],
      },
    },
  };
}

A wording function receives principalId, the principal its message is for, so each recipient can read its own words.

2. Build a notice from each event

This example reads one page of the feed. Pass its events to securityNotice with noticeOptions or the options returned by withWorkspaceOwners(ownerIds). It returns the notice to send, or undefined for an event it doesn’t cover or a notice you left off:

import { createClient } from '@agentpost-tools/identityhound-sdk';
import { securityNotice } from '@agentpost-tools/identityhound-sdk/notices';

const identity = createClient({ token: key });
const { events } = await identity.events.read({ after: 0 });
const notices = events.flatMap((event) => {
  const notice = securityNotice(event, noticeOptions);
  return notice ? [notice] : [];
});

Each notice has its kind, the facts read from the event, such as a key’s name and prefix, and its recipients. Each recipient has its message: a subject, ordered blocks of text, facts, and link, and a footer. Render them as text, HTML, or both.

3. Read the addresses and send

noticeRecipients reads each recipient’s verified email addresses with your client and pairs them with the message. By default it returns every verified email address that matches the recipient’s filters, and leaves out a recipient with none, such as a principal that signs in only with an API key. Pass choose to pick fewer, such as the first:

import { noticeRecipients } from '@agentpost-tools/identityhound-sdk/notices';

for (const notice of notices) {
  const deliveries = await noticeRecipients(identity, notice, {
    choose: (emails) => emails.slice(0, 1),
  });
  for (const { to, message } of deliveries) {
    const text = [
      ...message.blocks.map((block) =>
        block.kind === 'text'
          ? block.text
          : block.kind === 'facts'
            ? block.rows.map((row) => `${row.label}: ${row.value}`).join('\n')
            : `${block.label}: ${block.url}`,
      ),
      message.footer,
    ].join('\n\n');
    for (const address of to)
      console.log(`to ${address}: ${message.subject}\n\n${text}`);
  }
}

Replace the console.log with your mail service’s send. For a merge, both recipients read the surviving account. The helper uses the moved identity IDs from the event to select addresses for the merged account and exclude those addresses for the survivor.

Save your cursor after a page’s notices are sent, as the change feed guide saves it after a page’s records, so a restart sends a notice again rather than skipping it. The feed keeps events for 30 days.

Check it worked

In a fresh dev project, sign in as ana@acme.test and add and verify a second address at .test. Then run steps 2 and 3 with noticeOptions. The output names the first address and shows the default subject:

to ana@acme.test: A new way to sign in was added to your Acme account

Change feed lists every event type and the read’s parameters.