All connectors

Meta Business Suite

OfficialMessaging

Meta Business Suite

Let agents read posts, comments, messages and insights for one Facebook Page and its linked Instagram professional account. Write access also permits publishing, scheduling, replying and moderation.

Customer conversations require Meta's Advanced Access, business verification and App Review. Replies are generally limited to 24 hours after the person's last message.

Requires a business portfolio and developer app. Ads and Facebook reel publishing are not included.

Connect Meta Business Suite.

Setup instructions

Connect Meta Business Suite

You need admin access to a business portfolio managing the Facebook Page, a Meta app connected to that portfolio, and (for Instagram) a linked professional account. Each Houston connection serves one Page.

  1. Create a Meta app for your portfolio. Choose the Page, Messenger and optional Instagram use cases; use API setup with Facebook Login for Instagram. Add the permissions below.

  2. In Business settings, open Users → System users. Create or select a system user and assign the app, Page and optional Instagram account with Full control.

  3. Select Generate token, choose the app and permissions below, and select a non-expiring token if available.

  4. In Graph API Explorer, paste that system user token and submit:

    me/accounts?fields=name,access_token
    
  5. Copy your Page's access_token. In the Access Token Debugger, confirm Type: Page and check its expiry.

  6. In Houston, choose Read or Write for Access, enter the Page access token, and save the connection.

Use the Page token, not the system user token. Customer conversations need Advanced Access, business verification and App Review. Until approved, messaging is limited to people with a role on the app, Page or portfolio.

Permissions

For Read: pages_show_list, pages_read_engagement, pages_read_user_content, read_insights, pages_manage_metadata, pages_messaging and business_management; for Instagram, also instagram_basic, instagram_manage_comments, instagram_manage_insights and instagram_manage_messages.

For Write, also: pages_manage_posts, pages_manage_engagement and publish_video when Meta offers it; for Instagram, instagram_content_publish and instagram_manage_contents.

Some Read permissions also allow changes: Meta requires pages_manage_metadata to read conversations, adds business_management with the Manage everything on your Page use case for business-owned Pages, and grants reading and replying to messages together (pages_messaging, instagram_manage_messages). Leave out messaging permissions if you do not need the inbox. With Read access Houston blocks every write, whatever the token allows. See Meta's permissions reference.

Advanced
  • Messaging: request Advanced Access for pages_messaging, pages_manage_metadata, pages_read_engagement and, for Instagram, instagram_basic and instagram_manage_messages. In Instagram, enable Allow access to messages under Connected tools.
  • Expiry or changed permissions: generate a new system user token, derive a new Page token and update Houston. Some businesses must use expiring tokens.
  • Missing Instagram: link the professional account to the Page and assign it to the system user. Page insights require at least 100 followers.
  • appsecret_proof errors: disable Require app secret in the app's Advanced → Security settings; Houston does not send app secret proofs.
  • Reply limits: Meta generally permits replies within 24 hours. Hashtag search needs Instagram Public Content Access through App Review.
  • Revoke access: remove the system user's Page access in Business settings.

Files

  • connector.luau
    -- Meta Graph API v26.0 for one Facebook Page and its linked Instagram account. Arguments and
    -- results keep Meta's native field names.
    type Options = {[string]: any}
    type Endpoint = {method: string, path: string, access: string?, host: string?, query: {string}?, required: {string}?, paging: {string}?,
    	body: {string}?, fields: string?, upload: boolean?, about: string}
    
    -- Graph versions work for two years after their successor ships; v26.0 has no sunset date yet.
    local VERSION = "v26.0"
    local API = "https://graph.facebook.com/" .. VERSION
    local VIDEO_API = "https://graph-video.facebook.com/" .. VERSION
    local ID = "^[%w_][%w_.:$=+-]*$"
    local CURSORS = {"limit", "after", "before"}
    local NONE: {string} = table.freeze({})
    local NULL = json.decode("null")
    
    local POST_FIELDS = "id,message,story,created_time,permalink_url,status_type,full_picture,is_published,from,comments.summary(true).limit(0),reactions.summary(true).limit(0)"
    local VIDEO_FIELDS = "id,title,description,created_time,length,permalink_url,published"
    local IG_MEDIA_FIELDS = "id,caption,media_type,media_product_type,media_url,thumbnail_url,permalink,timestamp,like_count,comments_count"
    local IG_STORY_FIELDS = "id,caption,media_type,media_product_type,media_url,thumbnail_url,permalink,timestamp"
    local IG_COMMENT_FIELDS = "id,text,timestamp,username,like_count,hidden"
    local HASHTAG_MEDIA_FIELDS = "id,caption,media_type,permalink,timestamp,like_count,comments_count"
    
    -- Edges and parameters of Meta's reference and Business SDK v26.0.2, checked on 2026-10-19.
    -- Page functions act on /me, the Page the token belongs to. Path {fields} are IDs; listed query
    -- fields are taken from the options, and the other options form the body of writes. paging lists
    -- the cursor options; any paging list, even an empty one, also accepts next. body limits the
    -- writes to one object (a post, comment or media) to its own fields, so they cannot change the Page.
    local endpoints: {[string]: Endpoint} = {
    	getPage = {method = "GET", path = "/me",
    		fields = "id,name,username,link,category,about,description,website,phone,emails,followers_count,fan_count,verification_status",
    		about = "The connected Page. With Instagram permissions, fields='id,name,instagram_business_account{id,username}' adds the linked account, whose id is the ig_user of Instagram functions."},
    	getObject = {method = "GET", path = "/{id}",
    		about = "Any object the Page can see: a post, comment, photo, video, conversation, message, Instagram account, media, comment or container. Without fields Meta returns only a few defaults."},
    
    	listFeed = {method = "GET", path = "/me/feed", query = {"since", "until", "include_hidden", "show_expired"}, paging = CURSORS, fields = POST_FIELDS,
    		about = "Posts on the Page by the Page and by others, newest first, without reels. limit is at most 100; Meta returns about 600 ranked posts per year."},
    	listPublishedPosts = {method = "GET", path = "/me/published_posts", query = {"since", "until", "include_hidden"}, paging = CURSORS, fields = POST_FIELDS,
    		about = "Posts the Page published."},
    	listScheduledPosts = {method = "GET", path = "/me/scheduled_posts", query = {"since", "until"}, paging = CURSORS, fields = "id,message,created_time,scheduled_publish_time,permalink_url",
    		about = "Posts waiting for their scheduled_publish_time."},
    	listTaggedPosts = {method = "GET", path = "/me/tagged", query = {"since", "until"}, paging = CURSORS, fields = "id,message,created_time,permalink_url,from",
    		about = "Posts by others that tag the Page."},
    	listPhotos = {method = "GET", path = "/me/photos", query = {"type"}, paging = CURSORS, fields = "id,name,created_time,link,picture,alt_text",
    		about = "type='uploaded' lists the Page's own photos, type='tagged' photos it is tagged in; the default lists its profile pictures."},
    	listVideos = {method = "GET", path = "/me/videos", paging = CURSORS, fields = VIDEO_FIELDS, about = "The Page's videos."},
    	listReels = {method = "GET", path = "/me/video_reels", query = {"since", "until"}, paging = CURSORS, fields = VIDEO_FIELDS, about = "The Page's reels."},
    	listRatings = {method = "GET", path = "/me/ratings", paging = CURSORS, fields = "created_time,recommendation_type,review_text,has_review,reviewer",
    		about = "Recommendations and reviews of the Page; recommendation_type is positive or negative."},
    	listComments = {method = "GET", path = "/{object}/comments", query = {"filter", "order", "summary", "since"}, paging = CURSORS,
    		fields = "id,message,created_time,from,like_count,comment_count,is_hidden,can_hide,can_remove,permalink_url",
    		about = "Comments on a Facebook post, photo, video or comment (replies). filter: toplevel (default) or stream for all; order: chronological or reverse_chronological; summary=true adds summary.total_count."},
    	listReactions = {method = "GET", path = "/{object}/reactions", query = {"type", "summary"}, paging = CURSORS,
    		about = "Reactions to a post or comment. type: LIKE, LOVE, WOW, HAHA, SORRY, ANGRY or CARE; summary='total_count' adds summary.total_count. Meta names only the Page among reacting profiles."},
    	getInsights = {method = "GET", path = "/{object}/insights",
    		query = {"metric", "period", "since", "until", "date_preset", "breakdown", "metric_type", "timeframe"}, required = {"metric"}, paging = NONE,
    		about = "Metrics of the Page ('me'), a post, the Instagram account or Instagram media; see Insights above. metric and breakdown take an array or a comma-separated string."},
    	listConversations = {method = "GET", path = "/me/conversations", query = {"platform", "user_id", "folder"}, paging = CURSORS,
    		fields = "id,updated_time,participants",
    		about = "Inbox threads, latest first. platform: messenger or instagram; user_id finds the thread with one person (PSID or IGSID). Messenger threads also have snippet, unread_count, message_count, can_reply and link."},
    	listMessages = {method = "GET", path = "/{conversation}/messages", paging = CURSORS, fields = "id,created_time,from,to,message,attachments",
    		about = "Messages of a conversation, newest first. Only the 20 most recent have details."},
    
    	getInstagramAccount = {method = "GET", path = "/{ig_user}",
    		fields = "id,username,name,biography,website,followers_count,follows_count,media_count,profile_picture_url",
    		about = "The linked Instagram professional account. fields='business_discovery.username(name){followers_count,media_count,media{caption,like_count}}' reads another business or creator account."},
    	listInstagramMedia = {method = "GET", path = "/{ig_user}/media", query = {"since", "until"}, paging = CURSORS, fields = IG_MEDIA_FIELDS,
    		about = "Posts and reels, newest first, at most the latest 10,000. media_product_type is FEED, REELS or AD."},
    	listInstagramStories = {method = "GET", path = "/{ig_user}/stories", paging = CURSORS, fields = IG_STORY_FIELDS, about = "Stories of the last 24 hours."},
    	listInstagramTags = {method = "GET", path = "/{ig_user}/tags", paging = CURSORS, fields = "id,caption,media_type,media_url,permalink,timestamp,username",
    		about = "Media by others that tag the account."},
    	listInstagramChildren = {method = "GET", path = "/{media}/children", fields = "id,media_type,media_url,thumbnail_url,timestamp",
    		about = "The images and videos of a carousel."},
    	listInstagramComments = {method = "GET", path = "/{media}/comments", paging = CURSORS, fields = IG_COMMENT_FIELDS .. ",replies{" .. IG_COMMENT_FIELDS .. "}",
    		about = "Top-level comments on Instagram media, newest first, with their replies. limit is at most 50."},
    	listInstagramReplies = {method = "GET", path = "/{comment}/replies", paging = CURSORS, fields = IG_COMMENT_FIELDS, about = "Replies to an Instagram comment."},
    	getInstagramPublishingLimit = {method = "GET", path = "/{ig_user}/content_publishing_limit", query = {"since"}, fields = "config,quota_usage",
    		about = "Posts published through the API in the last 24 hours (quota_usage) and the quota (config.quota_total). Needs the instagram_content_publish permission."},
    	searchInstagramHashtag = {method = "GET", path = "/ig_hashtag_search", query = {"user_id", "q"}, required = {"user_id", "q"},
    		about = "The ID of a hashtag (q without #); user_id is your ig_user. At most 30 different hashtags per 7 days; needs Meta's Instagram Public Content Access feature."},
    	listHashtagTopMedia = {method = "GET", path = "/{hashtag}/top_media", query = {"user_id"}, required = {"user_id"}, paging = {"limit", "after"},
    		fields = HASHTAG_MEDIA_FIELDS, about = "Most popular public media with a hashtag. limit is at most 50."},
    	listHashtagRecentMedia = {method = "GET", path = "/{hashtag}/recent_media", query = {"user_id"}, required = {"user_id"}, paging = {"limit", "after"},
    		fields = HASHTAG_MEDIA_FIELDS, about = "Public media with a hashtag from the last 24 hours. limit is at most 50."},
    
    	createPost = {method = "POST", path = "/me/feed", access = "data:write",
    		about = "Body {message?, link?, published?, scheduled_publish_time?, attached_media?, place?}. Posts as the Page; returns {id}. Pass message or link."},
    	updatePost = {method = "POST", path = "/{post}", access = "data:write", body = {"message", "is_hidden", "is_published", "scheduled_publish_time", "is_pinned", "timeline_visibility"},
    		about = "Body {message?, is_hidden?, is_published?, scheduled_publish_time?, is_pinned?, timeline_visibility?}. Only posts made through the token's Meta app can change."},
    	uploadPhoto = {method = "POST", path = "/me/photos", access = "data:write", upload = true,
    		about = "Body {url | path, caption?, published?, temporary?, scheduled_publish_time?, no_story?, alt_text_custom?}. JPEG, PNG, GIF, BMP or TIFF up to 10 MB; returns {id, post_id}."},
    	uploadVideo = {method = "POST", path = "/me/videos", access = "data:write", host = VIDEO_API, upload = true,
    		about = "Body {file_url | path, title?, description?, published?, scheduled_publish_time?, no_story?}. Returns {id}; Meta processes the video afterwards."},
    	createComment = {method = "POST", path = "/{object}/comments", access = "data:write",
    		about = "Body {message?, attachment_url?, attachment_id?, attachment_share_url?}. Comments as the Page on a Facebook post, photo, video or comment, or on Instagram media (message only); returns {id}."},
    	updateComment = {method = "POST", path = "/{comment}", access = "data:write", body = {"message", "is_hidden", "hide", "attachment_url", "attachment_id", "attachment_share_url"},
    		about = "Body {is_hidden} or {message} for a Facebook comment, {hide} for an Instagram comment."},
    	createInstagramReply = {method = "POST", path = "/{comment}/replies", access = "data:write", required = {"message"},
    		about = "Body {message}. Replies as the account to a top-level Instagram comment; returns {id}."},
    	updateInstagramMedia = {method = "POST", path = "/{media}", access = "data:write", required = {"comment_enabled"}, body = {"comment_enabled"},
    		about = "Body {comment_enabled}. Turns comments on Instagram media on or off."},
    	deleteObject = {method = "DELETE", path = "/{id}", access = "data:write",
    		about = "Deletes a Facebook post, photo, video or comment, or Instagram media or comment. Instagram media need the instagram_manage_contents permission; carousels are deleted whole."},
    	sendMessage = {method = "POST", path = "/me/messages", access = "data:write", required = {"recipient"},
    		about = "Body {recipient, messaging_type?, message? | sender_action?, tag?, notification_type?, reply_to?}. Sends as the Page on Messenger or Instagram, or privately replies to a Facebook comment; see Inbox above. Returns {recipient_id, message_id}."},
    	sendInstagramPrivateReply = {method = "POST", path = "/{ig_user}/messages", access = "data:write", required = {"recipient", "message"},
    		about = "Body {recipient={comment_id}, message={text}}. Sends the commenter the one private message allowed per Instagram comment, within 7 days of it; at most 750 per hour."},
    	createInstagramContainer = {method = "POST", path = "/{ig_user}/media", access = "data:write",
    		about = "Body {image_url? (JPEG), video_url?, media_type? (REELS, STORIES, CAROUSEL or VIDEO for carousel items), caption?, children?, is_carousel_item?, alt_text?, cover_url?, share_to_feed?, location_id?, user_tags?, collaborators?}. Returns {id}; see Publishing to Instagram above."},
    	publishInstagramMedia = {method = "POST", path = "/{ig_user}/media_publish", access = "data:write", required = {"creation_id"},
    		about = "Body {creation_id}. Publishes a FINISHED container; returns the media {id}."},
    }
    
    -- Write bodies never send these: method replaces the HTTP verb, batch runs other requests,
    -- callback and suppress_http_code turn errors into HTTP 200, fields reads the written object
    -- back (a Page's own access_token included), next belongs to paging, and the rest carry or
    -- reveal credentials.
    local RESERVED = table.freeze({method = true, batch = true, callback = true, suppress_http_code = true, include_headers = true,
    	attached_files = true, fields = true, next = true, access_token = true, appsecret_proof = true, appsecret_time = true, input_token = true, ids = true})
    -- Throttling: app, user, Pages, custom and Business Use Case (80000-80014) limits. Meta refuses
    -- these before acting, unlike its temporary errors (1, 2), after which a write may have happened.
    local THROTTLED = table.freeze({[4] = true, [17] = true, [32] = true, [341] = true, [613] = true})
    local TEMPORARY = table.freeze({[1] = true, [2] = true})
    
    local function options(input: Options?): Options
    	if input == nil then return {} end
    	assert(type(input) == "table", "opts must be an object")
    	for key in input do assert(type(key) == "string", "opts must have named fields") end
    	return table.clone(input)
    end
    
    local function text(value: any, field: string): string
    	assert(type(value) == "string" and value ~= "" and not string.find(value, "%c"), field .. " must be a nonempty string without control characters")
    	return value
    end
    
    -- IDs exceed 2^53, so only strings keep them exact. Meta's IDs (123_456, t_1, m_1, mid.$c1,
    -- aWdG...=) use these characters only.
    local function segment(value: any, field: string): string
    	assert(type(value) == "string", field .. " must be an ID string, such as '123_456'")
    	assert(string.match(value, ID), field .. " must be one Meta ID, such as '123_456' or 't_123'")
    	-- Post IDs name their Page, so a post update can never reach the Page node itself.
    	assert(field ~= "post" or string.match(value, "^%d+_%d+$"), "post must be a post ID such as '123_456'")
    	return url.segment(value, field)
    end
    
    -- A Graph field list with expansions such as comments.limit(5){message}. A Page can read its
    -- own access_token field, so no field may name a token.
    local function fieldList(value: any): string
    	assert(type(value) == "string" and #value <= 4096 and string.match(value, "^[%w_,.(){}:=+/ -]+$"),
    		"fields must be a Graph field list such as 'id,message,comments.limit(5){message}'")
    	assert(not string.find(string.lower(value), "token", 1, true), "fields cannot request access tokens")
    	return value
    end
    
    local function int(value: any): string?
    	return if type(value) == "number" and value % 1 == 0 and math.abs(value) < 2 ^ 53 then string.format("%d", value) else nil
    end
    
    -- Integers without exponents; other values as tostring renders them.
    local function plain(value: any): string
    	return int(value) or tostring(value)
    end
    
    local function scalar(value: any, field: string): string
    	local kind = type(value)
    	assert(kind == "string" or kind == "boolean" or kind == "number", field .. " must be a string, boolean, number or array of those")
    	return url.encode(plain(value))
    end
    
    -- Metric and breakdown lists are comma-separated, encoded like fields so paging links keep them.
    local function queryValue(value: any, field: string): string
    	if type(value) ~= "table" then return scalar(value, field) end
    	local parts: {string} = {}
    	for index, item in value do
    		assert(type(index) == "number" and index == #parts + 1, field .. " must be an array, not an object")
    		table.insert(parts, scalar(item, field))
    	end
    	assert(#parts > 0, field .. " must not be an empty array")
    	return table.concat(parts, "%2C")
    end
    
    local function nextPage(name: string, token: any): string
    	local ok, link = pcall(houston.unseal, token)
    	assert(ok and type(link) == "table" and link.operation == name and type(link.url) == "string"
    		and string.sub(link.url, 1, #API + 1) == API .. "/", "next must be the paging.next value of an earlier " .. name .. " result")
    	return link.url
    end
    
    -- Meta writes the request's access token into its links as an access_token parameter, which goes
    -- whole whatever its characters. Callers drop or refuse links that still name a token after it.
    local function scrub(link: string): string
    	local base, query, fragment = string.match(link, "^([^?#]*)%?([^#]*)(.*)$")
    	if not base or not query or not fragment or not string.find(query, "access_token", 1, true) then return link end
    	local kept: {string} = {}
    	for pair in string.gmatch(query, "[^&]+") do
    		if string.sub(pair, 1, 13) ~= "access_token=" then table.insert(kept, pair) end
    	end
    	return base .. (if #kept > 0 then "?" .. table.concat(kept, "&") else "") .. fragment
    end
    
    -- Error messages also echo tokens: an access_token value, or a bare user or Page (EAA...) or
    -- Instagram (IG...) token of at least 30 more characters.
    local ECHOED = string.rep("[%w_-]", 30) .. "[%w_-]*"
    local function scrubError(text: string): string
    	local value = string.gsub(text, "access_token=[^&#%s\"]*", "access_token=[redacted]")
    	value = string.gsub(value, "access_token%%3[Dd][^&#%s\"]*", "access_token%%3D[redacted]")
    	-- No word boundary: an echoed token may follow %3D or %22.
    	value = string.gsub(value, "EAA" .. ECHOED, "EAA[redacted]")
    	return (string.gsub(value, "IG" .. ECHOED, "IG[redacted]"))
    end
    
    -- Results never carry credentials: Meta's links (graph, l.facebook.com redirects and the like)
    -- lose their token, and token fields, such as an expanded accounts edge's access_token, are
    -- dropped. Text from people is kept.
    local function redact(value: any)
    	if type(value) ~= "table" then return end
    	for key, child in value do
    		if type(key) == "string" and string.find(string.lower(key), "token", 1, true) then
    			value[key] = nil
    		elseif type(child) == "string" and string.find(child, "access_token", 1, true)
    			and string.match(child, "^https?://[%w.-]*facebook%.com/[^%s]*$") then
    			-- A link still naming access_token wraps it more deeply than scrub reaches, so it
    			-- becomes null, which also keeps an array's shape.
    			local clean = scrub(child)
    			value[key] = if string.find(clean, "access_token", 1, true) then NULL else clean
    		else
    			redact(child)
    		end
    	end
    end
    
    -- paging.next goes back to callers sealed with the function that produced it, so next can only
    -- continue an earlier result and never carries a URL, query or method a caller chose. A link
    -- the scrub cannot clean fails the call rather than silently ending the list. paging.previous,
    -- which no call could replay, is dropped: cursors.before or an earlier since/until goes back.
    local function sealPaging(name: string, value: any)
    	local paging = if type(value) == "table" then value.paging else nil
    	if type(paging) ~= "table" then return end
    	if type(paging.next) == "string" then
    		local link = scrub(paging.next)
    		if string.find(link, "access_token", 1, true) or string.sub(link, 1, #API + 1) ~= API .. "/" then
    			houston.fail({operation = name, layer = "upstream", retryable = false,
    				message = "Meta returned a paging link Houston cannot replay (it carries a token or leaves API " .. VERSION .. "); narrow the request with since, until or limit"})
    		end
    		paging.next = houston.seal({operation = name, url = link})
    	end
    	paging.previous = nil
    end
    
    -- Business Use Case limits report, per Page or account, the minutes until calls succeed again.
    local function regainMinutes(response: HttpResponse): string?
    	local usage = response.headers["x-business-use-case-usage"]
    	if not usage or not usage[1] or #usage[1] > 16384 then return nil end
    	local ok, value = pcall(json.decode, usage[1])
    	if not ok or type(value) ~= "table" then return nil end
    	local longest = 0
    	for _, entries in value do
    		if type(entries) == "table" then
    			for _, entry in entries do
    				local minutes = if type(entry) == "table" then entry.estimated_time_to_regain_access else nil
    				if type(minutes) == "number" and minutes > longest then longest = minutes end
    			end
    		end
    	end
    	return if longest > 0 then int(math.ceil(longest)) else nil
    end
    
    -- Meta errors are {error = {message, type, code, error_subcode?, error_user_msg?, is_transient?, fbtrace_id}}.
    -- raw is the body when it was already read. Only reads retry a 5xx or temporary error, since a
    -- write may already have been applied.
    local function fail(name: string, response: HttpResponse, write: boolean, raw: string?): never
    	local status = response.statusCode
    	local message = "Meta HTTP " .. tostring(status)
    	local retryable = status == 429 or (not write and status >= 500)
    	-- A body that fails to arrive still yields the status and retry hint.
    	local ok, value = pcall(function(): any return json.decode(raw or await(response.body:readPrefix(16 * 1024))) end)
    	local problem = if ok and type(value) == "table" and type(value.error) == "table" then value.error else nil
    	if problem then
    		local code, subcode = int(problem.code), int(problem.error_subcode)
    		if code then message ..= " (#" .. code .. (if subcode then "/" .. subcode else "") .. ")" end
    		-- Meta repeats the code at the start of its message, as in "(#10) This endpoint requires...".
    		if type(problem.message) == "string" then
    			message ..= ": " .. string.sub((string.gsub(scrubError(problem.message), "^%(#[%d/]+%)%s*", "")), 1, 600)
    		end
    		if type(problem.error_user_msg) == "string" then message ..= " " .. string.sub(scrubError(problem.error_user_msg), 1, 600) end
    		-- Meta's code decides, so a 500 for an unsupported request is final.
    		local number = tonumber(code)
    		if number then
    			retryable = status == 429 or ((not write or status < 500) and (THROTTLED[number] == true or (number >= 80000 and number <= 80014)))
    				or (not write and TEMPORARY[number] == true)
    		end
    		if problem.is_transient == true and not write then retryable = true end
    		if number == 190 or number == 102 then message ..= "; the Page access token is invalid or expired: create a new one and update the connection" end
    		if type(problem.fbtrace_id) == "string" then message ..= " (fbtrace_id " .. string.sub(problem.fbtrace_id, 1, 64) .. ")" end
    	end
    	local minutes = regainMinutes(response)
    	if minutes then message ..= "; Meta expects calls to succeed again in about " .. minutes .. " min" end
    	return houston.fail({operation = name, layer = "upstream", upstream_status = status, retryable = retryable, message = message})
    end
    
    local function decode(name: string, endpoint: Endpoint, response: HttpResponse): any
    	if response.statusCode < 200 or response.statusCode >= 300 then fail(name, response, endpoint.method ~= "GET") end
    	local raw = await(response.body:readAll())
    	local ok, value = pcall(json.decode, raw)
    	if not ok or type(value) ~= "table" or not string.match(raw, "^%s*{") then
    		return houston.fail({operation = name, layer = "upstream", upstream_status = response.statusCode, retryable = false,
    			message = "Meta returned an invalid JSON object"})
    	end
    	if type(value.error) == "table" then fail(name, response, endpoint.method ~= "GET", raw) end
    	-- Always walked: JSON escapes can spell token keys the raw bytes do not show.
    	if endpoint.paging then sealPaging(name, value) end
    	redact(value)
    	return value
    end
    
    -- Streams a session file with the other options as form fields.
    local function formBody(args: Options): (any, string)
    	local source = text(args.path, "path")
    	args.path = nil
    	local names: {string} = {}
    	for key in args do table.insert(names, key) end
    	table.sort(names)
    	local parts: {any} = {}
    	for _, key in names do
    		local value = args[key]
    		assert(key ~= "source" and key ~= "url" and key ~= "file_url", "path cannot be combined with " .. key)
    		assert(value ~= NULL, "a file upload cannot send null as " .. key)
    		table.insert(parts, {name = key, body = if type(value) == "table" then json.encode(value) else plain(value)})
    	end
    	assert(await(fs.stat(source)).isFile, "path must be a session file")
    	-- multipart.create owns the file and closes it with the body; close it here if that fails.
    	local file = fs.open(source, "r")
    	table.insert(parts, {name = "source", filename = string.match(source, "[^/]+$"), contentType = "application/octet-stream", body = file})
    	local ok, form = pcall(multipart.create, parts)
    	if not ok then
    		pcall(function() await(file:close()) end)
    		error(form, 0)
    	end
    	return form.body, form.contentType
    end
    
    local function request(name: string, endpoint: Endpoint, input: Options?): any
    	local args = options(input)
    	if args.next ~= nil and endpoint.paging then
    		for key in args do assert(key == "next", "pass next alone, as {next = result.paging.next}") end
    		return decode(name, endpoint, await(http.request({method = "GET", url = nextPage(name, args.next), headers = {Accept = {"application/json"}}})))
    	end
    	local path = string.gsub(endpoint.path, "{([%w_]+)}", function(field: string): string
    		local value = segment(args[field], field)
    		args[field] = nil
    		return value
    	end)
    	for _, field in endpoint.required or NONE do
    		assert(args[field] ~= nil and args[field] ~= NULL, field .. " is required")
    	end
    	local query: {string} = {}
    	if endpoint.method == "GET" then
    		local fields = if args.fields == nil then endpoint.fields else args.fields
    		if fields ~= nil then table.insert(query, "fields=" .. url.encode(fieldList(fields))) end
    		args.fields = nil
    	end
    	for _, group in {endpoint.query or NONE, endpoint.paging or NONE} do
    		for _, field in group do
    			if args[field] ~= nil then table.insert(query, field .. "=" .. queryValue(args[field], field)) end
    			args[field] = nil
    		end
    	end
    	if #query > 0 then path ..= "?" .. table.concat(query, "&") end
    	local headers: HttpHeaders = {Accept = {"application/json"}}
    	local body: any = nil
    	if endpoint.method == "POST" then
    		-- Graph's PHP-style parser may trim names, map . and spaces to _ and read name[] as arrays, so only
    		-- plain snake_case names are sent.
    		for key in args do
    			assert(string.match(key, "^%l[%l%d_]*$") and not RESERVED[key] and (endpoint.body == nil or table.find(endpoint.body, key)),
    				name .. " cannot send " .. key)
    		end
    		if endpoint.upload and args.path ~= nil then
    			local contentType
    			body, contentType = formBody(args)
    			headers["Content-Type"] = {contentType}
    		else
    			headers["Content-Type"] = {"application/json"}
    			body = json.encode(args)
    		end
    		args = {}
    	end
    	local unknown = next(args)
    	assert(unknown == nil, name .. " has no option " .. tostring(unknown))
    	return decode(name, endpoint, await(http.request({method = endpoint.method, url = (endpoint.host or API) .. path, headers = headers, body = body})))
    end
    
    local exports: {[string]: any} = {}
    for name, endpoint in endpoints do
    	if not endpoint.access or houston.allows(endpoint.access) then
    		exports[name] = function(args: Options?): any return request(name, endpoint, args) end
    	end
    end
    
    -- name({path fields, query fields?, next?, ...body}) built from the endpoint itself.
    local function signature(endpoint: Endpoint): string
    	local fields: {string} = {}
    	for field in string.gmatch(endpoint.path, "{([%w_]+)}") do table.insert(fields, field) end
    	if endpoint.method == "GET" then table.insert(fields, "fields?") end
    	for _, group in {endpoint.query or NONE, endpoint.paging or NONE} do
    		for _, field in group do
    			table.insert(fields, if table.find(endpoint.required or NONE, field) then field else field .. "?")
    		end
    	end
    	if endpoint.paging then table.insert(fields, "next?") end
    	if endpoint.method == "POST" then
    		for _, field in endpoint.required or NONE do
    			if not table.find(fields, field) then table.insert(fields, field) end
    		end
    		table.insert(fields, "...body")
    	end
    	return "({" .. table.concat(fields, ", ") .. "})"
    end
    
    exports.help = function(): string
    	local lines = {
    		"Meta Graph API " .. VERSION .. " for one Facebook Page and the Instagram professional account linked to it. Each function takes one options object with Meta's snake_case names (? marks optional; ...body are the body fields after Body). Results are Meta's JSON, except that keys naming a token are dropped, Meta's links lose their access token (or become null when it cannot be removed) and the paging.next of list functions (those taking next?) is an opaque value; links inside expanded fields stay Meta's URLs. Connector calls return completed values: use them directly, without await.",
    		"Start with local page = meta.getPage(): page.id is the Page. For Instagram, local ig = meta.getPage({fields='id,instagram_business_account'}).instagram_business_account gives the linked account, whose ig.id is the ig_user of Instagram functions; it is nil when none is linked, and the call needs the instagram_basic permission. Page functions act on the connected Page itself. IDs are strings: posts look like '<page-id>_<post-id>', conversations 't_...', Messenger messages 'm_...'; Instagram media, comments and accounts are numeric strings, Instagram threads and messages opaque ones.",
    		"fields chooses what Meta returns and accepts field expansion, such as fields='id,message,comments.limit(5){message,from}' or, to get insights with each post, fields='id,message,insights.metric(post_media_view,post_clicks)'. Functions list their default fields; getObject without fields returns only Meta's minimal defaults. Access tokens cannot be requested. Media links (full_picture, picture, media_url, attachments) are signed CDN URLs that expire within days; read the object again for fresh ones.",
    		"Paging: lists return one page, {data, paging}. limit sets its size (default 25) and paging.cursors.after is the next call's after. While paging.next is present, call the same function with {next = result.paging.next} alone for the next page; stop when it is absent, as a page can be empty yet have next. To page backward, functions listing before? take before=result.paging.cursors.before; time-paged lists such as listFeed and getInsights take an earlier since/until. Expanded edges, such as business_discovery media, are paged with their own .after(cursor) modifier instead. until is a Luau keyword: write it [\"until\"] = value.",
    		"Insights: getInsights({object, metric, period?, since?, until?, ...}); since and until take Unix times or dates, at most 90 days apart for the Page, and paging.next moves to the following window; insights links continue past today, so stop once a window ends after the range you need. Page (object='me'): page_media_view, page_total_media_view_unique, page_daily_follows_unique, page_daily_unfollows_unique, page_post_engagements, page_total_actions, page_views_total, page_video_views, with period day, week or days_28, and page_follows with period day; needs 100 or more followers. Posts: post_media_view, post_total_media_view_unique, post_clicks, post_reactions_by_type_total, post_video_views (period lifetime). Instagram account: reach, views, accounts_engaged, total_interactions, likes, comments, shares, saves, replies, follows_and_unfollows, profile_links_taps, with period='day' and metric_type='total_value' (breakdown='media_product_type' splits most), covering the last 24 hours unless since/until are given; follower_demographics and engaged_audience_demographics need period='lifetime', timeframe='this_month' and breakdown age, city, country or gender. Instagram media: views, reach, likes, comments, shares, saved, total_interactions; reels add ig_reels_avg_watch_time, stories navigation (24 hours only). impressions, plays and page_fans no longer exist.",
    		"Inbox: listConversations({platform='messenger' or 'instagram'}), then listMessages({conversation=thread.id}). Meta returns conversations with your customers only once the app has Advanced Access for messaging.",
    		"Read-only connections omit writes. Meta also applies the token's permissions and the system user's tasks on the Page; a missing one fails with code 10 or 200 naming it. Errors give the HTTP status, Meta's code/subcode, message and fbtrace_id; retryable says whether repeating the call is safe: rate limits (codes 4, 17, 32, 341, 613, 80000-80014, which may say when calls succeed again) unless a write got a 5xx, and for reads also temporary errors (codes 1, 2) and a 5xx without another Meta code; a write that may already have been applied never is.",
    	}
    	local writing = {
    		"Replying: sendMessage({recipient={id=psid}, messaging_type='RESPONSE', message={text='Thanks!'}}) answers within 24 hours of the person's last message; after that Meta requires messaging_type='MESSAGE_TAG' with a tag it still accepts, such as 'HUMAN_AGENT' (within 7 days, once Meta approved its Human Agent feature). sendMessage({recipient={comment_id=id}, message}) sends the one private reply allowed to a Facebook comment, within 7 days; Instagram comments use sendInstagramPrivateReply, and if Meta refuses that route, sendMessage with the Instagram comment_id. Instagram texts are at most 1,000 bytes; recipients are the IDs in participants or from.",
    		"Publishing to Facebook: createPost({message='Hello'}) posts now; published=false with scheduled_publish_time (Unix time 10 minutes to 30 days ahead) schedules it. uploadPhoto and uploadVideo take a public url (file_url for videos) or path, a session file streamed to Meta. For several photos in one post, upload each with published=false (and temporary=true when the post is scheduled), then createPost({message, attached_media={{media_fbid=id1}, {media_fbid=id2}}}). Facebook reels cannot be published here.",
    		"Publishing to Instagram: createInstagramContainer({ig_user, image_url=jpeg_url, caption}) (or media_type='REELS' with video_url, media_type='STORIES', or media_type='CAROUSEL' with children='id1,id2', at most 10 made with is_carousel_item=true) returns {id}; poll getObject({id=container.id, fields='status_code'}) about once a minute, for at most 5 minutes, until FINISHED (EXPIRED after 24 hours, ERROR on failure); then publishInstagramMedia({ig_user, creation_id=container.id}). Meta fetches media from public HTTPS URLs. Captions take at most 2,200 characters, 30 hashtags and 20 @ tags; an account creates at most 400 containers a day, and getInstagramPublishingLimit gives the 24-hour publishing quota.",
    		"Moderation: updateComment({comment, is_hidden=true}) hides a Facebook comment and updateComment({comment, hide=true}) an Instagram one; deleteObject({id}) deletes either. Instagram comments can be deleted only on the account's own media.",
    		"Writes return {id} or {success=true}. There are no automatic retries: after a timeout or 5xx, read the Page again before repeating a write, since a post or message may already be live.",
    	}
    	if houston.allows("data:write") then table.move(writing, 1, #writing, #lines + 1, lines) end
    	local names: {string} = {}
    	for name in exports do if name ~= "help" then table.insert(names, name) end end
    	table.sort(names)
    	for _, name in names do
    		local endpoint = endpoints[name]
    		local defaults = if endpoint.fields then " Default fields: " .. endpoint.fields .. "." else ""
    		table.insert(lines, name .. signature(endpoint) .. ": " .. endpoint.about .. defaults .. " " .. endpoint.method .. " " .. endpoint.path)
    	end
    	return table.concat(lines, "\n")
    end
    return exports
    
  • houston.json
    {
      "schema_version": 2,
      "name": "Meta Business Suite",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "access": [
        {
          "name": "data",
          "label": "Access",
          "levels": [
            {
              "value": "read",
              "label": "Read"
            },
            {
              "value": "write",
              "label": "Write"
            }
          ],
          "default": "read"
        }
      ],
      "auth": {
        "token": {
          "type": "manual",
          "label": "Page access token",
          "config": {
            "token": {
              "type": "secret",
              "label": "Page access token",
              "description": "A Page access token made from a system user in Meta Business Settings.",
              "required": true
            }
          }
        }
      },
      "proxy": [
        {
          "match": {
            "protocol": "http",
            "host": [
              "graph.facebook.com"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/v26.0/{id}",
              "/v26.0/{id}/children",
              "/v26.0/{id}/comments",
              "/v26.0/{id}/content_publishing_limit",
              "/v26.0/{id}/conversations",
              "/v26.0/{id}/feed",
              "/v26.0/{id}/insights",
              "/v26.0/{id}/media",
              "/v26.0/{id}/messages",
              "/v26.0/{id}/photos",
              "/v26.0/{id}/published_posts",
              "/v26.0/{id}/ratings",
              "/v26.0/{id}/reactions",
              "/v26.0/{id}/recent_media",
              "/v26.0/{id}/replies",
              "/v26.0/{id}/scheduled_posts",
              "/v26.0/{id}/stories",
              "/v26.0/{id}/tagged",
              "/v26.0/{id}/tags",
              "/v26.0/{id}/top_media",
              "/v26.0/{id}/video_reels",
              "/v26.0/{id}/videos"
            ]
          },
          "action": {
            "headers": {
              "set": {
                "Authorization": "Bearer {{auth.token.token}}"
              }
            }
          }
        },
        {
          "if": "{{ allows access.data \"write\" }}",
          "match": {
            "protocol": "http",
            "host": [
              "graph.facebook.com"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/v26.0/{id}",
              "/v26.0/{id}/comments",
              "/v26.0/{id}/feed",
              "/v26.0/{id}/media",
              "/v26.0/{id}/media_publish",
              "/v26.0/{id}/messages",
              "/v26.0/{id}/photos",
              "/v26.0/{id}/replies"
            ]
          },
          "action": {
            "headers": {
              "set": {
                "Authorization": "Bearer {{auth.token.token}}"
              }
            }
          }
        },
        {
          "if": "{{ allows access.data \"write\" }}",
          "match": {
            "protocol": "http",
            "host": [
              "graph.facebook.com"
            ],
            "method": [
              "DELETE"
            ],
            "path": [
              "/v26.0/{id}"
            ]
          },
          "action": {
            "headers": {
              "set": {
                "Authorization": "Bearer {{auth.token.token}}"
              }
            }
          }
        },
        {
          "if": "{{ allows access.data \"write\" }}",
          "match": {
            "protocol": "http",
            "host": [
              "graph-video.facebook.com"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/v26.0/{id}/videos"
            ]
          },
          "action": {
            "headers": {
              "set": {
                "Authorization": "Bearer {{auth.token.token}}"
              }
            }
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Read your Facebook Page and Instagram posts, comments, messages and insights, and publish and reply as your business.
    ---
    
    # Meta Business Suite
    
    Let agents read posts, comments, messages and insights for one Facebook Page and
    its linked Instagram professional account. **Write** access also permits
    publishing, scheduling, replying and moderation.
    
    > Customer conversations require Meta's Advanced Access, business verification
    > and App Review. Replies are generally limited to 24 hours after the person's
    > last message.
    
    Requires a business portfolio and developer app. Ads and Facebook reel publishing
    are not included.
    
    [Connect Meta Business Suite](SETUP.md).
    
  • SETUP.md
    # Connect Meta Business Suite
    
    You need admin access to a business portfolio managing the Facebook Page, a Meta
    app connected to that portfolio, and (for Instagram) a linked professional account.
    Each Houston connection serves one Page.
    
    1. [Create a Meta app](https://developers.facebook.com/apps/creation/) for your
       portfolio. Choose the Page, Messenger and optional Instagram use cases; use
       **API setup with Facebook Login** for Instagram. Add the permissions below.
    2. In [Business settings](https://business.facebook.com/settings), open
       **Users → System users**. Create or select a system user and assign the app,
       Page and optional Instagram account with **Full control**.
    3. Select **Generate token**, choose the app and permissions below, and select a
       non-expiring token if available.
    4. In [Graph API Explorer](https://developers.facebook.com/tools/explorer/), paste
       that system user token and submit:
    
       ```text
       me/accounts?fields=name,access_token
       ```
    
    5. Copy your Page's `access_token`. In the
       [Access Token Debugger](https://developers.facebook.com/tools/debug/accesstoken/),
       confirm **Type: Page** and check its expiry.
    6. In Houston, choose **Read** or **Write** for **Access**, enter the
       Page access token, and save the connection.
    
    > Use the **Page token**, not the system user token. Customer conversations need
    > Advanced Access, business verification and App Review. Until approved, messaging
    > is limited to people with a role on the app, Page or portfolio.
    
    ## Permissions
    
    
    For **Read**: `pages_show_list`, `pages_read_engagement`,
    `pages_read_user_content`, `read_insights`, `pages_manage_metadata`,
    `pages_messaging` and `business_management`; for Instagram, also
    `instagram_basic`, `instagram_manage_comments`, `instagram_manage_insights` and
    `instagram_manage_messages`.
    
    For **Write**, also: `pages_manage_posts`, `pages_manage_engagement` and
    `publish_video` when Meta offers it; for Instagram, `instagram_content_publish` and
    `instagram_manage_contents`.
    
    Some **Read** permissions also allow changes: Meta requires `pages_manage_metadata`
    to read conversations, adds `business_management` with the **Manage everything on
    your Page** use case for business-owned Pages, and grants reading and replying to
    messages together (`pages_messaging`, `instagram_manage_messages`). Leave out
    messaging permissions if you do not need the inbox. With **Read** access
    Houston blocks every write, whatever the token allows. See Meta's
    [permissions reference](https://developers.facebook.com/docs/permissions).
    
    ## Advanced
    
    - **Messaging:** request Advanced Access for `pages_messaging`,
      `pages_manage_metadata`, `pages_read_engagement` and, for Instagram,
      `instagram_basic` and `instagram_manage_messages`. In Instagram, enable
      **Allow access to messages** under **Connected tools**.
    - **Expiry or changed permissions:** generate a new system user token, derive a
      new Page token and update Houston. Some businesses must use expiring tokens.
    - **Missing Instagram:** link the professional account to the Page and assign it
      to the system user. Page insights require at least 100 followers.
    - **appsecret_proof errors:** disable **Require app secret** in the app's
      **Advanced → Security** settings; Houston does not send app secret proofs.
    - **Reply limits:** Meta generally permits replies within 24 hours. Hashtag search
      needs Instagram Public Content Access through App Review.
    - **Revoke access:** remove the system user's Page access in Business settings.
    
  • tests
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = { token = "synthetic-method-secret" },
      				config = {},
      				endpoint = { "GET", "https://graph.facebook.com/v26.0/me" },
      				expected = "Bearer synthetic-method-secret",
      				header = "Authorization",
      				method = "token",
      				publisher = {},
      			},
      		})
      	end,
      }
      
    • endpoints.luau
      return {
      	contract = function(m)
      		local entries = m.endpoints()
      		local function host(entry)
      			return if string.find(entry.rest, "host = VIDEO_API", 1, true)
      				then "graph-video.facebook.com"
      				else "graph.facebook.com"
      		end
      		local want, got = {}, {}
      		for _, entry in entries do
      			local path = string.gsub(entry.path, "^/[^/]+", "/{id}")
      			path = string.gsub(path, "{[%w_]+}", "{id}")
      			table.insert(want, entry.method .. " " .. host(entry) .. "/v26.0" .. path)
      		end
      		for _, rule in m.raw.proxy do
      			for _, hostname in rule.match.host do
      				for _, method in rule.match.method do
      					for _, path in rule.match.path do
      						table.insert(got, method .. " " .. hostname .. path)
      					end
      				end
      			end
      		end
      		m.sortedEqual(want, got, true)
      		for _, access in { "read", "write" } do
      			local r, err = m.resolve(nil, {}, { token = "EAAPAGE" }, "token", { data = access })
      			assert(r and not err, tostring(err))
      			for _, entry in entries do
      				local route = entry.method
      					.. " https://"
      					.. host(entry)
      					.. "/v26.0"
      					.. string.gsub(entry.path, "{[%w_]+}", "101_1")
      				m.routes(r, "Bearer EAAPAGE", not entry.access or access == "write", { route })
      			end
      		end
      	end,
      }
      
    • errors.luau
      return {
      	scenario = {publisher = {}, access = {data = "write"}, config = {}, auth_method = "token", auth_config = {token = "fixture-page-token"}},
      	configure = function()
      		calls = 0
      		status, payload, responseHeaders = 200, "{}", {}
      		http = {request = function(req)
      			calls += 1
      			return fixture.operation({statusCode = status, headers = responseHeaders, body = fixture.reader(payload)})
      		end}
      	end,
      	run = function(meta)
      		local function upstream(code, body, headers, expected, absent)
      			status, payload, responseHeaders = code, body, headers
      			local before = calls
      			local ok, err = pcall(function() meta.createPost({message = "Fresh bread"}) end)
      			for _, text in expected do
      				assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err))
      			end
      			if absent then assert(not string.find(tostring(err), absent, 1, true), "unexpected " .. absent .. " in " .. tostring(err)) end
      			assert(calls == before + 1, "failed write was retried")
      		end
      		upstream(400, '{"error":{"message":"(#200) The permission(s) pages_manage_posts are not available.","type":"OAuthException","code":200,"fbtrace_id":"AZSAqjOKJ6IRMp"}}', {},
      			{"Meta HTTP 400 (#200)", "pages_manage_posts", "fbtrace_id AZSAqjOKJ6IRMp", '"retryable":false', '"upstream_status":400'})
      		upstream(400, '{"error":{"message":"Invalid parameter","type":"OAuthException","code":100,"error_subcode":1363026,"error_user_msg":"The scheduled time must be at least 10 minutes ahead."}}', {},
      			{"(#100/1363026): Invalid parameter The scheduled time must be at least 10 minutes ahead.", '"retryable":false'})
      		upstream(401, '{"error":{"message":"Invalid OAuth access token - Cannot parse access token","type":"OAuthException","code":190}}', {},
      			{"Meta HTTP 401 (#190)", "create a new one and update the connection", '"retryable":false'})
      		upstream(400, '{"error":{"message":"(#80001) There have been too many calls to this Page account.","type":"OAuthException","code":80001}}',
      			{["x-business-use-case-usage"] = {'{"101":[{"type":"pages","call_count":100,"total_cputime":20,"total_time":20,"estimated_time_to_regain_access":12.5}]}'}},
      			{"(#80001)", "succeed again in about 13 min", '"retryable":true'})
      		upstream(400, '{"error":{"message":"(#4) Application request limit reached","type":"OAuthException","code":4}}', {["x-business-use-case-usage"] = {"not json"}},
      			{"(#4)", '"retryable":true'}, "succeed again")
      		upstream(400, '{"error":{"message":"(#613) Calls to this api have exceeded the rate limit.","type":"OAuthException","code":613}}',
      			{["x-business-use-case-usage"] = {'{"101":[{"estimated_time_to_regain_access":0}]}'}}, {"(#613)", '"retryable":true'}, "succeed again")
      		upstream(400, '{"error":{"message":"(#368) The action attempted has been deemed abusive","type":"OAuthException","code":368}}', {},
      			{"(#368)", '"retryable":false'})
      		upstream(500, '{"error":{"message":"Service temporarily unavailable","type":"FacebookApiException","code":2,"is_transient":true}}', {},
      			{"Meta HTTP 500 (#2)", '"retryable":false'})
      		upstream(400, '{"error":{"message":"An unexpected error has occurred.","type":"OAuthException","code":1}}', {},
      			{"(#1)", '"retryable":false'})
      		upstream(400, '{"error":{"message":"Malformed access token EAAGZBpage0123456789abcdefghijklmnopqrstuvwxyz near https://graph.facebook.com/me?access_token=EAAGZBpage0123456789abcdefghijklmnopqrstuvwxyz","type":"OAuthException","code":190}}', {},
      			{"Malformed access token", "near https://graph.facebook.com/me", "create a new one and update the connection", '"retryable":false'}, "EAAGZBpage0123456789abcdefghijklmnopqrstuvwxyz")
      		upstream(500, '{"error":{"message":"Unsupported post request.","type":"GraphMethodException","code":100,"error_subcode":33,"is_transient":false}}', {},
      			{"Meta HTTP 500 (#100/33)", '"retryable":false'})
      		upstream(200, '{"error":{"message":"(#100) Invalid parameter","type":"OAuthException","code":100}}', {}, {"Meta HTTP 200 (#100)", '"retryable":false'})
      		upstream(400, '{"error":{"message":"Invalid OAuth access token: IGAAKxyz0123456789abcdefghijklmnopqrstuvwx and access_token=123|secret","type":"OAuthException","code":190}}', {},
      			{"Invalid OAuth access token"}, "secret")
      		upstream(400, '{"error":{"message":"Invalid OAuth access token: IGAAKxyz0123456789abcdefghijklmnopqrstuvwx","type":"OAuthException","code":190}}', {},
      			{"Invalid OAuth access token"}, "IGAAKxyz")
      		upstream(500, '{"error":{"message":"(#32) Page request limit reached","type":"OAuthException","code":32}}', {}, {"(#32)", '"retryable":false'})
      		upstream(400, '{"error":{"message":"Bad redirect https%3A%2F%2Fx%3Fr%3Daccess_token%3DEAAGZBpage0123456789abcdefghijklmnopqrstuvwxyz","type":"OAuthException","code":100}}', {},
      			{"Bad redirect"}, "EAAGZBpage")
      		upstream(429, "", {}, {"Meta HTTP 429", '"retryable":true'})
      		upstream(502, "<html>Bad gateway</html>", {}, {"Meta HTTP 502", '"retryable":false'})
      		upstream(400, json.encode({error = {message = string.rep("x", 5000), code = 100}}), {}, {"(#100)"})
      		upstream(200, "<html>Maintenance</html>", {}, {"invalid JSON object", '"upstream_status":200'})
      		upstream(200, "[]", {}, {"invalid JSON object"})
      
      		-- A write may already have happened when Meta reports a transient error or a 5xx, so only
      		-- throttling, which Meta refuses before acting, is retryable for writes; reads retry both.
      		status, payload, responseHeaders = 500, '{"error":{"message":"Service temporarily unavailable","code":2,"is_transient":true}}', {}
      		local readOk, readErr = pcall(function() meta.listFeed() end)
      		assert(not readOk and string.find(tostring(readErr), '"retryable":true', 1, true), tostring(readErr))
      		status, payload = 502, "<html>Bad gateway</html>"
      		readOk, readErr = pcall(function() meta.listFeed() end)
      		assert(not readOk and string.find(tostring(readErr), '"retryable":true', 1, true), tostring(readErr))
      
      		-- Reads map errors the same way.
      		status, payload, responseHeaders = 400, '{"error":{"message":"(#10) This endpoint requires the pages_read_engagement permission","type":"OAuthException","code":10}}', {}
      		local ok, err = pcall(function() meta.listFeed() end)
      		assert(not ok and string.find(tostring(err), "Meta HTTP 400 (#10): This endpoint requires the pages_read_engagement permission", 1, true), tostring(err))
      	end,
      }
      
    • manifest.luau
      return {
      	contract = function(m)
      		-- TestMetaAccessRoutes
      		do
      			local api = "https://graph.facebook.com/v26.0"
      			for _, access in { "read", "write" } do
      				local r, err = m.resolve(nil, {}, { token = "EAAPAGE" }, "token", { data = access })
      				assert(not err, tostring(err))
      				m.routes(r, "Bearer EAAPAGE", true, {
      					"GET " .. api .. "/me?fields=id%2Cname",
      					"GET " .. api .. "/me/conversations?platform=instagram",
      					"GET " .. api .. "/ig_hashtag_search?user_id=1&q=bread",
      					"GET " .. api .. "/t_1/messages?after=QUZU",
      				})
      				m.rejectOverrides(
      					r,
      					{ "GET " .. api .. "/me/feed", "GET " .. api .. "/1/content_publishing_limit" }
      				)
      				if access == "write" then
      					m.rejectOverrides(r, {
      						"POST " .. api .. "/me/feed",
      						"DELETE " .. api .. "/101_1",
      						"POST https://graph-video.facebook.com/v26.0/me/videos",
      					})
      				end
      				m.routes(r, "Bearer EAAPAGE", false, {
      					"GET " .. api .. "/me/accounts",
      					"GET " .. api .. "/oauth/access_token",
      					"GET " .. api .. "/me/permissions",
      					"GET " .. api .. "/me/subscribed_apps",
      					"POST " .. api .. "/me/subscribed_apps",
      					"GET " .. api .. "/act_1/ads",
      					"POST " .. api .. "/",
      					"GET " .. api .. "/",
      					"POST " .. api .. "/me/videos",
      					"PUT " .. api .. "/101_1",
      					"DELETE " .. api .. "/101_1/comments",
      					"GET https://graph.facebook.com/v25.0/me",
      					"GET https://graph.facebook.com/me",
      					"GET https://graph.instagram.com/v26.0/me",
      					"GET https://graph.facebook.com.evil.test/v26.0/me",
      					"GET https://www.facebook.com/v26.0/dialog/oauth",
      					"POST https://rupload.facebook.com/ig-api-upload/v26.0/1",
      					"GET https://graph-video.facebook.com/v26.0/me",
      					"POST https://graph-video.facebook.com/v26.0/me/feed",
      					"GET " .. api .. "/%2e%2e/me/accounts",
      					"GET " .. api .. "/me%2Faccounts",
      				})
      			end
      		end
      	end,
      }
      
    • read_only.luau
      return {
      	scenario = {publisher = {}, access = {data = "read"}, config = {}, auth_method = "token", auth_config = {token = "fixture-page-token"}},
      	configure = function()
      		requests, responses = {}, {}
      		-- Sealing is native; a table of opaque handles stands in for it.
      		local sealed, count = {}, 0
      		houston = table.clone(houston)
      		houston.seal = function(value)
      			count += 1
      			sealed["sealed:" .. count] = json.encode(value)
      			return "sealed:" .. count
      		end
      		houston.unseal = function(token)
      			assert(type(token) == "string" and sealed[token], "invalid sealed token")
      			return json.decode(sealed[token])
      		end
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation(table.remove(responses, 1))
      		end}
      		function respond(body)
      			table.insert(responses, {statusCode = 200, headers = {}, body = fixture.reader(body)})
      		end
      		function rejected(call, expected)
      			local before = #requests
      			local ok, err = pcall(call)
      			assert(not ok and string.find(tostring(err), expected, 1, true), "expected " .. expected .. ", got " .. tostring(err))
      			assert(#requests == before, "invalid input reached Meta")
      		end
      	end,
      	run = function(meta)
      		local names = {}
      		for name in meta do table.insert(names, name) end
      		table.sort(names)
      		assert(table.concat(names, ",") == table.concat({
      			"getInsights", "getInstagramAccount", "getInstagramPublishingLimit", "getObject", "getPage", "listComments",
      			"listConversations", "listFeed", "listHashtagRecentMedia", "listHashtagTopMedia", "listInstagramChildren",
      			"listInstagramComments", "listInstagramMedia", "listInstagramReplies", "listInstagramStories", "listInstagramTags",
      			"listMessages", "listPhotos", "listPublishedPosts", "listRatings", "listReactions", "listReels",
      			"listScheduledPosts", "listTaggedPosts", "listVideos", "searchInstagramHashtag",
      		}, ","), table.concat(names, ","))
      
      		-- Reads go to /v26.0 with Meta's field list; the proxy adds the credential.
      		respond('{"id":"101","name":"Bakery","instagram_business_account":{"id":"17841400000000001","username":"bakery"}}')
      		local page = meta.getPage({fields = "id,name,instagram_business_account{id,username}"})
      		assert(page.instagram_business_account.id == "17841400000000001")
      		local req = requests[1]
      		assert(req.method == "GET" and req.url == "https://graph.facebook.com/v26.0/me?fields=id%2Cname%2Cinstagram_business_account%7Bid%2Cusername%7D")
      		assert(req.headers.Authorization == nil and req.headers.Accept[1] == "application/json" and req.body == nil)
      
      		-- Default fields need no Instagram permission; Instagram functions name their account.
      		respond('{"id":"101","name":"Bakery"}')
      		meta.getPage()
      		assert(requests[2].url == "https://graph.facebook.com/v26.0/me?fields=id%2Cname%2Cusername%2Clink%2Ccategory%2Cabout%2Cdescription%2Cwebsite%2Cphone%2Cemails%2Cfollowers_count%2Cfan_count%2Cverification_status", requests[2].url)
      		table.remove(requests, 2)
      
      		-- Default fields, path IDs and paging options.
      		respond('{"data":[]}')
      		local empty = meta.listInstagramChildren({media = "17900000000000001"})
      		assert(json.encode(empty.data) == "[]")
      		assert(requests[2].url == "https://graph.facebook.com/v26.0/17900000000000001/children?fields=id%2Cmedia_type%2Cmedia_url%2Cthumbnail_url%2Ctimestamp")
      		respond('{"data":[{"id":"101_1","message":"Fresh bread"},{"id":"101_2"}],"paging":{"cursors":{"before":"QkVG","after":"QUZU"}}}')
      		local feed = meta.listFeed({fields = "id,message", limit = 2, after = "QUFB", since = 1760000000, include_hidden = true})
      		assert(#feed.data == 2 and feed.data[1].message == "Fresh bread" and feed.paging.cursors.after == "QUZU")
      		assert(requests[3].url == "https://graph.facebook.com/v26.0/me/feed?fields=id%2Cmessage&since=1760000000&include_hidden=true&limit=2&after=QUFB")
      		respond('{"data":[{"id":"t_1","updated_time":"2026-10-19T08:00:00+0000"}]}')
      		meta.listConversations({platform = "instagram", fields = "id,updated_time"})
      		assert(requests[4].url == "https://graph.facebook.com/v26.0/me/conversations?fields=id%2Cupdated_time&platform=instagram")
      		respond('{"data":[{"name":"page_media_view","period":"day","values":[{"value":42,"end_time":"2026-10-18T07:00:00+0000"}]}]}')
      		local insights = meta.getInsights({object = "me", metric = {"page_media_view", "page_follows"}, period = "day", since = "2026-10-01", ["until"] = "2026-10-18"})
      		assert(insights.data[1].values[1].value == 42)
      		assert(requests[5].url == "https://graph.facebook.com/v26.0/me/insights?metric=page_media_view%2Cpage_follows&period=day&since=2026-10-01&until=2026-10-18")
      		respond('{"data":[{"id":"17843853986012965"}]}')
      		meta.searchInstagramHashtag({user_id = "17841400000000001", q = "sourdough"})
      		assert(requests[6].url == "https://graph.facebook.com/v26.0/ig_hashtag_search?user_id=17841400000000001&q=sourdough")
      		respond('{"id":"t_1","messages":{"data":[]}}')
      		meta.getObject({id = "t_1", fields = "messages.limit(5){message,from}"})
      		assert(requests[7].url == "https://graph.facebook.com/v26.0/t_1?fields=messages.limit%285%29%7Bmessage%2Cfrom%7D")
      
      		-- Paging links come back sealed for the function that made them, without the token Meta
      		-- writes into them, and page on through that function.
      		respond(json.encode({data = {{id = "c1"}}, paging = {
      			cursors = {after = "QUZU"},
      			next = "https://graph.facebook.com/v26.0/101_1/comments?access_token=EAAPAGE&fields=id%2Cmessage&limit=1&after=QUZU",
      			previous = "https://graph.facebook.com/v26.0/101_1/comments?fields=id&limit=1&before=QkVG&access_token=EAAPAGE",
      		}}))
      		local comments = meta.listComments({object = "101_1", fields = "id,message", limit = 1})
      		assert(comments.paging.cursors.after == "QUZU" and not string.find(comments.paging.next, "graph", 1, true), comments.paging.next)
      		respond('{"data":[]}')
      		meta.listComments({next = comments.paging.next})
      		assert(requests[9].url == "https://graph.facebook.com/v26.0/101_1/comments?fields=id%2Cmessage&limit=1&after=QUZU" and requests[9].headers.Accept[1] == "application/json", requests[9].url)
      		-- previous cannot be replayed, so it is dropped; cursors.before pages backward.
      		assert(comments.paging.previous == nil and comments.paging.cursors.after == "QUZU")
      		-- Insights page through time the same way, whatever parameters Meta adds.
      		local insightsNext = "https://graph.facebook.com/v26.0/101/insights?metric=page_follows&period=day&since=1&until=2&__cppo=1"
      		respond(json.encode({data = {}, paging = {next = insightsNext}}))
      		local follows = meta.getInsights({object = "me", metric = "page_follows", period = "day"})
      		respond('{"data":[]}')
      		meta.getInsights({next = follows.paging.next})
      		assert(requests[11].url == insightsNext, requests[11].url)
      
      		-- Stories have no like or comment counts to ask for.
      		respond('{"data":[]}')
      		meta.listInstagramStories({ig_user = "17841400000000001"})
      		assert(requests[#requests].url == "https://graph.facebook.com/v26.0/17841400000000001/stories?fields=id%2Ccaption%2Cmedia_type%2Cmedia_product_type%2Cmedia_url%2Cthumbnail_url%2Cpermalink%2Ctimestamp", requests[#requests].url)
      
      		-- Query values are encoded, so they cannot add parameters.
      		respond('{"data":[]}')
      		meta.listReels({fields = "id", since = "1&method=delete", ["until"] = "a=b"})
      		assert(requests[#requests].url == "https://graph.facebook.com/v26.0/me/video_reels?fields=id&since=1%26method%3Ddelete&until=a%3Db", requests[#requests].url)
      		-- Token fields and the tokens in Meta's own links, repeated or encoded, are dropped;
      		-- text from people and cursors stay as they are.
      		respond(json.encode({id = "101", accounts = {data = {{id = "102", name = "Other", access_token = "EAAOTHER", page_token = "EAAPT"}}},
      			wrapped = "https://l.facebook.com/l.php?u=https%3A%2F%2Fgraph.facebook.com%2Fme%3Faccess_token%3DEAA6", plain = "http://graph.facebook.com/v26.0/101/feed?access_token=EAA5&limit=1",
      			kept = "https://graph.facebook.com/v26.0/101/feed?since=x%3F&access_token=EAA7", bare = "https://graph.facebook.com/v26.0/101/feed?access_token=EAA9#top", deep = "https://graph.facebook.com/v26.0/101/feed?r=x%253Faccess_token%253DEAA8", piped = "https://graph.facebook.com/v26.0/101/feed?access_token=123%7Csecret&limit=25", nested = "https://graph.facebook.com/v26.0/101/feed?r=x%3Fa%3D1%26access_token%3D123%7Csecret%26b%3D2", named = "https://graph.facebook.com/v26.0/101/feed?limit=5&page_access_token=kept&after=Q",
      			comments = {data = {}, paging = {next = "https://graph.facebook.com/v26.0/101_1/comments?access_token=EAA1&access_token=EAA2&limit=5",
      				previous = "https://graph.facebook.com/v26.0/101_1/comments?limit=5&redirect=x%3Faccess_token%3DEAAGZBpage0123456789abcdefghijklmnopqrstuvwxyz%26ref%3Dabc"}},
      			note = "see https://x.test/cb?access_token=abc&x=1 and thanks", message = "https://www.facebook.com/x?access_token=abc is this the right link? thanks", cursors = {after = "QUFB_EAAGZBpage0123456789abcdefghijklmnopqrstuvwxyz"}, comment = "Is EAAGLES2024 still open?"}))
      		local leaky = meta.getObject({id = "101", fields = "id,accounts,comments"})
      		assert(leaky.accounts.data[1].name == "Other" and leaky.accounts.data[1].access_token == nil and leaky.accounts.data[1].page_token == nil)
      		assert(leaky.comments.paging.next == "https://graph.facebook.com/v26.0/101_1/comments?limit=5", leaky.comments.paging.next)
      		-- Links that still name a token become JSON null, keeping arrays dense.
      		local NULL = json.decode("null")
      		assert(leaky.comments.paging.previous == NULL)
      		assert(leaky.message == "https://www.facebook.com/x?access_token=abc is this the right link? thanks" and leaky.note == "see https://x.test/cb?access_token=abc&x=1 and thanks" and leaky.comment == "Is EAAGLES2024 still open?", leaky.note)
      		assert(leaky.piped == "https://graph.facebook.com/v26.0/101/feed?limit=25" and leaky.nested == NULL and leaky.wrapped == NULL and leaky.plain == "http://graph.facebook.com/v26.0/101/feed?limit=1" and leaky.kept == "https://graph.facebook.com/v26.0/101/feed?since=x%3F", leaky.kept)
      		assert(leaky.bare == "https://graph.facebook.com/v26.0/101/feed#top" and leaky.deep == NULL and leaky.named == NULL)
      		assert(leaky.cursors.after == "QUFB_EAAGZBpage0123456789abcdefghijklmnopqrstuvwxyz", leaky.cursors.after)
      		-- Graph honours ?method=delete and batch even on GET, and a Page can read its own token.
      		rejected(function() meta.listFeed({method = "delete"}) end, "has no option method")
      		rejected(function() meta.getObject({id = "101", batch = "[]"}) end, "has no option batch")
      		rejected(function() meta.getPage({fields = "id,access_token"}) end, "cannot request access tokens")
      		rejected(function() meta.getPage({fields = "id,PAGE_TOKEN"}) end, "cannot request access tokens")
      		-- Expanded edges page with padded cursors and zoned times.
      		respond('{"id":"17841400000000001"}')
      		meta.getObject({id = "17841400000000001", fields = "media.after(QVF/MTAxNTE=).since(2026-10-01T00:00:00+0000){caption}"})
      		assert(requests[#requests].url == "https://graph.facebook.com/v26.0/17841400000000001?fields=media.after%28QVF%2FMTAxNTE%3D%29.since%282026-10-01T00%3A00%3A00%2B0000%29%7Bcaption%7D", requests[#requests].url)
      		rejected(function() meta.getObject({id = "101", fields = "id&method=delete"}) end, "Graph field list")
      		-- next takes only a link sealed by the same function, never a URL a caller wrote.
      		rejected(function() meta.listFeed({next = "https://graph.facebook.com/v26.0/101/feed?method=delete"}) end, "paging.next value of an earlier")
      		rejected(function() meta.listFeed({next = comments.paging.next}) end, "paging.next value of an earlier")
      		rejected(function() meta.listComments({next = houston.seal({operation = "listComments", url = "https://evil.test/v26.0/me"})}) end, "paging.next value of an earlier")
      		-- So does a link outside the pinned API version.
      		respond(json.encode({data = {}, paging = {next = "https://graph.facebook.com/101/feed?after=QUZU"}}))
      		local oldOk, oldErr = pcall(function() meta.listFeed() end)
      		assert(not oldOk and string.find(tostring(oldErr), "paging link", 1, true), tostring(oldErr))
      		-- A paging link the scrub cannot clean fails the call instead of ending the list early.
      		respond(json.encode({data = {{id = "101_1"}}, paging = {next = "https://graph.facebook.com/v26.0/101/feed?r=x%253Faccess_token%253DEAA8"}}))
      		local dirtyOk, dirtyErr = pcall(function() meta.listFeed() end)
      		assert(not dirtyOk and string.find(tostring(dirtyErr), "paging link", 1, true), tostring(dirtyErr))
      		rejected(function() meta.listComments({next = comments.paging.next, limit = 5}) end, "pass next alone")
      		rejected(function() meta.getPage({next = comments.paging.next}) end, "has no option next")
      
      		-- IDs are single path segments given as strings, and required options come first.
      		rejected(function() meta.listComments({object = "../me"}) end, "one Meta ID")
      		rejected(function() meta.getObject({id = "me?method=delete"}) end, "one Meta ID")
      		rejected(function() meta.getObject({id = "101#x"}) end, "one Meta ID")
      		rejected(function() meta.getObject({id = ".."}) end, "one Meta ID")
      		rejected(function() meta.getObject({id = "101 102"}) end, "one Meta ID")
      		rejected(function() meta.listComments({object = 1234567890}) end, "ID string")
      		rejected(function() meta.listComments({}) end, "ID string")
      		rejected(function() meta.getInsights({object = "me"}) end, "metric is required")
      		rejected(function() meta.getInsights({object = "me", metric = {}}) end, "empty array")
      		rejected(function() meta.getInsights({object = "me", metric = {name = "x"}}) end, "not an object")
      		rejected(function() meta.searchInstagramHashtag({q = "bread"}) end, "user_id is required")
      		rejected(function() meta.listFeed({limit = {}}) end, "empty array")
      		assert(#responses == 0)
      	end,
      }
      
    • writes.luau
      return {
      	scenario = {publisher = {}, access = {data = "write"}, config = {}, auth_method = "token", auth_config = {token = "fixture-page-token"}},
      	configure = function()
      		requests, responses = {}, {}
      		fs = fixture.files()
      		http = {request = function(req)
      			if req.body ~= nil and type(req.body) ~= "string" then req.body = await(req.body:readAll()) end
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation(table.remove(responses, 1))
      		end}
      		function respond(body)
      			table.insert(responses, {statusCode = 200, headers = {}, body = fixture.reader(body)})
      		end
      		function rejected(call, expected)
      			local before = #requests
      			local ok, err = pcall(call)
      			local text = if type(err) == "table" then json.encode(err) else tostring(err)
      			assert(not ok and string.find(text, expected, 1, true), "expected " .. expected .. ", got " .. text)
      			assert(#requests == before, "invalid input reached Meta")
      		end
      		function sent(index, method, url)
      			local req = requests[index]
      			assert(req.method == method and req.url == url, req.method .. " " .. req.url)
      			assert(req.headers.Authorization == nil)
      			return req
      		end
      	end,
      	run = function(meta)
      		for _, name in {"createComment", "createInstagramContainer", "createInstagramReply", "createPost", "deleteObject",
      			"publishInstagramMedia", "sendMessage", "sendInstagramPrivateReply", "updateComment", "updateInstagramMedia", "updatePost", "uploadPhoto", "uploadVideo",
      			"getPage", "listFeed"} do
      			assert(meta[name], "missing " .. name)
      		end
      
      		-- Writes send the remaining options as JSON, with nested objects and arrays intact.
      		respond('{"id":"101_9"}')
      		assert(meta.createPost({message = "Fresh bread", published = false, scheduled_publish_time = 1760003600,
      			attached_media = {{media_fbid = "201"}, {media_fbid = "202"}}}).id == "101_9")
      		local req = sent(1, "POST", "https://graph.facebook.com/v26.0/me/feed")
      		assert(req.headers["Content-Type"][1] == "application/json")
      		local body = json.decode(req.body)
      		assert(body.message == "Fresh bread" and body.published == false and body.scheduled_publish_time == 1760003600)
      		assert(body.attached_media[2].media_fbid == "202")
      
      		respond('{"recipient_id":"2400000000000001","message_id":"m_ABC"}')
      		meta.sendMessage({recipient = {id = "2400000000000001"}, messaging_type = "RESPONSE", message = {text = "Thanks!"}})
      		body = json.decode(sent(2, "POST", "https://graph.facebook.com/v26.0/me/messages").body)
      		assert(body.recipient.id == "2400000000000001" and body.message.text == "Thanks!" and body.messaging_type == "RESPONSE")
      
      		respond('{"success":true}')
      		assert(meta.updateComment({comment = "101_9_3", is_hidden = true}).success == true)
      		req = sent(3, "POST", "https://graph.facebook.com/v26.0/101_9_3")
      		assert(req.body == '{"is_hidden":true}' and req.headers.Accept[1] == "application/json", req.body)
      		respond('{"success":true}')
      		meta.deleteObject({id = "101_9"})
      		req = sent(4, "DELETE", "https://graph.facebook.com/v26.0/101_9")
      		assert(req.body == nil)
      
      		-- Instagram publishing: a container, then its publication.
      		respond('{"id":"17890000000000009"}')
      		local container = meta.createInstagramContainer({ig_user = "17841400000000001", image_url = "https://example.com/bread.jpg", caption = "Fresh #bread"})
      		body = json.decode(sent(5, "POST", "https://graph.facebook.com/v26.0/17841400000000001/media").body)
      		assert(body.image_url == "https://example.com/bread.jpg" and body.caption == "Fresh #bread" and body.ig_user == nil)
      		respond('{"id":"17900000000000010"}')
      		meta.publishInstagramMedia({ig_user = "17841400000000001", creation_id = container.id})
      		assert(json.decode(sent(6, "POST", "https://graph.facebook.com/v26.0/17841400000000001/media_publish").body).creation_id == "17890000000000009")
      		respond('{"id":"17870000000000011"}')
      		meta.createInstagramReply({comment = "17860000000000001", message = "Thank you!"})
      		assert(json.decode(sent(7, "POST", "https://graph.facebook.com/v26.0/17860000000000001/replies").body).message == "Thank you!")
      		respond('{"success":true}')
      		meta.updateInstagramMedia({media = "17900000000000010", comment_enabled = false})
      		assert(json.decode(sent(8, "POST", "https://graph.facebook.com/v26.0/17900000000000010").body).comment_enabled == false)
      
      		-- A public URL is sent as JSON; a session file streams as multipart with the other fields.
      		respond('{"id":"201","post_id":"101_10"}')
      		meta.uploadPhoto({url = "https://example.com/bread.jpg", caption = "Bread", published = false})
      		body = json.decode(sent(9, "POST", "https://graph.facebook.com/v26.0/me/photos").body)
      		assert(body.url == "https://example.com/bread.jpg" and body.published == false)
      		local bytes = string.char(255, 216, 255, 0) .. "jpeg bytes"
      		local file = fs.open("photos/bread.jpg", "w")
      		file:write(bytes)
      		await(file:close())
      		respond('{"id":"202","post_id":"101_11"}')
      		assert(meta.uploadPhoto({path = "photos/bread.jpg", caption = "Bread", published = false, scheduled_publish_time = 1760003600}).id == "202")
      		req = sent(10, "POST", "https://graph.facebook.com/v26.0/me/photos")
      		assert(string.find(req.headers["Content-Type"][1], "multipart/form-data", 1, true))
      		for _, part in {'name="source"; filename="bread.jpg"\r\nContent-Type: application/octet-stream', bytes, 'name="caption"\r\n\r\nBread', 'name="published"\r\n\r\nfalse',
      			'name="scheduled_publish_time"\r\n\r\n1760003600'} do
      			assert(string.find(req.body, part, 1, true), "missing multipart field " .. part)
      		end
      		assert(not string.find(req.body, 'name="path"', 1, true))
      		respond('{"id":"301"}')
      		meta.uploadVideo({path = "photos/bread.jpg", title = "Baking", description = "How we bake"})
      		req = sent(11, "POST", "https://graph-video.facebook.com/v26.0/me/videos")
      		assert(string.find(req.body, 'name="title"\r\n\r\nBaking', 1, true) and string.find(req.body, bytes, 1, true))
      		respond('{"id":"302"}')
      		meta.uploadVideo({file_url = "https://example.com/baking.mp4"})
      		assert(json.decode(sent(12, "POST", "https://graph-video.facebook.com/v26.0/me/videos").body).file_url == "https://example.com/baking.mp4")
      
      		-- Instagram private replies go through the account.
      		respond('{"recipient_id":"17840000000000002","message_id":"aWdGMTIz"}')
      		meta.sendInstagramPrivateReply({ig_user = "17841400000000001", recipient = {comment_id = "17860000000000001"}, message = {text = "Sent you the details"}})
      		assert(sent(13, "POST", "https://graph.facebook.com/v26.0/17841400000000001/messages").body
      			== json.encode({recipient = {comment_id = "17860000000000001"}, message = {text = "Sent you the details"}}))
      		respond('{"data":[{"quota_usage":2,"config":{"quota_total":50,"quota_duration":86400}}]}')
      		assert(meta.getInstagramPublishingLimit({ig_user = "17841400000000001"}).data[1].config.quota_total == 50)
      		sent(14, "GET", "https://graph.facebook.com/v26.0/17841400000000001/content_publishing_limit?fields=config%2Cquota_usage")
      
      		-- Graph reads method, batch and fields from bodies too: batch could fetch a token and
      		-- fields reads the written object back, its access_token included.
      		rejected(function() meta.updatePost({post = "101_9", message = "x", method = "delete"}) end, "cannot send method")
      		rejected(function() meta.createPost({message = "x", batch = "[]"}) end, "cannot send batch")
      		rejected(function() meta.updatePost({post = "101_9", message = "x", fields = "access_token"}) end, "cannot send fields")
      		-- Node updates take their own fields only, so they cannot change the Page itself.
      		rejected(function() meta.updatePost({post = "101_9", about = "x"}) end, "updatePost cannot send about")
      		for _, page in {"me", "101"} do
      			rejected(function() meta.updatePost({post = page, is_published = false}) end, "post must be a post ID")
      		end
      		rejected(function() meta.updateComment({comment = "101", website = "https://x.test"}) end, "updateComment cannot send website")
      		rejected(function() meta.updateInstagramMedia({media = "101", comment_enabled = true, phone = "1"}) end, "updateInstagramMedia cannot send phone")
      		rejected(function() meta.createComment({object = "101_9", message = "x", access_token = "EAAOTHER"}) end, "cannot send access_token")
      		rejected(function() meta.uploadPhoto({path = "photos/bread.jpg", callback = "f"}) end, "cannot send callback")
      		rejected(function() meta.uploadPhoto({path = "photos/bread.jpg", caption = json.decode("null")}) end, "cannot send null")
      		-- PHP-style parsers trim names, map . and spaces to _ and read name[] as arrays.
      		for _, key in {" method", "Method", "fields[]", "batch[0]", "suppress.http.code", "access token", "method "} do
      			rejected(function() meta.createPost({message = "x", [key] = "delete"}) end, "cannot send")
      			rejected(function() meta.uploadPhoto({path = "photos/bread.jpg", [key] = "get"}) end, "cannot send")
      		end
      		rejected(function() meta.deleteObject({id = "101_9", method = "get"}) end, "has no option method")
      		rejected(function() meta.createComment({object = "101_9", message = "hi", next = "https://graph.facebook.com/v26.0/101_9/comments?after=x"}) end, "cannot send next")
      		rejected(function() meta.sendMessage({message = {text = "hi"}}) end, "recipient is required")
      		rejected(function() meta.publishInstagramMedia({ig_user = "17841400000000001"}) end, "creation_id is required")
      		rejected(function() meta.deleteObject({id = "101/feed"}) end, "one Meta ID")
      		rejected(function() meta.uploadPhoto({path = "missing.jpg"}) end, '"code":"not_found"')
      		rejected(function() meta.uploadPhoto({path = "photos"}) end, "path must be a session file")
      		for _, key in {"source", "url", "file_url"} do
      			rejected(function() meta.uploadVideo({path = "photos/bread.jpg", [key] = "https://example.com/x"}) end, "path cannot be combined with " .. key)
      		end
      		assert(#responses == 0)
      	end,
      }