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