Skip to content
Skip to chapter

Chapter 47

Advanced integrations and data

21 min read

Post Slack alerts and handle slash commands

Post one bot message to a private Slack practice channel from Apps Script, then verify slash-command signatures on a separate Node server.

By the end

Tell bot authorization apart from request signatures, keep uncertain message outcomes, and return a small fictional command preview within Slack's three-second response window.

Chapter navigation

Separate a message from a command

Send one bot message to a private Slack channel from Apps Script. Save a local record of the attempt to avoid sending a duplicate if Slack's response is lost. The same practice app also provides a slash command, /as-workshop-preview. A person runs it, a separate Node server calculates a preview for three fictional requests, and only that person sees the result. The command does not schedule or post anything.

You need a disposable Slack workspace, a private Apps Script project, and a Linux host with a public hostname that its administrator has approved for this exercise. The message and the command work independently:

PathCredential and executionResult
From Apps Script, run manually, to the Slack Web APIGoogle authorizes URL Fetch. Slack authorizes the installed bot token.At most one chat.postMessage attempt for the saved message record, called the intent. A confirmed response supplies the channel and message timestamp.
From Slack, through a public HTTPS proxy, to a Node HTTP serverThe Node server verifies Slack's signature over the raw request bytes, then checks the configured workspace, app, channel, command, and allowed user IDs.One HTTP response containing an ephemeral fictional preview. The server does not call Apps Script, use the bot token, queue work, or change anything remotely.

The HTTP chapter introduced requests and responses. This chapter adds a second question, who may do what. A request can be valid HTTP and carry a valid Slack credential and still ask for an action that is not allowed. A sent request also does not prove that the message was posted.

warning

This exercise installs a Slack app, runs a service on a public HTTPS host, and sends ordinary Slack notifications in the practice channel. Get the workspace owner's and the host administrator's approval before you start.

Record the IDs and credentials first

Create a new private channel named as-workshop-practice in a practice workspace you are allowed to use. Keep the channel unshared: no Slack Connect, no organization-wide shared channel, no real operational conversations, and only the people approved for the practice.

Record two IDs:

  • The channel ID, shown in the channel's details. The code sends to this ID, because a channel name can change.

  • The workspace ID, the T... part of a URL such as app.slack.com/client/T.../C.... The workspace's domain name is not an ID.

The app needs no user-token scopes. It needs exactly these bot token scopes:

ScopeWhy this project needs itWhat it does not replace
chat:writeSend the one message as the app's bot.Private channel membership and workspace policy.
groups:readRead metadata for the private channel the app has joined before sending.Message-history access or permission to join arbitrary private channels.
commandsInstall the configured slash command.Verification of an incoming HTTP request.

Slack documents each scope: chat:write, groups:read, and commands. Do not add chat:write.public, history scopes, user scopes, incoming webhooks, or administrative scopes. A token alone does not let the bot post to a private channel. The bot must also be a member of that channel (chat.postMessage).

Before you create the app, check whether the workspace already has a /as-workshop-preview command. If it does, stop. Do not override an existing integration.

To create the app, open Manage Apps, choose Create New App > From a manifest (app manifest reference), select the practice workspace, and paste the supplied JSON. Before you paste it, replace its placeholder hostname slack-practice.example.invalid with the real hostname of your command server. The reserved .invalid name never resolves. Keep the command name /as-workshop-preview and the path /slack/commands unchanged.

slack-app-manifest.json
{
  "_metadata": {"major_version": 2, "minor_version": 1},
  "display_information": {
    "name": "Apps Script workshop practice",
    "description": "One private-channel bot message and a fictional slash-command preview."
  },
  "features": {
    "bot_user": {"display_name": "as-workshop-practice", "always_online": false},
    "slash_commands": [{
      "command": "/as-workshop-preview",
      "description": "Calculate a fictional workshop preparation preview without scheduling or posting work",
      "usage_hint": "preview REQ-001 2 | help",
      "should_escape": true,
      "url": "https://slack-practice.example.invalid/slack/commands"
    }]
  },
  "oauth_config": {"scopes": {"bot": ["chat:write", "groups:read", "commands"]}},
  "settings": {
    "org_deploy_enabled": false,
    "socket_mode_enabled": false,
    "token_rotation_enabled": false
  }
}

Download slack-app-manifest.json

In the created app, inspect OAuth & Permissions > Bot Token Scopes and Slash Commands. The Request URL must be the exact public URL https://YOUR-APPROVED-HOST/slack/commands. Do not use a redirect, an Apps Script deployment URL, localhost, or a private IP address. Keep Escape channels, users, and links sent to your app enabled. Escaping does not make the command text safe to trust. The parser below accepts only its small grammar and does not interpret Slack mention syntax.

If you change the command or scopes after installation, follow Slack's reinstall prompt and verify the resulting grants. Workspace app-approval policy still applies. Do not bypass it with a different token or workspace.

Keep this a single-workspace app. Do not enable public distribution, organization deployment, Socket Mode, event subscriptions, or interactive buttons. Slack sends publicly distributed slash commands an extra certificate check request (ssl_check). This handler does not answer ssl_check and does not accept a legacy verification token in place of a signature, so it works only for a single-workspace app.

Under OAuth & Permissions, choose Install to Workspace and approve only the intended grants. Copy the resulting Bot User OAuth Token (xoxb-...). You will paste it into the Apps Script project's Script Properties in the next section. Installing the app does not add its bot to any private channel. Add the bot to the practice channel yourself. In the channel's details, choose Integrations > Add apps, or type /invite in the channel. Check that the bot you added belongs to this app. Slack's settings guide and installation guide describe these steps.

In Basic Information > App Credentials, record the App ID (A...) and the Signing Secret. The signing secret goes only into the command host's protected credential file, described below. For each person allowed to run the command, open that person's Slack profile and choose More > Copy member ID. Allow one to five exact U... or W... IDs. A display name is not an ID.

ValueOwner and storageMeaning
Bot tokenApp installation administrator (private sender's SLACK_BOT_TOKEN Script Property). Project editors must be trusted to use it.Lets anyone holding it act as this installed bot, within its scopes and channel memberships.
Signing secretApp administrator (root-managed host file delivered with systemd LoadCredential).Shared key used to authenticate Slack's incoming request. Anyone holding it can forge a signature.
Workspace, app, channel, and allowed-user IDsPractice owners (non-secret server configuration and the matching sender properties).The list of who may run the command and where, checked after signature verification.
Apps Script Google consentThe person manually running the sender.Lets the script make external HTTP requests. It grants nothing in Slack.

Do not put either secret in the source, a command URL, a data file, logs, chat, screenshots, or a browser-side script. The Node server has no bot token. The Apps Script sender has no signing secret. The manifest leaves token rotation disabled. Rotated tokens expire, and this project has no code to refresh them, so do not enable rotation for this short practice installation.

Prepare and send one message from Apps Script

Create a private standalone Apps Script project named Slack practice message. Replace Code.gs with the supplied source. In Project Settings, enable Show "appsscript.json" manifest file in editor and replace the manifest with the supplied one. Keep Services empty. The project has no trigger, web-app deployment, doPost, or API-executable deployment.

appsscript.json
{
  "timeZone": "Etc/UTC",
  "runtimeVersion": "V8",
  "oauthScopes": ["https://www.googleapis.com/auth/script.external_request"]
}

Download appsscript.json

Under Project Settings > Script Properties, set only these initial values:

PropertyExact value to supply
SLACK_TEAM_IDThe practice workspace ID.
SLACK_CHANNEL_IDThe ID of the unshared private practice channel.
SLACK_BOT_TOKENThis installation's non-rotating Bot User OAuth Token, copied privately.
SLACK_PRACTICE_TEXTFictional workshop: confirm map labels

Script Properties do not hide values from project editors (property storage). Share neither the project nor its execution logs broadly. The example prints no secret.

Code.gs
/** @typedef {{teamId: string, channelId: string, token: string, text: string}} SlackConfig */
/** @typedef {'prepared' | 'dispatching' | 'accepted' | 'rejected' | 'unknown' | 'observed'} SlackIntentStatus */
/** @typedef {{version: number, id: string, teamId: string, channelId: string, text: string, createdAt: number, status: SlackIntentStatus, ts: string | null, detail: string}} SlackIntent */
/** @typedef {{httpStatus: number, value: Record<string, unknown>, retryAfter: string | null}} SlackReply */
const SLACK_INTENT_KEY = 'SLACK_PRACTICE_INTENT_V1';
const SLACK_REJECTION_CODES = [
  'invalid_auth', 'not_authed', 'account_inactive', 'token_revoked', 'token_expired',
  'missing_scope', 'channel_not_found', 'not_in_channel', 'no_permission', 'is_archived',
  'restricted_action', 'restricted_action_read_only_channel', 'restricted_action_thread_only_channel', 'no_text',
];

/** Preview local configuration/text only; no Slack request or saved intent. @returns {void} */
function previewSlackPracticeMessage() {
  const config = slackConfig_();
  console.log(JSON.stringify({stage: 'local_preview', teamId: config.teamId,
    channelId: config.channelId, fictionalText: config.text, sends: 0}));
}

/** Create this project's ONE intent. An existing record is never replaced. @returns {void} */
function prepareSlackPracticeMessage() {
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('SLACK_LOCAL_BUSY');
  try {
    const config = slackConfig_();
    if (loadSlackIntent_() !== null) throw new Error('SLACK_INTENT_EXISTS: inspect it; do not clear it to repost.');
    const id = Utilities.getUuid().toLowerCase();
    /** @type {SlackIntent} */
    const intent = {version: 1, id: id, teamId: config.teamId, channelId: config.channelId,
      text: config.text + ' [practice intent ' + id + ']', createdAt: Date.now(),
      status: 'prepared', ts: null, detail: 'local_intent_only'};
    saveSlackIntent_(intent);
    console.log(JSON.stringify({stage: 'prepared', intentId: id, teamId: intent.teamId,
      channelId: intent.channelId, fictionalText: intent.text}));
  } finally { lock.releaseLock(); }
}

/**
 * Explicit manual send: at most one chat.postMessage attempt for this saved intent.
 * All non-prepared states refuse another attempt. No automatic retries.
 * @returns {void}
 */
function sendPreparedSlackMessage() {
  const deadline = Date.now() + 40000;
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('SLACK_LOCAL_BUSY');
  try {
    const intent = loadSlackIntent_();
    if (intent === null || intent.status !== 'prepared') throw new Error('SLACK_NO_UNSENT_PREPARED_INTENT');
    const config = slackConfig_();
    if (config.teamId !== intent.teamId || config.channelId !== intent.channelId ||
        intent.text !== config.text + ' [practice intent ' + intent.id + ']') {
      throw new Error('SLACK_CONFIG_CHANGED: restore the reviewed configuration; no send started.');
    }
    const confirmation = PropertiesService.getScriptProperties().getProperty('SLACK_CONFIRM_INTENT_ID');
    if (confirmation !== intent.id) throw new Error('SLACK_CONFIRM_THE_EXACT_INTENT_ID');
    // These are identity/metadata reads. Their failure leaves the intent prepared.
    const identity = slackReadOk_(slackCall_('auth.test', config.token, null, deadline));
    if (identity.team_id !== intent.teamId || typeof identity.bot_id !== 'string' ||
        !/^B[A-Z0-9]{5,31}$/.test(identity.bot_id) || typeof identity.user_id !== 'string' ||
        !/^[UW][A-Z0-9]{5,31}$/.test(identity.user_id)) throw new Error('SLACK_WRONG_BOT_OR_WORKSPACE');
    const info = slackReadOk_(slackCall_('conversations.info', config.token, {channel: intent.channelId}, deadline));
    const channel = slackRecord_(info.channel);
    // groups:read covers private channels the app has joined. info may omit is_member.
    if (channel.id !== intent.channelId || channel.context_team_id !== intent.teamId ||
        channel.is_private !== true || channel.is_archived !== false ||
        channel.is_im !== false || channel.is_mpim !== false || channel.is_shared !== false ||
        channel.is_pending_ext_shared !== false || channel.is_member === false) {
      throw new Error('SLACK_EXPECTED_PRIVATE_UNSHARED_MEMBER_CHANNEL');
    }
    if (Date.now() + 1000 >= deadline) throw new Error('SLACK_READ_DEADLINE_NO_SEND');
    // Persist BEFORE possible dispatch. Failure/termination afterward must never enable repost.
    intent.status = 'dispatching';
    intent.detail = 'dispatch_may_have_started';
    saveSlackIntent_(intent);
    console.log(JSON.stringify({stage: 'dispatch_possible', intentId: intent.id, channelId: intent.channelId}));
    /** @type {SlackReply} */
    let reply;
    try {
      reply = slackCall_('chat.postMessage', config.token, {channel: intent.channelId, text: intent.text,
        mrkdwn: false, parse: 'none', unfurl_links: false, unfurl_media: false}, deadline);
    } catch (error) {
      intent.status = 'unknown';
      intent.detail = 'transport_or_response_unknown';
      saveSlackIntent_(intent);
      throw new Error('SLACK_DELIVERY_UNKNOWN: inspect the saved intent and private channel; never repost.');
    }
    const value = reply.value;
    if (reply.httpStatus === 200 && value.ok === true && value.channel === intent.channelId &&
        typeof value.ts === 'string' && /^[0-9]{10,12}\.[0-9]{6}$/.test(value.ts)) {
      // Keep ts as text, not a floating-point number. Slack can sanitize the returned message.
      intent.status = 'accepted';
      intent.ts = value.ts;
      intent.detail = 'api_confirmed';
    } else if (reply.httpStatus === 429) {
      intent.status = 'rejected';
      intent.detail = 'http_429';
    } else if (reply.httpStatus === 200 && value.ok === false && typeof value.error === 'string' &&
        SLACK_REJECTION_CODES.indexOf(value.error) !== -1) {
      intent.status = 'rejected';
      intent.detail = value.error;
    } else {
      // Slack explicitly allows partial success with internal_error/fatal_error.
      intent.status = 'unknown';
      intent.detail = 'unconfirmed_provider_outcome';
    }
    // If this write fails after Slack accepted, the earlier dispatching record still blocks sending.
    saveSlackIntent_(intent);
    console.log(JSON.stringify({stage: 'message_result', intentId: intent.id, status: intent.status,
      channelId: intent.channelId, ts: intent.ts, detail: intent.detail, retryAfterSeconds: reply.retryAfter}));
    if (intent.status !== 'accepted') throw new Error('SLACK_NOT_CONFIRMED: inspect the result; no automatic repost.');
  } finally { lock.releaseLock(); }
}

/** Inspect only this project's saved fictional operation, never its credential store. @returns {void} */
function inspectSlackMessageIntent() {
  const intent = loadSlackIntent_();
  console.log(JSON.stringify(intent === null ? {stage: 'no_intent'} : {stage: 'saved_intent', intent: intent}));
}

/** Record a HUMAN observation after matching the private channel, bot, text and intent ID. No Slack call. @returns {void} */
function recordObservedSlackMessage() {
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('SLACK_LOCAL_BUSY');
  try {
    const intent = loadSlackIntent_();
    const store = PropertiesService.getScriptProperties();
    const id = store.getProperty('SLACK_OBSERVED_INTENT_ID');
    const ts = store.getProperty('SLACK_OBSERVED_MESSAGE_TS');
    const confirmation = store.getProperty('SLACK_OBSERVATION_CONFIRMATION');
    if (intent === null || (intent.status !== 'dispatching' && intent.status !== 'unknown') ||
        id !== intent.id || typeof ts !== 'string' || !/^[0-9]{10,12}\.[0-9]{6}$/.test(ts) ||
        confirmation !== 'I matched the bot, channel, text and intent ID') throw new Error('SLACK_OBSERVATION_REQUIRED');
    intent.status = 'observed';
    intent.ts = ts;
    intent.detail = 'human_observed_not_api_verified';
    saveSlackIntent_(intent);
    console.log(JSON.stringify({stage: 'human_observation_saved', intentId: intent.id, ts: ts}));
  } finally { lock.releaseLock(); }
}

/** @returns {SlackConfig} */
function slackConfig_() {
  const store = PropertiesService.getScriptProperties();
  const teamId = store.getProperty('SLACK_TEAM_ID');
  const channelId = store.getProperty('SLACK_CHANNEL_ID');
  const token = store.getProperty('SLACK_BOT_TOKEN');
  const text = store.getProperty('SLACK_PRACTICE_TEXT');
  if (typeof teamId !== 'string' || !/^T[A-Z0-9]{5,31}$/.test(teamId) ||
      typeof channelId !== 'string' || !/^[CG][A-Z0-9]{5,31}$/.test(channelId) ||
      typeof token !== 'string' || !/^xoxb-[A-Za-z0-9-]{20,240}$/.test(token) ||
      typeof text !== 'string' || text.length > 160 ||
      !/^Fictional workshop: [A-Za-z0-9 ,.!()-]+$/.test(text) || text.trim() !== text) {
    throw new Error('SLACK_CONFIG_REQUIRED: use the documented IDs, non-rotating bot token and fictional text.');
  }
  return {teamId: teamId, channelId: channelId, token: token, text: text};
}

/** @returns {SlackIntent | null} */
function loadSlackIntent_() {
  const raw = PropertiesService.getScriptProperties().getProperty(SLACK_INTENT_KEY);
  if (raw === null) return null;
  if (raw.length > 4000) throw new Error('SLACK_INTENT_INVALID: retain it for inspection.');
  /** @type {unknown} */
  let parsed;
  try { parsed = JSON.parse(raw); } catch (error) { throw new Error('SLACK_INTENT_INVALID_JSON'); }
  const value = slackRecord_(parsed);
  const status = value.status;
  if (value.version !== 1 || typeof value.id !== 'string' ||
      !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value.id) ||
      typeof value.teamId !== 'string' || !/^T[A-Z0-9]{5,31}$/.test(value.teamId) ||
      typeof value.channelId !== 'string' || !/^[CG][A-Z0-9]{5,31}$/.test(value.channelId) ||
      typeof value.text !== 'string' || value.text.length > 240 ||
      !/^Fictional workshop: [A-Za-z0-9 ,.!()-]+ \[practice intent [0-9a-f-]+\]$/.test(value.text) ||
      !value.text.endsWith(' [practice intent ' + value.id + ']') ||
      typeof value.createdAt !== 'number' || !Number.isSafeInteger(value.createdAt) || value.createdAt <= 0 ||
      (status !== 'prepared' && status !== 'dispatching' && status !== 'accepted' &&
       status !== 'rejected' && status !== 'unknown' && status !== 'observed') ||
      typeof value.detail !== 'string' || !/^[a-z0-9_]{1,80}$/.test(value.detail) ||
      (value.ts !== null && (typeof value.ts !== 'string' || !/^[0-9]{10,12}\.[0-9]{6}$/.test(value.ts))) ||
      ((status === 'accepted' || status === 'observed') !== (value.ts !== null))) {
    throw new Error('SLACK_INTENT_INVALID: do not reset an uncertain send.');
  }
  return {version: 1, id: value.id, teamId: value.teamId, channelId: value.channelId,
    text: value.text, createdAt: value.createdAt, status: status, ts: value.ts, detail: value.detail};
}

/** @param {SlackIntent} intent @returns {void} */
function saveSlackIntent_(intent) {
  const text = JSON.stringify(intent);
  if (Utilities.newBlob(text).getBytes().length > 4000) throw new Error('SLACK_INTENT_TOO_LARGE');
  PropertiesService.getScriptProperties().setProperty(SLACK_INTENT_KEY, text);
}

/**
 * Fixed provider origin and exact method allowlist. No redirects or retries.
 * @param {'auth.test' | 'conversations.info' | 'chat.postMessage'} method
 * @param {string} token
 * @param {Record<string, string | boolean> | null} data
 * @param {number} deadline
 * @returns {SlackReply}
 */
function slackCall_(method, token, data, deadline) {
  if (method !== 'auth.test' && method !== 'conversations.info' && method !== 'chat.postMessage') {
    throw new Error('SLACK_METHOD_NOT_ALLOWED');
  }
  const seconds = Math.min(15, Math.floor((deadline - Date.now()) / 1000));
  if (seconds < 1) throw new Error('SLACK_DEADLINE');
  const readInfo = method === 'conversations.info';
  const channel = data === null ? null : data.channel;
  if (readInfo && (typeof channel !== 'string' || !/^[CG][A-Z0-9]{5,31}$/.test(channel))) {
    throw new Error('SLACK_INFO_CHANNEL_REQUIRED');
  }
  const url = 'https://slack.com/api/' + method + (readInfo ? '?channel=' + encodeURIComponent(String(channel)) : '');
  /** @type {{method: 'get' | 'post', headers: Record<string, string>, followRedirects: boolean, muteHttpExceptions: boolean, validateHttpsCertificates: boolean, timeoutSeconds: number}} */
  const options = {
    method: readInfo ? 'get' : 'post',
    headers: {Authorization: 'Bearer ' + token, Accept: 'application/json'},
    followRedirects: false, muteHttpExceptions: true, validateHttpsCertificates: true, timeoutSeconds: seconds,
  };
  const response = readInfo ? UrlFetchApp.fetch(url, options) :
    UrlFetchApp.fetch(url, Object.assign({}, options, {contentType: 'application/json; charset=utf-8', payload: JSON.stringify(data || {})}));
  if (Date.now() > deadline) throw new Error('SLACK_RESPONSE_DEADLINE');
  const status = response.getResponseCode();
  const headers = slackRecord_(response.getAllHeaders());
  const retry = slackHeader_(headers, 'retry-after');
  const retryAfter = retry !== null && /^[0-9]{1,8}$/.test(retry) ? retry : null;
  // HTTP 429 is an explicit rate refusal; its body need not be JSON.
  if (status === 429) return {httpStatus: status, value: {}, retryAfter: retryAfter};
  if (status !== 200) return {httpStatus: status, value: {}, retryAfter: retryAfter};
  const type = slackHeader_(headers, 'content-type');
  if (type === null || type.split(';')[0].trim().toLowerCase() !== 'application/json') throw new Error('SLACK_EXPECTED_JSON');
  const text = response.getContentText('UTF-8');
  // URL Fetch already downloaded this body; the limit bounds parsing, not transport.
  if (text.length === 0 || text.length > 65536 || Utilities.newBlob(text).getBytes().length > 65536) {
    throw new Error('SLACK_RESPONSE_SIZE');
  }
  /** @type {unknown} */
  let value;
  try { value = JSON.parse(text); } catch (error) { throw new Error('SLACK_INVALID_JSON'); }
  const result = slackRecord_(value);
  if (Date.now() > deadline) throw new Error('SLACK_RESPONSE_DEADLINE');
  return {httpStatus: status, value: result, retryAfter: retryAfter};
}

/** @param {SlackReply} reply @returns {Record<string, unknown>} */
function slackReadOk_(reply) {
  if (reply.httpStatus === 200 && reply.value.ok === true) return reply.value;
  const code = reply.value.error;
  console.error(JSON.stringify({stage: 'read_rejected', httpStatus: reply.httpStatus,
    code: typeof code === 'string' && /^[a-z0-9_]{1,80}$/.test(code) ? code : 'unknown', retryAfterSeconds: reply.retryAfter}));
  throw new Error('SLACK_PREFLIGHT_READ_FAILED: no message attempt started.');
}

/** @param {unknown} value @returns {Record<string, unknown>} */
function slackRecord_(value) {
  if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('SLACK_EXPECTED_OBJECT');
  return /** @type {Record<string, unknown>} */ (value);
}

/** @param {Record<string, unknown>} headers @param {string} wanted @returns {string | null} */
function slackHeader_(headers, wanted) {
  const names = Object.keys(headers).filter((name) => name.toLowerCase() === wanted);
  if (names.length !== 1) return null;
  const value = headers[names[0]];
  return typeof value === 'string' ? value : null;
}

Download Code.gs

Run the functions from the Apps Script editor in this order, and only after you have permission to make the final post:

  1. Run previewSlackPracticeMessage. It checks the format of the local values and logs local_preview, the configured IDs, the fictional text, and sends: 0. It does not contact Slack or check that the token works.

  2. Change only SLACK_PRACTICE_TEXT to Fictional workshop: confirm map labels today. Predict which preview field changes and whether a Slack message appears, then run the preview again. Only fictionalText changes, and no message is sent. Restore Fictional workshop: confirm map labels, preview once more, and review the destination and text before the next step.

  3. Run prepareSlackPracticeMessage once. It saves SLACK_PRACTICE_INTENT_V1 with a new intent ID, the destination, the final text, and the status prepared. The visible text ends with [practice intent YOUR-INTENT-ID] so that a person can tell this message apart from any other. This function makes no Slack request.

  4. Run inspectSlackMessageIntent to see the saved record. Add a new property, SLACK_CONFIRM_INTENT_ID, with the exact saved ID. This confirms that you picked the right record. Do not edit the saved JSON record.

  5. Run sendPreparedSlackMessage once. Approve the manifest's Google external-request scope if prompted. The script first calls auth.test to check the bot and workspace identity, then conversations.info to check that the channel is private, unarchived, and unshared. groups:read covers only channels the bot belongs to. The documented conversation response can omit is_member, so the code does not require it, but a false value still fails. If either read fails, the intent stays prepared and no message attempt has started.

  6. The script saves dispatching before its one possible chat.postMessage call. A checked success logs message_result with status: accepted, the channel, and a string ts. Inspect the private channel and match the bot, the complete fictional text, and the intent ID. Keep ts as text. It is a Slack message timestamp that also identifies the message, and converting it to a JavaScript number can change it.

  7. Run inspectSlackMessageIntent again. Predict what a second sender run will do. Then, if the first record is settled, run sendPreparedSlackMessage once more. It should refuse with SLACK_NO_UNSENT_PREPARED_INTENT before any Slack request, so no second message is created. Do not delete the record to make another run possible.

The sender permits one intent in this project. Its lock coordinates executions of this project only. It does not coordinate with other scripts or Slack clients. Project editors who erase properties, copy the sender into another project, or send directly can bypass this local guard, so keep editors trusted and the sender in one project.

Every request uses the fixed https://slack.com/api/ origin, a Bearer header, JSON, normal TLS certificate validation, and no redirects. The script limits the message text to a small fictional alphabet and disables formatting, link parsing, and unfurls. There is no arbitrary destination URL, mention syntax, attachment, or real recipient data.

The 40-second deadline in the source covers the lock, setup, and the three requests in sequence. Each fetch gets at most 15 seconds, and the script checks how much time remains. The 64 KiB response-size check runs after URL Fetch has downloaded the full response, so it limits how much the script parses, not how much is downloaded (URL Fetch options). These limits do not guarantee exact latency.

Keep uncertainty instead of resending

Slack's Web API commonly reports an application failure as HTTP 200 with ok: false. This sender treats a response as a success only when it has HTTP 200, ok: true, the expected channel, and a well-formed message ts. The script saves a recognized permission or input refusal, or an HTTP 429 rate-limit refusal, as rejected. It saves unknown for an unexpected body, an unrecognized error code, or a transport failure after the request may have been sent. Slack documents that internal_error and fatal_error can follow partial success (method errors).

Saved stateWhat the record establishesNext action
preparedThis code has not started the message attempt.Fix only a diagnosed read or setup problem, restore the reviewed configuration, and recheck the exact confirmation before you run the sender again.
dispatchingThe script saved this record immediately before the one possible request. Execution may have stopped at any point after that.Inspect the original intent and channel. Never infer failure from this state.
acceptedThe script checked Slack's success response and saved the returned timestamp.Keep the record and do not repost.
rejectedThe recorded response was a recognized refusal.Keep it. This exercise provides no function to resend or reset.
unknownThe attempt may have succeeded without a usable response.Check the channel manually. Not finding the message in a quick search does not prove it was not delivered.
observedA person recorded a matching message timestamp.Keep it. A person saw the message, although Slack's API did not confirm it.

Slack's post and the local property write can succeed or fail separately. If Slack accepted the message but saving accepted failed, the earlier dispatching record still blocks a second attempt. A process can also stop right after saving dispatching but before sending anything. The source cannot tell these two cases apart.

For dispatching or unknown, ask the practice channel's owner to inspect the exact channel, bot, final text, and intent ID. If the matching message is found, use its Slack Copy link action to identify its timestamp. A usual permalink ends in /p<seconds><six fractional digits>. Insert a dot before the final six digits, so /p1700000000123456 gives 1700000000.123456. Do not use a displayed clock time or an unrelated thread timestamp. If the link format differs or the match is ambiguous, leave the outcome unknown.

Only after that match, set SLACK_OBSERVED_INTENT_ID to the saved ID, SLACK_OBSERVED_MESSAGE_TS to that exact timestamp string, and SLACK_OBSERVATION_CONFIRMATION to I matched the bot, channel, text and intent ID. Then run recordObservedSlackMessage. It makes no Slack call and records the status observed with the detail human_observed_not_api_verified. It cannot show that no duplicate exists elsewhere. If the message cannot be found or has been deleted, keep the current status. Do not clear the intent or make up a timestamp.

chat.postMessage rate limits generally allow about one message per second per channel, with workspace-wide limits as well. A 429 includes Retry-After. The example records that value when it is a whole number of up to eight digits, but it does not wait or retry. Slack does not use the local intent ID to prevent duplicates. The ID only helps a person match the message by hand.

Host the command outside Apps Script

A Slack slash command sends an HTTP POST with form-encoded fields, including team_id, channel_id, user_id, api_app_id, command, and text. Its signature is in the request headers. An Apps Script web app's event object does not give doPost the raw request headers it needs to check that signature. Do not point the command at the doPost receiver from the webhooks chapter or at a copy of it. This command uses a Node HTTP server with access to the original bytes and headers.

Slack requires an acknowledgement within three seconds. This server calculates its answer locally and returns it in the same HTTP 200 response. It does not queue work for later, call Apps Script, or promise a delayed result. Slack also supplies a response_url for delayed replies, which the server never logs, follows, or uses (slash-command requests and responses).

Prepare the host

Use a dedicated Linux host that its owner administers and has approved for this exercise. It needs systemd with LoadCredential support, Node 24.21.0 installed at /usr/local/bin/node, and a maintained Caddy 2 installation running as its usual system service. Check those versions on the host before installing the source. The Node program refuses to run on any other Node version. It needs no package.json or npm install, and it does not depend on Express or Bolt.

The owner must supply:

  • A real public DNS hostname whose A record, and any AAAA record, resolve to this host.

  • Public inbound TCP ports 80 and 443.

  • Correct system time.

  • Writable, persistent certificate storage for Caddy.

Caddy obtains and renews a publicly trusted certificate (Caddy automatic HTTPS). An .invalid name, self-signed certificate, workstation loopback URL, private network address, blocked port, or stale AAAA record will not work. Certificate issuance and renewal contact an ACME provider, so the host owner's approval must cover that. Do not replace an existing shared Caddy configuration with this dedicated-site example.

On the dedicated host, the administrator creates a non-login slack-practice user and group, /opt/slack-practice for read-only source, and /etc/slack-practice for configuration. If the account or either path already exists, stop and inspect its ownership. Do not overwrite an existing service. With the host owner's approval, on a Linux installation with useradd, run:

Source
sudo useradd --system --user-group --no-create-home --shell /usr/sbin/nologin slack-practice
sudo install -d -o root -g root -m 755 /opt/slack-practice
sudo install -d -o root -g root -m 700 /etc/slack-practice

Install slash-server.mjs and practice-data.json below as root-owned files with mode 644 in /opt/slack-practice. Neither contains a credential.

practice-data.json
[
  {"id": "REQ-001", "label": "Maps and labels", "minutesPerKit": 12},
  {"id": "REQ-002", "label": "Fictional welcome cards", "minutesPerKit": 8},
  {"id": "REQ-003", "label": "Practice name tags", "minutesPerKit": 5}
]

Download practice-data.json
slash-server.mjs
import { Buffer } from 'node:buffer';
import { createHmac, timingSafeEqual } from 'node:crypto';
import { readFile, stat } from 'node:fs/promises';
import { createServer } from 'node:http';
import process from 'node:process';
import { clearTimeout, setTimeout } from 'node:timers';
import { TextDecoder } from 'node:util';
import { URL } from 'node:url';

/** @typedef {{id: string, label: string, minutesPerKit: number}} PracticeRow */
/** @typedef {{teamId: string, channelId: string, appId: string, allowedUsers: Set<string>, signingSecret: string}} CommandConfig */
const COMMAND = '/as-workshop-preview';
const PATH = '/slack/commands';
const MAX_BODY = 16384;
const LOCAL_DEADLINE_MS = 1800;

class RequestProblem extends Error {
  /** @param {number} status @param {string} code Fixed local diagnostics only. */
  constructor(status, code) { super(code); this.status = status; }
}

/** Load configuration/data before listening. No HTTP call, token or background work. @returns {Promise<void>} */
async function main() {
  if (process.version !== 'v24.21.0') throw new Error('EXPECTED_NODE_24_21_0');
  const teamId = requiredId('SLACK_TEAM_ID', /^T[A-Z0-9]{5,31}$/);
  const channelId = requiredId('SLACK_CHANNEL_ID', /^[CG][A-Z0-9]{5,31}$/);
  const appId = requiredId('SLACK_APP_ID', /^A[A-Z0-9]{5,31}$/);
  const users = (process.env.SLACK_ALLOWED_USER_IDS || '').split(',');
  if (users.length < 1 || users.length > 5 || users.some((id) => !/^[UW][A-Z0-9]{5,31}$/.test(id)) ||
      new Set(users).size !== users.length) throw new Error('EXPECTED_EXPLICIT_PRACTICE_USERS');
  const secretPath = process.env.SLACK_SIGNING_SECRET_FILE;
  if (typeof secretPath !== 'string' || !secretPath.startsWith('/')) throw new Error('EXPECTED_ABSOLUTE_SECRET_FILE');
  const signingSecret = (await smallFile(secretPath)).replace(/\r?\n$/, '');
  if (!/^[A-Za-z0-9]{16,256}$/.test(signingSecret)) throw new Error('INVALID_SIGNING_SECRET_FILE');
  /** @type {unknown} */
  const fixture = JSON.parse(await smallFile(new URL('./practice-data.json', import.meta.url)));
  const rows = practiceRows(fixture);
  /** @type {CommandConfig} */
  const config = {teamId, channelId, appId, allowedUsers: new Set(users), signingSecret};
  // The public HTTPS reverse proxy runs on the SAME host; this port is never public.
  const server = createServer({maxHeaderSize: 8192, headersTimeout: 2000, requestTimeout: 2000,
    connectionsCheckingInterval: 250, keepAliveTimeout: 1000}, (req, res) => {
    const started = Date.now();
    const timer = setTimeout(() => { res.destroy(); req.destroy(); }, LOCAL_DEADLINE_MS);
    res.once('close', () => clearTimeout(timer));
    res.once('error', () => { clearTimeout(timer); req.destroy(); });
    handleCommand(req, res, config, rows, started + LOCAL_DEADLINE_MS).catch((/** @type {unknown} */ error) => {
      if (!res.headersSent && !res.destroyed) {
        const status = error instanceof RequestProblem ? error.status : 500;
        res.writeHead(status, {'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', Connection: 'close'});
        res.end('Command request rejected.');
      } else { res.destroy(); }
      req.resume();
      // No raw headers, body, signature, IDs, secret path, response_url or input text.
      console.error(JSON.stringify({stage: 'command_rejected', code: error instanceof RequestProblem ? error.message : 'internal_failure'}));
    });
  });
  server.maxConnections = 32;
  server.on('error', () => { console.error('Command server failed; inspect service/port configuration.'); process.exitCode = 1; });
  server.listen(3000, '127.0.0.1', () => console.log('Command server listening on loopback; no Slack request verified yet.'));
  process.once('SIGTERM', () => {
    server.close();
    const timer = setTimeout(() => server.closeAllConnections(), 2000);
    timer.unref();
  });
}

/**
 * Authenticate actual bytes before form decoding or business validation.
 * Only a pure local calculation and the synchronous HTTP response happen here.
 * @param {import('node:http').IncomingMessage} req
 * @param {import('node:http').ServerResponse} res
 * @param {CommandConfig} config
 * @param {PracticeRow[]} rows
 * @param {number} deadline
 * @returns {Promise<void>}
 */
async function handleCommand(req, res, config, rows, deadline) {
  if (req.method !== 'POST' || req.url !== PATH) throw new RequestProblem(404, 'wrong_method_or_path');
  const contentType = oneHeader(req, 'content-type');
  if (!/^application\/x-www-form-urlencoded(?:\s*;\s*charset=utf-8)?$/i.test(contentType)) {
    throw new RequestProblem(415, 'expected_form_body');
  }
  if (req.headers['content-encoding'] !== undefined) throw new RequestProblem(415, 'encoded_body_not_supported');
  const timestamp = oneHeader(req, 'x-slack-request-timestamp');
  const signature = oneHeader(req, 'x-slack-signature');
  if (!/^[0-9]{10}$/.test(timestamp) || !/^v0=[0-9a-f]{64}$/.test(signature)) {
    throw new RequestProblem(401, 'invalid_signature_headers');
  }
  const raw = await readBody(req);
  if (Date.now() >= deadline) throw new RequestProblem(503, 'local_deadline');
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) throw new RequestProblem(401, 'stale_timestamp');
  // Never decode/re-encode the form before signing. Key is Slack's literal UTF-8 secret.
  const digest = createHmac('sha256', Buffer.from(config.signingSecret, 'utf8'))
    .update('v0:' + timestamp + ':', 'utf8').update(raw).digest();
  const supplied = Buffer.from(signature.slice(3), 'hex');
  // Regex guarantees 32 supplied bytes; keep the length guard before timingSafeEqual.
  if (supplied.length !== digest.length || !timingSafeEqual(digest, supplied)) throw new RequestProblem(401, 'bad_signature');
  const fields = decodeForm(raw);
  if (fields.get('team_id') !== config.teamId || fields.get('api_app_id') !== config.appId ||
      fields.get('channel_id') !== config.channelId || fields.get('command') !== COMMAND ||
      !config.allowedUsers.has(fields.get('user_id') || '')) throw new RequestProblem(403, 'practice_context_not_allowed');
  const input = fields.get('text');
  const preview = typeof input !== 'string' || input.length > 80 || /[\u0000-\u001f\u007f]/.test(input)
    ? 'Command input is not allowed. Use /as-workshop-preview help. No work is scheduled or posted.'
    : calculatePreview(input, rows);
  // Do not echo untrusted input. JSON encoding and plain_text blocks keep the result inert.
  const response = JSON.stringify({response_type: 'ephemeral', text: preview, mrkdwn: false,
    blocks: [{type: 'section', text: {type: 'plain_text', text: preview, emoji: false}}]});
  if (Buffer.byteLength(response, 'utf8') > 2048) throw new RequestProblem(500, 'response_limit');
  if (Date.now() >= deadline || res.destroyed) throw new RequestProblem(503, 'local_deadline');
  res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
    'Content-Length': Buffer.byteLength(response, 'utf8'), Connection: 'close'});
  res.end(response);
  // Calling end is not a receipt proving Slack received/displayed the response before 3 seconds.
}

/** @param {import('node:http').IncomingMessage} req @param {string} name @returns {string} */
function oneHeader(req, name) {
  /** @type {string[]} */
  const matches = [];
  for (let i = 0; i < req.rawHeaders.length; i += 2) {
    if (req.rawHeaders[i].toLowerCase() === name) matches.push(req.rawHeaders[i + 1]);
  }
  if (matches.length !== 1) throw new RequestProblem(400, 'missing_or_duplicate_header');
  return matches[0];
}

/** @param {import('node:http').IncomingMessage} req @returns {Promise<Buffer>} */
function readBody(req) {
  const declared = req.headers['content-length'];
  if (declared !== undefined && (typeof declared !== 'string' || !/^[0-9]{1,5}$/.test(declared) || Number(declared) > MAX_BODY)) {
    return Promise.reject(new RequestProblem(413, 'body_limit'));
  }
  return new Promise((resolve, reject) => {
    /** @type {Buffer[]} */
    const chunks = [];
    let size = 0;
    let failed = false;
    req.on('data', (/** @type {unknown} */ chunk) => {
      if (failed) return;
      if (!Buffer.isBuffer(chunk) || size + chunk.length > MAX_BODY) {
        failed = true;
        chunks.length = 0;
        reject(new RequestProblem(413, 'body_limit'));
        return;
      }
      size += chunk.length;
      chunks.push(chunk);
    });
    req.once('end', () => {
      if (failed) return;
      if (!req.complete || size === 0) reject(new RequestProblem(400, 'incomplete_body'));
      else resolve(Buffer.concat(chunks, size));
    });
    req.once('error', () => reject(new RequestProblem(400, 'body_stream_failed')));
    req.once('close', () => { if (!req.complete) reject(new RequestProblem(400, 'body_incomplete')); });
  });
}

/** Strict form decoding after authentication; no JSON payload wrapper for slash commands. @param {Buffer} raw @returns {Map<string, string>} */
function decodeForm(raw) {
  try {
    const parts = new TextDecoder('utf-8', {fatal: true}).decode(raw).split('&');
    if (parts.length > 32) throw new Error('field_count');
    /** @type {Map<string, string>} */
    const fields = new Map();
    for (const part of parts) {
      const index = part.indexOf('=');
      if (index < 1) throw new Error('missing_equals');
      const name = decodeURIComponent(part.slice(0, index).replace(/\+/g, ' '));
      const value = decodeURIComponent(part.slice(index + 1).replace(/\+/g, ' '));
      if (!/^[a-z_]{1,64}$/.test(name) || value.length > 4096 || fields.has(name)) throw new Error('invalid_field');
      fields.set(name, value);
    }
    return fields;
  } catch { throw new RequestProblem(400, 'malformed_form'); }
}

/** Pure fictional calculation. Unknown syntax gives help, never a queued job. @param {string} input @param {PracticeRow[]} rows @returns {string} */
function calculatePreview(input, rows) {
  const help = 'Fictional preview only. Use /as-workshop-preview preview REQ-001 2 (quantity 1 to 5), or /as-workshop-preview help. No work is scheduled or posted.';
  if (input === 'help' || input === '') return help;
  const match = /^preview (REQ-[0-9]{3}) ([1-5])$/.exec(input);
  if (match === null) return 'Command not understood. ' + help;
  const row = rows.find((item) => item.id === match[1]);
  if (row === undefined) return 'Unknown fictional request. ' + help;
  const count = Number(match[2]);
  return 'Fictional preview: ' + row.id + ' - ' + row.label + '. ' + count + ' kits x ' +
    row.minutesPerKit + ' minutes = ' + count * row.minutesPerKit + ' minutes. No work is scheduled or posted.';
}


/** @param {unknown} value @returns {PracticeRow[]} */
function practiceRows(value) {
  if (!Array.isArray(value) || value.length !== 3) throw new Error('EXPECTED_THREE_FICTIONAL_ROWS');
  /** @type {PracticeRow[]} */
  const rows = [];
  const candidates = /** @type {unknown[]} */ (value);
  for (const candidate of candidates) {
    if (candidate === null || typeof candidate !== 'object' || Array.isArray(candidate)) throw new Error('INVALID_ROW');
    const row = /** @type {Record<string, unknown>} */ (candidate);
    if (typeof row.id !== 'string' || !/^REQ-00[1-3]$/.test(row.id) || rows.some((item) => item.id === row.id) ||
        typeof row.label !== 'string' || !/^[A-Za-z][A-Za-z &-]{1,59}$/.test(row.label) ||
        typeof row.minutesPerKit !== 'number' || !Number.isSafeInteger(row.minutesPerKit) ||
        row.minutesPerKit < 1 || row.minutesPerKit > 60) throw new Error('INVALID_FICTIONAL_ROW');
    rows.push({id: row.id, label: row.label, minutesPerKit: row.minutesPerKit});
  }
  return rows;
}

/** @param {string | URL} path @returns {Promise<string>} */
async function smallFile(path) {
  const info = await stat(path);
  if (!info.isFile() || info.size < 1 || info.size > 4096) throw new Error('CONFIG_FILE_SIZE');
  const bytes = await readFile(path);
  if (bytes.length > 4096) throw new Error('CONFIG_FILE_SIZE');
  return new TextDecoder('utf-8', {fatal: true}).decode(bytes);
}

/** @param {string} name @param {RegExp} shape @returns {string} */
function requiredId(name, shape) {
  const value = process.env[name];
  if (typeof value !== 'string' || !shape.test(value)) throw new Error('REQUIRED_ENVIRONMENT_ID');
  return value;
}

main().catch(() => {
  console.error('Command startup failed. Inspect the approved Node version, configuration, credential and fixture without logging them.');
  process.exitCode = 1;
});

Download slash-server.mjs

Copy command.env.example to /etc/slack-practice/command.env, root-owned with mode 600. Fill in the exact IDs obtained earlier. SLACK_ALLOWED_USER_IDS is one to five comma-separated member IDs, with no spaces or empty trailing entry. Only these members can run the command.

command.env.example
# Copy to /etc/slack-practice/command.env on the approved host.
# Fill the actual IDs privately; empty values fail before listening.
# This file has no secret. systemd LoadCredential supplies the signing-secret FILE.
SLACK_TEAM_ID=
SLACK_CHANNEL_ID=
SLACK_APP_ID=
SLACK_ALLOWED_USER_IDS=

Download command.env.example

Create /etc/slack-practice/signing-secret, root-owned with mode 600, containing the Signing Secret from Slack's app credentials as one line. Enter it with the editor or secret-management process the administrator has approved. Do not put its value in a shell command, command history, environment variable, source file, or chat. Keep editor backups and synchronized folders out of this path. One trailing newline is allowed. The code uses the line as literal UTF-8 text and does not decode it as hexadecimal.

Install the following unit as /etc/systemd/system/slack-practice.service, root-owned with mode 644:

slack-practice.service
[Unit]
Description=Fictional Slack slash-command preview
After=network.target

[Service]
Type=exec
User=slack-practice
Group=slack-practice
WorkingDirectory=/opt/slack-practice
EnvironmentFile=/etc/slack-practice/command.env
LoadCredential=slack-signing-secret:/etc/slack-practice/signing-secret
Environment=SLACK_SIGNING_SECRET_FILE=%d/slack-signing-secret
ExecStart=/usr/local/bin/node /opt/slack-practice/slash-server.mjs
Restart=no
TimeoutStopSec=4
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
UMask=0077

[Install]
WantedBy=multi-user.target

Download slack-practice.service

LoadCredential reads the root-owned file and exposes a copy to the service in systemd's credential directory, which %d names. The environment variable SLACK_SIGNING_SECRET_FILE holds only that file path, not the secret. The service user needs no access to /etc/slack-practice/signing-secret, and the secret never sits in the environment, which systemd cautions is unsuitable for secrets. Anyone with administrator access to the host, and the service process itself, can still read the secret. File permissions do not protect it on a compromised host.

On this dedicated host only, install the following as Caddy's /etc/caddy/Caddyfile, replacing the one .invalid hostname with the hostname you used in the Slack Request URL:

Caddyfile
# Dedicated practice host only. Replace the reserved .invalid name before use.
# Caddy owns public TLS/certificate renewal; Node only listens on loopback.
slack-practice.example.invalid {
    handle /slack/commands {
        reverse_proxy 127.0.0.1:3000 {
            lb_retries 0
            lb_try_duration 0s
            transport http {
                dial_timeout 250ms
                response_header_timeout 2s
            }
        }
    }
    handle {
        respond "Not found" 404
    }
}

Download Caddyfile

The Node server listens only on 127.0.0.1:3000. Caddy terminates HTTPS and forwards the exact command path to it on the same host. Other paths return 404. Do not add body parsers, decompression, request rewrites, a login redirect, request-body logging, or another proxy between them. The signature covers the raw body bytes, and the Node server verifies it against those bytes.

The reverse-proxy defaults preserve the incoming method and URI and pass request headers through, and the example configures no body transformation. Both proxy retry controls are zero, and the backend response-header timeout is two seconds. Caddy's certificate-maintenance retries are separate from forwarding a command request.

On the host, after checking the installed paths and configuration, the administrator can load and start this service, then validate and reload this Caddy site:

Source
sudo systemctl daemon-reload
sudo systemctl start slack-practice.service
sudo systemctl status slack-practice.service --no-pager
sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy

The expected Node readiness line is Command server listening on loopback; no Slack request verified yet. It proves only that local startup succeeded. Check the service status and Caddy's certificate and route errors without printing secret files or raw requests. The server should reject a browser GET to https://YOUR-APPROVED-HOST/slack/commands. A browser request cannot test Slack signing. The unit uses Restart=no, and these steps do not enable it at boot, so after a crash or reboot an administrator must run systemctl start again.

Verify the request, then check who sent it

slash-server.mjs implements Slack's signing procedure in this order:

  1. Accept only POST /slack/commands with a form content type and an unencoded body. Limit the headers to 8 KiB and the raw body to 16 KiB before processing.

  2. Read exactly one X-Slack-Request-Timestamp and one X-Slack-Signature, matching header names case-insensitively. Keep the body as a Buffer. Do not turn + into spaces, parse fields, or stringify anything yet.

  3. Require a timestamp within five minutes of the host clock. Compute HMAC-SHA256 with the literal signing secret over v0:, the timestamp, :, and the raw body bytes.

  4. Require the v0= prefix and the exact digest length, then compare the two digests with Node's timingSafeEqual instead of ordinary string equality (Node crypto).

  5. Only then decode the form, rejecting duplicate fields, bad escapes, more than 32 fields, and oversized values. Check the workspace, app, channel, command, and allowed user. The server rejects a genuine Slack request from any other workspace, app, channel, command, or user.

  6. Validate text, calculate against the three local fictional rows, and JSON-encode an ephemeral result of at most 2,048 bytes. The response uses a plain_text block with Markdown disabled in the fallback text. The server never echoes or evaluates raw command text. For unknown syntax, it returns help. It does not parse mentions or links into instructions.

The server compares only the channel ID. It does not ask Slack whether the channel is still private or what roles users currently have, because there is no time for that within the three-second limit. The owners confirm during setup that the ID belongs to the private practice channel. Keep the allowlist and channel ownership current. The Apps Script sender still performs its own metadata read before it sends.

A valid signature shows that the sender has the app's signing secret and that the request was not changed in transit. It does not show that this person may run this command. The workspace, app, channel, command, and allowed-user checks decide that. Someone with a stolen signing secret can forge those fields too, so TLS, host security, and secret rotation still matter.

The timestamp check rejects old requests, but it does not detect repeats. A captured valid request can be replayed within the five minutes, and a person can send the same command twice. Slack's Events API retry identifiers and deduplication rules do not apply to slash commands. This server keeps no record of past requests. Repeats are harmless here because the only computation reads in-memory fictional data and returns a preview. The server posts no message, writes no record, sends no email, and schedules no work. A duplicate or missing ephemeral display is still possible.

The request handler sets a 1.8-second local deadline from the moment Node receives the request headers, caps body size and output, and makes no network requests. Node also limits how long it waits for headers, bodies, and connections (Node HTTP). These limits leave some room under Slack's three seconds, but they cannot reserve network time, proxy connection time, CPU time, or Slack display time. Calling res.end() does not tell you whether Slack displayed the result. If the deadline passes, the handler responds with an error or closes the connection. It does not continue the work in the background.

Predict, change, and restore a command

After the host is ready and Slack's installed command shows the exact HTTPS Request URL, sign in as an allowed practice user and type in the private practice channel's main message box, not in a thread. App-created slash commands are not supported in threads (invocation restrictions).

  1. Enter /as-workshop-preview help. Expect an ephemeral explanation that only you can see. The bot posts nothing to the channel. The text says that no work is scheduled or posted.

  2. Enter /as-workshop-preview preview REQ-001 2. The supplied row has 12 minutes per kit. Predict the total before submitting. Expected text is Fictional preview: REQ-001 - Maps and labels. 2 kits x 12 minutes = 24 minutes. No work is scheduled or posted.

  3. Change only the quantity to 3. Predict 36 minutes, then submit /as-workshop-preview preview REQ-001 3. Only the preview changes. No data is stored and no task is created.

  4. Submit the original command /as-workshop-preview preview REQ-001 2 again. Expect 24 again. Repeating the command is harmless because it stores nothing and creates no task.

  5. Try /as-workshop-preview preview REQ-001 0. The quantity is outside the grammar's range of 1 to 5. Expect an ephemeral Command not understood explanation. Stop after these five commands. Do not flood the endpoint to test rate limits.

The three fictional rows come from the local practice-data.json file. The allowed request IDs are REQ-001, REQ-002, and REQ-003. The server fetches nothing from Apps Script, and the command changes no data. Slack may still keep service and request metadata under its own policies, and Caddy and systemd keep their usual logs.

Diagnose failures

ObservationMeaning and next check
SLACK_CONFIG_REQUIREDLocal sender configuration failed before HTTP. Inspect only the named properties, privately. Do not dump the whole property store.
SLACK_INTENT_EXISTS or SLACK_NO_UNSENT_PREPARED_INTENTThe saved record blocked a new intent or attempt. Inspect and keep the existing record, and do not reset it to get past the guard.
SLACK_PREFLIGHT_READ_FAILEDThe identity or private-channel metadata read did not pass. Inspect the recorded HTTP status or error code, installed scopes, workspace, bot identity, and private membership. No message attempt has started. A channel_not_found can mean that the bot cannot see the channel, even though it exists.
SLACK_CONFIG_CHANGED or confirmation failureRestore the reviewed configuration and confirmation ID. The script does not silently send a saved message to a new destination.
Message ok: false, 429, or unconfirmed resultKeep the recorded status. Check unknown or dispatching outcomes in the channel by hand. Do not repost.
Node startup failureCheck the exact Node version, the source and data file paths, IDs, credential file, and service permissions. The program does not print exception dumps that could contain secrets.
Public 404, 502, TLS, or connection errorCheck the exact route, whether Caddy and the Node service are running, public DNS and ports, and the trusted certificate. Do not change the signature algorithm to solve a hosting error.
Node 401The signature or freshness check failed. Check the app's actual signing secret, correct host time, exact raw-body forwarding, and signing headers. Never disable verification to make the command work.
Node 403A signed request failed the workspace, app, channel, command, or user check. Correct the configured ID, or run the command from the right channel as an allowed user. Do not widen the allowed list to make it pass.
Node 400, 413, or 415The server rejected the request format, body size, or content type. A request sent from a browser or curl is not a signed Slack command. Do not log the raw body to debug it.
Valid authorized command with invalid inputThe server returns HTTP 200 with an ephemeral explanation or help text, not a server error.
Slack operation_timeout or a missing previewSlack did not receive a usable response in time. Check the host, Caddy, and the handler's deadline. The calculation may already have run. Sending the command again changes no data, but it does not guarantee that a preview appears.

Remove only the practice integration

First inspect the saved message intent and match it against the channel. Keep its ID, status, channel, and known timestamp for as long as you need the record. If you cannot find a matching message, the outcome stays unknown. Deleting logs or removing a credential does not prove that the message was not delivered.

When you are approved to remove the command, delete only /as-workshop-preview from this app's Slash Commands configuration, so that Slack stops sending it to your host. Then the host administrator stops only slack-practice.service with sudo systemctl stop slack-practice.service. Stopping can interrupt a response already in flight. After in-flight requests have ended, remove only this dedicated Caddy site and reload Caddy with administrator approval. Do not stop other hosted services or clear shared certificate storage. The exercise leaves no enabled boot service or restart loop.

If the disposable app is no longer needed, the workspace or app owner can uninstall this practice app through Slack's installed-app controls to remove its bot access and command. Deleting SLACK_BOT_TOKEN locally does not revoke the token in Slack. If any credential leaked, revoke or regenerate it in Slack and update every legitimate holder. Regenerating a signing secret invalidates requests signed with the old key once verifiers stop accepting that key.

After the Slack app and command are removed and the message record is checked, remove the sender's configuration and confirmation properties, but keep SLACK_PRACTICE_INTENT_V1 for as long as you need the record. Remove /etc/slack-practice/signing-secret and /etc/slack-practice/command.env on the command host once slack-practice.service is stopped.

Next, read Send and inspect a Twilio SMS.

Project files

Complete source files for this chapter's examples.

Send one Slack message and answer a fictional slash command

Code.gs
/** @typedef {{teamId: string, channelId: string, token: string, text: string}} SlackConfig */
/** @typedef {'prepared' | 'dispatching' | 'accepted' | 'rejected' | 'unknown' | 'observed'} SlackIntentStatus */
/** @typedef {{version: number, id: string, teamId: string, channelId: string, text: string, createdAt: number, status: SlackIntentStatus, ts: string | null, detail: string}} SlackIntent */
/** @typedef {{httpStatus: number, value: Record<string, unknown>, retryAfter: string | null}} SlackReply */
const SLACK_INTENT_KEY = 'SLACK_PRACTICE_INTENT_V1';
const SLACK_REJECTION_CODES = [
  'invalid_auth', 'not_authed', 'account_inactive', 'token_revoked', 'token_expired',
  'missing_scope', 'channel_not_found', 'not_in_channel', 'no_permission', 'is_archived',
  'restricted_action', 'restricted_action_read_only_channel', 'restricted_action_thread_only_channel', 'no_text',
];

/** Preview local configuration/text only; no Slack request or saved intent. @returns {void} */
function previewSlackPracticeMessage() {
  const config = slackConfig_();
  console.log(JSON.stringify({stage: 'local_preview', teamId: config.teamId,
    channelId: config.channelId, fictionalText: config.text, sends: 0}));
}

/** Create this project's ONE intent. An existing record is never replaced. @returns {void} */
function prepareSlackPracticeMessage() {
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('SLACK_LOCAL_BUSY');
  try {
    const config = slackConfig_();
    if (loadSlackIntent_() !== null) throw new Error('SLACK_INTENT_EXISTS: inspect it; do not clear it to repost.');
    const id = Utilities.getUuid().toLowerCase();
    /** @type {SlackIntent} */
    const intent = {version: 1, id: id, teamId: config.teamId, channelId: config.channelId,
      text: config.text + ' [practice intent ' + id + ']', createdAt: Date.now(),
      status: 'prepared', ts: null, detail: 'local_intent_only'};
    saveSlackIntent_(intent);
    console.log(JSON.stringify({stage: 'prepared', intentId: id, teamId: intent.teamId,
      channelId: intent.channelId, fictionalText: intent.text}));
  } finally { lock.releaseLock(); }
}

/**
 * Explicit manual send: at most one chat.postMessage attempt for this saved intent.
 * All non-prepared states refuse another attempt. No automatic retries.
 * @returns {void}
 */
function sendPreparedSlackMessage() {
  const deadline = Date.now() + 40000;
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('SLACK_LOCAL_BUSY');
  try {
    const intent = loadSlackIntent_();
    if (intent === null || intent.status !== 'prepared') throw new Error('SLACK_NO_UNSENT_PREPARED_INTENT');
    const config = slackConfig_();
    if (config.teamId !== intent.teamId || config.channelId !== intent.channelId ||
        intent.text !== config.text + ' [practice intent ' + intent.id + ']') {
      throw new Error('SLACK_CONFIG_CHANGED: restore the reviewed configuration; no send started.');
    }
    const confirmation = PropertiesService.getScriptProperties().getProperty('SLACK_CONFIRM_INTENT_ID');
    if (confirmation !== intent.id) throw new Error('SLACK_CONFIRM_THE_EXACT_INTENT_ID');
    // These are identity/metadata reads. Their failure leaves the intent prepared.
    const identity = slackReadOk_(slackCall_('auth.test', config.token, null, deadline));
    if (identity.team_id !== intent.teamId || typeof identity.bot_id !== 'string' ||
        !/^B[A-Z0-9]{5,31}$/.test(identity.bot_id) || typeof identity.user_id !== 'string' ||
        !/^[UW][A-Z0-9]{5,31}$/.test(identity.user_id)) throw new Error('SLACK_WRONG_BOT_OR_WORKSPACE');
    const info = slackReadOk_(slackCall_('conversations.info', config.token, {channel: intent.channelId}, deadline));
    const channel = slackRecord_(info.channel);
    // groups:read covers private channels the app has joined. info may omit is_member.
    if (channel.id !== intent.channelId || channel.context_team_id !== intent.teamId ||
        channel.is_private !== true || channel.is_archived !== false ||
        channel.is_im !== false || channel.is_mpim !== false || channel.is_shared !== false ||
        channel.is_pending_ext_shared !== false || channel.is_member === false) {
      throw new Error('SLACK_EXPECTED_PRIVATE_UNSHARED_MEMBER_CHANNEL');
    }
    if (Date.now() + 1000 >= deadline) throw new Error('SLACK_READ_DEADLINE_NO_SEND');
    // Persist BEFORE possible dispatch. Failure/termination afterward must never enable repost.
    intent.status = 'dispatching';
    intent.detail = 'dispatch_may_have_started';
    saveSlackIntent_(intent);
    console.log(JSON.stringify({stage: 'dispatch_possible', intentId: intent.id, channelId: intent.channelId}));
    /** @type {SlackReply} */
    let reply;
    try {
      reply = slackCall_('chat.postMessage', config.token, {channel: intent.channelId, text: intent.text,
        mrkdwn: false, parse: 'none', unfurl_links: false, unfurl_media: false}, deadline);
    } catch (error) {
      intent.status = 'unknown';
      intent.detail = 'transport_or_response_unknown';
      saveSlackIntent_(intent);
      throw new Error('SLACK_DELIVERY_UNKNOWN: inspect the saved intent and private channel; never repost.');
    }
    const value = reply.value;
    if (reply.httpStatus === 200 && value.ok === true && value.channel === intent.channelId &&
        typeof value.ts === 'string' && /^[0-9]{10,12}\.[0-9]{6}$/.test(value.ts)) {
      // Keep ts as text, not a floating-point number. Slack can sanitize the returned message.
      intent.status = 'accepted';
      intent.ts = value.ts;
      intent.detail = 'api_confirmed';
    } else if (reply.httpStatus === 429) {
      intent.status = 'rejected';
      intent.detail = 'http_429';
    } else if (reply.httpStatus === 200 && value.ok === false && typeof value.error === 'string' &&
        SLACK_REJECTION_CODES.indexOf(value.error) !== -1) {
      intent.status = 'rejected';
      intent.detail = value.error;
    } else {
      // Slack explicitly allows partial success with internal_error/fatal_error.
      intent.status = 'unknown';
      intent.detail = 'unconfirmed_provider_outcome';
    }
    // If this write fails after Slack accepted, the earlier dispatching record still blocks sending.
    saveSlackIntent_(intent);
    console.log(JSON.stringify({stage: 'message_result', intentId: intent.id, status: intent.status,
      channelId: intent.channelId, ts: intent.ts, detail: intent.detail, retryAfterSeconds: reply.retryAfter}));
    if (intent.status !== 'accepted') throw new Error('SLACK_NOT_CONFIRMED: inspect the result; no automatic repost.');
  } finally { lock.releaseLock(); }
}

/** Inspect only this project's saved fictional operation, never its credential store. @returns {void} */
function inspectSlackMessageIntent() {
  const intent = loadSlackIntent_();
  console.log(JSON.stringify(intent === null ? {stage: 'no_intent'} : {stage: 'saved_intent', intent: intent}));
}

/** Record a HUMAN observation after matching the private channel, bot, text and intent ID. No Slack call. @returns {void} */
function recordObservedSlackMessage() {
  const lock = LockService.getScriptLock();
  if (!lock.tryLock(1000)) throw new Error('SLACK_LOCAL_BUSY');
  try {
    const intent = loadSlackIntent_();
    const store = PropertiesService.getScriptProperties();
    const id = store.getProperty('SLACK_OBSERVED_INTENT_ID');
    const ts = store.getProperty('SLACK_OBSERVED_MESSAGE_TS');
    const confirmation = store.getProperty('SLACK_OBSERVATION_CONFIRMATION');
    if (intent === null || (intent.status !== 'dispatching' && intent.status !== 'unknown') ||
        id !== intent.id || typeof ts !== 'string' || !/^[0-9]{10,12}\.[0-9]{6}$/.test(ts) ||
        confirmation !== 'I matched the bot, channel, text and intent ID') throw new Error('SLACK_OBSERVATION_REQUIRED');
    intent.status = 'observed';
    intent.ts = ts;
    intent.detail = 'human_observed_not_api_verified';
    saveSlackIntent_(intent);
    console.log(JSON.stringify({stage: 'human_observation_saved', intentId: intent.id, ts: ts}));
  } finally { lock.releaseLock(); }
}

/** @returns {SlackConfig} */
function slackConfig_() {
  const store = PropertiesService.getScriptProperties();
  const teamId = store.getProperty('SLACK_TEAM_ID');
  const channelId = store.getProperty('SLACK_CHANNEL_ID');
  const token = store.getProperty('SLACK_BOT_TOKEN');
  const text = store.getProperty('SLACK_PRACTICE_TEXT');
  if (typeof teamId !== 'string' || !/^T[A-Z0-9]{5,31}$/.test(teamId) ||
      typeof channelId !== 'string' || !/^[CG][A-Z0-9]{5,31}$/.test(channelId) ||
      typeof token !== 'string' || !/^xoxb-[A-Za-z0-9-]{20,240}$/.test(token) ||
      typeof text !== 'string' || text.length > 160 ||
      !/^Fictional workshop: [A-Za-z0-9 ,.!()-]+$/.test(text) || text.trim() !== text) {
    throw new Error('SLACK_CONFIG_REQUIRED: use the documented IDs, non-rotating bot token and fictional text.');
  }
  return {teamId: teamId, channelId: channelId, token: token, text: text};
}

/** @returns {SlackIntent | null} */
function loadSlackIntent_() {
  const raw = PropertiesService.getScriptProperties().getProperty(SLACK_INTENT_KEY);
  if (raw === null) return null;
  if (raw.length > 4000) throw new Error('SLACK_INTENT_INVALID: retain it for inspection.');
  /** @type {unknown} */
  let parsed;
  try { parsed = JSON.parse(raw); } catch (error) { throw new Error('SLACK_INTENT_INVALID_JSON'); }
  const value = slackRecord_(parsed);
  const status = value.status;
  if (value.version !== 1 || typeof value.id !== 'string' ||
      !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value.id) ||
      typeof value.teamId !== 'string' || !/^T[A-Z0-9]{5,31}$/.test(value.teamId) ||
      typeof value.channelId !== 'string' || !/^[CG][A-Z0-9]{5,31}$/.test(value.channelId) ||
      typeof value.text !== 'string' || value.text.length > 240 ||
      !/^Fictional workshop: [A-Za-z0-9 ,.!()-]+ \[practice intent [0-9a-f-]+\]$/.test(value.text) ||
      !value.text.endsWith(' [practice intent ' + value.id + ']') ||
      typeof value.createdAt !== 'number' || !Number.isSafeInteger(value.createdAt) || value.createdAt <= 0 ||
      (status !== 'prepared' && status !== 'dispatching' && status !== 'accepted' &&
       status !== 'rejected' && status !== 'unknown' && status !== 'observed') ||
      typeof value.detail !== 'string' || !/^[a-z0-9_]{1,80}$/.test(value.detail) ||
      (value.ts !== null && (typeof value.ts !== 'string' || !/^[0-9]{10,12}\.[0-9]{6}$/.test(value.ts))) ||
      ((status === 'accepted' || status === 'observed') !== (value.ts !== null))) {
    throw new Error('SLACK_INTENT_INVALID: do not reset an uncertain send.');
  }
  return {version: 1, id: value.id, teamId: value.teamId, channelId: value.channelId,
    text: value.text, createdAt: value.createdAt, status: status, ts: value.ts, detail: value.detail};
}

/** @param {SlackIntent} intent @returns {void} */
function saveSlackIntent_(intent) {
  const text = JSON.stringify(intent);
  if (Utilities.newBlob(text).getBytes().length > 4000) throw new Error('SLACK_INTENT_TOO_LARGE');
  PropertiesService.getScriptProperties().setProperty(SLACK_INTENT_KEY, text);
}

/**
 * Fixed provider origin and exact method allowlist. No redirects or retries.
 * @param {'auth.test' | 'conversations.info' | 'chat.postMessage'} method
 * @param {string} token
 * @param {Record<string, string | boolean> | null} data
 * @param {number} deadline
 * @returns {SlackReply}
 */
function slackCall_(method, token, data, deadline) {
  if (method !== 'auth.test' && method !== 'conversations.info' && method !== 'chat.postMessage') {
    throw new Error('SLACK_METHOD_NOT_ALLOWED');
  }
  const seconds = Math.min(15, Math.floor((deadline - Date.now()) / 1000));
  if (seconds < 1) throw new Error('SLACK_DEADLINE');
  const readInfo = method === 'conversations.info';
  const channel = data === null ? null : data.channel;
  if (readInfo && (typeof channel !== 'string' || !/^[CG][A-Z0-9]{5,31}$/.test(channel))) {
    throw new Error('SLACK_INFO_CHANNEL_REQUIRED');
  }
  const url = 'https://slack.com/api/' + method + (readInfo ? '?channel=' + encodeURIComponent(String(channel)) : '');
  /** @type {{method: 'get' | 'post', headers: Record<string, string>, followRedirects: boolean, muteHttpExceptions: boolean, validateHttpsCertificates: boolean, timeoutSeconds: number}} */
  const options = {
    method: readInfo ? 'get' : 'post',
    headers: {Authorization: 'Bearer ' + token, Accept: 'application/json'},
    followRedirects: false, muteHttpExceptions: true, validateHttpsCertificates: true, timeoutSeconds: seconds,
  };
  const response = readInfo ? UrlFetchApp.fetch(url, options) :
    UrlFetchApp.fetch(url, Object.assign({}, options, {contentType: 'application/json; charset=utf-8', payload: JSON.stringify(data || {})}));
  if (Date.now() > deadline) throw new Error('SLACK_RESPONSE_DEADLINE');
  const status = response.getResponseCode();
  const headers = slackRecord_(response.getAllHeaders());
  const retry = slackHeader_(headers, 'retry-after');
  const retryAfter = retry !== null && /^[0-9]{1,8}$/.test(retry) ? retry : null;
  // HTTP 429 is an explicit rate refusal; its body need not be JSON.
  if (status === 429) return {httpStatus: status, value: {}, retryAfter: retryAfter};
  if (status !== 200) return {httpStatus: status, value: {}, retryAfter: retryAfter};
  const type = slackHeader_(headers, 'content-type');
  if (type === null || type.split(';')[0].trim().toLowerCase() !== 'application/json') throw new Error('SLACK_EXPECTED_JSON');
  const text = response.getContentText('UTF-8');
  // URL Fetch already downloaded this body; the limit bounds parsing, not transport.
  if (text.length === 0 || text.length > 65536 || Utilities.newBlob(text).getBytes().length > 65536) {
    throw new Error('SLACK_RESPONSE_SIZE');
  }
  /** @type {unknown} */
  let value;
  try { value = JSON.parse(text); } catch (error) { throw new Error('SLACK_INVALID_JSON'); }
  const result = slackRecord_(value);
  if (Date.now() > deadline) throw new Error('SLACK_RESPONSE_DEADLINE');
  return {httpStatus: status, value: result, retryAfter: retryAfter};
}

/** @param {SlackReply} reply @returns {Record<string, unknown>} */
function slackReadOk_(reply) {
  if (reply.httpStatus === 200 && reply.value.ok === true) return reply.value;
  const code = reply.value.error;
  console.error(JSON.stringify({stage: 'read_rejected', httpStatus: reply.httpStatus,
    code: typeof code === 'string' && /^[a-z0-9_]{1,80}$/.test(code) ? code : 'unknown', retryAfterSeconds: reply.retryAfter}));
  throw new Error('SLACK_PREFLIGHT_READ_FAILED: no message attempt started.');
}

/** @param {unknown} value @returns {Record<string, unknown>} */
function slackRecord_(value) {
  if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('SLACK_EXPECTED_OBJECT');
  return /** @type {Record<string, unknown>} */ (value);
}

/** @param {Record<string, unknown>} headers @param {string} wanted @returns {string | null} */
function slackHeader_(headers, wanted) {
  const names = Object.keys(headers).filter((name) => name.toLowerCase() === wanted);
  if (names.length !== 1) return null;
  const value = headers[names[0]];
  return typeof value === 'string' ? value : null;
}

appsscript.json

Download file
appsscript.json
{
  "timeZone": "Etc/UTC",
  "runtimeVersion": "V8",
  "oauthScopes": ["https://www.googleapis.com/auth/script.external_request"]
}

slash-server.mjs

Download file
slash-server.mjs
import { Buffer } from 'node:buffer';
import { createHmac, timingSafeEqual } from 'node:crypto';
import { readFile, stat } from 'node:fs/promises';
import { createServer } from 'node:http';
import process from 'node:process';
import { clearTimeout, setTimeout } from 'node:timers';
import { TextDecoder } from 'node:util';
import { URL } from 'node:url';

/** @typedef {{id: string, label: string, minutesPerKit: number}} PracticeRow */
/** @typedef {{teamId: string, channelId: string, appId: string, allowedUsers: Set<string>, signingSecret: string}} CommandConfig */
const COMMAND = '/as-workshop-preview';
const PATH = '/slack/commands';
const MAX_BODY = 16384;
const LOCAL_DEADLINE_MS = 1800;

class RequestProblem extends Error {
  /** @param {number} status @param {string} code Fixed local diagnostics only. */
  constructor(status, code) { super(code); this.status = status; }
}

/** Load configuration/data before listening. No HTTP call, token or background work. @returns {Promise<void>} */
async function main() {
  if (process.version !== 'v24.21.0') throw new Error('EXPECTED_NODE_24_21_0');
  const teamId = requiredId('SLACK_TEAM_ID', /^T[A-Z0-9]{5,31}$/);
  const channelId = requiredId('SLACK_CHANNEL_ID', /^[CG][A-Z0-9]{5,31}$/);
  const appId = requiredId('SLACK_APP_ID', /^A[A-Z0-9]{5,31}$/);
  const users = (process.env.SLACK_ALLOWED_USER_IDS || '').split(',');
  if (users.length < 1 || users.length > 5 || users.some((id) => !/^[UW][A-Z0-9]{5,31}$/.test(id)) ||
      new Set(users).size !== users.length) throw new Error('EXPECTED_EXPLICIT_PRACTICE_USERS');
  const secretPath = process.env.SLACK_SIGNING_SECRET_FILE;
  if (typeof secretPath !== 'string' || !secretPath.startsWith('/')) throw new Error('EXPECTED_ABSOLUTE_SECRET_FILE');
  const signingSecret = (await smallFile(secretPath)).replace(/\r?\n$/, '');
  if (!/^[A-Za-z0-9]{16,256}$/.test(signingSecret)) throw new Error('INVALID_SIGNING_SECRET_FILE');
  /** @type {unknown} */
  const fixture = JSON.parse(await smallFile(new URL('./practice-data.json', import.meta.url)));
  const rows = practiceRows(fixture);
  /** @type {CommandConfig} */
  const config = {teamId, channelId, appId, allowedUsers: new Set(users), signingSecret};
  // The public HTTPS reverse proxy runs on the SAME host; this port is never public.
  const server = createServer({maxHeaderSize: 8192, headersTimeout: 2000, requestTimeout: 2000,
    connectionsCheckingInterval: 250, keepAliveTimeout: 1000}, (req, res) => {
    const started = Date.now();
    const timer = setTimeout(() => { res.destroy(); req.destroy(); }, LOCAL_DEADLINE_MS);
    res.once('close', () => clearTimeout(timer));
    res.once('error', () => { clearTimeout(timer); req.destroy(); });
    handleCommand(req, res, config, rows, started + LOCAL_DEADLINE_MS).catch((/** @type {unknown} */ error) => {
      if (!res.headersSent && !res.destroyed) {
        const status = error instanceof RequestProblem ? error.status : 500;
        res.writeHead(status, {'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', Connection: 'close'});
        res.end('Command request rejected.');
      } else { res.destroy(); }
      req.resume();
      // No raw headers, body, signature, IDs, secret path, response_url or input text.
      console.error(JSON.stringify({stage: 'command_rejected', code: error instanceof RequestProblem ? error.message : 'internal_failure'}));
    });
  });
  server.maxConnections = 32;
  server.on('error', () => { console.error('Command server failed; inspect service/port configuration.'); process.exitCode = 1; });
  server.listen(3000, '127.0.0.1', () => console.log('Command server listening on loopback; no Slack request verified yet.'));
  process.once('SIGTERM', () => {
    server.close();
    const timer = setTimeout(() => server.closeAllConnections(), 2000);
    timer.unref();
  });
}

/**
 * Authenticate actual bytes before form decoding or business validation.
 * Only a pure local calculation and the synchronous HTTP response happen here.
 * @param {import('node:http').IncomingMessage} req
 * @param {import('node:http').ServerResponse} res
 * @param {CommandConfig} config
 * @param {PracticeRow[]} rows
 * @param {number} deadline
 * @returns {Promise<void>}
 */
async function handleCommand(req, res, config, rows, deadline) {
  if (req.method !== 'POST' || req.url !== PATH) throw new RequestProblem(404, 'wrong_method_or_path');
  const contentType = oneHeader(req, 'content-type');
  if (!/^application\/x-www-form-urlencoded(?:\s*;\s*charset=utf-8)?$/i.test(contentType)) {
    throw new RequestProblem(415, 'expected_form_body');
  }
  if (req.headers['content-encoding'] !== undefined) throw new RequestProblem(415, 'encoded_body_not_supported');
  const timestamp = oneHeader(req, 'x-slack-request-timestamp');
  const signature = oneHeader(req, 'x-slack-signature');
  if (!/^[0-9]{10}$/.test(timestamp) || !/^v0=[0-9a-f]{64}$/.test(signature)) {
    throw new RequestProblem(401, 'invalid_signature_headers');
  }
  const raw = await readBody(req);
  if (Date.now() >= deadline) throw new RequestProblem(503, 'local_deadline');
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) throw new RequestProblem(401, 'stale_timestamp');
  // Never decode/re-encode the form before signing. Key is Slack's literal UTF-8 secret.
  const digest = createHmac('sha256', Buffer.from(config.signingSecret, 'utf8'))
    .update('v0:' + timestamp + ':', 'utf8').update(raw).digest();
  const supplied = Buffer.from(signature.slice(3), 'hex');
  // Regex guarantees 32 supplied bytes; keep the length guard before timingSafeEqual.
  if (supplied.length !== digest.length || !timingSafeEqual(digest, supplied)) throw new RequestProblem(401, 'bad_signature');
  const fields = decodeForm(raw);
  if (fields.get('team_id') !== config.teamId || fields.get('api_app_id') !== config.appId ||
      fields.get('channel_id') !== config.channelId || fields.get('command') !== COMMAND ||
      !config.allowedUsers.has(fields.get('user_id') || '')) throw new RequestProblem(403, 'practice_context_not_allowed');
  const input = fields.get('text');
  const preview = typeof input !== 'string' || input.length > 80 || /[\u0000-\u001f\u007f]/.test(input)
    ? 'Command input is not allowed. Use /as-workshop-preview help. No work is scheduled or posted.'
    : calculatePreview(input, rows);
  // Do not echo untrusted input. JSON encoding and plain_text blocks keep the result inert.
  const response = JSON.stringify({response_type: 'ephemeral', text: preview, mrkdwn: false,
    blocks: [{type: 'section', text: {type: 'plain_text', text: preview, emoji: false}}]});
  if (Buffer.byteLength(response, 'utf8') > 2048) throw new RequestProblem(500, 'response_limit');
  if (Date.now() >= deadline || res.destroyed) throw new RequestProblem(503, 'local_deadline');
  res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store',
    'Content-Length': Buffer.byteLength(response, 'utf8'), Connection: 'close'});
  res.end(response);
  // Calling end is not a receipt proving Slack received/displayed the response before 3 seconds.
}

/** @param {import('node:http').IncomingMessage} req @param {string} name @returns {string} */
function oneHeader(req, name) {
  /** @type {string[]} */
  const matches = [];
  for (let i = 0; i < req.rawHeaders.length; i += 2) {
    if (req.rawHeaders[i].toLowerCase() === name) matches.push(req.rawHeaders[i + 1]);
  }
  if (matches.length !== 1) throw new RequestProblem(400, 'missing_or_duplicate_header');
  return matches[0];
}

/** @param {import('node:http').IncomingMessage} req @returns {Promise<Buffer>} */
function readBody(req) {
  const declared = req.headers['content-length'];
  if (declared !== undefined && (typeof declared !== 'string' || !/^[0-9]{1,5}$/.test(declared) || Number(declared) > MAX_BODY)) {
    return Promise.reject(new RequestProblem(413, 'body_limit'));
  }
  return new Promise((resolve, reject) => {
    /** @type {Buffer[]} */
    const chunks = [];
    let size = 0;
    let failed = false;
    req.on('data', (/** @type {unknown} */ chunk) => {
      if (failed) return;
      if (!Buffer.isBuffer(chunk) || size + chunk.length > MAX_BODY) {
        failed = true;
        chunks.length = 0;
        reject(new RequestProblem(413, 'body_limit'));
        return;
      }
      size += chunk.length;
      chunks.push(chunk);
    });
    req.once('end', () => {
      if (failed) return;
      if (!req.complete || size === 0) reject(new RequestProblem(400, 'incomplete_body'));
      else resolve(Buffer.concat(chunks, size));
    });
    req.once('error', () => reject(new RequestProblem(400, 'body_stream_failed')));
    req.once('close', () => { if (!req.complete) reject(new RequestProblem(400, 'body_incomplete')); });
  });
}

/** Strict form decoding after authentication; no JSON payload wrapper for slash commands. @param {Buffer} raw @returns {Map<string, string>} */
function decodeForm(raw) {
  try {
    const parts = new TextDecoder('utf-8', {fatal: true}).decode(raw).split('&');
    if (parts.length > 32) throw new Error('field_count');
    /** @type {Map<string, string>} */
    const fields = new Map();
    for (const part of parts) {
      const index = part.indexOf('=');
      if (index < 1) throw new Error('missing_equals');
      const name = decodeURIComponent(part.slice(0, index).replace(/\+/g, ' '));
      const value = decodeURIComponent(part.slice(index + 1).replace(/\+/g, ' '));
      if (!/^[a-z_]{1,64}$/.test(name) || value.length > 4096 || fields.has(name)) throw new Error('invalid_field');
      fields.set(name, value);
    }
    return fields;
  } catch { throw new RequestProblem(400, 'malformed_form'); }
}

/** Pure fictional calculation. Unknown syntax gives help, never a queued job. @param {string} input @param {PracticeRow[]} rows @returns {string} */
function calculatePreview(input, rows) {
  const help = 'Fictional preview only. Use /as-workshop-preview preview REQ-001 2 (quantity 1 to 5), or /as-workshop-preview help. No work is scheduled or posted.';
  if (input === 'help' || input === '') return help;
  const match = /^preview (REQ-[0-9]{3}) ([1-5])$/.exec(input);
  if (match === null) return 'Command not understood. ' + help;
  const row = rows.find((item) => item.id === match[1]);
  if (row === undefined) return 'Unknown fictional request. ' + help;
  const count = Number(match[2]);
  return 'Fictional preview: ' + row.id + ' - ' + row.label + '. ' + count + ' kits x ' +
    row.minutesPerKit + ' minutes = ' + count * row.minutesPerKit + ' minutes. No work is scheduled or posted.';
}


/** @param {unknown} value @returns {PracticeRow[]} */
function practiceRows(value) {
  if (!Array.isArray(value) || value.length !== 3) throw new Error('EXPECTED_THREE_FICTIONAL_ROWS');
  /** @type {PracticeRow[]} */
  const rows = [];
  const candidates = /** @type {unknown[]} */ (value);
  for (const candidate of candidates) {
    if (candidate === null || typeof candidate !== 'object' || Array.isArray(candidate)) throw new Error('INVALID_ROW');
    const row = /** @type {Record<string, unknown>} */ (candidate);
    if (typeof row.id !== 'string' || !/^REQ-00[1-3]$/.test(row.id) || rows.some((item) => item.id === row.id) ||
        typeof row.label !== 'string' || !/^[A-Za-z][A-Za-z &-]{1,59}$/.test(row.label) ||
        typeof row.minutesPerKit !== 'number' || !Number.isSafeInteger(row.minutesPerKit) ||
        row.minutesPerKit < 1 || row.minutesPerKit > 60) throw new Error('INVALID_FICTIONAL_ROW');
    rows.push({id: row.id, label: row.label, minutesPerKit: row.minutesPerKit});
  }
  return rows;
}

/** @param {string | URL} path @returns {Promise<string>} */
async function smallFile(path) {
  const info = await stat(path);
  if (!info.isFile() || info.size < 1 || info.size > 4096) throw new Error('CONFIG_FILE_SIZE');
  const bytes = await readFile(path);
  if (bytes.length > 4096) throw new Error('CONFIG_FILE_SIZE');
  return new TextDecoder('utf-8', {fatal: true}).decode(bytes);
}

/** @param {string} name @param {RegExp} shape @returns {string} */
function requiredId(name, shape) {
  const value = process.env[name];
  if (typeof value !== 'string' || !shape.test(value)) throw new Error('REQUIRED_ENVIRONMENT_ID');
  return value;
}

main().catch(() => {
  console.error('Command startup failed. Inspect the approved Node version, configuration, credential and fixture without logging them.');
  process.exitCode = 1;
});

practice-data.json

Download file
practice-data.json
[
  {"id": "REQ-001", "label": "Maps and labels", "minutesPerKit": 12},
  {"id": "REQ-002", "label": "Fictional welcome cards", "minutesPerKit": 8},
  {"id": "REQ-003", "label": "Practice name tags", "minutesPerKit": 5}
]

slack-app-manifest.json

Download file
slack-app-manifest.json
{
  "_metadata": {"major_version": 2, "minor_version": 1},
  "display_information": {
    "name": "Apps Script workshop practice",
    "description": "One private-channel bot message and a fictional slash-command preview."
  },
  "features": {
    "bot_user": {"display_name": "as-workshop-practice", "always_online": false},
    "slash_commands": [{
      "command": "/as-workshop-preview",
      "description": "Calculate a fictional workshop preparation preview without scheduling or posting work",
      "usage_hint": "preview REQ-001 2 | help",
      "should_escape": true,
      "url": "https://slack-practice.example.invalid/slack/commands"
    }]
  },
  "oauth_config": {"scopes": {"bot": ["chat:write", "groups:read", "commands"]}},
  "settings": {
    "org_deploy_enabled": false,
    "socket_mode_enabled": false,
    "token_rotation_enabled": false
  }
}

command.env.example

Download file
command.env.example
# Copy to /etc/slack-practice/command.env on the approved host.
# Fill the actual IDs privately; empty values fail before listening.
# This file has no secret. systemd LoadCredential supplies the signing-secret FILE.
SLACK_TEAM_ID=
SLACK_CHANNEL_ID=
SLACK_APP_ID=
SLACK_ALLOWED_USER_IDS=

slack-practice.service

Download file
slack-practice.service
[Unit]
Description=Fictional Slack slash-command preview
After=network.target

[Service]
Type=exec
User=slack-practice
Group=slack-practice
WorkingDirectory=/opt/slack-practice
EnvironmentFile=/etc/slack-practice/command.env
LoadCredential=slack-signing-secret:/etc/slack-practice/signing-secret
Environment=SLACK_SIGNING_SECRET_FILE=%d/slack-signing-secret
ExecStart=/usr/local/bin/node /opt/slack-practice/slash-server.mjs
Restart=no
TimeoutStopSec=4
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
UMask=0077

[Install]
WantedBy=multi-user.target

Caddyfile

Download file
Caddyfile
# Dedicated practice host only. Replace the reserved .invalid name before use.
# Caddy owns public TLS/certificate renewal; Node only listens on loopback.
slack-practice.example.invalid {
    handle /slack/commands {
        reverse_proxy 127.0.0.1:3000 {
            lb_retries 0
            lb_try_duration 0s
            transport http {
                dial_timeout 250ms
                response_header_timeout 2s
            }
        }
    }
    handle {
        respond "Not found" 404
    }
}