/** @typedef {'baseline' | 'changed'} TwilioVariant */ /** @typedef {{accountSid: string, from: string, to: string, senderLabel: string, variant: TwilioVariant}} TwilioConfig */ /** @typedef {{sid: string, secret: string}} TwilioCredential */ /** @typedef {'prepared' | 'dispatching' | 'created' | 'rejected' | 'unknown' | 'reconciled'} TwilioIntentState */ /** * @typedef {{ * version: number, * id: string, * accountSid: string, * from: string, * to: string, * senderLabel: string, * variant: TwilioVariant, * body: string, * preparedAt: number, * dispatchStartedAt: number | null, * state: TwilioIntentState, * messageSid: string | null, * identityVerified: boolean, * createHttpStatus: number | null, * createErrorCode: number | null, * lastStatus: string | null, * lastObservedAt: number | null * }} TwilioIntent */ /** @typedef {{httpStatus: number, value: Record | null, retryAfterSeconds: number | null}} TwilioReply */ const TWILIO_INTENT_KEY = 'TWILIO_SMS_INTENT_V1'; const TWILIO_CONFIRMATION = 'I checked current consent, sender approval and charges for this one SMS'; /** Local redacted preview only; no credential read, HTTP request or state write. @returns {void} */ function previewTwilioPracticeSms() { const config = twilioConfig_(); const body = twilioBody_(config.senderLabel, config.variant, Utilities.getUuid().toLowerCase()); console.log(JSON.stringify({stage: 'local_preview', variant: config.variant, from: twilioMask_(config.from), to: twilioMask_(config.to), body: '[redacted]', bodyCharacters: body.length, gsm7Units: body.length, predictedSegments: 1, createAttempts: 0, approvalClock: new Date().toISOString()})); } /** Save this project's one intent without contacting Twilio. Never replaces an existing record. @returns {void} */ function prepareTwilioPracticeSms() { const lock = LockService.getScriptLock(); if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY'); try { if (twilioLoadIntent_() !== null) throw new Error('TWILIO_INTENT_EXISTS: inspect; do not clear it to send again.'); const config = twilioConfig_(); if (config.variant !== 'baseline') throw new Error('TWILIO_RESTORE_BASELINE_BEFORE_PREPARING'); const id = Utilities.getUuid().toLowerCase(); /** @type {TwilioIntent} */ const intent = {version: 1, id: id, accountSid: config.accountSid, from: config.from, to: config.to, senderLabel: config.senderLabel, variant: config.variant, body: twilioBody_(config.senderLabel, config.variant, id), preparedAt: Date.now(), dispatchStartedAt: null, state: 'prepared', messageSid: null, identityVerified: false, createHttpStatus: null, createErrorCode: null, lastStatus: null, lastObservedAt: null}; twilioSaveIntent_(intent); twilioLogIntent_('prepared', intent); } finally { lock.releaseLock(); } } /** * One deliberately approved Messages POST. All non-prepared states refuse another create. * A durable local marker is not a Twilio idempotency key or a cross-service transaction. * @returns {void} */ function sendPreparedTwilioSms() { const deadline = Date.now() + 20000; const lock = LockService.getScriptLock(); if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY'); try { const intent = twilioLoadIntent_(); if (intent === null || intent.state !== 'prepared') throw new Error('TWILIO_NO_UNSENT_PREPARED_INTENT'); const config = twilioConfig_(); if (config.accountSid !== intent.accountSid || config.from !== intent.from || config.to !== intent.to || config.senderLabel !== intent.senderLabel || config.variant !== intent.variant || twilioBody_(config.senderLabel, config.variant, intent.id) !== intent.body) throw new Error('TWILIO_CONFIG_CHANGED'); twilioRequireApproval_(intent.id); const credential = twilioCredential_('CREATE'); const form = 'To=' + encodeURIComponent(intent.to) + '&From=' + encodeURIComponent(intent.from) + '&Body=' + encodeURIComponent(intent.body) + '&ValidityPeriod=60'; if (Date.now() + 1000 >= deadline) throw new Error('TWILIO_SETUP_DEADLINE_NO_CREATE'); intent.state = 'dispatching'; intent.dispatchStartedAt = Date.now(); twilioSaveIntent_(intent); twilioLogIntent_('dispatch_possible', intent); /** @type {TwilioReply} */ let reply; try { reply = twilioRequest_(intent.accountSid, credential, null, form, deadline); } catch (error) { intent.state = 'unknown'; twilioSaveIntent_(intent); throw new Error('TWILIO_CREATE_OUTCOME_UNKNOWN: reconcile; never repost.'); } intent.createHttpStatus = reply.httpStatus; intent.createErrorCode = twilioErrorCode_(reply.value === null ? null : reply.value.code); // Preserve a returned SID as a candidate BEFORE checking the remaining representation. const value = reply.value; if (value !== null && value.account_sid === intent.accountSid && typeof value.sid === 'string' && /^SM[0-9a-fA-F]{32}$/.test(value.sid)) { intent.messageSid = value.sid; intent.state = 'unknown'; twilioSaveIntent_(intent); } if (reply.httpStatus === 201 && value !== null && intent.messageSid !== null) { twilioVerifyIdentity_(value, intent, intent.messageSid, true); intent.identityVerified = true; intent.state = 'created'; // Save confirmed identity even if a new/unusable status field prevents status inspection. twilioSaveIntent_(intent); intent.lastStatus = twilioStatus_(value.status); intent.lastObservedAt = Date.now(); } else if (intent.messageSid === null && [400, 401, 403, 404, 405, 422, 429].indexOf(reply.httpStatus) !== -1) { intent.state = 'rejected'; } else { intent.state = 'unknown'; } twilioSaveIntent_(intent); twilioLogIntent_('create_result', intent); console.log(JSON.stringify({stage: 'create_response', httpStatus: reply.httpStatus, code: intent.createErrorCode, retryAfterSeconds: reply.retryAfterSeconds})); if (intent.state !== 'created') throw new Error('TWILIO_CREATE_NOT_CONFIRMED: inspect the original intent; no retry.'); } finally { lock.releaseLock(); } } /** Read redacted local evidence only, never the raw property store. @returns {void} */ function inspectTwilioSmsIntent() { const intent = twilioLoadIntent_(); if (intent === null) console.log(JSON.stringify({stage: 'no_intent'})); else twilioLogIntent_('saved_intent', intent); } /** * One independent GET for the saved SID, using only the READ key and saved intent. * A failed read never discards the original create receipt or enables another POST. * @returns {void} */ function readKnownTwilioMessage() { const deadline = Date.now() + 20000; const lock = LockService.getScriptLock(); if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY'); try { const intent = twilioLoadIntent_(); if (intent === null || intent.messageSid === null) throw new Error('TWILIO_KNOWN_SID_REQUIRED'); const reply = twilioRequest_(intent.accountSid, twilioCredential_('READ'), intent.messageSid, null, deadline); const value = twilioReadOk_(reply); twilioVerifyIdentity_(value, intent, intent.messageSid, !intent.identityVerified); if (!intent.identityVerified) { intent.identityVerified = true; intent.state = 'reconciled'; } // Keep identity before optional status/diagnostic parsing, too. twilioSaveIntent_(intent); twilioRecordObservation_(intent, value); } finally { lock.releaseLock(); } } /** * After human Console matching, fetch ONE candidate SID and prove its identity against the intent. * No list/search API, create, callback or replacement of a saved SID. * @returns {void} */ function reconcileTwilioSmsFromConsole() { const deadline = Date.now() + 20000; const lock = LockService.getScriptLock(); if (!lock.tryLock(1000)) throw new Error('TWILIO_LOCAL_BUSY'); try { const intent = twilioLoadIntent_(); const store = PropertiesService.getScriptProperties(); const candidate = store.getProperty('TWILIO_RECONCILE_MESSAGE_SID'); if (intent === null || (intent.state !== 'dispatching' && intent.state !== 'unknown') || intent.messageSid !== null || store.getProperty('TWILIO_RECONCILE_INTENT_ID') !== intent.id || typeof candidate !== 'string' || !/^SM[0-9a-fA-F]{32}$/.test(candidate)) throw new Error('TWILIO_RECONCILIATION_REQUIRED'); const value = twilioReadOk_(twilioRequest_(intent.accountSid, twilioCredential_('READ'), candidate, null, deadline)); twilioVerifyIdentity_(value, intent, candidate, true); intent.messageSid = candidate; intent.identityVerified = true; intent.state = 'reconciled'; twilioSaveIntent_(intent); twilioRecordObservation_(intent, value); } finally { lock.releaseLock(); } } /** @param {TwilioIntent} intent @param {Record} value @returns {void} */ function twilioRecordObservation_(intent, value) { const status = twilioStatus_(value.status); const errorCode = twilioErrorCode_(value.error_code); const segments = typeof value.num_segments === 'string' && /^[0-9]{1,5}$/.test(value.num_segments) ? value.num_segments : null; const price = typeof value.price === 'string' && /^-?[0-9]{1,8}(\.[0-9]{1,8})?$/.test(value.price) ? value.price : null; const priceUnit = typeof value.price_unit === 'string' && /^[A-Za-z]{3}$/.test(value.price_unit) ? value.price_unit : null; intent.lastStatus = status; intent.lastObservedAt = Date.now(); twilioSaveIntent_(intent); console.log(JSON.stringify({stage: 'message_observation', intentId: intent.id, messageSid: intent.messageSid, status: status, meaning: twilioStatusMeaning_(status), observedAt: new Date(intent.lastObservedAt).toISOString(), errorCode: errorCode, numSegments: segments, price: price, priceUnit: priceUnit, body: '[redacted]', from: twilioMask_(intent.from), to: twilioMask_(intent.to)})); } /** @returns {TwilioConfig} */ function twilioConfig_() { const store = PropertiesService.getScriptProperties(); const accountSid = store.getProperty('TWILIO_ACCOUNT_SID'); const from = store.getProperty('TWILIO_FROM_PHONE'); const to = store.getProperty('TWILIO_TO_PHONE'); const senderLabel = store.getProperty('TWILIO_SENDER_LABEL'); const variant = store.getProperty('TWILIO_VARIANT'); if (store.getProperty('TWILIO_ENVIRONMENT') !== 'paid-us1' || typeof accountSid !== 'string' || !/^AC[0-9a-fA-F]{32}$/.test(accountSid) || typeof from !== 'string' || !/^\+1(800|833|844|855|866|877|888)[0-9]{7}$/.test(from) || typeof to !== 'string' || !/^\+1[2-9][0-9]{2}[2-9][0-9]{6}$/.test(to) || from === to || typeof senderLabel !== 'string' || !/^[A-Za-z][A-Za-z0-9 -]{1,23}$/.test(senderLabel) || senderLabel.trim() !== senderLabel || (variant !== 'baseline' && variant !== 'changed')) throw new Error('TWILIO_LOCAL_CONFIG_REQUIRED'); // Shapes do not prove paid account status, US destination, SMS capability, approval or consent. return {accountSid: accountSid, from: from, to: to, senderLabel: senderLabel, variant: variant}; } /** @param {'CREATE' | 'READ'} purpose @returns {TwilioCredential} */ function twilioCredential_(purpose) { const store = PropertiesService.getScriptProperties(); const sid = store.getProperty('TWILIO_' + purpose + '_KEY_SID'); const secret = store.getProperty('TWILIO_' + purpose + '_KEY_SECRET'); if (typeof sid !== 'string' || !/^SK[0-9a-fA-F]{32}$/.test(sid) || typeof secret !== 'string' || secret.length < 16 || secret.length > 256 || /[\u0000-\u0020\u007f]/.test(secret)) throw new Error('TWILIO_RESTRICTED_KEY_REQUIRED'); return {sid: sid, secret: secret}; } /** @param {string} id @returns {void} */ function twilioRequireApproval_(id) { const store = PropertiesService.getScriptProperties(); const approvalAt = store.getProperty('TWILIO_APPROVAL_AT'); const time = approvalAt === null ? NaN : Date.parse(approvalAt); const age = Date.now() - time; if (store.getProperty('TWILIO_CONFIRM_INTENT_ID') !== id || store.getProperty('TWILIO_SEND_CONFIRMATION') !== TWILIO_CONFIRMATION || !Number.isFinite(time) || new Date(time).toISOString() !== approvalAt || age < 0 || age > 15 * 60 * 1000) { throw new Error('TWILIO_FRESH_EXPLICIT_APPROVAL_REQUIRED'); } } /** * Fixed US1 origin and 2010-04-01 API. Exactly POST collection or GET known SMS SID. * @param {string} accountSid @param {TwilioCredential} credential * @param {string | null} messageSid @param {string | null} form @param {number} deadline * @returns {TwilioReply} */ function twilioRequest_(accountSid, credential, messageSid, form, deadline) { if (!/^AC[0-9a-fA-F]{32}$/.test(accountSid) || (messageSid === null) !== (form !== null) || (messageSid !== null && !/^SM[0-9a-fA-F]{32}$/.test(messageSid))) throw new Error('TWILIO_REQUEST_SHAPE'); const seconds = Math.min(15, Math.floor((deadline - Date.now()) / 1000)); if (seconds < 1) throw new Error('TWILIO_REQUEST_DEADLINE'); const url = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/Messages' + (messageSid === null ? '' : '/' + messageSid) + '.json'; /** @type {UrlFetchApp.HTTPResponse} */ let response; try { response = UrlFetchApp.fetch(url, { method: messageSid === null ? 'post' : 'get', headers: {Authorization: 'Basic ' + Utilities.base64Encode(credential.sid + ':' + credential.secret, Utilities.Charset.UTF_8), Accept: 'application/json'}, followRedirects: false, muteHttpExceptions: true, validateHttpsCertificates: true, timeoutSeconds: seconds, ...(form === null ? {} : {contentType: 'application/x-www-form-urlencoded; charset=utf-8', payload: form}), }); } catch (error) { throw new Error('TWILIO_TRANSPORT_OR_TIMEOUT: do not log the original exception.'); } if (Date.now() > deadline) throw new Error('TWILIO_RESPONSE_DEADLINE'); const httpStatus = response.getResponseCode(); const headers = twilioObject_(response.getAllHeaders()); const retry = twilioHeader_(headers, 'retry-after'); const retryAfterSeconds = retry !== null && /^[0-9]{1,8}$/.test(retry) ? Number(retry) : null; const type = twilioHeader_(headers, 'content-type'); /** @type {Record | null} */ let value = null; const text = response.getContentText('UTF-8'); // URL Fetch already downloaded this body. This bounds parsing, not transport bytes. if (type !== null && type.split(';')[0].trim().toLowerCase() === 'application/json' && text.length > 0 && text.length <= 32768 && Utilities.newBlob(text).getBytes().length <= 32768) { try { value = twilioObject_(JSON.parse(text)); } catch (error) { value = null; } } if (Date.now() > deadline) throw new Error('TWILIO_PARSE_DEADLINE'); return {httpStatus: httpStatus, value: value, retryAfterSeconds: retryAfterSeconds}; } /** @param {TwilioReply} reply @returns {Record} */ function twilioReadOk_(reply) { if (reply.httpStatus === 200 && reply.value !== null) return reply.value; console.error(JSON.stringify({stage: 'status_read_failed', httpStatus: reply.httpStatus, code: twilioErrorCode_(reply.value === null ? null : reply.value.code), retryAfterSeconds: reply.retryAfterSeconds})); throw new Error('TWILIO_READ_NOT_CONFIRMED: saved create evidence is unchanged.'); } /** @param {Record} value @param {TwilioIntent} intent @param {string} sid @param {boolean} requireContent @returns {void} */ function twilioVerifyIdentity_(value, intent, sid, requireContent) { if (value.sid !== sid || value.account_sid !== intent.accountSid || value.direction !== 'outbound-api' || value.api_version !== '2010-04-01' || value.num_media !== '0') throw new Error('TWILIO_MESSAGE_IDENTITY_MISMATCH'); if (requireContent) { const created = typeof value.date_created === 'string' ? Date.parse(value.date_created) : NaN; if (value.from !== intent.from || value.to !== intent.to || value.body !== intent.body || intent.dispatchStartedAt === null || !Number.isFinite(created) || Math.abs(created - intent.dispatchStartedAt) > 5 * 60 * 1000) throw new Error('TWILIO_MESSAGE_MATCH_NOT_PROVEN'); } } /** @param {unknown} value @returns {string} */ function twilioStatus_(value) { if (typeof value !== 'string' || !/^[a-z_]{1,32}$/.test(value)) throw new Error('TWILIO_STATUS_NOT_READABLE'); return value; } /** @param {unknown} value @returns {number | null} */ function twilioErrorCode_(value) { return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= 99999999 ? value : null; } /** @param {unknown} value @returns {Record | null} */ function twilioObject_(value) { return value !== null && typeof value === 'object' && !Array.isArray(value) ? /** @type {Record} */ (value) : null; } /** @param {Record | null} headers @param {string} name @returns {string | null} */ function twilioHeader_(headers, name) { if (headers === null) return null; const names = Object.keys(headers).filter((key) => key.toLowerCase() === name); if (names.length !== 1) return null; const value = headers[names[0]]; return typeof value === 'string' ? value : null; } /** @param {string} phone @returns {string} */ function twilioMask_(phone) { return '[redacted]...' + phone.slice(-4); } /** @param {string} stage @param {TwilioIntent} intent @returns {void} */ function twilioLogIntent_(stage, intent) { console.log(JSON.stringify({stage: stage, intentId: intent.id, state: intent.state, messageSid: intent.messageSid, identityVerified: intent.identityVerified, lastStatus: intent.lastStatus, lastObservedAt: intent.lastObservedAt, createHttpStatus: intent.createHttpStatus, createErrorCode: intent.createErrorCode, from: twilioMask_(intent.from), to: twilioMask_(intent.to), body: '[redacted]', bodyCharacters: intent.body.length})); } /** @returns {TwilioIntent | null} */ function twilioLoadIntent_() { const raw = PropertiesService.getScriptProperties().getProperty(TWILIO_INTENT_KEY); if (raw === null) return null; if (raw.length > 4000) throw new Error('TWILIO_INTENT_INVALID: retain the original record.'); /** @type {Record | null} */ let value; try { value = twilioObject_(JSON.parse(raw)); } catch (error) { throw new Error('TWILIO_INTENT_INVALID_JSON'); } if (value === null) throw new Error('TWILIO_INTENT_INVALID'); const state = value.state; const variant = value.variant; 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.accountSid !== 'string' || !/^AC[0-9a-fA-F]{32}$/.test(value.accountSid) || typeof value.from !== 'string' || !/^\+1(800|833|844|855|866|877|888)[0-9]{7}$/.test(value.from) || typeof value.to !== 'string' || !/^\+1[2-9][0-9]{2}[2-9][0-9]{6}$/.test(value.to) || value.from === value.to || typeof value.senderLabel !== 'string' || !/^[A-Za-z][A-Za-z0-9 -]{1,23}$/.test(value.senderLabel) || (variant !== 'baseline' && variant !== 'changed') || typeof value.body !== 'string' || value.body !== twilioBody_(value.senderLabel, variant, value.id) || typeof value.preparedAt !== 'number' || !Number.isSafeInteger(value.preparedAt) || value.preparedAt <= 0 || !twilioNullableTime_(value.dispatchStartedAt) || !twilioNullableTime_(value.lastObservedAt) || (state !== 'prepared' && state !== 'dispatching' && state !== 'created' && state !== 'rejected' && state !== 'unknown' && state !== 'reconciled') || typeof value.identityVerified !== 'boolean' || (value.messageSid !== null && (typeof value.messageSid !== 'string' || !/^SM[0-9a-fA-F]{32}$/.test(value.messageSid))) || (value.createHttpStatus !== null && (typeof value.createHttpStatus !== 'number' || !Number.isInteger(value.createHttpStatus) || value.createHttpStatus < 100 || value.createHttpStatus > 599)) || (value.createErrorCode !== null && twilioErrorCode_(value.createErrorCode) === null) || (value.lastStatus !== null && (typeof value.lastStatus !== 'string' || !/^[a-z_]{1,32}$/.test(value.lastStatus))) || ((state === 'prepared') !== (value.dispatchStartedAt === null)) || ((state === 'created' || state === 'reconciled') !== value.identityVerified) || (value.identityVerified && value.messageSid === null) || (state === 'rejected' && value.messageSid !== null) || (state === 'prepared' && (value.messageSid !== null || value.createHttpStatus !== null || value.createErrorCode !== null || value.lastStatus !== null)) || (state === 'dispatching' && value.messageSid !== null) || (state === 'created' && value.createHttpStatus !== 201) || (value.lastStatus !== null && !value.identityVerified) || ((value.lastStatus === null) !== (value.lastObservedAt === null))) throw new Error('TWILIO_INTENT_INVALID: do not reset it.'); return {version: 1, id: value.id, accountSid: value.accountSid, from: value.from, to: value.to, senderLabel: value.senderLabel, variant: variant, body: value.body, preparedAt: value.preparedAt, dispatchStartedAt: value.dispatchStartedAt, state: state, messageSid: value.messageSid, identityVerified: value.identityVerified, createHttpStatus: value.createHttpStatus, createErrorCode: /** @type {number | null} */ (value.createErrorCode), lastStatus: value.lastStatus, lastObservedAt: value.lastObservedAt}; } /** @param {unknown} value @returns {value is number | null} */ function twilioNullableTime_(value) { return value === null || (typeof value === 'number' && Number.isSafeInteger(value) && value > 0); } /** @param {TwilioIntent} intent @returns {void} */ function twilioSaveIntent_(intent) { const raw = JSON.stringify(intent); if (Utilities.newBlob(raw).getBytes().length > 4000) throw new Error('TWILIO_INTENT_STORAGE_BOUND'); try { PropertiesService.getScriptProperties().setProperty(TWILIO_INTENT_KEY, raw); } catch (error) { throw new Error('TWILIO_LOCAL_SAVE_FAILED: possible dispatch remains uncertain; never repost.'); } }