Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(ntfy): update, clear and delete notifications, send files and trigger on new messages (#15969)

Odai Ahmad3bcc3625339b
diff --git a/bun.lock b/bun.lock
index 268a780215e..ccf465fd93b 100644
--- a/bun.lock
+++ b/bun.lock
@@ -6378,7 +6378,7 @@
},
"packages/pieces/community/ntfy": {
"name": "@activepieces/piece-ntfy",
- "version": "0.3.0",
+ "version": "0.4.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -6387,6 +6387,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/nuelink": {
diff --git a/packages/pieces/community/ntfy/package.json b/packages/pieces/community/ntfy/package.json
index d6fccaffa27..4c817b774c2 100644
--- a/packages/pieces/community/ntfy/package.json
+++ b/packages/pieces/community/ntfy/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-ntfy",
- "version": "0.3.0",
+ "version": "0.4.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
@@ -15,6 +16,7 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
+ "vitest": "3.2.6",
"tslib": "2.6.2"
}
}
diff --git a/packages/pieces/community/ntfy/src/i18n/translation.json b/packages/pieces/community/ntfy/src/i18n/translation.json
index c43197ffdd4..d02af647b79 100644
--- a/packages/pieces/community/ntfy/src/i18n/translation.json
+++ b/packages/pieces/community/ntfy/src/i18n/translation.json
@@ -6,8 +6,30 @@
"Ntfy Access Token": "Ntfy Access Token",
"\n To obtain a token:\n\n 1. Log in to your Ntfy instance.\n 2. Click on Account\n 3. Go under, on Access tokens and click on the button icon to copy your Token or CREATE ACCESS TOKEN if you do not have\n 4. Please pay attention to the expiration time when copying/creating a Token.\n 4. Copy your access token & and paste them into the fields below.\n ": "\n To obtain a token:\n\n 1. Log in to your Ntfy instance.\n 2. Click on Account\n 3. Go under, on Access tokens and click on the button icon to copy your Token or CREATE ACCESS TOKEN if you do not have\n 4. Please pay attention to the expiration time when copying/creating a Token.\n 4. Copy your access token & and paste them into the fields below.\n ",
"Send Notification": "Send Notification",
+ "Send File": "Send File",
+ "Update Notification": "Update Notification",
+ "Clear Notification": "Clear Notification",
+ "Delete Notification": "Delete Notification",
+ "Fetch Messages": "Fetch Messages",
+ "List Scheduled Messages": "List Scheduled Messages",
+ "Publish Message": "Publish Message",
+ "Get Account": "Get Account",
+ "Get Server Stats": "Get Server Stats",
+ "Check Server Health": "Check Server Health",
+ "Get Attachment Info": "Get Attachment Info",
"Custom API Call": "Custom API Call",
"Send a notification to ntfy": "Send a notification to ntfy",
+ "Send a notification with a file from your flow attached. ntfy.sh accepts files up to 2 MB without an account; self-hosted servers allow 15 MB by default.": "Send a notification with a file from your flow attached. ntfy.sh accepts files up to 2 MB without an account; self-hosted servers allow 15 MB by default.",
+ "Replace a notification already sent (or still scheduled) with new content, e.g. a progress update. Fields left empty are not copied from the original. Requires ntfy server v2.16.0 or later.": "Replace a notification already sent (or still scheduled) with new content, e.g. a progress update. Fields left empty are not copied from the original. Requires ntfy server v2.16.0 or later.",
+ "Mark a notification as read and dismiss it from phones and the web app. Requires ntfy server v2.16.0 or later.": "Mark a notification as read and dismiss it from phones and the web app. Requires ntfy server v2.16.0 or later.",
+ "Remove a notification from phones and the web app, or cancel a scheduled one before it is delivered. Requires ntfy server v2.16.0 or later.": "Remove a notification from phones and the web app, or cancel a scheduled one before it is delivered. Requires ntfy server v2.16.0 or later.",
+ "Read messages that the ntfy server has cached for one or more topics. A message sent a few seconds ago may not be listed yet.": "Read messages that the ntfy server has cached for one or more topics. A message sent a few seconds ago may not be listed yet.",
+ "List messages that are scheduled for later delivery and have not been delivered yet. A message scheduled a few seconds ago may not be listed yet.": "List messages that are scheduled for later delivery and have not been delivered yet. A message scheduled a few seconds ago may not be listed yet.",
+ "Publish a notification to a ntfy topic with typed fields.": "Publish a notification to a ntfy topic with typed fields.",
+ "Get the ntfy account behind the connection, with its limits and usage today.": "Get the ntfy account behind the connection, with its limits and usage today.",
+ "Get the total number of messages the ntfy server has published and its current message rate.": "Get the total number of messages the ntfy server has published and its current message rate.",
+ "Check that the ntfy server on the connection is up and accepts the connection's token.": "Check that the ntfy server on the connection is up and accepts the connection's token.",
+ "Check whether a file uploaded with a notification is still on the ntfy server, and its size.": "Check whether a file uploaded with a notification is still on the ntfy server, and its size.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Topic": "Topic",
"Title": "Title",
@@ -18,14 +40,38 @@
"Actions": "Actions",
"Click": "Click",
"Delay": "Delay",
+ "Attachment URL": "Attachment URL",
+ "Attachment File Name": "Attachment File Name",
+ "Markdown": "Markdown",
+ "Email To": "Email To",
+ "Phone Call To": "Phone Call To",
+ "Sequence ID": "Sequence ID",
+ "Server Cache": "Server Cache",
+ "Firebase": "Firebase",
+ "File": "File",
+ "File Name": "File Name",
+ "Click URL": "Click URL",
+ "Icon URL": "Icon URL",
+ "Action Buttons": "Action Buttons",
+ "Topics": "Topics",
+ "Since": "Since",
+ "Priority Filter": "Priority Filter",
+ "Tags Filter": "Tags Filter",
+ "Title Filter": "Title Filter",
+ "Message Filter": "Message Filter",
+ "Include Clear/Delete Events": "Include Clear/Delete Events",
+ "Limit": "Limit",
+ "Do Not Cache": "Do Not Cache",
+ "Do Not Forward to Firebase": "Do Not Forward to Firebase",
+ "Message ID": "Message ID",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
"Body Type": "Body Type",
"Body": "Body",
- "Response is Binary ?": "Response is Binary ?",
- "No Error on Failure": "No Error on Failure",
- "Timeout (in seconds)": "Timeout (in seconds)",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
"Follow redirects": "Follow redirects",
"The topic/channel to send the notification to, e.g. test1": "The topic/channel to send the notification to, e.g. test1",
"The title of the notification": "The title of the notification",
@@ -36,16 +82,63 @@
"Add Action buttons to notifications, see https://docs.ntfy.sh/publish/#action-buttons": "Add Action buttons to notifications, see https://docs.ntfy.sh/publish/#action-buttons",
"You can define which URL to open when a notification is clicked, see https://docs.ntfy.sh/publish/#click-action": "You can define which URL to open when a notification is clicked, see https://docs.ntfy.sh/publish/#click-action",
"Let ntfy send messages at a later date, e.g. 'tomorrow, 10am', see https://docs.ntfy.sh/publish/#scheduled-delivery": "Let ntfy send messages at a later date, e.g. 'tomorrow, 10am', see https://docs.ntfy.sh/publish/#scheduled-delivery",
+ "Public URL of a file to attach, e.g. https://example.com/report.pdf. ntfy does not download it; the apps link to it.": "Public URL of a file to attach, e.g. https://example.com/report.pdf. ntfy does not download it; the apps link to it.",
+ "Name shown for the attachment, e.g. report.pdf. Only used together with an attachment.": "Name shown for the attachment, e.g. report.pdf. Only used together with an attachment.",
+ "Render the message as Markdown (supported in the web app and on Android).": "Render the message as Markdown (supported in the web app and on Android).",
+ "Also send the notification to this email address, e.g. [email protected]. ntfy.sh allows 5 emails a day without an account; with an access token, ntfy.sh only sends to addresses verified in the account settings.": "Also send the notification to this email address, e.g. [email protected]. ntfy.sh allows 5 emails a day without an account; with an access token, ntfy.sh only sends to addresses verified in the account settings.",
+ "Also read the message out in a phone call to this number, e.g. +12223334444, or \"yes\" for your first verified number. Needs a paid ntfy.sh plan (or a self-hosted server with Twilio) and a verified number.": "Also read the message out in a phone call to this number, e.g. +12223334444, or \"yes\" for your first verified number. Needs a paid ntfy.sh plan (or a self-hosted server with Twilio) and a verified number.",
+ "Your own ID for this notification, e.g. backup-job-42, so later steps can update, clear or delete it. Letters, digits, \"-\" and \"_\". Needs ntfy server v2.16.0+.": "Your own ID for this notification, e.g. backup-job-42, so later steps can update, clear or delete it. Letters, digits, \"-\" and \"_\". Needs ntfy server v2.16.0+.",
+ "Leave empty to let the server cache the message (default), so it can be fetched later. \"Do not cache\" delivers it only to clients connected right now.": "Leave empty to let the server cache the message (default), so it can be fetched later. \"Do not cache\" delivers it only to clients connected right now.",
+ "Leave empty to also push through Firebase (default, needed for instant delivery on Google Play Android apps). \"Do not forward\" skips Firebase.": "Leave empty to also push through Firebase (default, needed for instant delivery on Google Play Android apps). \"Do not forward\" skips Firebase.",
+ "The topic name, e.g. backups_home. 1-64 characters: letters, digits, \"-\" and \"_\". Anyone who knows a public topic name can read it, so pick a hard-to-guess name.": "The topic name, e.g. backups_home. 1-64 characters: letters, digits, \"-\" and \"_\". Anyone who knows a public topic name can read it, so pick a hard-to-guess name.",
+ "The file to attach, e.g. the output of a previous step.": "The file to attach, e.g. the output of a previous step.",
+ "Name shown for the file, e.g. report.pdf. Defaults to the file's own name.": "Name shown for the file, e.g. report.pdf. Defaults to the file's own name.",
+ "Notification body, up to 4,096 bytes. Leave empty and ntfy shows \"You received a file: <file name>\".": "Notification body, up to 4,096 bytes. Leave empty and ntfy shows \"You received a file: <file name>\".",
+ "Optional notification title, e.g. \"Backup finished\". Defaults to the topic URL in the apps.": "Optional notification title, e.g. \"Backup finished\". Defaults to the topic URL in the apps.",
+ "How urgently the phone should alert. Leave empty for the default (3).": "How urgently the phone should alert. Leave empty for the default (3).",
+ "Tags shown with the notification. Tags that match an emoji short code (e.g. warning, white_check_mark, rotating_light) are shown as that emoji.": "Tags shown with the notification. Tags that match an emoji short code (e.g. warning, white_check_mark, rotating_light) are shown as that emoji.",
+ "Web page or app link opened when the notification is tapped, e.g. https://example.com/orders/42": "Web page or app link opened when the notification is tapped, e.g. https://example.com/orders/42",
+ "Schedule delivery for later: a duration (30m, 2h, 1 day), a Unix timestamp or natural language like 'tomorrow, 10am'. Between 10 seconds and 3 days on default servers.": "Schedule delivery for later: a duration (30m, 2h, 1 day), a Unix timestamp or natural language like 'tomorrow, 10am'. Between 10 seconds and 3 days on default servers.",
+ "The notification to replace: the Message ID returned when it was sent, or the Sequence ID you gave it, e.g. backup-job-42.": "The notification to replace: the Message ID returned when it was sent, or the Sequence ID you gave it, e.g. backup-job-42.",
+ "The new notification body, up to 4,096 bytes, e.g. \"Download 50% done\".": "The new notification body, up to 4,096 bytes, e.g. \"Download 50% done\".",
+ "URL of a JPEG or PNG image used as the notification icon, e.g. https://example.com/icon.png": "URL of a JPEG or PNG image used as the notification icon, e.g. https://example.com/icon.png",
+ "Up to 3 buttons as a JSON array, e.g. [{\"action\":\"view\",\"label\":\"Open\",\"url\":\"https://example.com\"}]. Types: view, http, broadcast, copy. See https://docs.ntfy.sh/publish/#action-buttons": "Up to 3 buttons as a JSON array, e.g. [{\"action\":\"view\",\"label\":\"Open\",\"url\":\"https://example.com\"}]. Types: view, http, broadcast, copy. See https://docs.ntfy.sh/publish/#action-buttons",
+ "The notification to clear: the Message ID returned when it was sent, or the Sequence ID you gave it, e.g. backup-job-42.": "The notification to clear: the Message ID returned when it was sent, or the Sequence ID you gave it, e.g. backup-job-42.",
+ "The notification to delete or cancel: the Message ID returned when it was sent, or the Sequence ID you gave it, e.g. reminder-42.": "The notification to delete or cancel: the Message ID returned when it was sent, or the Sequence ID you gave it, e.g. reminder-42.",
+ "One topic, or several separated by commas, e.g. alerts,backups_home. Letters, digits, \"-\" and \"_\" only.": "One topic, or several separated by commas, e.g. alerts,backups_home. Letters, digits, \"-\" and \"_\" only.",
+ "How far back to read: a duration (2h), a Unix timestamp, a message ID (messages after it), \"latest\" or \"all\". Defaults to 12h.": "How far back to read: a duration (2h), a Unix timestamp, a message ID (messages after it), \"latest\" or \"all\". Defaults to 12h.",
+ "Only return messages with any of these priorities. Leave empty for all.": "Only return messages with any of these priorities. Leave empty for all.",
+ "Only return messages that have all of these tags, e.g. backup.": "Only return messages that have all of these tags, e.g. backup.",
+ "Only return messages whose title is exactly this text.": "Only return messages whose title is exactly this text.",
+ "Only return messages whose body is exactly this text.": "Only return messages whose body is exactly this text.",
+ "Also return the message_clear and message_delete events created by Clear/Delete Notification.": "Also return the message_clear and message_delete events created by Clear/Delete Notification.",
+ "Maximum number of messages to return (newest first), 1-1000. Defaults to 100.": "Maximum number of messages to return (newest first), 1-1000. Defaults to 100.",
+ "Notification body, up to 4,096 bytes, e.g. \"Backup finished in 4m 12s\". ntfy uses \"triggered\" when empty (or \"You received a file: <name>\" with an attachment).": "Notification body, up to 4,096 bytes, e.g. \"Backup finished in 4m 12s\". ntfy uses \"triggered\" when empty (or \"You received a file: <name>\" with an attachment).",
+ "Whole number 1 (min) to 5 (max, urgent). Leave empty for the default 3.": "Whole number 1 (min) to 5 (max, urgent). Leave empty for the default 3.",
+ "Deliver only to clients connected right now; the message cannot be fetched later. Cannot be combined with Delay.": "Deliver only to clients connected right now; the message cannot be fetched later. Cannot be combined with Delay.",
+ "Skip Firebase push (Google Play Android apps then only get it while connected).": "Skip Firebase push (Google Play Android apps then only get it while connected).",
+ "ID of the message the file was uploaded with, e.g. TCZJOKUErDsd (the \"id\" returned by Send File). A trailing file extension such as .txt is ignored.": "ID of the message the file was uploaded with, e.g. TCZJOKUErDsd (the \"id\" returned by Send File). A trailing file extension such as .txt is ignored.",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "Do not cache": "Do not cache",
+ "Do not forward to Firebase": "Do not forward to Firebase",
+ "1 - Min": "1 - Min",
+ "2 - Low": "2 - Low",
+ "3 - Default": "3 - Default",
+ "4 - High": "4 - High",
+ "5 - Max (urgent)": "5 - Max (urgent)",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "JSON": "JSON",
- "Form Data": "Form Data",
- "Raw": "Raw"
+ "New Message": "New Message",
+ "Triggers when a message is published to a ntfy topic. Needs the server to cache messages (ntfy.sh keeps them 12 hours); messages sent with \"Do not cache\" are never seen.": "Triggers when a message is published to a ntfy topic. Needs the server to cache messages (ntfy.sh keeps them 12 hours); messages sent with \"Do not cache\" are never seen.",
+ "Only trigger for messages with any of these priorities. Leave empty for all.": "Only trigger for messages with any of these priorities. Leave empty for all.",
+ "Only trigger for messages that have all of these tags, e.g. backup.": "Only trigger for messages that have all of these tags, e.g. backup."
}
\ No newline at end of file
diff --git a/packages/pieces/community/ntfy/src/index.ts b/packages/pieces/community/ntfy/src/index.ts
index 346909ac3c1..a964265b14f 100644
--- a/packages/pieces/community/ntfy/src/index.ts
+++ b/packages/pieces/community/ntfy/src/index.ts
@@ -1,55 +1,51 @@
import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import {
- PieceAuth,
- Property,
- createPiece,
-} from '@activepieces/pieces-framework';
+import { createPiece } from '@activepieces/pieces-framework';
import { PieceCategory } from '@activepieces/pieces-framework';
+import { ntfyAuth } from './lib/auth';
+import { ntfyClient } from './lib/common/client';
import { sendNotification } from './lib/actions/send-notification';
+import { publishMessage } from './lib/actions/publish-message';
+import { updateNotification } from './lib/actions/update-notification';
+import { clearNotification } from './lib/actions/clear-notification';
+import { deleteNotification } from './lib/actions/delete-notification';
+import { sendFile } from './lib/actions/send-file';
+import { fetchMessages } from './lib/actions/fetch-messages';
+import { listScheduledMessages } from './lib/actions/list-scheduled-messages';
+import { getAccount } from './lib/actions/get-account';
+import { getServerStats } from './lib/actions/get-server-stats';
+import { checkServerHealth } from './lib/actions/check-server-health';
+import { getAttachmentInfo } from './lib/actions/get-attachment-info';
+import { newMessage } from './lib/triggers/new-message';
-export const ntfyAuth = PieceAuth.CustomAuth({
- description: `
- To obtain a token:
-
- 1. Log in to your Ntfy instance.
- 2. Click on Account
- 3. Go under, on Access tokens and click on the button icon to copy your Token or CREATE ACCESS TOKEN if you do not have
- 4. Please pay attention to the expiration time when copying/creating a Token.
- 4. Copy your access token & and paste them into the fields below.
- `,
- props: {
- base_url: Property.ShortText({
- displayName: 'Server URL',
- description: 'Ntfy Instance URL',
- required: true,
- }),
- access_token: PieceAuth.SecretText({
- displayName: 'Access Token',
- description: 'Ntfy Access Token',
- required: false,
- }),
- },
- required: true,
-});
+export { ntfyAuth };
export const ntfy = createPiece({
displayName: 'ntfy',
description: 'Notification management made easy',
logoUrl: 'https://cdn.activepieces.com/pieces/ntfy.png',
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
categories: [PieceCategory.COMMUNICATION],
auth: ntfyAuth,
authors: ["MyWay","facferreira","la3rence","kishanprmr","MoShizzle","khaledmashaly","abuaboud"],
actions: [
sendNotification,
+ sendFile,
+ updateNotification,
+ clearNotification,
+ deleteNotification,
+ fetchMessages,
+ listScheduledMessages,
+ publishMessage,
+ getAccount,
+ getServerStats,
+ checkServerHealth,
+ getAttachmentInfo,
createCustomApiCallAction({
- baseUrl: (auth) => (auth?.props.base_url ?? ''),
+ baseUrl: (auth) => (auth ? ntfyClient.baseUrl(auth) : ''),
auth: ntfyAuth,
- authMapping: async (auth) => ({
- Authorization: `Bearer ${auth.props.access_token}`,
- }),
+ authMapping: async (auth) => ntfyClient.authHeaders(auth),
}),
],
- triggers: [],
+ triggers: [newMessage],
});
diff --git a/packages/pieces/community/ntfy/src/lib/actions/check-server-health.ts b/packages/pieces/community/ntfy/src/lib/actions/check-server-health.ts
new file mode 100644
index 00000000000..3650dac6a4f
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/check-server-health.ts
@@ -0,0 +1,32 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { ntfyAuth } from '../auth';
+import { ntfyClient } from '../common/client';
+import { serverHealthOutputSchema } from '../output-schemas';
+
+export const checkServerHealth = createAction({
+ auth: ntfyAuth,
+ name: 'ntfy_check_server_health',
+ classification: 'READ',
+ displayName: 'Check Server Health',
+ description: 'Check that the ntfy server on the connection is up and accepts the connection\'s token.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Calls the ntfy server\'s health endpoint with the connection\'s credentials and reports whether it is healthy. Use to confirm a self-hosted server is reachable before publishing; an invalid access token makes it fail with HTTP 401. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: serverHealthOutputSchema,
+ async run({ auth }) {
+ const response = await ntfyClient.request<{ healthy?: boolean }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/v1/health',
+ });
+ return {
+ healthy: response.body?.healthy === true,
+ server_url: ntfyClient.baseUrl(auth),
+ };
+ },
+});
diff --git a/packages/pieces/community/ntfy/src/lib/actions/clear-notification.ts b/packages/pieces/community/ntfy/src/lib/actions/clear-notification.ts
new file mode 100644
index 00000000000..55aaeacd226
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/clear-notification.ts
@@ -0,0 +1,38 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { ntfyAuth } from '../auth';
+import { ntfyClient, NtfyMessage } from '../common/client';
+import { ntfyProps } from '../common/props';
+import { sequenceEventOutputSchema } from '../output-schemas';
+
+export const clearNotification = createAction({
+ auth: ntfyAuth,
+ name: 'clear_notification',
+ classification: 'WRITE',
+ displayName: 'Clear Notification',
+ description:
+ 'Mark a notification as read and dismiss it from phones and the web app. Requires ntfy server v2.16.0 or later.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Marks a delivered notification as read and dismisses it from the notification drawer on subscribed clients, keeping it in their history. Use Delete Notification to remove it entirely or cancel a scheduled one. Needs ntfy server v2.16.0+; ntfy accepts any valid sequence ID, so a wrong ID is not reported. Idempotent: repeating it leaves the notification cleared.',
+ idempotent: true,
+ },
+ props: {
+ topic: ntfyProps.topic(),
+ sequence_id: ntfyProps.sequenceId(
+ 'The notification to clear: the Message ID returned when it was sent, or the Sequence ID you gave it, e.g. backup-job-42.'
+ ),
+ },
+ outputSchema: sequenceEventOutputSchema,
+ async run({ auth, propsValue }) {
+ const topic = ntfyClient.validateId({ value: propsValue.topic, label: 'Topic' });
+ const sequenceId = ntfyClient.validateId({ value: propsValue.sequence_id, label: 'Sequence ID' });
+ const response = await ntfyClient.request<NtfyMessage>({
+ auth,
+ method: HttpMethod.PUT,
+ path: `/${topic}/${sequenceId}/clear`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/ntfy/src/lib/actions/delete-notification.ts b/packages/pieces/community/ntfy/src/lib/actions/delete-notification.ts
new file mode 100644
index 00000000000..3731b53acdd
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/delete-notification.ts
@@ -0,0 +1,38 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { ntfyAuth } from '../auth';
+import { ntfyClient, NtfyMessage } from '../common/client';
+import { ntfyProps } from '../common/props';
+import { sequenceEventOutputSchema } from '../output-schemas';
+
+export const deleteNotification = createAction({
+ auth: ntfyAuth,
+ name: 'delete_notification',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Notification',
+ description:
+ 'Remove a notification from phones and the web app, or cancel a scheduled one before it is delivered. Requires ntfy server v2.16.0 or later.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Deletes a notification by sequence ID: a scheduled message is removed from the server and never delivered, and a delivered one is removed from subscribed clients. Use Clear Notification to only mark it read. Needs ntfy server v2.16.0+; ntfy accepts any valid sequence ID, so a wrong ID is not reported. Idempotent: repeating it leaves the notification deleted.',
+ idempotent: true,
+ },
+ props: {
+ topic: ntfyProps.topic(),
+ sequence_id: ntfyProps.sequenceId(
+ 'The notification to delete or cancel: the Message ID returned when it was sent, or the Sequence ID you gave it, e.g. reminder-42.'
+ ),
+ },
+ outputSchema: sequenceEventOutputSchema,
+ async run({ auth, propsValue }) {
+ const topic = ntfyClient.validateId({ value: propsValue.topic, label: 'Topic' });
+ const sequenceId = ntfyClient.validateId({ value: propsValue.sequence_id, label: 'Sequence ID' });
+ const response = await ntfyClient.request<NtfyMessage>({
+ auth,
+ method: HttpMethod.DELETE,
+ path: `/${topic}/${sequenceId}`,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/ntfy/src/lib/actions/fetch-messages.ts b/packages/pieces/community/ntfy/src/lib/actions/fetch-messages.ts
new file mode 100644
index 00000000000..df3a3b0b686
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/fetch-messages.ts
@@ -0,0 +1,95 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { ntfyAuth } from '../auth';
+import { ntfyClient } from '../common/client';
+import { ntfyProps, PRIORITY_OPTIONS } from '../common/props';
+import { fetchMessagesOutputSchema } from '../output-schemas';
+
+export const fetchMessages = createAction({
+ auth: ntfyAuth,
+ name: 'fetch_messages',
+ classification: 'SEARCH',
+ displayName: 'Fetch Messages',
+ description:
+ 'Read messages that the ntfy server has cached for one or more topics. A message sent a few seconds ago may not be listed yet.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Reads cached messages from one or more ntfy topics, newest first, optionally only since a duration, Unix timestamp or message ID, and filtered by priority, tags, exact title or exact message. "latest" returns only the newest entry, which is dropped when it is a clear/delete event and those are not included. Use to look back at what was sent; use List Scheduled Messages for pending ones. Only works while the server caches messages (12 hours on ntfy.sh); ntfy.sh writes its cache in batches, so a message published 1-3 seconds earlier may not be returned yet. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ topics: ntfyProps.topics(),
+ since: Property.ShortText({
+ displayName: 'Since',
+ description:
+ 'How far back to read: a duration (2h), a Unix timestamp, a message ID (messages after it), "latest" or "all". Defaults to 12h.',
+ required: false,
+ defaultValue: '12h',
+ }),
+ priority: Property.StaticMultiSelectDropdown({
+ displayName: 'Priority Filter',
+ description: 'Only return messages with any of these priorities. Leave empty for all.',
+ required: false,
+ options: { options: PRIORITY_OPTIONS },
+ }),
+ tags: Property.Array({
+ displayName: 'Tags Filter',
+ description: 'Only return messages that have all of these tags, e.g. backup.',
+ required: false,
+ }),
+ title: Property.ShortText({
+ displayName: 'Title Filter',
+ description: 'Only return messages whose title is exactly this text.',
+ required: false,
+ }),
+ message: Property.ShortText({
+ displayName: 'Message Filter',
+ description: 'Only return messages whose body is exactly this text.',
+ required: false,
+ }),
+ include_events: Property.Checkbox({
+ displayName: 'Include Clear/Delete Events',
+ description: 'Also return the message_clear and message_delete events created by Clear/Delete Notification.',
+ required: false,
+ defaultValue: false,
+ }),
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: 'Maximum number of messages to return (newest first), 1-1000. Defaults to 100.',
+ required: false,
+ defaultValue: 100,
+ }),
+ },
+ outputSchema: fetchMessagesOutputSchema,
+ async run({ auth, propsValue }) {
+ const topics = ntfyClient.validateTopicList(propsValue.topics);
+ const since = propsValue.since?.trim() || '12h';
+ const limit = propsValue.limit ?? 100;
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {
+ throw new Error('Limit must be a whole number from 1 to 1000.');
+ }
+ const result = await ntfyClient.pollMessages({
+ auth,
+ topics,
+ since,
+ filters: {
+ priority: ntfyClient.normalizePriorityFilter(propsValue.priority),
+ tags: ntfyClient.normalizeTags(propsValue.tags),
+ title: propsValue.title?.trim() || undefined,
+ message: propsValue.message?.trim() || undefined,
+ },
+ });
+ const allowedEvents = propsValue.include_events
+ ? ['message', 'message_clear', 'message_delete']
+ : ['message'];
+ const matched = ntfyClient.newestFirst(result.messages.filter((m) => allowedEvents.includes(m.event)));
+ const messages = matched.slice(0, limit);
+ return {
+ messages,
+ count: messages.length,
+ total_matched: matched.length,
+ has_more: matched.length > messages.length,
+ server_truncated: result.truncated,
+ };
+ },
+});
diff --git a/packages/pieces/community/ntfy/src/lib/actions/get-account.ts b/packages/pieces/community/ntfy/src/lib/actions/get-account.ts
new file mode 100644
index 00000000000..e76441b04d9
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/get-account.ts
@@ -0,0 +1,90 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { ntfyAuth } from '../auth';
+import { ntfyClient } from '../common/client';
+import { accountOutputSchema } from '../output-schemas';
+
+export const getAccount = createAction({
+ auth: ntfyAuth,
+ name: 'ntfy_get_account',
+ classification: 'READ',
+ displayName: 'Get Account',
+ description: 'Get the ntfy account behind the connection, with its limits and usage today.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns the ntfy account the connection uses (or the anonymous visitor when there is no token): username, role, tier, daily limits and how much of each was used today, plus reserved topic names. Use to check remaining message/email quota or attachment size limits before publishing. Never returns tokens, emails or phone numbers. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: accountOutputSchema,
+ async run({ auth }) {
+ const response = await ntfyClient.request<AccountResponse>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/v1/account',
+ });
+ const account = response.body ?? {};
+ const limits = account.limits ?? {};
+ const stats = account.stats ?? {};
+ return {
+ username: account.username ?? null,
+ role: account.role ?? null,
+ tier_code: account.tier?.code ?? null,
+ tier_name: account.tier?.name ?? null,
+ limits_basis: limits.basis ?? null,
+ limits_messages: limits.messages ?? null,
+ limits_messages_expiry_duration: limits.messages_expiry_duration ?? null,
+ limits_emails: limits.emails ?? null,
+ limits_calls: limits.calls ?? null,
+ limits_reservations: limits.reservations ?? null,
+ limits_attachment_file_size: limits.attachment_file_size ?? null,
+ limits_attachment_total_size: limits.attachment_total_size ?? null,
+ limits_attachment_expiry_duration: limits.attachment_expiry_duration ?? null,
+ limits_attachment_bandwidth: limits.attachment_bandwidth ?? null,
+ stats_messages: stats.messages ?? null,
+ stats_messages_remaining: stats.messages_remaining ?? null,
+ stats_emails: stats.emails ?? null,
+ stats_emails_remaining: stats.emails_remaining ?? null,
+ stats_calls: stats.calls ?? null,
+ stats_calls_remaining: stats.calls_remaining ?? null,
+ stats_reservations: stats.reservations ?? null,
+ stats_reservations_remaining: stats.reservations_remaining ?? null,
+ stats_attachment_total_size: stats.attachment_total_size ?? null,
+ stats_attachment_total_size_remaining: stats.attachment_total_size_remaining ?? null,
+ reserved_topics: (account.reservations ?? []).map((r) => r.topic).join(','),
+ };
+ },
+});
+
+type AccountResponse = {
+ username?: string;
+ role?: string;
+ tier?: { code?: string; name?: string };
+ limits?: Partial<Record<LimitKey, number>> & { basis?: string };
+ stats?: Partial<Record<StatKey, number>>;
+ reservations?: { topic: string }[];
+};
+
+type LimitKey =
+ | 'messages'
+ | 'messages_expiry_duration'
+ | 'emails'
+ | 'calls'
+ | 'reservations'
+ | 'attachment_total_size'
+ | 'attachment_file_size'
+ | 'attachment_expiry_duration'
+ | 'attachment_bandwidth';
+
+type StatKey =
+ | 'messages'
+ | 'messages_remaining'
+ | 'emails'
+ | 'emails_remaining'
+ | 'calls'
+ | 'calls_remaining'
+ | 'reservations'
+ | 'reservations_remaining'
+ | 'attachment_total_size'
+ | 'attachment_total_size_remaining';
diff --git a/packages/pieces/community/ntfy/src/lib/actions/get-attachment-info.ts b/packages/pieces/community/ntfy/src/lib/actions/get-attachment-info.ts
new file mode 100644
index 00000000000..ef6e0549c37
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/get-attachment-info.ts
@@ -0,0 +1,56 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { ntfyAuth } from '../auth';
+import { ntfyClient, NtfyRequestError } from '../common/client';
+import { attachmentInfoOutputSchema } from '../output-schemas';
+
+export const getAttachmentInfo = createAction({
+ auth: ntfyAuth,
+ name: 'ntfy_get_attachment_info',
+ classification: 'READ',
+ displayName: 'Get Attachment Info',
+ description: 'Check whether a file uploaded with a notification is still on the ntfy server, and its size.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Checks a file attachment that was uploaded to the ntfy server with a message (not attachment URLs) without downloading it, returning whether it still exists, its size and its download URL. Use before sharing an attachment link; uploaded files expire (3 hours by default). Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ message_id: Property.ShortText({
+ displayName: 'Message ID',
+ description:
+ 'ID of the message the file was uploaded with, e.g. TCZJOKUErDsd (the "id" returned by Send File). A trailing file extension such as .txt is ignored.',
+ required: true,
+ }),
+ },
+ outputSchema: attachmentInfoOutputSchema,
+ async run({ auth, propsValue }) {
+ const messageId = ntfyClient.validateId({
+ value: (propsValue.message_id ?? '').trim().replace(/\.[A-Za-z0-9]{1,16}$/, ''),
+ label: 'Message ID',
+ });
+ const url = `${ntfyClient.baseUrl(auth)}/file/${messageId}`;
+ try {
+ const response = await ntfyClient.request({
+ auth,
+ method: HttpMethod.HEAD,
+ path: `/file/${messageId}`,
+ });
+ const length = Number(ntfyClient.firstHeader({ headers: response.headers, name: 'content-length' }));
+ return {
+ message_id: messageId,
+ exists: true,
+ size_bytes: Number.isFinite(length) ? length : null,
+ content_type: ntfyClient.firstHeader({ headers: response.headers, name: 'content-type' }) ?? null,
+ url,
+ };
+ } catch (error) {
+ if (error instanceof NtfyRequestError && error.status === 404) {
+ return { message_id: messageId, exists: false, size_bytes: null, content_type: null, url };
+ }
+ throw error;
+ }
+ },
+});
+
diff --git a/packages/pieces/community/ntfy/src/lib/actions/get-server-stats.ts b/packages/pieces/community/ntfy/src/lib/actions/get-server-stats.ts
new file mode 100644
index 00000000000..002604b6d74
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/get-server-stats.ts
@@ -0,0 +1,32 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { ntfyAuth } from '../auth';
+import { ntfyClient } from '../common/client';
+import { serverStatsOutputSchema } from '../output-schemas';
+
+export const getServerStats = createAction({
+ auth: ntfyAuth,
+ name: 'ntfy_get_server_stats',
+ classification: 'READ',
+ displayName: 'Get Server Stats',
+ description: 'Get the total number of messages the ntfy server has published and its current message rate.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Returns server-wide statistics for the ntfy server on the connection: total messages published and the recent average messages per second. Use to gauge server load; use Get Account for this account\'s own quota. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: serverStatsOutputSchema,
+ async run({ auth }) {
+ const response = await ntfyClient.request<{ messages?: number; messages_rate?: number }>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/v1/stats',
+ });
+ return {
+ messages: response.body?.messages ?? null,
+ messages_rate: response.body?.messages_rate ?? null,
+ };
+ },
+});
diff --git a/packages/pieces/community/ntfy/src/lib/actions/list-scheduled-messages.ts b/packages/pieces/community/ntfy/src/lib/actions/list-scheduled-messages.ts
new file mode 100644
index 00000000000..d7b4ec107cf
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/list-scheduled-messages.ts
@@ -0,0 +1,32 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { ntfyAuth } from '../auth';
+import { ntfyClient } from '../common/client';
+import { ntfyProps } from '../common/props';
+import { listScheduledMessagesOutputSchema } from '../output-schemas';
+
+export const listScheduledMessages = createAction({
+ auth: ntfyAuth,
+ name: 'list_scheduled_messages',
+ classification: 'SEARCH',
+ displayName: 'List Scheduled Messages',
+ description:
+ 'List messages that are scheduled for later delivery and have not been delivered yet. A message scheduled a few seconds ago may not be listed yet.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the messages on one or more ntfy topics that were published with a delay and are still waiting to be delivered, soonest first. Use before cancelling one with Delete Notification or replacing it with Update Notification; use Fetch Messages for delivered ones. ntfy.sh writes its cache in batches, so a message scheduled 1-3 seconds earlier may not be listed yet. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ topics: ntfyProps.topics(),
+ },
+ outputSchema: listScheduledMessagesOutputSchema,
+ async run({ auth, propsValue }) {
+ const topics = ntfyClient.validateTopicList(propsValue.topics);
+ const result = await ntfyClient.pollMessages({ auth, topics, since: 'all', scheduled: true });
+ const messages = result.messages
+ .filter((m) => m.event === 'message' && m.time > result.serverNow)
+ .sort((a, b) => a.time - b.time);
+ return { messages, count: messages.length, server_truncated: result.truncated };
+ },
+});
diff --git a/packages/pieces/community/ntfy/src/lib/actions/publish-message.ts b/packages/pieces/community/ntfy/src/lib/actions/publish-message.ts
new file mode 100644
index 00000000000..44e47413b2b
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/publish-message.ts
@@ -0,0 +1,67 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { ntfyAuth } from '../auth';
+import { ntfyClient, NtfyMessage } from '../common/client';
+import { ntfyProps } from '../common/props';
+import { publishedMessageOutputSchema } from '../output-schemas';
+
+export const publishMessage = createAction({
+ auth: ntfyAuth,
+ name: 'ntfy_publish_message',
+ classification: 'WRITE',
+ displayName: 'Publish Message',
+ description: 'Publish a notification to a ntfy topic with typed fields.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Publishes a push notification to one ntfy topic as JSON: message, title, priority 1-5, tags, click URL, icon, attachment URL, Markdown, up to 3 action buttons, email or phone-call forwarding, a scheduled delay (not combinable with email or disable_cache), and an optional sequence_id for later update/clear/delete. Use this to alert someone; use Update Notification to change one already sent. Not idempotent: each call publishes a new message.',
+ idempotent: false,
+ },
+ props: {
+ topic: ntfyProps.topic(),
+ message: ntfyProps.optionalMessage(
+ 'Notification body, up to 4,096 bytes, e.g. "Backup finished in 4m 12s". ntfy uses "triggered" when empty (or "You received a file: <name>" with an attachment).'
+ ),
+ title: ntfyProps.title(),
+ priority: Property.Number({
+ displayName: 'Priority',
+ description: 'Whole number 1 (min) to 5 (max, urgent). Leave empty for the default 3.',
+ required: false,
+ }),
+ tags: ntfyProps.tags(),
+ click: ntfyProps.click(),
+ icon: ntfyProps.icon(),
+ attach: ntfyProps.attach(),
+ filename: ntfyProps.filename(),
+ markdown: ntfyProps.markdown(),
+ actions: ntfyProps.actions(),
+ delay: ntfyProps.delay(),
+ email: ntfyProps.email(),
+ call: ntfyProps.call(),
+ sequence_id: ntfyProps.publishSequenceId(),
+ disable_cache: Property.Checkbox({
+ displayName: 'Do Not Cache',
+ description: 'Deliver only to clients connected right now; the message cannot be fetched later. Cannot be combined with Delay.',
+ required: false,
+ defaultValue: false,
+ }),
+ disable_firebase: Property.Checkbox({
+ displayName: 'Do Not Forward to Firebase',
+ description: 'Skip Firebase push (Google Play Android apps then only get it while connected).',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: publishedMessageOutputSchema,
+ async run({ auth, propsValue }) {
+ const body = ntfyClient.buildJsonPublishBody(propsValue);
+ const response = await ntfyClient.request<NtfyMessage>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/',
+ headers: { 'Content-Type': 'application/json' },
+ body,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/ntfy/src/lib/actions/send-file.ts b/packages/pieces/community/ntfy/src/lib/actions/send-file.ts
new file mode 100644
index 00000000000..0d984e7b303
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/send-file.ts
@@ -0,0 +1,82 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { ntfyAuth } from '../auth';
+import { ntfyClient, NtfyMessage } from '../common/client';
+import { ntfyProps } from '../common/props';
+import { sentFileOutputSchema } from '../output-schemas';
+
+export const sendFile = createAction({
+ auth: ntfyAuth,
+ name: 'send_file',
+ classification: 'WRITE',
+ displayName: 'Send File',
+ description:
+ 'Send a notification with a file from your flow attached. ntfy.sh accepts files up to 2 MB without an account; self-hosted servers allow 15 MB by default.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Uploads a file from the flow to the ntfy server and publishes it as a notification attachment, with an optional message, title, priority, tags and click URL. Agents attaching a file by URL should use Publish Message with an attachment URL instead. Not idempotent: each call uploads the file again and sends a new notification.',
+ idempotent: false,
+ },
+ props: {
+ topic: ntfyProps.topic(),
+ file: Property.File({
+ displayName: 'File',
+ description: 'The file to attach, e.g. the output of a previous step.',
+ required: true,
+ }),
+ filename: Property.ShortText({
+ displayName: 'File Name',
+ description: 'Name shown for the file, e.g. report.pdf. Defaults to the file\'s own name.',
+ required: false,
+ }),
+ message: ntfyProps.optionalMessage(
+ 'Notification body, up to 4,096 bytes. Leave empty and ntfy shows "You received a file: <file name>".'
+ ),
+ title: ntfyProps.title(),
+ priority: ntfyProps.priority(),
+ tags: ntfyProps.tags(),
+ click: ntfyProps.click(),
+ delay: ntfyProps.delay(),
+ },
+ outputSchema: sentFileOutputSchema,
+ async run({ auth, propsValue }) {
+ const topic = ntfyClient.validateId({ value: propsValue.topic, label: 'Topic' });
+ const file = propsValue.file;
+ const data = fileBytes(file);
+ const filename = propsValue.filename?.trim() || file.filename || 'file';
+ const priority = ntfyClient.parsePriority(propsValue.priority);
+ const tags = ntfyClient.normalizeTags(propsValue.tags);
+ const message = propsValue.message?.trim() ? propsValue.message : undefined;
+ const title = propsValue.title?.trim() || undefined;
+ const click = propsValue.click?.trim() || undefined;
+ const delay = propsValue.delay?.trim() || undefined;
+ const response = await ntfyClient.request<NtfyMessage>({
+ auth,
+ method: HttpMethod.PUT,
+ path: `/${topic}`,
+ headers: {
+ 'Content-Type': 'application/octet-stream',
+ 'X-Filename': ntfyClient.encodeToRFC2047(filename),
+ ...(message ? { 'X-Message': ntfyClient.encodeToRFC2047(message) } : {}),
+ ...(title ? { 'X-Title': ntfyClient.encodeToRFC2047(title) } : {}),
+ ...(priority !== undefined ? { 'X-Priority': String(priority) } : {}),
+ ...(tags ? { 'X-Tags': ntfyClient.headerValue(tags.join(',')) } : {}),
+ ...(click ? { 'X-Click': ntfyClient.headerValue(click) } : {}),
+ ...(delay ? { 'X-Delay': ntfyClient.headerValue(delay) } : {}),
+ },
+ body: data,
+ });
+ return response.body;
+ },
+});
+
+function fileBytes(file: { data?: unknown; base64?: unknown }): Buffer {
+ if (Buffer.isBuffer(file.data)) {
+ return file.data;
+ }
+ if (typeof file.base64 === 'string' && file.base64.length > 0) {
+ return Buffer.from(file.base64, 'base64');
+ }
+ throw new Error('The File input is empty. Map a file from a previous step or upload one.');
+}
diff --git a/packages/pieces/community/ntfy/src/lib/actions/send-notification.ts b/packages/pieces/community/ntfy/src/lib/actions/send-notification.ts
index 4f2f057d48d..8afde1cce09 100644
--- a/packages/pieces/community/ntfy/src/lib/actions/send-notification.ts
+++ b/packages/pieces/community/ntfy/src/lib/actions/send-notification.ts
@@ -4,21 +4,19 @@ import {
httpClient,
HttpMethod,
} from '@activepieces/pieces-common';
-import { ntfyAuth } from '../..';
+import { ntfyAuth } from '../auth';
+import { ntfyClient } from '../common/client';
+import { ntfyProps } from '../common/props';
import { sendNotificationActionOutputSchema } from '../output-schemas';
-const encodeToRFC2047 = (text: string) => {
- return `=?UTF-8?B?${Buffer.from(text, 'utf-8').toString('base64')}?=`;
-};
-
export const sendNotification = createAction({
auth: ntfyAuth,
name: 'send_notification',
classification: 'WRITE',
displayName: 'Send Notification',
description: 'Send a notification to ntfy',
- audience: 'both',
- aiMetadata: { description: 'Publishes a push notification to a ntfy topic on the configured ntfy server, optionally with a title, priority (1-5), tags, icon, click-through URL, action buttons, or scheduled delay. Choose this to alert a user or channel via ntfy. Requires a topic and message; each call sends a new notification (not idempotent).', idempotent: false },
+ audience: 'human',
+ aiMetadata: { description: 'Publishes a push notification to a ntfy topic using ntfy\'s header format, optionally with a title, priority, tags, icon, click URL, action buttons, attachment URL, Markdown, email, sequence ID or scheduled delay. Agents should prefer Publish Message (ntfy_publish_message), which takes typed fields. Not idempotent: each call sends a new notification.', idempotent: false },
props: {
topic: Property.ShortText({
displayName: 'Topic',
@@ -70,6 +68,26 @@ export const sendNotification = createAction({
"Let ntfy send messages at a later date, e.g. 'tomorrow, 10am', see https://docs.ntfy.sh/publish/#scheduled-delivery",
required: false,
}),
+ attach: ntfyProps.attach(),
+ filename: ntfyProps.filename(),
+ markdown: ntfyProps.markdown(),
+ email: ntfyProps.email(),
+ call: ntfyProps.call(),
+ sequence_id: ntfyProps.publishSequenceId(),
+ cache: Property.StaticDropdown({
+ displayName: 'Server Cache',
+ description:
+ 'Leave empty to let the server cache the message (default), so it can be fetched later. "Do not cache" delivers it only to clients connected right now.',
+ required: false,
+ options: { options: [{ label: 'Do not cache', value: 'no' }] },
+ }),
+ firebase: Property.StaticDropdown({
+ displayName: 'Firebase',
+ description:
+ 'Leave empty to also push through Firebase (default, needed for instant delivery on Google Play Android apps). "Do not forward" skips Firebase.',
+ required: false,
+ options: { options: [{ label: 'Do not forward to Firebase', value: 'no' }] },
+ }),
},
outputSchema: sendNotificationActionOutputSchema,
async run({ auth, propsValue }) {
@@ -77,16 +95,6 @@ export const sendNotification = createAction({
const accessToken = auth.props.access_token;
const topic = propsValue.topic;
- let title = propsValue.title;
- let message = propsValue.message;
- title = encodeToRFC2047(title as string);
- message = encodeToRFC2047(message as string);
- const priority = propsValue.priority;
- const tags = propsValue.tags;
- const icon = propsValue.icon;
- const actions = propsValue.actions;
- const click = propsValue.click;
- const delay = propsValue.delay;
return await httpClient.sendRequest({
method: HttpMethod.POST,
@@ -97,16 +105,24 @@ export const sendNotification = createAction({
token: accessToken,
},
}),
- headers: {
- 'X-Message': message,
- 'X-Title': title,
- 'X-Priority': priority,
- 'X-Tags': tags?.join(','),
- 'X-Icon': icon,
- 'X-Actions': actions,
- 'X-Click': click,
- 'X-Delay': delay,
- },
+ headers: ntfyClient.buildSendNotificationHeaders({
+ message: propsValue.message,
+ title: propsValue.title,
+ priority: propsValue.priority,
+ tags: propsValue.tags,
+ icon: propsValue.icon,
+ actions: propsValue.actions,
+ click: propsValue.click,
+ delay: propsValue.delay,
+ attach: propsValue.attach,
+ filename: propsValue.filename,
+ markdown: propsValue.markdown,
+ email: propsValue.email,
+ call: propsValue.call,
+ sequence_id: propsValue.sequence_id,
+ cache: propsValue.cache,
+ firebase: propsValue.firebase,
+ }),
});
},
});
diff --git a/packages/pieces/community/ntfy/src/lib/actions/update-notification.ts b/packages/pieces/community/ntfy/src/lib/actions/update-notification.ts
new file mode 100644
index 00000000000..505262489a2
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/actions/update-notification.ts
@@ -0,0 +1,53 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { ntfyAuth } from '../auth';
+import { ntfyClient, NtfyMessage } from '../common/client';
+import { ntfyProps } from '../common/props';
+import { publishedMessageOutputSchema } from '../output-schemas';
+
+export const updateNotification = createAction({
+ auth: ntfyAuth,
+ name: 'update_notification',
+ classification: 'WRITE',
+ displayName: 'Update Notification',
+ description:
+ 'Replace a notification already sent (or still scheduled) with new content, e.g. a progress update. Fields left empty are not copied from the original. Requires ntfy server v2.16.0 or later.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Replaces an earlier notification on subscribed phones and web apps by publishing a new message with the same sequence ID; if the original is still scheduled, the server deletes it and schedules this one instead. The new message fully replaces the old one, so resend every field that should stay (title, tags, priority). Use for progress or status updates; use Publish Message for a new alert. Needs ntfy server v2.16.0+. Not idempotent: each call appends a new message to the topic.',
+ idempotent: false,
+ },
+ props: {
+ topic: ntfyProps.topic(),
+ sequence_id: ntfyProps.sequenceId(
+ 'The notification to replace: the Message ID returned when it was sent, or the Sequence ID you gave it, e.g. backup-job-42.'
+ ),
+ message: ntfyProps.requiredMessage('The new notification body, up to 4,096 bytes, e.g. "Download 50% done".'),
+ title: ntfyProps.title(),
+ priority: ntfyProps.priority(),
+ tags: ntfyProps.tags(),
+ click: ntfyProps.click(),
+ icon: ntfyProps.icon(),
+ attach: ntfyProps.attach(),
+ filename: ntfyProps.filename(),
+ markdown: ntfyProps.markdown(),
+ actions: ntfyProps.actions(),
+ delay: ntfyProps.delay(),
+ },
+ outputSchema: publishedMessageOutputSchema,
+ async run({ auth, propsValue }) {
+ const body = ntfyClient.buildJsonPublishBody({
+ ...propsValue,
+ sequence_id: ntfyClient.validateId({ value: propsValue.sequence_id, label: 'Sequence ID' }),
+ });
+ const response = await ntfyClient.request<NtfyMessage>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/',
+ headers: { 'Content-Type': 'application/json' },
+ body,
+ });
+ return response.body;
+ },
+});
diff --git a/packages/pieces/community/ntfy/src/lib/auth.ts b/packages/pieces/community/ntfy/src/lib/auth.ts
new file mode 100644
index 00000000000..f9778b9038e
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/auth.ts
@@ -0,0 +1,26 @@
+import { PieceAuth, Property } from '@activepieces/pieces-framework';
+
+export const ntfyAuth = PieceAuth.CustomAuth({
+ description: `
+ To obtain a token:
+
+ 1. Log in to your Ntfy instance.
+ 2. Click on Account
+ 3. Go under, on Access tokens and click on the button icon to copy your Token or CREATE ACCESS TOKEN if you do not have
+ 4. Please pay attention to the expiration time when copying/creating a Token.
+ 4. Copy your access token & and paste them into the fields below.
+ `,
+ props: {
+ base_url: Property.ShortText({
+ displayName: 'Server URL',
+ description: 'Ntfy Instance URL',
+ required: true,
+ }),
+ access_token: PieceAuth.SecretText({
+ displayName: 'Access Token',
+ description: 'Ntfy Access Token',
+ required: false,
+ }),
+ },
+ required: true,
+});
diff --git a/packages/pieces/community/ntfy/src/lib/common/client.ts b/packages/pieces/community/ntfy/src/lib/common/client.ts
new file mode 100644
index 00000000000..8055e537410
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/common/client.ts
@@ -0,0 +1,554 @@
+import {
+ httpClient,
+ HttpHeaders,
+ HttpMethod,
+ HttpRequest,
+ HttpResponse,
+ QueryParams,
+} from '@activepieces/pieces-common';
+import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
+import { ntfyAuth } from '../auth';
+
+const NTFY_ID_PATTERN = /^[-_A-Za-z0-9]{1,64}$/;
+const CURSOR_OVERLAP_SECONDS = 60;
+
+function encodeToRFC2047(text: string): string {
+ return `=?UTF-8?B?${Buffer.from(text, 'utf-8').toString('base64')}?=`;
+}
+
+function baseUrl(auth: NtfyAuthValue): string {
+ const raw = (auth.props.base_url ?? '').trim().replace(/\/+$/, '');
+ if (!URL.canParse(raw)) {
+ throw new Error(
+ 'The Server URL on the ntfy connection is not a valid URL. Use the full address, e.g. https://ntfy.sh'
+ );
+ }
+ const { protocol, search, hash, username, password } = new URL(raw);
+ if (protocol !== 'https:' && protocol !== 'http:') {
+ throw new Error('The Server URL on the ntfy connection must start with https:// or http://');
+ }
+ if (search.length > 0 || hash.length > 0 || raw.includes('?') || raw.includes('#')) {
+ throw new Error(
+ 'The Server URL on the ntfy connection must not contain "?" or "#". Use only the server address, e.g. https://ntfy.example.com'
+ );
+ }
+ if (username.length > 0 || password.length > 0) {
+ throw new Error(
+ 'The Server URL on the ntfy connection must not contain a user name or password. Put the access token in the Access Token field.'
+ );
+ }
+ return raw;
+}
+
+function authHeaders(auth: NtfyAuthValue): Record<string, string> {
+ const token = auth.props.access_token;
+ if (typeof token === 'string' && token.trim().length > 0) {
+ return { Authorization: `Bearer ${token.trim()}` };
+ }
+ return {};
+}
+
+function validateId({ value, label }: { value: unknown; label: string }): string {
+ const id = typeof value === 'string' ? value.trim() : '';
+ if (!NTFY_ID_PATTERN.test(id)) {
+ throw new Error(
+ `${label} "${String(value ?? '')}" is not valid. ntfy only accepts 1-64 letters, digits, "-" and "_".`
+ );
+ }
+ return id;
+}
+
+function validateTopicList(value: unknown): string {
+ const raw = typeof value === 'string' ? value : '';
+ const topics = raw
+ .split(',')
+ .map((t) => t.trim())
+ .filter((t) => t.length > 0);
+ if (topics.length === 0) {
+ throw new Error('Topic is required. Separate several topics with commas, e.g. alerts,backups');
+ }
+ return topics.map((t) => validateId({ value: t, label: 'Topic' })).join(',');
+}
+
+function parsePriority(value: unknown): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const n = typeof value === 'number' ? value : Number(String(value).trim());
+ if (!Number.isInteger(n) || n < 1 || n > 5) {
+ throw new Error(`Priority must be a whole number from 1 (min) to 5 (max), got "${String(value)}".`);
+ }
+ return n;
+}
+
+function normalizePriorityFilter(value: unknown): number[] | undefined {
+ const list = toList(value);
+ if (list.length === 0) {
+ return undefined;
+ }
+ const priorities = list.map((v) => parsePriority(v)).filter((v): v is number => v !== undefined);
+ return priorities.length > 0 ? priorities : undefined;
+}
+
+function normalizeTags(value: unknown): string[] | undefined {
+ const tags = toList(value)
+ .map((t) => String(t ?? '').trim())
+ .filter((t) => t.length > 0);
+ return tags.length > 0 ? tags : undefined;
+}
+
+function toList(value: unknown): unknown[] {
+ if (value === undefined || value === null || value === '') {
+ return [];
+ }
+ if (Array.isArray(value)) {
+ return value.flatMap((item) => (typeof item === 'string' ? textToList(item) : [item]));
+ }
+ if (typeof value === 'string') {
+ return textToList(value);
+ }
+ return [value];
+}
+
+function textToList(value: string): unknown[] {
+ const text = value.trim();
+ if (text.startsWith('[')) {
+ const parsed = tryParseJson(text);
+ if (Array.isArray(parsed)) {
+ return parsed;
+ }
+ }
+ return text.split(',');
+}
+
+function newestFirst(messages: NtfyMessage[]): NtfyMessage[] {
+ return [...messages].reverse().sort((a, b) => b.time - a.time);
+}
+
+function headerValue(value: string | undefined): string | undefined {
+ if (value === undefined) {
+ return undefined;
+ }
+ const trimmed = value.trim();
+ if (/^[\x20-\x7e]*$/.test(trimmed)) {
+ return value;
+ }
+ return encodeToRFC2047(trimmed);
+}
+
+function tagsHeader(tags: unknown): string | undefined {
+ if (Array.isArray(tags)) {
+ return headerValue(tags.join(','));
+ }
+ return headerValue(normalizeTags(tags)?.join(','));
+}
+
+function parseActions(value: unknown): Record<string, unknown>[] | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed = typeof value === 'string' ? parseJsonOrThrow(value) : value;
+ if (!Array.isArray(parsed)) {
+ throw new Error('Action Buttons must be a JSON array of action objects.');
+ }
+ if (parsed.length === 0) {
+ return undefined;
+ }
+ if (parsed.length > 3) {
+ throw new Error('ntfy allows at most 3 action buttons per notification.');
+ }
+ return parsed.map((item) => {
+ if (!isRecord(item)) {
+ throw new Error('Each action button must be a JSON object with at least "action" and "label".');
+ }
+ return item;
+ });
+}
+
+function buildSendNotificationHeaders(input: SendNotificationHeaderInput): HttpHeaders {
+ const attach = nonEmpty(input.attach);
+ const filename = nonEmpty(input.filename);
+ const email = nonEmpty(input.email);
+ const call = nonEmpty(input.call);
+ const sequenceId = nonEmpty(input.sequence_id);
+ return {
+ 'X-Message': encodeToRFC2047(input.message),
+ ...(typeof input.title === 'string' && input.title.length > 0
+ ? { 'X-Title': encodeToRFC2047(input.title) }
+ : {}),
+ 'X-Priority': headerValue(input.priority),
+ 'X-Tags': tagsHeader(input.tags),
+ 'X-Icon': headerValue(input.icon),
+ 'X-Actions': headerValue(input.actions),
+ 'X-Click': headerValue(input.click),
+ 'X-Delay': headerValue(input.delay),
+ ...(attach ? { 'X-Attach': headerValue(attach) } : {}),
+ ...(filename ? { 'X-Filename': encodeToRFC2047(filename) } : {}),
+ ...(input.markdown === true ? { 'X-Markdown': 'yes' } : {}),
+ ...(email ? { 'X-Email': headerValue(email) } : {}),
+ ...(call ? { 'X-Call': headerValue(call) } : {}),
+ ...(sequenceId ? { 'X-Sequence-ID': validateId({ value: sequenceId, label: 'Sequence ID' }) } : {}),
+ ...(input.cache === 'no' ? { 'X-Cache': 'no' } : {}),
+ ...(input.firebase === 'no' ? { 'X-Firebase': 'no' } : {}),
+ };
+}
+
+function buildJsonPublishBody(input: JsonPublishInput): Record<string, unknown> {
+ const textFields = ['title', 'click', 'icon', 'attach', 'filename', 'delay', 'email', 'call'] as const;
+ const texts = Object.fromEntries(
+ textFields
+ .map((key) => [key, nonEmpty(input[key])] as const)
+ .filter(([, v]) => v !== undefined)
+ );
+ const message = typeof input.message === 'string' && input.message.trim().length > 0 ? input.message : undefined;
+ const priority = parsePriority(input.priority);
+ const tags = normalizeTags(input.tags);
+ const actions = parseActions(input.actions);
+ const sequenceId = nonEmpty(input.sequence_id);
+ if (texts['delay'] !== undefined && input.disable_cache === true) {
+ throw new Error('Do Not Cache cannot be combined with Delay: ntfy can only schedule cached messages.');
+ }
+ if (texts['delay'] !== undefined && texts['email'] !== undefined) {
+ throw new Error('Email To cannot be combined with Delay: ntfy does not send scheduled emails.');
+ }
+ return {
+ topic: validateId({ value: input.topic, label: 'Topic' }),
+ ...(message !== undefined ? { message } : {}),
+ ...texts,
+ ...(priority !== undefined ? { priority } : {}),
+ ...(tags ? { tags } : {}),
+ ...(actions ? { actions } : {}),
+ ...(input.markdown === true ? { markdown: true } : {}),
+ ...(sequenceId ? { sequence_id: validateId({ value: sequenceId, label: 'Sequence ID' }) } : {}),
+ ...(input.disable_cache === true ? { cache: 'no' } : {}),
+ ...(input.disable_firebase === true ? { firebase: 'no' } : {}),
+ };
+}
+
+function parseNdjson(body: unknown): NtfyMessage[] {
+ if (body === undefined || body === null || body === '') {
+ return [];
+ }
+ if (typeof body !== 'string') {
+ const items: unknown[] = Array.isArray(body) ? body : [body];
+ return items.filter(isNtfyMessage);
+ }
+ return body
+ .split('\n')
+ .map((line, index) => ({ line: line.trim(), index }))
+ .filter(({ line }) => line.length > 0)
+ .map(({ line, index }) => {
+ const parsed: unknown = parseNdjsonLine({ line, index });
+ if (!isNtfyMessage(parsed)) {
+ throw new Error(`ntfy returned an unexpected line ${index + 1}: ${line.slice(0, 200)}`);
+ }
+ return parsed;
+ });
+}
+
+function serverNowSeconds(headers: HttpHeaders | undefined): number {
+ const value = firstHeader({ headers, name: 'date' });
+ const parsed = value ? Date.parse(value) : NaN;
+ return Math.floor((Number.isNaN(parsed) ? Date.now() : parsed) / 1000);
+}
+
+function toNtfyError(error: unknown): unknown {
+ const response = isRecord(error) && isRecord(error['response']) ? error['response'] : undefined;
+ const status = response?.['status'];
+ if (typeof status !== 'number') {
+ return error;
+ }
+ const body = normalizeErrorBody(response?.['body']);
+ return new NtfyRequestError({
+ status,
+ message: `ntfy request failed with HTTP ${status}: ${body}.${statusHint(status)}`,
+ });
+}
+
+async function request<T = unknown>({
+ auth,
+ path,
+ method,
+ headers,
+ body,
+ queryParams,
+ responseType,
+}: NtfyRequestParams): Promise<HttpResponse<T>> {
+ const url = `${baseUrl(auth)}${path}`;
+ try {
+ return await httpClient.sendRequest<T>({
+ method,
+ url,
+ body,
+ queryParams,
+ responseType,
+ headers: { ...authHeaders(auth), ...headers },
+ });
+ } catch (error) {
+ throw toNtfyError(error);
+ }
+}
+
+async function pollMessages({
+ auth,
+ topics,
+ since,
+ scheduled,
+ filters,
+}: {
+ auth: NtfyAuthValue;
+ topics: string;
+ since: string;
+ scheduled?: boolean;
+ filters?: PollFilters;
+}): Promise<{ messages: NtfyMessage[]; truncated: boolean; serverNow: number }> {
+ const f = filters ?? {};
+ const queryParams: QueryParams = {
+ poll: '1',
+ since,
+ ...(scheduled ? { sched: '1' } : {}),
+ ...(f.priority && f.priority.length > 0 ? { priority: f.priority.join(',') } : {}),
+ ...(f.tags && f.tags.length > 0 ? { tags: f.tags.join(',') } : {}),
+ ...(f.title ? { title: f.title } : {}),
+ ...(f.message ? { message: f.message } : {}),
+ };
+ const response = await request<string>({
+ auth,
+ method: HttpMethod.GET,
+ path: `/${topics}/json`,
+ queryParams,
+ responseType: 'text',
+ });
+ const truncatedHeader = firstHeader({ headers: response.headers, name: 'x-messages-truncated' });
+ return {
+ messages: parseNdjson(response.body),
+ truncated: truncatedHeader === '1' || truncatedHeader === 'true',
+ serverNow: serverNowSeconds(response.headers),
+ };
+}
+
+function advanceCursor({ cursor, fetched }: { cursor: NtfyCursor; fetched: NtfyMessage[] }): {
+ newItems: NtfyMessage[];
+ cursor: NtfyCursor;
+} {
+ const windowFloor = cursor.lastTime - CURSOR_OVERLAP_SECONDS;
+ const messages = fetched.filter((m) => m.event === 'message');
+ const alreadySeen = new Set(cursor.seen.map((s) => s.id));
+ const newItems = uniqueById(messages)
+ .filter((m) => !alreadySeen.has(m.id) && m.time >= windowFloor)
+ .sort((a, b) => a.time - b.time);
+ const lastTime = messages.reduce((max, m) => Math.max(max, m.time), cursor.lastTime);
+ const keepFloor = lastTime - CURSOR_OVERLAP_SECONDS;
+ const seen = [...cursor.seen, ...newItems.map((m) => ({ id: m.id, time: m.time }))].filter(
+ (s) => s.time >= keepFloor
+ );
+ return { newItems, cursor: { lastTime, seen } };
+}
+
+function uniqueById(messages: NtfyMessage[]): NtfyMessage[] {
+ const ids = new Set<string>();
+ return messages.filter((m) => {
+ if (ids.has(m.id)) {
+ return false;
+ }
+ ids.add(m.id);
+ return true;
+ });
+}
+
+function nonEmpty(value: unknown): string | undefined {
+ if (typeof value !== 'string') {
+ return undefined;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function isNtfyMessage(value: unknown): value is NtfyMessage {
+ return (
+ isRecord(value) &&
+ typeof value['id'] === 'string' &&
+ typeof value['time'] === 'number' &&
+ typeof value['event'] === 'string'
+ );
+}
+
+function parseJsonOrThrow(value: string): unknown {
+ try {
+ return JSON.parse(value);
+ } catch {
+ throw new Error(
+ 'Action Buttons must be a JSON array, e.g. [{"action":"view","label":"Open","url":"https://example.com"}]'
+ );
+ }
+}
+
+function parseNdjsonLine({ line, index }: { line: string; index: number }): unknown {
+ try {
+ return JSON.parse(line);
+ } catch {
+ throw new Error(`ntfy returned a line that is not JSON (line ${index + 1}): ${line.slice(0, 200)}`);
+ }
+}
+
+function firstHeader({ headers, name }: { headers: HttpHeaders | undefined; name: string }): string | undefined {
+ if (!headers) {
+ return undefined;
+ }
+ const key = Object.keys(headers).find((k) => k.toLowerCase() === name);
+ const raw = key ? headers[key] : undefined;
+ return Array.isArray(raw) ? raw[0] : raw;
+}
+
+function normalizeErrorBody(body: unknown): string {
+ const parsed = typeof body === 'string' ? tryParseJson(body) : body;
+ if (isRecord(parsed) && typeof parsed['error'] === 'string') {
+ const code = parsed['code'];
+ return `${parsed['error']}${typeof code === 'number' ? ` (ntfy code ${code})` : ''}`;
+ }
+ if (typeof body === 'string' && body.length > 0) {
+ return body.slice(0, 300);
+ }
+ return 'no details';
+}
+
+function tryParseJson(value: string): unknown {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+}
+
+function statusHint(status: number): string {
+ if (status === 401 || status === 403) {
+ return ' Check the Access Token on the connection and that it may read/write this topic.';
+ }
+ if (status === 429) {
+ return ' The ntfy server rate-limited this request (daily message, email or bandwidth quota). Try again later.';
+ }
+ if (status === 413) {
+ return ' The message or attachment is larger than the server allows.';
+ }
+ return '';
+}
+
+export class NtfyRequestError extends Error {
+ readonly status: number;
+
+ constructor({ status, message }: { status: number; message: string }) {
+ super(message);
+ this.name = 'NtfyRequestError';
+ this.status = status;
+ }
+}
+
+export const ntfyClient = {
+ NTFY_ID_PATTERN,
+ CURSOR_OVERLAP_SECONDS,
+ encodeToRFC2047,
+ baseUrl,
+ authHeaders,
+ validateId,
+ validateTopicList,
+ parsePriority,
+ normalizePriorityFilter,
+ normalizeTags,
+ parseActions,
+ headerValue,
+ buildSendNotificationHeaders,
+ buildJsonPublishBody,
+ parseNdjson,
+ newestFirst,
+ serverNowSeconds,
+ toNtfyError,
+ firstHeader,
+ request,
+ pollMessages,
+ advanceCursor,
+};
+
+export type NtfyAuthValue = AppConnectionValueForAuthProperty<typeof ntfyAuth>;
+
+export type NtfyMessage = {
+ id: string;
+ time: number;
+ event: string;
+ topic: string;
+ expires?: number;
+ sequence_id?: string;
+ title?: string;
+ message?: string;
+ priority?: number;
+ tags?: string[];
+ click?: string;
+ icon?: string;
+ actions?: Record<string, unknown>[];
+ attachment?: Record<string, unknown>;
+ content_type?: string;
+};
+
+export type NtfyCursor = {
+ lastTime: number;
+ seen: { id: string; time: number }[];
+};
+
+export type PollFilters = {
+ priority?: number[];
+ tags?: string[];
+ title?: string;
+ message?: string;
+};
+
+export type SendNotificationHeaderInput = {
+ message: string;
+ title?: string;
+ priority?: string;
+ tags?: unknown;
+ icon?: string;
+ actions?: string;
+ click?: string;
+ delay?: string;
+ attach?: string;
+ filename?: string;
+ markdown?: boolean;
+ email?: string;
+ call?: string;
+ sequence_id?: string;
+ cache?: string;
+ firebase?: string;
+};
+
+export type JsonPublishInput = {
+ topic: unknown;
+ message?: unknown;
+ title?: unknown;
+ priority?: unknown;
+ tags?: unknown;
+ click?: unknown;
+ icon?: unknown;
+ attach?: unknown;
+ filename?: unknown;
+ markdown?: unknown;
+ actions?: unknown;
+ delay?: unknown;
+ email?: unknown;
+ call?: unknown;
+ sequence_id?: unknown;
+ disable_cache?: unknown;
+ disable_firebase?: unknown;
+};
+
+type NtfyRequestParams = {
+ auth: NtfyAuthValue;
+ path: string;
+ method: HttpMethod;
+ headers?: HttpHeaders;
+ body?: HttpRequest['body'];
+ queryParams?: QueryParams;
+ responseType?: HttpRequest['responseType'];
+};
diff --git a/packages/pieces/community/ntfy/src/lib/common/props.ts b/packages/pieces/community/ntfy/src/lib/common/props.ts
new file mode 100644
index 00000000000..d056e5e83f0
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/common/props.ts
@@ -0,0 +1,129 @@
+import { Property } from '@activepieces/pieces-framework';
+
+export const PRIORITY_OPTIONS = [
+ { label: '1 - Min', value: 1 },
+ { label: '2 - Low', value: 2 },
+ { label: '3 - Default', value: 3 },
+ { label: '4 - High', value: 4 },
+ { label: '5 - Max (urgent)', value: 5 },
+];
+
+export const ntfyProps = {
+ topic: () =>
+ Property.ShortText({
+ displayName: 'Topic',
+ description:
+ 'The topic name, e.g. backups_home. 1-64 characters: letters, digits, "-" and "_". Anyone who knows a public topic name can read it, so pick a hard-to-guess name.',
+ required: true,
+ }),
+ topics: () =>
+ Property.ShortText({
+ displayName: 'Topics',
+ description:
+ 'One topic, or several separated by commas, e.g. alerts,backups_home. Letters, digits, "-" and "_" only.',
+ required: true,
+ }),
+ sequenceId: (description: string) =>
+ Property.ShortText({
+ displayName: 'Sequence ID',
+ description,
+ required: true,
+ }),
+ requiredMessage: (description: string) =>
+ Property.LongText({
+ displayName: 'Message',
+ description,
+ required: true,
+ }),
+ optionalMessage: (description: string) =>
+ Property.LongText({
+ displayName: 'Message',
+ description,
+ required: false,
+ }),
+ title: () =>
+ Property.ShortText({
+ displayName: 'Title',
+ description: 'Optional notification title, e.g. "Backup finished". Defaults to the topic URL in the apps.',
+ required: false,
+ }),
+ priority: () =>
+ Property.StaticDropdown({
+ displayName: 'Priority',
+ description: 'How urgently the phone should alert. Leave empty for the default (3).',
+ required: false,
+ options: { options: PRIORITY_OPTIONS },
+ }),
+ tags: () =>
+ Property.Array({
+ displayName: 'Tags',
+ description:
+ 'Tags shown with the notification. Tags that match an emoji short code (e.g. warning, white_check_mark, rotating_light) are shown as that emoji.',
+ required: false,
+ }),
+ click: () =>
+ Property.ShortText({
+ displayName: 'Click URL',
+ description: 'Web page or app link opened when the notification is tapped, e.g. https://example.com/orders/42',
+ required: false,
+ }),
+ icon: () =>
+ Property.ShortText({
+ displayName: 'Icon URL',
+ description: 'URL of a JPEG or PNG image used as the notification icon, e.g. https://example.com/icon.png',
+ required: false,
+ }),
+ attach: () =>
+ Property.ShortText({
+ displayName: 'Attachment URL',
+ description: 'Public URL of a file to attach, e.g. https://example.com/report.pdf. ntfy does not download it; the apps link to it.',
+ required: false,
+ }),
+ filename: () =>
+ Property.ShortText({
+ displayName: 'Attachment File Name',
+ description: 'Name shown for the attachment, e.g. report.pdf. Only used together with an attachment.',
+ required: false,
+ }),
+ markdown: () =>
+ Property.Checkbox({
+ displayName: 'Markdown',
+ description: 'Render the message as Markdown (supported in the web app and on Android).',
+ required: false,
+ defaultValue: false,
+ }),
+ actions: () =>
+ Property.Json({
+ displayName: 'Action Buttons',
+ description:
+ 'Up to 3 buttons as a JSON array, e.g. [{"action":"view","label":"Open","url":"https://example.com"}]. Types: view, http, broadcast, copy. See https://docs.ntfy.sh/publish/#action-buttons',
+ required: false,
+ }),
+ delay: () =>
+ Property.ShortText({
+ displayName: 'Delay',
+ description:
+ "Schedule delivery for later: a duration (30m, 2h, 1 day), a Unix timestamp or natural language like 'tomorrow, 10am'. Between 10 seconds and 3 days on default servers.",
+ required: false,
+ }),
+ email: () =>
+ Property.ShortText({
+ displayName: 'Email To',
+ description: 'Also send the notification to this email address, e.g. [email protected]. ntfy.sh allows 5 emails a day without an account; with an access token, ntfy.sh only sends to addresses verified in the account settings.',
+ required: false,
+ }),
+ call: () =>
+ Property.ShortText({
+ displayName: 'Phone Call To',
+ description:
+ 'Also read the message out in a phone call to this number, e.g. +12223334444, or "yes" for your first verified number. Needs a paid ntfy.sh plan (or a self-hosted server with Twilio) and a verified number.',
+ required: false,
+ }),
+ publishSequenceId: () =>
+ Property.ShortText({
+ displayName: 'Sequence ID',
+ description:
+ 'Your own ID for this notification, e.g. backup-job-42, so later steps can update, clear or delete it. Letters, digits, "-" and "_". Needs ntfy server v2.16.0+.',
+ required: false,
+ }),
+};
diff --git a/packages/pieces/community/ntfy/src/lib/output-schemas.ts b/packages/pieces/community/ntfy/src/lib/output-schemas.ts
index d001aac2272..edb6de8f741 100644
--- a/packages/pieces/community/ntfy/src/lib/output-schemas.ts
+++ b/packages/pieces/community/ntfy/src/lib/output-schemas.ts
@@ -1,89 +1,288 @@
-import { OutputSchema } from '@activepieces/pieces-framework';
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
-export const sendNotificationActionOutputSchema: OutputSchema = {
- fields: [
+function messageFields({
+ prefix = '',
+ uploads = true,
+ omit = [],
+}: {
+ prefix?: string;
+ uploads?: boolean;
+ omit?: string[];
+} = {}): OutputSchemaField[] {
+ const at = (key: string) => (prefix ? { value: `${prefix}${key}` } : {});
+ const attachmentChildren: OutputSchemaField[] = [
+ { key: 'name', label: 'File Name' },
+ { key: 'url', label: 'URL', format: 'url' },
+ ];
+ if (uploads) {
+ attachmentChildren.push(
+ { key: 'type', label: 'MIME Type' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ {
+ key: 'expires',
+ label: 'Expires',
+ description: 'Unix timestamp in seconds when the uploaded file is deleted (3 hours after upload by default).',
+ }
+ );
+ }
+ const fields: OutputSchemaField[] = [
{
key: 'id',
label: 'Message ID',
- value: 'body.id',
+ ...at('id'),
description: 'Identifier ntfy assigned to the published message.',
},
{
key: 'topic',
label: 'Topic',
- value: 'body.topic',
+ ...at('topic'),
description: 'The topic the message was published to.',
},
{
key: 'title',
label: 'Title',
- value: 'body.title',
+ ...at('title'),
},
{
key: 'message',
label: 'Message',
- value: 'body.message',
+ ...at('message'),
},
{
key: 'time',
label: 'Delivery Time',
- value: 'body.time',
+ ...at('time'),
description:
'Unix timestamp in seconds for when ntfy delivers the message. Equal to the send time unless Delay was set, in which case it is the scheduled delivery time.',
},
{
key: 'expires',
label: 'Expires',
- value: 'body.expires',
+ ...at('expires'),
description:
'Unix timestamp in seconds for when ntfy stops caching the message, always 12 hours after Delivery Time.',
},
{
key: 'event',
label: 'Event',
- value: 'body.event',
+ ...at('event'),
description: 'The ntfy event type, "message" for a published notification.',
},
{
key: 'priority',
label: 'Priority',
- value: 'body.priority',
+ ...at('priority'),
format: 'number',
description: '1 (lowest) to 5 (highest). Omitted by ntfy when the default priority 3 was used.',
},
{
key: 'tags',
label: 'Tags',
- value: 'body.tags',
+ ...at('tags'),
description: 'Only present when tags were sent.',
},
{
key: 'click',
label: 'Click URL',
- value: 'body.click',
+ ...at('click'),
format: 'url',
description: 'Opened when the notification is clicked. Only present when a click URL was sent.',
},
{
key: 'icon',
label: 'Icon',
- value: 'body.icon',
+ ...at('icon'),
format: 'image',
description: 'Only present when an icon URL was sent.',
},
{
key: 'actions',
label: 'Action Buttons',
- value: 'body.actions',
+ ...at('actions'),
labelKey: 'label',
description: 'Only present when action buttons were sent.',
listItems: [
{ key: 'id', label: 'Action ID' },
- { key: 'action', label: 'Type', description: 'One of "view", "http" or "broadcast".' },
+ { key: 'action', label: 'Type', description: 'One of "view", "http", "broadcast" or "copy".' },
{ key: 'label', label: 'Label' },
{ key: 'url', label: 'URL', format: 'url' },
{ key: 'clear', label: 'Clear Notification', format: 'boolean' },
],
},
+ {
+ key: 'sequence_id',
+ label: 'Sequence ID',
+ ...at('sequence_id'),
+ description:
+ 'Only present when a Sequence ID was set. Use it (or the Message ID) to update, clear or delete this notification.',
+ },
+ {
+ key: 'content_type',
+ label: 'Content Type',
+ ...at('content_type'),
+ description: '"text/markdown" when the message was sent as Markdown, otherwise absent.',
+ },
+ {
+ key: 'attachment',
+ label: 'Attachment',
+ ...at('attachment'),
+ description: uploads
+ ? 'Only present when a file or attachment URL was sent. Type, size and expiry are only set for files uploaded to the ntfy server.'
+ : 'Only present when an attachment URL was sent.',
+ children: attachmentChildren,
+ },
+ ];
+ return fields.filter((field) => !omit.includes(field.key));
+}
+
+export const sendNotificationActionOutputSchema: OutputSchema = {
+ fields: messageFields({ prefix: 'body.', uploads: false }),
+};
+
+export const publishedMessageOutputSchema: OutputSchema = {
+ fields: messageFields({ uploads: false }),
+};
+
+export const sentFileOutputSchema: OutputSchema = {
+ fields: messageFields({ omit: ['icon', 'actions', 'sequence_id', 'content_type'] }),
+};
+
+export const sequenceEventOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'id', label: 'Event ID', description: 'ID of the clear/delete event ntfy appended to the topic.' },
+ { key: 'sequence_id', label: 'Sequence ID', description: 'The notification the event applies to.' },
+ { key: 'topic', label: 'Topic' },
+ {
+ key: 'event',
+ label: 'Event',
+ description: '"message_clear" (marked read and dismissed) or "message_delete" (removed, or scheduled message cancelled).',
+ },
+ { key: 'time', label: 'Time', description: 'Unix timestamp in seconds when the event was published.' },
+ { key: 'expires', label: 'Expires', description: 'Unix timestamp in seconds for when ntfy stops caching the event.' },
+ ],
+};
+
+const messageListFields = (description: string): OutputSchemaField[] => [
+ {
+ key: 'messages',
+ label: 'Messages',
+ labelKey: 'message',
+ description,
+ listItems: messageFields(),
+ },
+ { key: 'count', label: 'Count', format: 'number', description: 'Number of messages returned.' },
+];
+
+const serverTruncatedField: OutputSchemaField = {
+ key: 'server_truncated',
+ label: 'Server Truncated',
+ format: 'boolean',
+ description: 'True when the ntfy server capped the replay (X-Messages-Truncated), so some messages were not returned.',
+};
+
+export const fetchMessagesOutputSchema: OutputSchema = {
+ fields: [
+ ...messageListFields('Cached messages, newest first.'),
+ {
+ key: 'total_matched',
+ label: 'Total Matched',
+ format: 'number',
+ description: 'Messages that matched before Limit was applied.',
+ },
+ {
+ key: 'has_more',
+ label: 'Has More',
+ format: 'boolean',
+ description: 'True when Limit cut off older matching messages.',
+ },
+ serverTruncatedField,
+ ],
+};
+
+export const listScheduledMessagesOutputSchema: OutputSchema = {
+ fields: [
+ ...messageListFields('Messages scheduled for later delivery that have not been delivered yet, soonest first.'),
+ serverTruncatedField,
+ ],
+};
+
+export const accountOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'username', label: 'Username', description: '"*" for anonymous access (no token or no account).' },
+ { key: 'role', label: 'Role', description: 'anonymous, user or admin.' },
+ { key: 'tier_code', label: 'Tier Code' },
+ { key: 'tier_name', label: 'Tier Name' },
+ { key: 'limits_basis', label: 'Limits Based On', description: '"ip" (per IP address) or "tier".' },
+ { key: 'limits_messages', label: 'Daily Message Limit', format: 'number' },
+ {
+ key: 'limits_messages_expiry_duration',
+ label: 'Message Cache Duration',
+ format: 'number',
+ description: 'Seconds.',
+ },
+ { key: 'limits_emails', label: 'Daily Email Limit', format: 'number' },
+ { key: 'limits_calls', label: 'Daily Call Limit', format: 'number' },
+ { key: 'limits_reservations', label: 'Reserved Topic Limit', format: 'number' },
+ { key: 'limits_attachment_file_size', label: 'Max Attachment Size', format: 'filesize' },
+ { key: 'limits_attachment_total_size', label: 'Attachment Storage Limit', format: 'filesize' },
+ {
+ key: 'limits_attachment_expiry_duration',
+ label: 'Attachment Expiry',
+ format: 'number',
+ description: 'Seconds.',
+ },
+ { key: 'limits_attachment_bandwidth', label: 'Daily Attachment Bandwidth', format: 'filesize' },
+ { key: 'stats_messages', label: 'Messages Sent Today', format: 'number' },
+ { key: 'stats_messages_remaining', label: 'Messages Remaining Today', format: 'number' },
+ { key: 'stats_emails', label: 'Emails Sent Today', format: 'number' },
+ { key: 'stats_emails_remaining', label: 'Emails Remaining Today', format: 'number' },
+ { key: 'stats_calls', label: 'Calls Made Today', format: 'number' },
+ { key: 'stats_calls_remaining', label: 'Calls Remaining Today', format: 'number' },
+ { key: 'stats_reservations', label: 'Reserved Topics', format: 'number' },
+ { key: 'stats_reservations_remaining', label: 'Reserved Topics Remaining', format: 'number' },
+ { key: 'stats_attachment_total_size', label: 'Attachment Storage Used', format: 'filesize' },
+ { key: 'stats_attachment_total_size_remaining', label: 'Attachment Storage Remaining', format: 'filesize' },
+ {
+ key: 'reserved_topics',
+ label: 'Reserved Topics',
+ description: 'Comma-separated names of topics reserved by this account, empty when none.',
+ },
+ ],
+};
+
+export const serverStatsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'messages', label: 'Messages Published', format: 'number', description: 'Total messages since the server started counting.' },
+ { key: 'messages_rate', label: 'Messages per Second', format: 'number', description: 'Recent average publish rate.' },
+ ],
+};
+
+export const serverHealthOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'healthy', label: 'Healthy', format: 'boolean' },
+ { key: 'server_url', label: 'Server URL', format: 'url' },
+ ],
+};
+
+export const attachmentInfoOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'message_id', label: 'Message ID' },
+ { key: 'exists', label: 'Exists', format: 'boolean', description: 'False when the file was never uploaded or has expired.' },
+ { key: 'size_bytes', label: 'Size', format: 'filesize' },
+ { key: 'content_type', label: 'Content Type', description: 'Null when the server does not report it.' },
+ { key: 'url', label: 'Download URL', format: 'url' },
+ ],
+};
+
+export const newMessageTriggerOutputSchema: OutputSchema = {
+ fields: [
+ ...messageFields(),
+ {
+ key: 'replay_truncated',
+ label: 'Replay Truncated',
+ format: 'boolean',
+ description:
+ 'True when the ntfy server capped this poll on at least one of the topics (more than 10 MB of messages), so messages published since the previous poll may have been skipped. ntfy keeps only the newest 10 MB per topic and offers no way to fetch the rest.',
+ },
],
};
diff --git a/packages/pieces/community/ntfy/src/lib/triggers/new-message.ts b/packages/pieces/community/ntfy/src/lib/triggers/new-message.ts
new file mode 100644
index 00000000000..f810a39e027
--- /dev/null
+++ b/packages/pieces/community/ntfy/src/lib/triggers/new-message.ts
@@ -0,0 +1,127 @@
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
+import { ntfyAuth } from '../auth';
+import { ntfyClient, NtfyAuthValue, NtfyCursor, PollFilters } from '../common/client';
+import { ntfyProps, PRIORITY_OPTIONS } from '../common/props';
+import { newMessageTriggerOutputSchema } from '../output-schemas';
+
+const CURSOR_KEY = 'ntfy_new_message_cursor';
+
+export const newMessage = createTrigger({
+ auth: ntfyAuth,
+ name: 'new_message',
+ classification: 'READ',
+ displayName: 'New Message',
+ description:
+ 'Triggers when a message is published to a ntfy topic. Needs the server to cache messages (ntfy.sh keeps them 12 hours); messages sent with "Do not cache" are never seen.',
+ aiMetadata: {
+ description:
+ 'Fires once per new message published to the chosen ntfy topic(s), including scheduled messages when they are delivered and updates sent with a sequence ID; optionally only for given priorities or tags. Clear and delete events do not fire it. Polls the server cache, so uncached messages are missed. If more than 10 MB of messages arrive on any of the topics between two polls, the server returns only the newest ones and cannot return the rest; every run from that poll carries replay_truncated: true.',
+ },
+ props: {
+ topics: ntfyProps.topics(),
+ priority: Property.StaticMultiSelectDropdown({
+ displayName: 'Priority Filter',
+ description: 'Only trigger for messages with any of these priorities. Leave empty for all.',
+ required: false,
+ options: { options: PRIORITY_OPTIONS },
+ }),
+ tags: Property.Array({
+ displayName: 'Tags Filter',
+ description: 'Only trigger for messages that have all of these tags, e.g. backup.',
+ required: false,
+ }),
+ },
+ outputSchema: newMessageTriggerOutputSchema,
+ sampleData: {
+ id: 'GjpkhqcNaNyE',
+ time: 1790662726,
+ expires: 1790705926,
+ event: 'message',
+ topic: 'backups_home',
+ title: 'Backup finished',
+ message: 'Nightly backup finished in 4m 12s',
+ priority: 4,
+ tags: ['white_check_mark', 'backup'],
+ click: 'https://example.com/backups/42',
+ replay_truncated: false,
+ },
+ type: TriggerStrategy.POLLING,
+ async onEnable(context) {
+ if (context.isRepublish && (await context.store.get<NtfyCursor>(CURSOR_KEY))) {
+ return;
+ }
+ const cursor = await initialCursor({ auth: context.auth, propsValue: context.propsValue });
+ await context.store.put(CURSOR_KEY, cursor);
+ },
+ async onDisable(context) {
+ await context.store.delete(CURSOR_KEY);
+ },
+ async test(context) {
+ const topics = ntfyClient.validateTopicList(context.propsValue.topics);
+ const result = await ntfyClient.pollMessages({
+ auth: context.auth,
+ topics,
+ since: '12h',
+ filters: filtersFrom(context.propsValue),
+ });
+ return ntfyClient
+ .newestFirst(result.messages.filter((m) => m.event === 'message'))
+ .slice(0, 5)
+ .map((message) => ({ ...message, replay_truncated: result.truncated }));
+ },
+ async run(context) {
+ const stored = await context.store.get<NtfyCursor>(CURSOR_KEY);
+ if (!stored) {
+ await context.store.put(
+ CURSOR_KEY,
+ await initialCursor({ auth: context.auth, propsValue: context.propsValue })
+ );
+ return [];
+ }
+ const topics = ntfyClient.validateTopicList(context.propsValue.topics);
+ const since = Math.max(0, stored.lastTime - ntfyClient.CURSOR_OVERLAP_SECONDS);
+ const result = await ntfyClient.pollMessages({
+ auth: context.auth,
+ topics,
+ since: String(since),
+ filters: filtersFrom(context.propsValue),
+ });
+ const { newItems, cursor } = ntfyClient.advanceCursor({ cursor: stored, fetched: result.messages });
+ await context.store.put(CURSOR_KEY, cursor);
+ return newItems.map((message) => ({ ...message, replay_truncated: result.truncated }));
+ },
+});
+
+async function initialCursor({
+ auth,
+ propsValue,
+}: {
+ auth: NtfyAuthValue;
+ propsValue: TriggerPropsValue;
+}): Promise<NtfyCursor> {
+ const topics = ntfyClient.validateTopicList(propsValue.topics);
+ const result = await ntfyClient.pollMessages({
+ auth,
+ topics,
+ since: `${ntfyClient.CURSOR_OVERLAP_SECONDS}s`,
+ filters: filtersFrom(propsValue),
+ });
+ const seeded = ntfyClient.advanceCursor({
+ cursor: { lastTime: result.serverNow, seen: [] },
+ fetched: result.messages,
+ });
+ return seeded.cursor;
+}
+
+function filtersFrom(propsValue: TriggerPropsValue): PollFilters {
+ return {
+ priority: ntfyClient.normalizePriorityFilter(propsValue.priority),
+ tags: ntfyClient.normalizeTags(propsValue.tags),
+ };
+}
+
+type TriggerPropsValue = {
+ topics?: string;
+ priority?: unknown[];
+ tags?: unknown[];
+};
diff --git a/packages/pieces/community/ntfy/test/actions.test.ts b/packages/pieces/community/ntfy/test/actions.test.ts
new file mode 100644
index 00000000000..5e2a1432393
--- /dev/null
+++ b/packages/pieces/community/ntfy/test/actions.test.ts
@@ -0,0 +1,399 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { sendNotification } from '../src/lib/actions/send-notification';
+import { publishMessage } from '../src/lib/actions/publish-message';
+import { deleteNotification } from '../src/lib/actions/delete-notification';
+import { clearNotification } from '../src/lib/actions/clear-notification';
+import { updateNotification } from '../src/lib/actions/update-notification';
+import { fetchMessages } from '../src/lib/actions/fetch-messages';
+import { listScheduledMessages } from '../src/lib/actions/list-scheduled-messages';
+import { getAccount } from '../src/lib/actions/get-account';
+import { getAttachmentInfo } from '../src/lib/actions/get-attachment-info';
+import { sendFile } from '../src/lib/actions/send-file';
+import { newMessage } from '../src/lib/triggers/new-message';
+import { ntfy } from '../src/index';
+import { ntfyClient } from '../src/lib/common/client';
+import { ndjson, runAction, testAuth, triggerContext } from './helpers';
+
+const sendRequest = vi.fn();
+
+vi.mock('@activepieces/pieces-common', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@activepieces/pieces-common')>();
+ return {
+ ...actual,
+ httpClient: {
+ sendRequest: (...args: unknown[]) => sendRequest(...args),
+ },
+ };
+});
+
+beforeEach(() => {
+ sendRequest.mockReset();
+});
+
+describe('Send Notification', () => {
+ it('publishes with an empty title (0.3.0 crashed here) and no X-Title header', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: { id: 'x' } });
+ const result = await runAction({
+ action: sendNotification,
+ propsValue: { topic: 'alerts', message: 'hello', title: undefined },
+ });
+ const request = sendRequest.mock.calls[0][0];
+ expect(request.method).toBe(HttpMethod.POST);
+ expect(request.url).toBe('https://ntfy.example.com/alerts');
+ expect(request.headers).not.toHaveProperty('X-Title');
+ expect(request.authentication).toBeUndefined();
+ expect(result).toEqual({ status: 200, headers: {}, body: { id: 'x' } });
+ });
+});
+
+describe('Publish Message (JSON)', () => {
+ it('posts JSON to the root URL with the bearer token', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: { id: 'm1', event: 'message' } });
+ const result = await runAction({
+ action: publishMessage,
+ token: 'tk_abc',
+ propsValue: { topic: 'alerts', message: 'hi', priority: 5, tags: ['warning'], markdown: false },
+ });
+ const request = sendRequest.mock.calls[0][0];
+ expect(request.url).toBe('https://ntfy.example.com/');
+ expect(request.headers).toMatchObject({ Authorization: 'Bearer tk_abc', 'Content-Type': 'application/json' });
+ expect(request.body).toEqual({ topic: 'alerts', message: 'hi', priority: 5, tags: ['warning'] });
+ expect(result).toEqual({ id: 'm1', event: 'message' });
+ });
+});
+
+describe('Delete Notification', () => {
+ it('sends DELETE /<topic>/<sequence_id> and no Authorization header without a token', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: { id: 'e', event: 'message_delete' } });
+ await runAction({ action: deleteNotification, propsValue: { topic: 'alerts', sequence_id: 'job-1' } });
+ const request = sendRequest.mock.calls[0][0];
+ expect(request.method).toBe(HttpMethod.DELETE);
+ expect(request.url).toBe('https://ntfy.example.com/alerts/job-1');
+ expect(request.headers).not.toHaveProperty('Authorization');
+ });
+});
+
+describe('Fetch Messages', () => {
+ it('parses NDJSON, filters events, sorts newest first and reports limit cut-off', async () => {
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: { 'x-messages-truncated': '1' },
+ body: ndjson([
+ { id: 'a', time: 1, event: 'message', topic: 't' },
+ { id: 'b', time: 3, event: 'message', topic: 't' },
+ { id: 'c', time: 2, event: 'message_clear', topic: 't' },
+ { id: 'd', time: 2, event: 'message', topic: 't' },
+ ]),
+ });
+ const result = await runAction({
+ action: fetchMessages,
+ propsValue: { topics: 't', since: undefined, priority: [4, 5], tags: ['x'], limit: 2 },
+ });
+ const request = sendRequest.mock.calls[0][0];
+ expect(request.url).toBe('https://ntfy.example.com/t/json');
+ expect(request.responseType).toBe('text');
+ expect(request.queryParams).toEqual({ poll: '1', since: '12h', priority: '4,5', tags: 'x' });
+ expect(result).toEqual({
+ messages: [
+ { id: 'b', time: 3, event: 'message', topic: 't' },
+ { id: 'd', time: 2, event: 'message', topic: 't' },
+ ],
+ count: 2,
+ total_matched: 3,
+ has_more: true,
+ server_truncated: true,
+ });
+ });
+});
+
+describe('List Scheduled Messages', () => {
+ it('keeps only messages due after the server time', async () => {
+ const now = 1790662800;
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: { date: new Date(now * 1000).toUTCString() },
+ body: ndjson([
+ { id: 'past', time: now - 10, event: 'message', topic: 't' },
+ { id: 'later', time: now + 7200, event: 'message', topic: 't' },
+ { id: 'soon', time: now + 60, event: 'message', topic: 't' },
+ ]),
+ });
+ const result = await runAction({ action: listScheduledMessages, propsValue: { topics: 't' } });
+ expect(sendRequest.mock.calls[0][0].queryParams).toMatchObject({ poll: '1', sched: '1', since: 'all' });
+ expect(result).toMatchObject({ count: 2, server_truncated: false });
+ expect(JSON.stringify(result)).toMatch(/"soon".*"later"/);
+ });
+
+ it('reports when the server capped the replay', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: { 'x-messages-truncated': '1' }, body: '' });
+ const result = await runAction({ action: listScheduledMessages, propsValue: { topics: 't' } });
+ expect(result).toMatchObject({ count: 0, server_truncated: true });
+ });
+});
+
+describe('Update Notification', () => {
+ it('posts JSON to the root URL with the sequence id and only the fields that are set', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: { id: 'u1', sequence_id: 'job-1' } });
+ const result = await runAction({
+ action: updateNotification,
+ propsValue: { topic: 'alerts', sequence_id: ' job-1 ', message: '50% done', title: '', priority: 3 },
+ });
+ const request = sendRequest.mock.calls[0][0];
+ expect(request.method).toBe(HttpMethod.POST);
+ expect(request.url).toBe('https://ntfy.example.com/');
+ expect(request.body).toEqual({ topic: 'alerts', message: '50% done', priority: 3, sequence_id: 'job-1' });
+ expect(result).toEqual({ id: 'u1', sequence_id: 'job-1' });
+ });
+
+ it('refuses an invalid sequence id before any request', async () => {
+ await expect(
+ runAction({ action: updateNotification, propsValue: { topic: 'alerts', sequence_id: 'a/b', message: 'x' } })
+ ).rejects.toThrow(/Sequence ID/);
+ expect(sendRequest).not.toHaveBeenCalled();
+ });
+});
+
+describe('Clear Notification', () => {
+ it('sends PUT /<topic>/<sequence_id>/clear', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: { id: 'c', event: 'message_clear' } });
+ await runAction({ action: clearNotification, propsValue: { topic: 'alerts', sequence_id: 'job-1' } });
+ const request = sendRequest.mock.calls[0][0];
+ expect(request.method).toBe(HttpMethod.PUT);
+ expect(request.url).toBe('https://ntfy.example.com/alerts/job-1/clear');
+ });
+});
+
+describe('Get Account', () => {
+ it('never returns tokens, emails, phone numbers or the sync topic', async () => {
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: {},
+ body: {
+ username: 'jane',
+ role: 'user',
+ sync_topic: 'secret-sync',
+ tokens: [{ token: 'tk_secret', label: 'x' }],
+ emails: [{ address: '[email protected]', primary: true }],
+ phone_numbers: ['+12223334444'],
+ tier: { code: 'free', name: 'Free' },
+ limits: { basis: 'tier', messages: 250 },
+ stats: { messages: 8, messages_remaining: 242 },
+ reservations: [{ topic: 'mine', everyone: 'deny-all' }],
+ },
+ });
+ const result = await runAction({ action: getAccount, propsValue: {}, token: 'tk_secret' });
+ const text = JSON.stringify(result);
+ expect(text).not.toMatch(/tk_secret|[email protected]|2223334444|secret-sync/);
+ expect(result).toMatchObject({
+ username: 'jane',
+ tier_name: 'Free',
+ limits_messages: 250,
+ stats_messages_remaining: 242,
+ reserved_topics: 'mine',
+ });
+ });
+});
+
+describe('Get Attachment Info', () => {
+ it('returns exists:false on 404 and strips a file extension', async () => {
+ sendRequest.mockRejectedValueOnce({ response: { status: 404, body: { code: 40401, error: 'page not found' } } });
+ const result = await runAction({ action: getAttachmentInfo, propsValue: { message_id: 'NOPEnope1234.txt' } });
+ expect(sendRequest.mock.calls[0][0]).toMatchObject({
+ method: HttpMethod.HEAD,
+ url: 'https://ntfy.example.com/file/NOPEnope1234',
+ });
+ expect(result).toEqual({
+ message_id: 'NOPEnope1234',
+ exists: false,
+ size_bytes: null,
+ content_type: null,
+ url: 'https://ntfy.example.com/file/NOPEnope1234',
+ });
+ });
+
+ it('rethrows other errors', async () => {
+ sendRequest.mockRejectedValueOnce({ response: { status: 401, body: { error: 'unauthorized' } } });
+ await expect(runAction({ action: getAttachmentInfo, propsValue: { message_id: 'abc' } })).rejects.toThrow(
+ /HTTP 401/
+ );
+ });
+});
+
+describe('Send File', () => {
+ it('uploads the file bytes with a duck-typed file object', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: { id: 'f1' } });
+ await runAction({
+ action: sendFile,
+ propsValue: {
+ topic: 'alerts',
+ file: { filename: 'note.txt', data: Buffer.from('hello'), extension: 'txt', base64: 'aGVsbG8=' },
+ message: undefined,
+ priority: 4,
+ },
+ });
+ const request = sendRequest.mock.calls[0][0];
+ expect(request.method).toBe(HttpMethod.PUT);
+ expect(request.body.toString()).toBe('hello');
+ expect(request.headers).toMatchObject({ 'X-Priority': '4' });
+ expect(request.headers).not.toHaveProperty('X-Message');
+ });
+
+ it('encodes a non-ASCII tag so the request can be sent', async () => {
+ sendRequest.mockResolvedValueOnce({ status: 200, headers: {}, body: { id: 'f2' } });
+ await runAction({
+ action: sendFile,
+ propsValue: { topic: 'alerts', file: { filename: 'a.txt', data: Buffer.from('a') }, tags: ['✅', 'ok'] },
+ });
+ const tags = sendRequest.mock.calls[0][0].headers['X-Tags'];
+ expect(tags).toBe(ntfyClient.encodeToRFC2047('✅,ok'));
+ expect(() => new Headers({ 'X-Tags': tags })).not.toThrow();
+ });
+});
+
+describe('New Message trigger', () => {
+ it('seeds the cursor on enable, then emits each new message once', async () => {
+ const store = new Map<string, string>();
+ const ctx = triggerContext({ propsValue: { topics: 't', priority: undefined, tags: undefined }, store });
+ const now = 1790662800;
+ const dateHeader = { date: new Date(now * 1000).toUTCString() };
+
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: dateHeader,
+ body: ndjson([{ id: 'before', time: now - 5, event: 'message', topic: 't' }]),
+ });
+ await newMessage.onEnable(ctx);
+ expect(sendRequest.mock.calls[0][0].queryParams).toMatchObject({ since: '60s' });
+
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: dateHeader,
+ body: ndjson([
+ { id: 'before', time: now - 5, event: 'message', topic: 't' },
+ { id: 'n1', time: now + 10, event: 'message', topic: 't' },
+ { id: 'n2', time: now + 11, event: 'message', topic: 't' },
+ ]),
+ });
+ const first = await newMessage.run(ctx);
+ expect(sendRequest.mock.calls[1][0].queryParams).toMatchObject({ since: String(now - 60) });
+ expect(first).toEqual([expect.objectContaining({ id: 'n1' }), expect.objectContaining({ id: 'n2' })]);
+
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: dateHeader,
+ body: ndjson([
+ { id: 'n1', time: now + 10, event: 'message', topic: 't' },
+ { id: 'n2', time: now + 11, event: 'message', topic: 't' },
+ ]),
+ });
+ expect(await newMessage.run(ctx)).toEqual([]);
+ });
+
+ it('marks the runs of a capped replay that may have skipped messages and still advances the cursor', async () => {
+ const store = new Map<string, string>([['ntfy_new_message_cursor', JSON.stringify({ lastTime: 1000, seen: [] })]]);
+ const ctx = triggerContext({ propsValue: { topics: 't', priority: undefined, tags: undefined }, store });
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: { 'x-messages-truncated': '1' },
+ body: ndjson([
+ { id: 'k1', time: 1500, event: 'message', topic: 't' },
+ { id: 'k2', time: 1501, event: 'message', topic: 't' },
+ ]),
+ });
+ const truncated = await newMessage.run(ctx);
+ expect(truncated).toEqual([
+ expect.objectContaining({ id: 'k1', replay_truncated: true }),
+ expect.objectContaining({ id: 'k2', replay_truncated: true }),
+ ]);
+ expect(JSON.parse(store.get('ntfy_new_message_cursor') ?? 'null')).toMatchObject({ lastTime: 1501 });
+
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: {},
+ body: ndjson([
+ { id: 'k2', time: 1501, event: 'message', topic: 't' },
+ { id: 'k3', time: 1502, event: 'message', topic: 't' },
+ ]),
+ });
+ expect(await newMessage.run(ctx)).toEqual([expect.objectContaining({ id: 'k3', replay_truncated: false })]);
+ });
+
+ it('flags every run of a multi-topic poll when one topic was capped, even if another topic returns older messages', async () => {
+ const store = new Map<string, string>([
+ ['ntfy_new_message_cursor', JSON.stringify({ lastTime: 1000, seen: [{ id: 'b-old', time: 990 }] })],
+ ]);
+ const ctx = triggerContext({ propsValue: { topics: 'ta,tb', priority: undefined, tags: undefined }, store });
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: { 'x-messages-truncated': '1' },
+ body: ndjson([
+ { id: 'b-old', time: 990, event: 'message', topic: 'tb' },
+ { id: 'a-kept', time: 1400, event: 'message', topic: 'ta' },
+ { id: 'b-new', time: 1401, event: 'message', topic: 'tb' },
+ ]),
+ });
+ const runs = await newMessage.run(ctx);
+ expect(sendRequest.mock.calls[0][0].url).toBe('https://ntfy.example.com/ta,tb/json');
+ expect(runs).toEqual([
+ expect.objectContaining({ id: 'a-kept', replay_truncated: true }),
+ expect.objectContaining({ id: 'b-new', replay_truncated: true }),
+ ]);
+ });
+
+ it('flags a capped poll even when the only messages returned are older than the cursor', async () => {
+ const store = new Map<string, string>([['ntfy_new_message_cursor', JSON.stringify({ lastTime: 1000, seen: [] })]]);
+ const ctx = triggerContext({ propsValue: { topics: 't', priority: [5], tags: undefined }, store });
+ sendRequest.mockResolvedValueOnce({
+ status: 200,
+ headers: { 'x-messages-truncated': '1' },
+ body: ndjson([{ id: 'late', time: 995, event: 'message', topic: 't', priority: 5 }]),
+ });
+ expect(await newMessage.run(ctx)).toEqual([expect.objectContaining({ id: 'late', replay_truncated: true })]);
+ });
+
+ it('keeps the cursor on republish', async () => {
+ const store = new Map<string, string>([['ntfy_new_message_cursor', JSON.stringify({ lastTime: 5, seen: [] })]]);
+ const ctx = { ...triggerContext({ propsValue: { topics: 't' }, store }), isRepublish: true };
+ await newMessage.onEnable(ctx);
+ expect(sendRequest).not.toHaveBeenCalled();
+ expect(JSON.parse(store.get('ntfy_new_message_cursor') ?? 'null')).toEqual({ lastTime: 5, seen: [] });
+ });
+});
+
+describe('Custom API Call base URL', () => {
+ const propsValue = { url: { url: '/v1/health' }, method: HttpMethod.GET, headers: {}, queryParams: {}, body: {} };
+
+ it('uses the validated Server URL, so a relative path cannot land in a query string', async () => {
+ const customApiCall = ntfy.getAction('custom_api_call');
+ if (!customApiCall) {
+ throw new Error('custom_api_call is missing');
+ }
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockImplementation(async () => new Response('{"healthy":true}', { status: 200, headers: { 'content-type': 'application/json' } }));
+ try {
+ await runAction({ action: customApiCall, propsValue });
+ const transport = { mockedHttpClientCalls: sendRequest.mock.calls.length, fetchCalls: fetchSpy.mock.calls.length };
+ expect(transport).toEqual({ mockedHttpClientCalls: 0, fetchCalls: 1 });
+ expect(String(fetchSpy.mock.calls[0][0])).toBe('https://ntfy.example.com/v1/health');
+ fetchSpy.mockClear();
+ await expect(
+ runAction({ action: customApiCall, propsValue, baseUrl: 'https://ntfy.example.com/?t=1' })
+ ).rejects.toThrow(/"\?" or "#"/);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ expect(sendRequest).not.toHaveBeenCalled();
+ } finally {
+ fetchSpy.mockRestore();
+ }
+ });
+});
+
+describe('Custom API Call auth mapping', () => {
+ it('sends no Authorization header without a token (0.3.0 sent "Bearer undefined") and Bearer with one', () => {
+ expect(ntfy.getAction('custom_api_call')).toBeDefined();
+ expect(ntfyClient.authHeaders(testAuth())).toEqual({});
+ expect(ntfyClient.authHeaders(testAuth({ token: ' ' }))).toEqual({});
+ expect(ntfyClient.authHeaders(testAuth({ token: 'tk_abc' }))).toEqual({ Authorization: 'Bearer tk_abc' });
+ });
+});
diff --git a/packages/pieces/community/ntfy/test/client.test.ts b/packages/pieces/community/ntfy/test/client.test.ts
new file mode 100644
index 00000000000..341fe12eb35
--- /dev/null
+++ b/packages/pieces/community/ntfy/test/client.test.ts
@@ -0,0 +1,305 @@
+import { describe, expect, it } from 'vitest';
+import { AppConnectionType } from '@activepieces/pieces-framework';
+import { ntfyClient, NtfyAuthValue, NtfyMessage } from '../src/lib/common/client';
+
+const decode = (v: unknown) => {
+ const m = /^=\?UTF-8\?B\?(.*)\?=$/.exec(String(v));
+ return m ? Buffer.from(m[1], 'base64').toString('utf-8') : undefined;
+};
+
+function legacyHeaders(p: {
+ title: string;
+ message: string;
+ priority?: string;
+ tags?: string[];
+ icon?: string;
+ actions?: string;
+ click?: string;
+ delay?: string;
+}) {
+ return {
+ 'X-Message': ntfyClient.encodeToRFC2047(p.message),
+ 'X-Title': ntfyClient.encodeToRFC2047(p.title),
+ 'X-Priority': p.priority,
+ 'X-Tags': p.tags?.join(','),
+ 'X-Icon': p.icon,
+ 'X-Actions': p.actions,
+ 'X-Click': p.click,
+ 'X-Delay': p.delay,
+ };
+}
+
+describe('buildSendNotificationHeaders (Send Notification)', () => {
+ it('does not crash and sends no X-Title when the title is empty', () => {
+ expect(() => ntfyClient.buildSendNotificationHeaders({ message: 'hi', title: undefined })).not.toThrow();
+ const headers = ntfyClient.buildSendNotificationHeaders({ message: 'hi', title: undefined });
+ expect(headers).not.toHaveProperty('X-Title');
+ expect(ntfyClient.buildSendNotificationHeaders({ message: 'hi', title: '' })).not.toHaveProperty('X-Title');
+ expect(decode(headers['X-Message'])).toBe('hi');
+ });
+
+ it('builds the same headers as 0.3.0 when a title is set and no new props are used', () => {
+ const input = {
+ title: 'Ünïcode title',
+ message: 'multi\nline',
+ priority: 'high',
+ tags: ['a', 'b'],
+ icon: 'https://example.com/i.png',
+ actions: 'view, Open, https://example.com',
+ click: 'https://example.com',
+ delay: '30m',
+ };
+ expect(ntfyClient.buildSendNotificationHeaders(input)).toEqual(legacyHeaders(input));
+ expect(ntfyClient.buildSendNotificationHeaders({ ...input, markdown: false, cache: undefined })).toEqual(
+ legacyHeaders(input)
+ );
+ });
+
+ it('sends the new optional headers only when set', () => {
+ const headers = ntfyClient.buildSendNotificationHeaders({
+ message: 'm',
+ attach: ' https://example.com/f.pdf ',
+ filename: 'rapport-é.pdf',
+ markdown: true,
+ email: '[email protected]',
+ call: '+12223334444',
+ sequence_id: 'job-42',
+ cache: 'no',
+ firebase: 'no',
+ });
+ expect(headers['X-Attach']).toBe('https://example.com/f.pdf');
+ expect(decode(headers['X-Filename'])).toBe('rapport-é.pdf');
+ expect(headers['X-Markdown']).toBe('yes');
+ expect(headers['X-Email']).toBe('[email protected]');
+ expect(headers['X-Call']).toBe('+12223334444');
+ expect(headers['X-Sequence-ID']).toBe('job-42');
+ expect(headers['X-Cache']).toBe('no');
+ expect(headers['X-Firebase']).toBe('no');
+ });
+
+ it('encodes non-ASCII header values instead of passing bytes fetch rejects', () => {
+ const headers = ntfyClient.buildSendNotificationHeaders({
+ message: 'm',
+ tags: ['✅', 'backup'],
+ actions: 'view, Öffnen, https://example.com',
+ delay: 'demain, 10h',
+ });
+ expect(decode(headers['X-Tags'])).toBe('✅,backup');
+ expect(decode(headers['X-Actions'])).toBe('view, Öffnen, https://example.com');
+ expect(headers['X-Delay']).toBe('demain, 10h');
+ expect(() => new Headers({ 'X-Tags': String(headers['X-Tags']), 'X-Actions': String(headers['X-Actions']) })).not.toThrow();
+ });
+
+ it('leaves ASCII values with surrounding whitespace as 0.3.0 sent them and encodes multi-line ones', () => {
+ const trailing = ntfyClient.buildSendNotificationHeaders({ message: 'm', actions: 'view, Open, https://example.com\n' });
+ expect(trailing['X-Actions']).toBe('view, Open, https://example.com\n');
+ const multiLine = ntfyClient.buildSendNotificationHeaders({
+ message: 'm',
+ actions: 'view, Open, https://example.com;\nview, Docs, https://docs.ntfy.sh',
+ });
+ expect(decode(multiLine['X-Actions'])).toBe('view, Open, https://example.com;\nview, Docs, https://docs.ntfy.sh');
+ });
+
+ it('accepts tags given as a comma-separated or JSON-array string', () => {
+ expect(ntfyClient.buildSendNotificationHeaders({ message: 'm', tags: 'a, b' })['X-Tags']).toBe('a,b');
+ expect(ntfyClient.buildSendNotificationHeaders({ message: 'm', tags: '["a","b"]' })['X-Tags']).toBe('a,b');
+ });
+
+ it('rejects a sequence id ntfy would refuse', () => {
+ expect(() => ntfyClient.buildSendNotificationHeaders({ message: 'm', sequence_id: 'has space' })).toThrow(
+ /Sequence ID/
+ );
+ });
+});
+
+describe('buildJsonPublishBody', () => {
+ it('drops unset fields and types the rest', () => {
+ const body = ntfyClient.buildJsonPublishBody({
+ topic: ' alerts ',
+ message: '**hi**',
+ title: ' ',
+ priority: '4',
+ tags: ['warning', ' ', 'test'],
+ actions: '[{"action":"view","label":"Open","url":"https://example.com"}]',
+ markdown: true,
+ sequence_id: 's1',
+ disable_cache: true,
+ disable_firebase: false,
+ });
+ expect(body).toEqual({
+ topic: 'alerts',
+ message: '**hi**',
+ priority: 4,
+ tags: ['warning', 'test'],
+ actions: [{ action: 'view', label: 'Open', url: 'https://example.com' }],
+ markdown: true,
+ sequence_id: 's1',
+ cache: 'no',
+ });
+ });
+
+ it('validates priority, actions and topic', () => {
+ expect(() => ntfyClient.buildJsonPublishBody({ topic: 't', priority: 6 })).toThrow(/Priority/);
+ expect(() => ntfyClient.buildJsonPublishBody({ topic: 't', actions: '{bad' })).toThrow(/JSON array/);
+ expect(() => ntfyClient.buildJsonPublishBody({ topic: 't', actions: [{}, {}, {}, {}] })).toThrow(/at most 3/);
+ expect(() => ntfyClient.buildJsonPublishBody({ topic: '../v1/account' })).toThrow(/Topic/);
+ });
+
+ it('refuses Delay with Do Not Cache or Email To, which ntfy rejects with HTTP 400', () => {
+ expect(() => ntfyClient.buildJsonPublishBody({ topic: 't', delay: '2h', disable_cache: true })).toThrow(
+ /Do Not Cache cannot be combined with Delay/
+ );
+ expect(() => ntfyClient.buildJsonPublishBody({ topic: 't', delay: '2h', email: '[email protected]' })).toThrow(
+ /Email To cannot be combined with Delay/
+ );
+ expect(ntfyClient.buildJsonPublishBody({ topic: 't', delay: ' ', disable_cache: true })).toEqual({
+ topic: 't',
+ cache: 'no',
+ });
+ });
+});
+
+describe('normalizeTags / normalizePriorityFilter', () => {
+ it('reads arrays, JSON-array strings and comma-separated strings', () => {
+ expect(ntfyClient.normalizeTags(['a', ' b '])).toEqual(['a', 'b']);
+ expect(ntfyClient.normalizeTags('["a","b"]')).toEqual(['a', 'b']);
+ expect(ntfyClient.normalizeTags('a, b')).toEqual(['a', 'b']);
+ expect(ntfyClient.normalizeTags('')).toBeUndefined();
+ expect(ntfyClient.normalizePriorityFilter([4, '5'])).toEqual([4, 5]);
+ expect(ntfyClient.normalizePriorityFilter('[4,5]')).toEqual([4, 5]);
+ expect(ntfyClient.normalizePriorityFilter('4,5')).toEqual([4, 5]);
+ expect(ntfyClient.normalizePriorityFilter([])).toBeUndefined();
+ expect(() => ntfyClient.normalizePriorityFilter('9')).toThrow(/Priority/);
+ });
+
+ it('splits a mapped "4,5" that the engine wraps into a one-item list', () => {
+ expect(ntfyClient.normalizePriorityFilter(['4,5'])).toEqual([4, 5]);
+ expect(ntfyClient.normalizeTags(['backup, warning'])).toEqual(['backup', 'warning']);
+ });
+});
+
+describe('newestFirst', () => {
+ it('puts the later of two same-second messages first, as ntfy returns them oldest first', () => {
+ const ordered = ntfyClient.newestFirst([
+ { id: 'a', time: 10, event: 'message', topic: 't' },
+ { id: 'b', time: 20, event: 'message', topic: 't' },
+ { id: 'c', time: 20, event: 'message', topic: 't' },
+ ]);
+ expect(ordered.map((m) => m.id)).toEqual(['c', 'b', 'a']);
+ });
+});
+
+describe('validateTopicList / baseUrl', () => {
+ it('accepts comma-separated topics and rejects path tricks', () => {
+ expect(ntfyClient.validateTopicList(' a , b_2,c-3 ')).toBe('a,b_2,c-3');
+ expect(() => ntfyClient.validateTopicList('a,b/json')).toThrow(/Topic/);
+ expect(() => ntfyClient.validateTopicList('')).toThrow(/required/);
+ });
+
+ it('trims trailing slashes and refuses non-http URLs', () => {
+ const auth = (base_url: string): NtfyAuthValue => ({
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: { base_url, access_token: undefined },
+ });
+ expect(ntfyClient.baseUrl(auth(' https://ntfy.example.com/sub/ '))).toBe('https://ntfy.example.com/sub');
+ expect(() => ntfyClient.baseUrl(auth('ftp://ntfy.example.com'))).toThrow(/https/);
+ expect(() => ntfyClient.baseUrl(auth('ntfy.example.com'))).toThrow(/not a valid URL/);
+ });
+
+ it('refuses a query, fragment or credentials that would swallow the API path', () => {
+ const auth = (base_url: string): NtfyAuthValue => ({
+ type: AppConnectionType.CUSTOM_AUTH,
+ props: { base_url, access_token: undefined },
+ });
+ expect(() => ntfyClient.baseUrl(auth('https://ntfy.example.com/?tenant=a'))).toThrow(/"\?" or "#"/);
+ expect(() => ntfyClient.baseUrl(auth('https://ntfy.example.com/#x'))).toThrow(/"\?" or "#"/);
+ expect(() => ntfyClient.baseUrl(auth('https://ntfy.example.com?'))).toThrow(/"\?" or "#"/);
+ expect(() => ntfyClient.baseUrl(auth('https://user:[email protected]'))).toThrow(/user name or password/);
+ });
+});
+
+describe('parseNdjson', () => {
+ it('parses one message per line and skips blank lines', () => {
+ const text =
+ '{"id":"a","time":1,"event":"message","topic":"t","message":"x"}\n\n{"id":"b","time":2,"event":"message_clear","topic":"t"}\n';
+ expect(ntfyClient.parseNdjson(text).map((m) => m.id)).toEqual(['a', 'b']);
+ });
+
+ it('returns [] for an empty body and wraps an already-parsed object', () => {
+ expect(ntfyClient.parseNdjson('')).toEqual([]);
+ expect(ntfyClient.parseNdjson(undefined)).toEqual([]);
+ expect(ntfyClient.parseNdjson({ id: 'a', time: 1, event: 'message', topic: 't' })).toHaveLength(1);
+ });
+
+ it('throws on a line that is not JSON', () => {
+ expect(() => ntfyClient.parseNdjson('{"id":"a","time":1,"event":"message"}\nnot json')).toThrow(/line 2/);
+ });
+});
+
+describe('advanceCursor (New Message trigger)', () => {
+ const msg = ({ id, time, event = 'message' }: { id: string; time: number; event?: string }): NtfyMessage => ({
+ id,
+ time,
+ event,
+ topic: 't',
+ });
+
+ it('emits unseen messages oldest first and skips non-message events', () => {
+ const { newItems, cursor } = ntfyClient.advanceCursor({
+ cursor: { lastTime: 1000, seen: [] },
+ fetched: [msg({ id: 'b', time: 1002 }), msg({ id: 'a', time: 1001 }), msg({ id: 'c', time: 1003, event: 'message_delete' })],
+ });
+ expect(newItems.map((m) => m.id)).toEqual(['a', 'b']);
+ expect(cursor.lastTime).toBe(1002);
+ expect(cursor.seen.map((s) => s.id).sort()).toEqual(['a', 'b']);
+ });
+
+ it('does not re-emit messages returned again by the overlap window', () => {
+ const first = ntfyClient.advanceCursor({
+ cursor: { lastTime: 1000, seen: [] },
+ fetched: [msg({ id: 'a', time: 1001 }), msg({ id: 'b', time: 1001 })],
+ });
+ const second = ntfyClient.advanceCursor({
+ cursor: first.cursor,
+ fetched: [msg({ id: 'a', time: 1001 }), msg({ id: 'b', time: 1001 }), msg({ id: 'c', time: 1001 })],
+ });
+ expect(second.newItems.map((m) => m.id)).toEqual(['c']);
+ });
+
+ it('catches a scheduled message delivered with an earlier time than the newest one', () => {
+ const first = ntfyClient.advanceCursor({
+ cursor: { lastTime: 1000, seen: [] },
+ fetched: [msg({ id: 'late-writer', time: 1030 })],
+ });
+ const second = ntfyClient.advanceCursor({
+ cursor: first.cursor,
+ fetched: [msg({ id: 'sched', time: 1020 }), msg({ id: 'late-writer', time: 1030 })],
+ });
+ expect(second.newItems.map((m) => m.id)).toEqual(['sched']);
+ });
+
+ it('ignores messages older than the overlap window and keeps the seen list bounded', () => {
+ const overlap = ntfyClient.CURSOR_OVERLAP_SECONDS;
+ const { newItems, cursor } = ntfyClient.advanceCursor({
+ cursor: { lastTime: 5000, seen: [{ id: 'old', time: 5000 - overlap - 10 }, { id: 'recent', time: 4990 }] },
+ fetched: [msg({ id: 'ancient', time: 100 }), msg({ id: 'new', time: 5000 + overlap + 5 })],
+ });
+ expect(newItems.map((m) => m.id)).toEqual(['new']);
+ expect(cursor.seen.map((s) => s.id)).toEqual(['new']);
+ });
+});
+
+describe('toNtfyError', () => {
+ it('turns an ntfy JSON error into a readable message with the status', () => {
+ const error = ntfyClient.toNtfyError({
+ response: { status: 401, body: { code: 40101, http: 401, error: 'unauthorized' } },
+ });
+ expect(error).toBeInstanceOf(Error);
+ expect(String(error)).toMatch(/HTTP 401: unauthorized \(ntfy code 40101\).*Access Token/);
+ });
+
+ it('rethrows errors without an HTTP status unchanged', () => {
+ const original = new Error('socket hang up');
+ expect(ntfyClient.toNtfyError(original)).toBe(original);
+ });
+});
diff --git a/packages/pieces/community/ntfy/test/helpers.ts b/packages/pieces/community/ntfy/test/helpers.ts
new file mode 100644
index 00000000000..5ab5b1164a0
--- /dev/null
+++ b/packages/pieces/community/ntfy/test/helpers.ts
@@ -0,0 +1,64 @@
+import {
+ ActionContext,
+ AppConnectionType,
+ InputPropertyMap,
+ StaticPropsValue,
+ TriggerHookContext,
+ TriggerStrategy,
+} from '@activepieces/pieces-framework';
+import { createMockActionContext, createMockPollingTriggerContext } from '../../../framework/src/lib/test';
+import { ntfyAuth } from '../src/lib/auth';
+
+export function runAction<Props extends InputPropertyMap>({
+ action,
+ propsValue,
+ token,
+ baseUrl,
+}: {
+ action: { run: (context: ActionContext<typeof ntfyAuth, Props>) => Promise<unknown> };
+ propsValue: StaticPropsValue<Props>;
+ token?: string;
+ baseUrl?: string;
+}) {
+ return action.run({
+ ...createMockActionContext<Props>({ propsValue }),
+ auth: testAuth({ token, baseUrl }),
+ });
+}
+
+export function triggerContext<Props extends InputPropertyMap>({
+ propsValue,
+ store,
+}: {
+ propsValue: StaticPropsValue<Props>;
+ store: Map<string, string>;
+}): TriggerHookContext<typeof ntfyAuth, Props, TriggerStrategy.POLLING> {
+ return {
+ ...createMockPollingTriggerContext<Props>({ propsValue }),
+ auth: testAuth(),
+ store: {
+ put: async <T>(key: string, value: T) => {
+ store.set(key, JSON.stringify(value));
+ return value;
+ },
+ get: async <T>(key: string): Promise<T | null> => {
+ const raw = store.get(key);
+ return raw === undefined ? null : JSON.parse(raw);
+ },
+ delete: async (key: string) => {
+ store.delete(key);
+ },
+ },
+ };
+}
+
+export function testAuth({ token, baseUrl = 'https://ntfy.example.com/' }: { token?: string; baseUrl?: string } = {}) {
+ return {
+ type: AppConnectionType.CUSTOM_AUTH as const,
+ props: { base_url: baseUrl, access_token: token },
+ };
+}
+
+export function ndjson(lines: Record<string, unknown>[]): string {
+ return lines.map((l) => JSON.stringify(l)).join('\n') + '\n';
+}
diff --git a/packages/pieces/community/ntfy/vitest.config.ts b/packages/pieces/community/ntfy/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/ntfy/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})