All connectors

Dropbox

OfficialFiles

Dropbox

Search and read files, download folders, and manage sharing and file requests. Choose Write for Files to upload and organize files, or turn on Limit to folders to restrict file access to the folders you list.

Connect by signing in to Dropbox using the shared app.

Setup instructions

Connect Dropbox

Choose None, Read or Write for Files, Sharing and File requests, then authorize your Dropbox account. No app setup is needed for the standard sign-in.

Advanced

Folder permissions

Limit to folders applies to existing folders, with Read or Write for Files. Give each folder read-only or read-write; read-write folders also need Write for Files. Unlisted folders are denied, and the most specific rule wins. Houston enforces these limits; Dropbox itself grants broader app permissions. Sharing, file requests and batch operations are unavailable in this mode. Restart any ongoing file listing after changing permissions.

Limits and reconnecting

Uploads support files up to 150 MiB. Full team-space traversal is not supported. Raising an access level requires signing in again. Remove access anytime in Dropbox connected apps.

Files

  • connector.luau
    -- Dropbox API v2. Arguments and results keep Dropbox's native field names.
    type Options = {[string]: any}
    type Endpoint = {route: string, scope: string, access: string?, required: {[string]: string}?, style: ("download" | "upload")?, void: boolean?, emptyResult: boolean?, help: string, inputSchema: Options}
    local API = "https://api.dropboxapi.com/2/"
    local CONTENT = "https://content.dropboxapi.com/2/"
    local MAX_SAFE_INTEGER = 9007199254740991
    local MAX_UPLOAD_BYTES = 150 * 1024 * 1024 -- Dropbox's limit for one upload request.
    
    local function text(value: any, field: string): string
    	assert(type(value) == "string" and value ~= "", field .. " must be a nonempty string")
    	return value
    end
    
    local function options(endpoint: Endpoint, value: any): Options
    	if value == nil then value = {} end
    	assert(type(value) == "table", "opts must be an object")
    	for key in value do assert(type(key) == "string", "opts must have named fields") end
    	if endpoint.void then assert(next(value) == nil, "this operation takes no options") end
    	if endpoint.required then
    		for field, kind in endpoint.required do
    			local actual = type(value[field])
    			local valid = if kind == "union" then actual == "string" or actual == "table"
    				elseif kind == "array" or kind == "struct" then actual == "table" else actual == kind
    			assert(valid, field .. " must be a " .. kind)
    		end
    	end
    	return table.clone(value)
    end
    
    -- Dropbox-API-Arg must be HTTP header safe: escape DEL and every non-ASCII character.
    local function headerJSON(value: Options): string
    	return (string.gsub(json.encode(value), "[\127-\244][\128-\191]*", function(char: string): string
    		local code = utf8.codepoint(char)
    		if code < 0x10000 then return string.format("\\u%04x", code) end
    		code -= 0x10000
    		return string.format("\\u%04x\\u%04x", 0xD800 + code // 0x400, 0xDC00 + code % 0x400)
    	end))
    end
    
    local function fail(operation: string, response: HttpResponse): never
    	local raw = await(response.body:readPrefix(4096))
    	-- Route errors are JSON with an error_summary such as "path/not_found/.."; bad input is plain text.
    	local ok, decoded = pcall(json.decode, raw)
    	local problem = if ok and type(decoded) == "table" then decoded else {}
    	local summary = if type(problem.error_summary) == "string" then problem.error_summary else raw
    	local message = "Dropbox HTTP " .. tostring(response.statusCode)
    	if summary ~= "" then message ..= ": " .. string.sub(summary, 1, 600) end
    	local user = problem.user_message
    	if type(user) == "table" and type(user.text) == "string" then message ..= " (" .. string.sub(user.text, 1, 300) .. ")" end
    	local retry = response.headers["retry-after"]
    	if retry and retry[1] then message ..= "; Retry-After: " .. retry[1] end
    	-- Dropbox asks callers to retry when concurrent writes to one namespace collide.
    	local contended = string.find(summary, "too_many_write_operations", 1, true) ~= nil
    	return houston.fail({operation = operation, layer = "upstream", upstream_status = response.statusCode,
    		retryable = response.statusCode == 429 or response.statusCode >= 500 or contended, message = message})
    end
    
    local function invalid(operation: string, response: HttpResponse, message: string): never
    	return houston.fail({operation = operation, layer = "upstream", upstream_status = response.statusCode, retryable = false, message = message})
    end
    
    -- Returns the JSON object or array Dropbox sent, or {success=true} for routes whose result is null.
    local function decode(operation: string, endpoint: Endpoint, response: HttpResponse): any
    	if response.statusCode < 200 or response.statusCode >= 300 then fail(operation, response) end
    	local raw = await(response.body:readAll())
    	if endpoint.emptyResult and string.match(raw, "^%s*null%s*$") then return {success = true} end
    	local ok, value = pcall(json.decode, raw)
    	if not ok or type(value) ~= "table" then invalid(operation, response, "Dropbox returned invalid JSON") end
    	return value
    end
    
    local function rpc(name: string, endpoint: Endpoint, input: any): any
    	local args = options(endpoint, input)
    	return decode(name, endpoint, await(http.request({method = "POST", url = API .. endpoint.route,
    		headers = if endpoint.void then nil else {["Content-Type"] = {"application/json"}},
    		body = if endpoint.void then nil else json.encode(args)})))
    end
    
    -- Content routes take a session file path beside Dropbox's argument, which travels in a header.
    local function content(endpoint: Endpoint, input: any, headers: HttpHeaders): (HttpRequest, string)
    	local args = options(endpoint, input)
    	local path = text(args.session_path, "session_path")
    	args.session_path = nil
    	headers["Dropbox-API-Arg"] = {headerJSON(args)}
    	return {method = "POST", url = CONTENT .. endpoint.route, headers = headers}, path
    end
    
    -- Discards the destination, keeping any previous file, and waits until the path can be opened again.
    local function discard(output: any)
    	output:cancel()
    	pcall(function() await(output:close()) end)
    end
    
    -- Streams the response body to a session file; Dropbox describes it in the Dropbox-API-Result header.
    local function download(name: string, endpoint: Endpoint, input: any, guard: ((any) -> any)?): Options
    	local request, path = content(endpoint, input, {})
    	-- Opening the session file first refuses an invalid path before any Dropbox request.
    	local output = fs.open(path, "w")
    	local opened, response = pcall(function(): HttpResponse
    		await(output)
    		return await(http.request(request))
    	end)
    	if not opened then
    		discard(output)
    		error(response, 0)
    	end
    	if response.statusCode < 200 or response.statusCode >= 300 then
    		discard(output)
    		fail(name, response)
    	end
    	local header = response.headers["dropbox-api-result"]
    	local ok, result = pcall(json.decode, if header and header[1] then header[1] else "")
    	if not ok or type(result) ~= "table" then
    		response.body:close()
    		discard(output)
    		invalid(name, response, "Dropbox returned no Dropbox-API-Result metadata")
    	end
    	if guard then
    		local allowed, problem = pcall(guard, result)
    		if not allowed then
    			response.body:close()
    			discard(output)
    			error(problem, 0)
    		end
    	end
    	output:write(response.body)
    	await(output:close())
    	return {session_path = path, url = await(fs.signedGetUrl(path)), size = await(fs.stat(path)).size, result = result}
    end
    
    local function upload(name: string, endpoint: Endpoint, input: any): any
    	local request, path = content(endpoint, input, {["Content-Type"] = {"application/octet-stream"}})
    	local file = await(fs.stat(path))
    	assert(file.isFile, "session_path must be a file")
    	assert(file.size <= MAX_UPLOAD_BYTES, "upload sends at most 150 MiB; larger files are not supported")
    	request.body = fs.open(path, "r")
    	return decode(name, endpoint, await(http.request(request)))
    end
    
    -- Shared JSON Schema shapes. Dropbox unions accept a tag string when the variant has no payload.
    local STRING = {type = "string"}
    local NONEMPTY = {type = "string", minLength = 1}
    local FALSE = {type = "boolean", default = false}
    local TRUE = {type = "boolean", default = true}
    local PATH = {type = "string", description = "Dropbox path or supported id:/rev:/ns: identifier; see paths."}
    local ROOT_PATH = {type = "string", description = "Folder path or ID; use an empty string for the root. See paths."}
    local SESSION_PATH = {type = "string", minLength = 1, description = "Relative Houston session file path; see transfers."}
    local REV = {type = "string", pattern = "^[0-9a-f]+$", description = "Dropbox revision from file metadata."}
    local TIMESTAMP = {type = "string", format = "date-time", description = "UTC timestamp, for example 2026-01-15T12:00:00Z."}
    local CURSOR_SCHEMA = {type = "string", minLength = 1, description = "Opaque cursor from the preceding page; keep it intact. See pagination."}
    local function object(properties: Options, required: {string}?): Options
    	return {type = "object", properties = properties, required = required or json.decode("[]"), additionalProperties = true}
    end
    local function list(items: Options, minimum: number?, maximum: number?): Options
    	return {type = "array", items = items, minItems = minimum, maxItems = maximum}
    end
    local function limit(maximum: number, default: number?): Options
    	return {type = "integer", minimum = 1, maximum = maximum, default = default}
    end
    local function tags(values: {string}, default: string?): Options
    	return {oneOf = {{type = "string", enum = values}, object({[".tag"] = {type = "string", enum = values}}, {".tag"})}, default = default}
    end
    local function variant(tag: string, fields: Options, required: {string}?): Options
    	local properties = table.clone(fields)
    	properties[".tag"] = {const = tag}
    	local keys = table.clone(required or {})
    	table.insert(keys, ".tag")
    	return object(properties, keys)
    end
    local MEMBER = {oneOf = {
    	variant("email", {email = {type = "string", format = "email"}}, {"email"}),
    	variant("dropbox_id", {dropbox_id = NONEMPTY}, {"dropbox_id"}),
    }}
    local ACCESS = tags({"editor", "viewer", "viewer_no_comment"})
    local AUDIENCE = tags({"public", "team", "no_one"})
    local LINK_SETTINGS = object({require_password = {type = "boolean"}, link_password = STRING, expires = TIMESTAMP,
    	audience = AUDIENCE, access = tags({"viewer", "editor", "max"}),
    	requested_visibility = tags({"public", "team_only", "password"}), allow_download = {type = "boolean"}})
    local DEADLINE = object({deadline = TIMESTAMP, allow_late_uploads = tags({"one_day", "two_days", "seven_days", "thirty_days", "always"})}, {"deadline"})
    local PROPERTY_FILTER = variant("filter_some", {filter_some = list(NONEMPTY, 1)}, {"filter_some"})
    local PROPERTY_GROUPS = list(object({template_id = NONEMPTY,
    	fields = list(object({name = STRING, value = STRING}, {"name", "value"}))}, {"template_id", "fields"}))
    local FILE_ACTIONS = list(tags({"disable_viewer_info", "edit_contents", "enable_viewer_info", "invite_viewer", "invite_viewer_no_comment", "invite_editor", "unshare", "relinquish_membership", "share_link", "create_link", "create_view_link", "create_edit_link"}))
    local FOLDER_ACTIONS = list(tags({"change_options", "disable_viewer_info", "edit_contents", "enable_viewer_info", "invite_editor", "invite_viewer", "invite_viewer_no_comment", "relinquish_membership", "unmount", "unshare", "leave_a_copy", "share_link", "create_link", "create_view_link", "create_edit_link", "set_access_inheritance"}))
    local MEMBER_ACTIONS = list(tags({"leave_a_copy", "make_editor", "make_owner", "make_viewer", "make_viewer_no_comment", "remove"}))
    local RELOCATION = object({from_path = PATH, to_path = PATH}, {"from_path", "to_path"})
    local SEARCH_OPTIONS = object({path = ROOT_PATH, max_results = limit(1000, 100), order_by = tags({"relevance", "last_modified_time"}),
    	file_status = tags({"active", "deleted"}, "active"), filename_only = FALSE, file_extensions = list(STRING),
    	file_categories = list(tags({"image", "document", "pdf", "spreadsheet", "presentation", "audio", "video", "folder", "paper", "others"})), account_id = NONEMPTY})
    local FOLDER_OPTIONS = {path = ROOT_PATH, recursive = FALSE, include_media_info = FALSE, include_deleted = FALSE,
    	include_has_explicit_shared_members = FALSE, include_mounted_folders = TRUE, limit = limit(2000),
    	shared_link = object({url = NONEMPTY, password = STRING}, {"url"}), include_property_groups = PROPERTY_FILTER,
    	include_non_downloadable_files = TRUE, include_restorable_info = FALSE}
    local function schema(properties: Options, example: Options): Options
    	local result = object(properties)
    	result.examples = {example}
    	return result
    end
    
    local ENTRIES = " complete.entries holds one result per entry."
    local function job(starters: string, tags: string?): string
    	return "Returns {['.tag']=" .. (tags or "'in_progress'|'complete'|'failed'") .. ", ...}. Polls " .. starters .. "."
    end
    local endpoints: {[string]: Endpoint} = {
    	-- Account
    	getCurrentAccount = {inputSchema = schema({}, {}),
    		route = "users/get_current_account", scope = "account_info.read", void = true,
    		help = "Returns {account_id, name, email, root_info, ...}. root_info identifies the account's home and root namespaces."},
    	getSpaceUsage = {inputSchema = schema({}, {}),
    		route = "users/get_space_usage", scope = "account_info.read", void = true, help = "Returns {used, allocation}. Bytes used and the quota."},
    	getAccount = {inputSchema = schema({account_id = NONEMPTY}, {account_id = "dbid:AAH4f99T0taONIb-OurWxbNQ6ywGRopQngc"}),
    		route = "users/get_account", scope = "sharing.read", required = {account_id = "string"}, access = "sharing:read", help = "Returns {account_id, name, email, ...}. Another Dropbox user, e.g. a folder member."},
    
    	-- Files and folders
    	getMetadata = {inputSchema = schema({path = PATH, include_media_info = FALSE, include_deleted = FALSE, include_has_explicit_shared_members = FALSE, include_property_groups = PROPERTY_FILTER}, {path = "/Reports/report.pdf"}),
    		route = "files/get_metadata", scope = "files.metadata.read", required = {path = "string"}, access = "files:read",
    		help = "Returns file, folder or deleted metadata; ['.tag'] tells which."},
    	listFolder = {inputSchema = schema(FOLDER_OPTIONS, {path = "/Reports", recursive = false, limit = 100}),
    		route = "files/list_folder", scope = "files.metadata.read", required = {path = "string"}, access = "files:read",
    		help = "List one page of files and folders. Returns {entries, cursor, has_more}; entries use ['.tag']='file'|'folder'|'deleted'. Continue with listFolderContinue while has_more is true. path='' is the root. limit is a hint up to 2000; recursive traversal can be expensive. include_media_info is deprecated and has no effect on listing."},
    	listFolderContinue = {inputSchema = schema({cursor = CURSOR_SCHEMA}, {cursor = "cursor-from-previous-page"}),
    		route = "files/list_folder/continue", scope = "files.metadata.read", required = {cursor = "string"}, access = "files:read", help = "Returns {entries, cursor, has_more}. Continues listFolder, or returns changes after listFolderGetLatestCursor; save the latest cursor and continue while has_more is true."},
    	listFolderGetLatestCursor = {inputSchema = schema(FOLDER_OPTIONS, {path = "/Reports", recursive = false, limit = 100}),
    		route = "files/list_folder/get_latest_cursor", scope = "files.metadata.read", required = {path = "string"}, access = "files:read",
    		help = "Returns {cursor}. A cursor at the current state; listFolderContinue on it later returns only changes."},
    	search = {inputSchema = schema({query = {type = "string", maxLength = 1000}, options = SEARCH_OPTIONS, match_field_options = object({include_highlights = FALSE}), include_highlights = {type = "boolean"}}, {query = "report", options = {path = "/Reports", max_results = 20}}),
    		route = "files/search_v2", scope = "files.metadata.read", required = {query = "string"}, access = "files:read",
    		help = "Returns {matches, has_more, cursor?}. Matches names and content; matches[i].metadata.metadata is the file."},
    	searchContinue = {inputSchema = schema({cursor = CURSOR_SCHEMA}, {cursor = "cursor-from-previous-page"}),
    		route = "files/search/continue_v2", scope = "files.metadata.read", required = {cursor = "string"}, access = "files:read", help = "Returns {matches, has_more, cursor?}. Continues search using its opaque cursor; matches[i].metadata.metadata contains the file. Up to 10,000 matches across pages; indexing can lag and results may repeat or be omitted."},
    	listRevisions = {inputSchema = schema({path = PATH, mode = tags({"path", "id"}, "path"), limit = limit(100, 10), before_rev = REV, include_restorable_info = FALSE}, {path = "/Reports/report.pdf", limit = 10}),
    		route = "files/list_revisions", scope = "files.metadata.read", required = {path = "string"}, access = "files:read", help = "Returns {is_deleted, entries, has_more}. A file's versions, newest first; pass the last entry's rev as before_rev for older ones."},
    	getTemporaryLink = {inputSchema = schema({path = PATH}, {path = "/Reports/report.pdf"}),
    		route = "files/get_temporary_link", scope = "files.content.read", required = {path = "string"}, access = "files:read",
    		help = "Returns {metadata, link}. A direct download link valid for four hours, to hand to a person or an outside client; Houston scripts transfer files with download."},
    	download = {inputSchema = schema({path = PATH, rev = REV, session_path = SESSION_PATH}, {path = "/Reports/report.pdf", session_path = "downloads/report.pdf"}),
    		route = "files/download", scope = "files.content.read", required = {path = "string"}, access = "files:read", style = "download", help = "Returns {session_path, url, size, result=file metadata}."},
    	downloadZip = {inputSchema = schema({path = PATH, session_path = SESSION_PATH}, {path = "/Reports", session_path = "downloads/reports.zip"}),
    		route = "files/download_zip", scope = "files.content.read", required = {path = "string"}, access = "files:read", style = "download",
    		help = "Returns {session_path, url, size, result={metadata}}. A folder as a zip: Dropbox requires under 20 GB total, under 4 GB per file and fewer than 10,000 files/folders including the root. Houston's smaller transfer limit still applies."},
    	export = {inputSchema = schema({path = PATH, export_format = STRING, session_path = SESSION_PATH}, {path = "/Reports/Notes.paper", export_format = "markdown", session_path = "downloads/notes.md"}),
    		route = "files/export", scope = "files.content.read", required = {path = "string"}, access = "files:read", style = "download",
    		help = "Returns {session_path, url, size, result={export_metadata, file_metadata}}. Converts files that have no downloadable bytes, such as Paper docs: their metadata has export_info.export_as, and export_info.export_options lists other export_format values."},
    	getPreview = {inputSchema = schema({path = PATH, rev = REV, session_path = SESSION_PATH}, {path = "/Reports/report.pdf", session_path = "downloads/report.pdf"}),
    		route = "files/get_preview", scope = "files.content.read", required = {path = "string"}, access = "files:read", style = "download",
    		help = "Returns {session_path, url, size, result=file metadata}. A PDF preview of documents or an HTML preview of spreadsheets."},
    	getThumbnail = {inputSchema = schema({path = PATH, format = tags({"jpeg", "png", "webp"}, "jpeg"), size = tags({"w32h32", "w64h64", "w128h128", "w256h256", "w480h320", "w640h480", "w960h640", "w1024h768", "w2048h1536"}, "w64h64"), mode = tags({"strict", "bestfit", "fitone_bestfit"}, "strict"), exclude_media_info = {type = "boolean"}, session_path = SESSION_PATH}, {path = "/Reports/photo.jpg", format = "png", size = "w256h256", session_path = "downloads/thumbnail.png"}),
    		route = "files/get_thumbnail", scope = "files.content.read", required = {path = "string"}, access = "files:read", style = "download",
    		help = "Returns {session_path, url, size, result=file metadata}. Images only; defaults to a 64x64 JPEG."},
    	createFolder = {inputSchema = schema({path = PATH, autorename = FALSE}, {path = "/Reports/New folder"}),
    		route = "files/create_folder_v2", scope = "files.content.write", required = {path = "string"}, access = "files:write", help = "Create one folder. Returns {metadata} with its name, ID and canonical paths. Existing destinations fail unless autorename=true is available and requested; inspect the returned path."},
    	upload = {inputSchema = schema({path = PATH, session_path = SESSION_PATH, mode = {oneOf = {tags({"add", "overwrite"}), variant("update", {update = REV}, {"update"})}, default = "add"}, autorename = FALSE, client_modified = TIMESTAMP, mute = FALSE, property_groups = PROPERTY_GROUPS, strict_conflict = FALSE, content_hash = {type = "string", pattern = "^[0-9a-f]{64}$"}}, {path = "/Reports/upload.txt", session_path = "upload.txt", mode = "add"}),
    		route = "files/upload", scope = "files.content.write", required = {path = "string"}, access = "files:write", style = "upload",
    		help = "Upload an existing session file. Returns file metadata including id, name, size, rev and canonical paths. Sends at most 150 MiB. mode defaults to add; overwrite replaces the destination, while update requires its revision. autorename resolves conflicts with a different name; inspect the returned path. mute suppresses client notifications; strict_conflict rejects revision mismatches even for deleted or identical files. content_hash uses Dropbox's block hash algorithm, not an ordinary whole-file SHA-256."},
    	saveUrl = {inputSchema = schema({path = PATH, url = {type = "string", format = "uri"}}, {path = "/Reports/report.pdf", url = "https://example.com/report.pdf"}),
    		route = "files/save_url", scope = "files.content.write", required = {path = "string", url = "string"}, access = "files:write",
    		help = "Returns {['.tag']='async_job_id'|'complete', ...}. Dropbox downloads a public URL into path within 15 minutes; poll saveUrlCheckJobStatus."},
    	saveUrlCheckJobStatus = {inputSchema = schema({async_job_id = NONEMPTY}, {async_job_id = "job-from-start-operation"}),
    		route = "files/save_url/check_job_status", scope = "files.content.write", required = {async_job_id = "string"}, access = "files:write", help = job("saveUrl")},
    	move = {inputSchema = schema({from_path = PATH, to_path = PATH, autorename = FALSE, allow_shared_folder = FALSE, allow_ownership_transfer = FALSE}, {from_path = "/Reports/report.pdf", to_path = "/Reports/renamed.pdf"}),
    		route = "files/move_v2", scope = "files.content.write", required = {from_path = "string", to_path = "string"}, access = "files:write", help = "Returns {metadata}. Moves or renames a file or folder."},
    	copy = {inputSchema = schema({from_path = PATH, to_path = PATH, autorename = FALSE, allow_shared_folder = FALSE, allow_ownership_transfer = FALSE}, {from_path = "/Reports/report.pdf", to_path = "/Reports/renamed.pdf"}),
    		route = "files/copy_v2", scope = "files.content.write", required = {from_path = "string", to_path = "string"}, access = "files:write", help = "Returns {metadata}."},
    	delete = {inputSchema = schema({path = PATH, parent_rev = REV}, {path = "/Reports/old.pdf"}),
    		route = "files/delete_v2", scope = "files.content.write", required = {path = "string"}, access = "files:write",
    		help = "Returns {metadata}. Deleted files stay recoverable with restore for the account's retention period."},
    	restore = {inputSchema = schema({path = PATH, rev = REV}, {path = "/Reports/report.pdf", rev = "a1c10ce0dd78"}),
    		route = "files/restore", scope = "files.content.write", required = {path = "string", rev = "string"}, access = "files:write", help = "Returns file metadata. Restores a deleted file or an earlier revision from listRevisions."},
    	moveBatch = {inputSchema = schema({entries = list(RELOCATION, 1, 1000), autorename = FALSE, allow_ownership_transfer = FALSE}, {entries = {{from_path = "/Reports/report.pdf", to_path = "/Archive/report.pdf"}}}),
    		route = "files/move_batch_v2", scope = "files.content.write", required = {entries = "array"}, access = "files:write",
    		help = "Returns {['.tag']='async_job_id'|'complete', ...}. Up to 1,000 entries; poll moveBatchCheck."},
    	moveBatchCheck = {inputSchema = schema({async_job_id = NONEMPTY}, {async_job_id = "job-from-start-operation"}),
    		route = "files/move_batch/check_v2", scope = "files.content.write", required = {async_job_id = "string"}, access = "files:write", help = job("moveBatch", "'in_progress'|'complete'") .. ENTRIES},
    	copyBatch = {inputSchema = schema({entries = list(RELOCATION, 1, 1000), autorename = FALSE}, {entries = {{from_path = "/Reports/report.pdf", to_path = "/Archive/report.pdf"}}}),
    		route = "files/copy_batch_v2", scope = "files.content.write", required = {entries = "array"}, access = "files:write",
    		help = "Returns {['.tag']='async_job_id'|'complete', ...}. Up to 1,000 entries; poll copyBatchCheck."},
    	copyBatchCheck = {inputSchema = schema({async_job_id = NONEMPTY}, {async_job_id = "job-from-start-operation"}),
    		route = "files/copy_batch/check_v2", scope = "files.content.write", required = {async_job_id = "string"}, access = "files:write", help = job("copyBatch", "'in_progress'|'complete'") .. ENTRIES},
    	deleteBatch = {inputSchema = schema({entries = list(object({path = PATH, parent_rev = REV}, {"path"}), 0, 1000)}, {entries = {{path = "/Reports/old.pdf"}}}),
    		route = "files/delete_batch", scope = "files.content.write", required = {entries = "array"}, access = "files:write",
    		help = "Returns {['.tag']='async_job_id'|'complete', ...}. Up to 1,000 entries; poll deleteBatchCheck."},
    	deleteBatchCheck = {inputSchema = schema({async_job_id = NONEMPTY}, {async_job_id = "job-from-start-operation"}),
    		route = "files/delete_batch/check", scope = "files.content.write", required = {async_job_id = "string"}, access = "files:write", help = job("deleteBatch") .. ENTRIES},
    
    	-- Shared links
    	listSharedLinks = {inputSchema = schema({path = PATH, cursor = CURSOR_SCHEMA, direct_only = {type = "boolean"}}, {path = "/Reports/report.pdf", direct_only = true}),
    		route = "sharing/list_shared_links", scope = "sharing.read", access = "sharing:read",
    		help = "Returns {links, has_more, cursor?}. Without path, every link the account created; pass cursor back for the next page."},
    	getSharedLinkMetadata = {inputSchema = schema({url = NONEMPTY, path = STRING, link_password = STRING}, {url = "https://www.dropbox.com/s/example/report.pdf?dl=0"}),
    		route = "sharing/get_shared_link_metadata", scope = "sharing.read", required = {url = "string"}, access = "sharing:read", help = "Returns link metadata. path selects an item inside a shared folder link."},
    	getSharedLinkFile = {inputSchema = schema({url = NONEMPTY, path = STRING, link_password = STRING, session_path = SESSION_PATH}, {url = "https://www.dropbox.com/s/example/report.pdf?dl=0", session_path = "downloads/shared.pdf"}),
    		route = "sharing/get_shared_link_file", scope = "sharing.read", required = {url = "string"}, access = "sharing:read", style = "download",
    		help = "Returns {session_path, url, size, result=link metadata}. Downloads a file behind a shared link, including links from other accounts."},
    	createSharedLinkWithSettings = {inputSchema = schema({path = PATH, settings = LINK_SETTINGS}, {path = "/Reports/report.pdf", settings = {audience = "public", access = "viewer"}}),
    		route = "sharing/create_shared_link_with_settings", scope = "sharing.write", required = {path = "string"}, access = "sharing:write",
    		help = "Returns link metadata. Fails with shared_link_already_exists when a link exists; use listSharedLinks({path, direct_only=true})."},
    	modifySharedLinkSettings = {inputSchema = schema({url = NONEMPTY, settings = LINK_SETTINGS, remove_expiration = FALSE}, {url = "https://www.dropbox.com/s/example/report.pdf?dl=0", settings = {allow_download = false}}),
    		route = "sharing/modify_shared_link_settings", scope = "sharing.write", required = {url = "string", settings = "struct"}, access = "sharing:write", help = "Returns link metadata."},
    	revokeSharedLink = {inputSchema = schema({url = NONEMPTY}, {url = "https://www.dropbox.com/s/example/report.pdf?dl=0"}),
    		route = "sharing/revoke_shared_link", scope = "sharing.write", required = {url = "string"}, access = "sharing:write", emptyResult = true, help = "Returns {success=true}."},
    
    	-- Shared folders
    	listSharedFolders = {inputSchema = schema({limit = limit(1000, 1000), actions = FOLDER_ACTIONS}, {limit = 100}),
    		route = "sharing/list_folders", scope = "sharing.read", access = "sharing:read", help = "Returns {entries, cursor?}. Shared folders the account has joined."},
    	listSharedFoldersContinue = {inputSchema = schema({cursor = CURSOR_SCHEMA}, {cursor = "cursor-from-previous-page"}),
    		route = "sharing/list_folders/continue", scope = "sharing.read", required = {cursor = "string"}, access = "sharing:read", help = "Returns {entries, cursor?}. Continues listSharedFolders while a cursor is present."},
    	listMountableFolders = {inputSchema = schema({limit = limit(1000, 1000), actions = FOLDER_ACTIONS}, {limit = 100}),
    		route = "sharing/list_mountable_folders", scope = "sharing.read", access = "sharing:read", help = "Returns {entries, cursor?}. Shared folders the account can add to its Dropbox."},
    	listMountableFoldersContinue = {inputSchema = schema({cursor = CURSOR_SCHEMA}, {cursor = "cursor-from-previous-page"}),
    		route = "sharing/list_mountable_folders/continue", scope = "sharing.read", required = {cursor = "string"}, access = "sharing:read", help = "Returns {entries, cursor?}. Continues listMountableFolders while a cursor is present."},
    	getSharedFolderMetadata = {inputSchema = schema({shared_folder_id = NONEMPTY, actions = FOLDER_ACTIONS}, {shared_folder_id = "84528192421"}),
    		route = "sharing/get_folder_metadata", scope = "sharing.read", required = {shared_folder_id = "string"}, access = "sharing:read",
    		help = "Returns shared folder metadata. The ID is a folder's shared_folder_id or sharing_info.shared_folder_id."},
    	listFolderMembers = {inputSchema = schema({shared_folder_id = NONEMPTY, path = STRING, actions = MEMBER_ACTIONS, limit = limit(1000, 1000)}, {shared_folder_id = "84528192421", limit = 100}),
    		route = "sharing/list_folder_members", scope = "sharing.read", required = {shared_folder_id = "string"}, access = "sharing:read", help = "Returns {users, groups, invitees, cursor?}."},
    	listFolderMembersContinue = {inputSchema = schema({cursor = CURSOR_SCHEMA}, {cursor = "cursor-from-previous-page"}),
    		route = "sharing/list_folder_members/continue", scope = "sharing.read", required = {cursor = "string"}, access = "sharing:read", help = "Returns {users, groups, invitees, cursor?}. Continues listFolderMembers while a cursor is present."},
    	shareFolder = {inputSchema = schema({path = PATH, member_policy = tags({"team", "anyone"}), acl_update_policy = tags({"owner", "editors"}), shared_link_policy = tags({"anyone", "members"}), force_async = FALSE, viewer_info_policy = tags({"enabled", "disabled"}), access_inheritance = tags({"inherit", "no_inherit"}, "inherit"), actions = FOLDER_ACTIONS, link_settings = object({access_level = tags({"viewer", "viewer_no_comment"}), audience = AUDIENCE, expiry = {oneOf = {tags({"remove_expiry"}), variant("set_expiry", {set_expiry = TIMESTAMP}, {"set_expiry"})}}, password = {oneOf = {tags({"remove_password"}), variant("set_password", {set_password = STRING}, {"set_password"})}}})}, {path = "/Reports", force_async = true}),
    		route = "sharing/share_folder", scope = "sharing.write", required = {path = "string"}, access = "sharing:write",
    		help = "Returns {['.tag']='complete', ...} or {['.tag']='async_job_id', ...}; poll checkShareJobStatus."},
    	checkShareJobStatus = {inputSchema = schema({async_job_id = NONEMPTY}, {async_job_id = "job-from-start-operation"}),
    		route = "sharing/check_share_job_status", scope = "sharing.write", required = {async_job_id = "string"}, access = "sharing:write", help = job("shareFolder")},
    	addFolderMember = {inputSchema = schema({shared_folder_id = NONEMPTY, members = list(object({member = MEMBER, access_level = ACCESS}, {"member"})), quiet = FALSE, custom_message = NONEMPTY}, {shared_folder_id = "84528192421", members = {{member = {[".tag"] = "email", email = "[email protected]"}, access_level = "viewer"}}, quiet = true}),
    		route = "sharing/add_folder_member", scope = "sharing.write", required = {shared_folder_id = "string", members = "array"}, access = "sharing:write", emptyResult = true,
    		help = "Returns {success=true}. Dropbox emails new members unless quiet=true."},
    	updateFolderMember = {inputSchema = schema({shared_folder_id = NONEMPTY, member = variant("dropbox_id", {dropbox_id = NONEMPTY}, {"dropbox_id"}), access_level = ACCESS}, {shared_folder_id = "84528192421", member = {[".tag"] = "dropbox_id", dropbox_id = "dbid:AAH4f99T0taONIb-OurWxbNQ6ywGRopQngc"}, access_level = "viewer"}),
    		route = "sharing/update_folder_member", scope = "sharing.write", required = {shared_folder_id = "string", member = "union", access_level = "union"}, access = "sharing:write",
    		help = "Returns member result. This route requires a Dropbox account ID, not an email selector."},
    	removeFolderMember = {inputSchema = schema({shared_folder_id = NONEMPTY, member = MEMBER, leave_a_copy = {type = "boolean"}}, {shared_folder_id = "84528192421", member = {[".tag"] = "email", email = "[email protected]"}, leave_a_copy = false}),
    		route = "sharing/remove_folder_member", scope = "sharing.write", required = {shared_folder_id = "string", member = "union", leave_a_copy = "boolean"}, access = "sharing:write",
    		help = "Returns {['.tag']='async_job_id', ...}; poll checkRemoveMemberJobStatus."},
    	checkRemoveMemberJobStatus = {inputSchema = schema({async_job_id = NONEMPTY}, {async_job_id = "job-from-start-operation"}),
    		route = "sharing/check_remove_member_job_status", scope = "sharing.write", required = {async_job_id = "string"}, access = "sharing:write", help = job("removeFolderMember")},
    	unshareFolder = {inputSchema = schema({shared_folder_id = NONEMPTY, leave_a_copy = FALSE}, {shared_folder_id = "84528192421", leave_a_copy = false}),
    		route = "sharing/unshare_folder", scope = "sharing.write", required = {shared_folder_id = "string"}, access = "sharing:write",
    		help = "Returns {['.tag']='complete'} or {['.tag']='async_job_id', ...}; poll checkJobStatus."},
    	checkJobStatus = {inputSchema = schema({async_job_id = NONEMPTY}, {async_job_id = "job-from-start-operation"}),
    		route = "sharing/check_job_status", scope = "sharing.write", required = {async_job_id = "string"}, access = "sharing:write", help = job("unshareFolder and relinquishFolderMembership")},
    	mountFolder = {inputSchema = schema({shared_folder_id = NONEMPTY}, {shared_folder_id = "84528192421"}),
    		route = "sharing/mount_folder", scope = "sharing.write", required = {shared_folder_id = "string"}, access = "sharing:write", help = "Returns shared folder metadata. Adds a shared folder to the account's Dropbox."},
    	unmountFolder = {inputSchema = schema({shared_folder_id = NONEMPTY}, {shared_folder_id = "84528192421"}),
    		route = "sharing/unmount_folder", scope = "sharing.write", required = {shared_folder_id = "string"}, access = "sharing:write", emptyResult = true, help = "Returns {success=true}. Removes it from the account's Dropbox without leaving it."},
    	relinquishFolderMembership = {inputSchema = schema({shared_folder_id = NONEMPTY, leave_a_copy = FALSE}, {shared_folder_id = "84528192421", leave_a_copy = false}),
    		route = "sharing/relinquish_folder_membership", scope = "sharing.write", required = {shared_folder_id = "string"}, access = "sharing:write",
    		help = "Returns {['.tag']='complete'} or {['.tag']='async_job_id', ...}. Leaves a shared folder; poll checkJobStatus."},
    
    	-- Shared files
    	listReceivedFiles = {inputSchema = schema({limit = limit(300, 100), actions = FILE_ACTIONS}, {limit = 100}),
    		route = "sharing/list_received_files", scope = "sharing.read", access = "sharing:read", help = "Returns {entries, cursor?}. Files others shared with the account."},
    	listReceivedFilesContinue = {inputSchema = schema({cursor = CURSOR_SCHEMA}, {cursor = "cursor-from-previous-page"}),
    		route = "sharing/list_received_files/continue", scope = "sharing.read", required = {cursor = "string"}, access = "sharing:read", help = "Returns {entries, cursor?}. Continues listReceivedFiles while a cursor is present."},
    	getSharedFileMetadata = {inputSchema = schema({file = PATH, actions = FILE_ACTIONS}, {file = "/Reports/report.pdf"}),
    		route = "sharing/get_file_metadata", scope = "sharing.read", required = {file = "string"}, access = "sharing:read", help = "Returns shared file metadata. file is a path or 'id:...'."},
    	listFileMembers = {inputSchema = schema({file = PATH, actions = MEMBER_ACTIONS, include_inherited = TRUE, limit = limit(300, 100)}, {file = "/Reports/report.pdf", limit = 100}),
    		route = "sharing/list_file_members", scope = "sharing.read", required = {file = "string"}, access = "sharing:read", help = "Returns {users, groups, invitees, cursor?}."},
    	listFileMembersContinue = {inputSchema = schema({cursor = CURSOR_SCHEMA}, {cursor = "cursor-from-previous-page"}),
    		route = "sharing/list_file_members/continue", scope = "sharing.read", required = {cursor = "string"}, access = "sharing:read", help = "Returns {users, groups, invitees, cursor?}. Continues listFileMembers while a cursor is present."},
    	addFileMember = {inputSchema = schema({file = PATH, members = list(MEMBER), access_level = ACCESS, quiet = FALSE, custom_message = STRING, add_message_as_comment = FALSE}, {file = "/Reports/report.pdf", members = {{[".tag"] = "email", email = "[email protected]"}}, access_level = "viewer", quiet = true}),
    		route = "sharing/add_file_member", scope = "sharing.write", required = {file = "string", members = "array"}, access = "sharing:write",
    		help = "Returns one result per member. Dropbox emails them unless quiet=true."},
    	removeFileMember = {inputSchema = schema({file = PATH, member = MEMBER}, {file = "/Reports/report.pdf", member = {[".tag"] = "email", email = "[email protected]"}}),
    		route = "sharing/remove_file_member_2", scope = "sharing.write", required = {file = "string", member = "union"}, access = "sharing:write", help = "Returns {['.tag']='success'|'member_error', ...}."},
    	unshareFile = {inputSchema = schema({file = PATH}, {file = "/Reports/report.pdf"}),
    		route = "sharing/unshare_file", scope = "sharing.write", required = {file = "string"}, access = "sharing:write", emptyResult = true, help = "Returns {success=true}. Removes every member."},
    	relinquishFileMembership = {inputSchema = schema({file = PATH}, {file = "/Reports/report.pdf"}),
    		route = "sharing/relinquish_file_membership", scope = "sharing.write", required = {file = "string"}, access = "sharing:write", emptyResult = true, help = "Returns {success=true}. Leaves a file shared with the account."},
    
    	-- File requests
    	listFileRequests = {inputSchema = schema({limit = {type = "integer", minimum = 0, default = 1000}}, {limit = 100}),
    		route = "file_requests/list_v2", scope = "file_requests.read", access = "file_requests:read", help = "Returns {file_requests, cursor, has_more}."},
    	listFileRequestsContinue = {inputSchema = schema({cursor = CURSOR_SCHEMA}, {cursor = "cursor-from-previous-page"}),
    		route = "file_requests/list/continue", scope = "file_requests.read", required = {cursor = "string"}, access = "file_requests:read", help = "Returns {file_requests, cursor, has_more}. Continues listFileRequests while has_more is true."},
    	getFileRequest = {inputSchema = schema({id = NONEMPTY}, {id = "oaCAVmEyrqYnkZX9955Y"}),
    		route = "file_requests/get", scope = "file_requests.read", required = {id = "string"}, access = "file_requests:read", help = "Returns file request."},
    	createFileRequest = {inputSchema = schema({title = NONEMPTY, destination = PATH, deadline = DEADLINE, open = TRUE, description = STRING, video_project_id = STRING}, {title = "Submit reports", destination = "/Reports/Submissions", open = true}),
    		route = "file_requests/create", scope = "file_requests.write", required = {title = "string", destination = "string"}, access = "file_requests:write",
    		help = "Returns file request with its url. Anyone with the url can upload into destination."},
    	updateFileRequest = {inputSchema = schema({id = NONEMPTY, title = NONEMPTY, destination = PATH, deadline = {oneOf = {tags({"no_update"}), variant("update", DEADLINE.properties)}}, open = {type = "boolean"}, description = STRING}, {id = "oaCAVmEyrqYnkZX9955Y", open = false}),
    		route = "file_requests/update", scope = "file_requests.write", required = {id = "string"}, access = "file_requests:write", help = "Returns file request. open=false closes it; deadline={['.tag']='update'} alone clears the deadline."},
    	deleteFileRequest = {inputSchema = schema({ids = list(NONEMPTY)}, {ids = {"oaCAVmEyrqYnkZX9955Y"}}),
    		route = "file_requests/delete", scope = "file_requests.write", required = {ids = "array"}, access = "file_requests:write", help = "Returns {file_requests}. Only closed requests can be deleted."},
    }
    
    local help: Options = {
    	text = "Dropbox API v2. Operations use Dropbox's snake_case arguments and return its JSON. Select an exact operation section for its signature, arguments, result and runnable example, or a shared topic below. Calls return completed values; do not await them. Only configured operations appear in the index.",
    	functions = {},
    	sections = {
    		values = "Union values use a tag string for a payload-free variant, or a table such as {['.tag']='update', update='a1c10ce0dd78'}. Use json.decode('[]') for an empty list. Required top-level types are checked locally; Dropbox validates nested values and provider constraints. Extra provider options are forwarded. Routes without a result return {success=true}. Provider reference: https://www.dropbox.com/developers/documentation/http/documentation",
    		paths = "Paths start with '/', are case-insensitive and use '' for the root folder (not '/'). Routes may also accept 'id:...' from metadata, 'rev:...' for a revision or 'ns:<namespace_id>/...' for accessible namespaces; support varies by route. Ordinary paths remain rooted in the member's folder. Dropbox-API-Path-Root is not set, so full team-space traversal is unsupported.",
    		pagination = "Lists return one page. While has_more is true, or a sharing list returns a cursor, pass that cursor to the matching Continue operation. Keep cursors intact. There is no hidden paging. Replace example cursors with a value returned by the preceding page.",
    		errors = "The connector adds no retries; Houston may retry eligible rate-limit responses. Errors report the HTTP status and Dropbox error_summary, with retryable and Retry-After when available. For example, HTTP 409 path/not_found means the path is missing or inaccessible. A failed or timed-out change may already have happened; check before repeating.",
    	},
    }
    local exports: {[string]: any} = {help = help}
    local policy: any = nil
    if config.folder_policy then
    	policy = require("lib/policy.luau")(config.path_access, function(path: string): Options?
    		local response = await(http.request({method = "POST", url = API .. "files/get_metadata",
    			headers = {["Content-Type"] = {"application/json"}}, body = json.encode({path = path, include_deleted = true})}))
    		if response.statusCode < 200 or response.statusCode >= 300 then
    			local ok, body = pcall(json.decode, await(response.body:readPrefix(4096)))
    			if response.statusCode == 409 and ok and type(body) == "table" and type(body.error_summary) == "string"
    				and string.find(body.error_summary, "path/not_found/", 1, true) == 1 then return nil end
    			invalid("folderAccess", response, "Dropbox folder access could not be verified")
    		end
    		return decode("folderAccess", endpoints.getMetadata, response)
    	end)
    end
    
    local function invoke(name: string, endpoint: Endpoint, input: any): any
    	local args, context = options(endpoint, input), nil
    	if policy then args, context = policy.prepare(name, args) end
    	if endpoint.style == "download" then
    		return download(name, endpoint, args, if policy then function(value: any): any return policy.result(name, value, context) end else nil)
    	end
    	local result = if endpoint.style == "upload" then upload(name, endpoint, args) else rpc(name, endpoint, args)
    	return if policy then policy.result(name, result, context) else result
    end
    
    -- Exposes an operation its access rows and known OAuth scopes allow; a folder policy keeps the file
    -- operations it checks, and writes only when a folder is read-write.
    local function enabled(name: string, endpoint: Endpoint): boolean
    	local supported = policy == nil or (policy.supports(if name == "statFile" then "getMetadata" else name)
    		and (policy.writable or endpoint.access ~= "files:write")
    		and (auth.scopes == nil or table.find(auth.scopes, "files.metadata.read") ~= nil))
    	return supported and (endpoint.access == nil or houston.allows(endpoint.access)) and (auth.scopes == nil or table.find(auth.scopes, endpoint.scope) ~= nil)
    end
    
    for name, endpoint in endpoints do
    	if enabled(name, endpoint) then
    		local input = endpoint.inputSchema
    		if endpoint.required then
    			for field in endpoint.required do table.insert(input.required, field) end
    		end
    		if endpoint.style then table.insert(input.required, "session_path") end
    		table.sort(input.required)
    		if endpoint.void then input.additionalProperties = false end
    		if policy then input = policy.schema(name, input) end
    		local description = endpoint.help .. " Route: " .. endpoint.route .. "."
    		if endpoint.style then description ..= " See transfers for session files and size limits." end
    		if policy then description ..= " Folder access and argument restrictions apply; see folderAccess." end
    		help.functions[name] = {description = description, inputSchema = input,
    			args = if endpoint.void then {} else nil,
    			annotations = {readOnlyHint = endpoint.access == nil or string.find(endpoint.access, ":write", 1, true) == nil}}
    		exports[name] = function(args: Options?): any return invoke(name, endpoint, args) end
    	end
    end
    
    -- Fixed-signature file lookup shared with other storage connectors.
    if enabled("statFile", endpoints.getMetadata) then
    	help.functions.statFile = {
    		description = "Read normalized file metadata: {id, name, isFolder, size?}; size is absent for folders. " .. (if policy then "Takes exactly one positional ordinary absolute path inside a configured folder. IDs, revision paths and namespace aliases are not accepted; see folderAccess." else "Takes exactly one positional file path or ID; see paths."),
    		args = {"id"},
    		inputSchema = {type = "object", properties = {id = if policy then {type = "string", minLength = 1, pattern = "^/[^/].*", description = "Ordinary absolute path inside a configured folder; IDs, revision paths and namespace aliases are not accepted. See folderAccess."} else NONEMPTY}, required = {"id"}, additionalProperties = false,
    			examples = {{id = if policy then policy.examplePath() .. "/report.pdf" else "/Reports/report.pdf"}}},
    		outputSchema = object({id = NONEMPTY, name = STRING, isFolder = {type = "boolean"}, size = {type = "integer", minimum = 0, maximum = MAX_SAFE_INTEGER}}, {"id", "name", "isFolder"}),
    		annotations = {readOnlyHint = true},
    	}
    	function exports.statFile(...: any): {id: string, name: string, isFolder: boolean, size: number?}
    		assert(select("#", ...) == 1, "statFile takes exactly one file ID or path")
    		local file = invoke("getMetadata", endpoints.getMetadata, {path = text((...), "file ID")})
    		local isFolder = file[".tag"] == "folder"
    		local size = if isFolder then nil else file.size
    		if type(file.id) ~= "string" or file.id == "" or type(file.name) ~= "string"
    			or (not isFolder and (type(size) ~= "number" or size < 0 or size % 1 ~= 0 or size > MAX_SAFE_INTEGER)) then
    			houston.fail({operation = "statFile", layer = "upstream", retryable = false, message = "Dropbox returned invalid file metadata"})
    		end
    		return {id = file.id, name = file.name, isFolder = isFolder, size = size}
    	end
    end
    
    if exports.listSharedLinks then
    	help.sections.pagination ..= " listSharedLinks takes its cursor back in the same operation."
    end
    if exports.listRevisions then
    	help.sections.pagination ..= " listRevisions pages with before_rev from the last entry while has_more is true."
    end
    if exports.search then
    	help.sections.pagination ..= " Search returns at most 10,000 matches across pages; indexing can lag, and results may repeat or be omitted."
    end
    if exports.download or exports.downloadZip or exports.export or exports.getPreview or exports.getThumbnail or exports.getSharedLinkFile or exports.upload then
    	help.sections.transfers = "Content operations transfer session files; never inline file bytes. A transfer must finish within the call's time limit and stops at Houston's 256 MiB file limit."
    	if exports.download or exports.downloadZip or exports.export or exports.getPreview or exports.getThumbnail or exports.getSharedLinkFile then
    		help.sections.transfers ..= " Downloads save to session_path and return {session_path, url, size, result}; url is a signed Houston link, size counts bytes, and result is Dropbox metadata. A failed download leaves the existing session file unchanged."
    	end
    	if exports.upload then
    		help.sections.transfers ..= " upload reads an existing session_path and stops at Dropbox's 150 MiB single-request limit. Create the session file before running its example. mode defaults to add; overwrite replaces the existing file and update checks its revision."
    	end
    end
    if exports.saveUrlCheckJobStatus or exports.moveBatchCheck or exports.copyBatchCheck or exports.deleteBatchCheck or exports.checkJobStatus or exports.checkShareJobStatus or exports.checkRemoveMemberJobStatus then
    	help.sections.jobs = "Some mutations return {['.tag']='async_job_id', async_job_id=...}; call the status operation named in that function's section. Replace example job IDs with the returned ID. There is no hidden polling. Inspect the final tag and every batch entry: HTTP success does not guarantee all entries succeeded, and a failed job may have partially changed data. Check state before retrying."
    end
    if policy then
    	help.sections.folderAccess = policy.help()
    	help.sections.paths = "Folder limits require ordinary absolute paths in the member's folder, not IDs, namespace aliases or revision paths. Begin at an explicitly granted folder; path='' requires a '/' rule. Parent folders must exist before creating a child. Full team-space traversal is unsupported. See folderAccess for the configured grants."
    	help.sections.values = "Union values use tag strings or {['.tag']=...} tables. Use json.decode('[]') for an empty list. Only the options in each operation's schema are available with folder limits. Dropbox validates nested values and provider constraints."
    	help.sections.pagination ..= " Folder pagination cursors are Houston tokens tied to this connection and its settings."
    end
    return exports
    
  • houston.json
    {
      "schema_version": 2,
      "name": "Dropbox",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "access": [
        {
          "name": "files",
          "label": "Files",
          "description": "Find, read, download, upload and organize files and folders.",
          "levels": [
            {
              "value": "none",
              "label": "None"
            },
            {
              "value": "read",
              "label": "Read"
            },
            {
              "value": "write",
              "label": "Write"
            }
          ],
          "default": "read"
        },
        {
          "name": "sharing",
          "label": "Sharing",
          "description": "Shared links, shared folders and files, and their members.",
          "levels": [
            {
              "value": "none",
              "label": "None"
            },
            {
              "value": "read",
              "label": "Read"
            },
            {
              "value": "write",
              "label": "Write"
            }
          ],
          "default": "read"
        },
        {
          "name": "file_requests",
          "label": "File requests",
          "description": "Requests that let others upload files to your Dropbox.",
          "levels": [
            {
              "value": "none",
              "label": "None"
            },
            {
              "value": "read",
              "label": "Read"
            },
            {
              "value": "write",
              "label": "Write"
            }
          ],
          "default": "read"
        }
      ],
      "config": {
        "folder_policy": {
          "default": false,
          "description": "Houston limits file operations to the folders you list; sharing, file requests and batch operations become unavailable.",
          "label": "Limit to folders",
          "order": 1,
          "type": "boolean"
        },
        "path_access": {
          "default": "{\n  \"/Finance\": \"read-only\",\n  \"/Incoming\": \"read-write\"\n}",
          "description": "Give each folder read-only or read-write. read-write folders also need Write for Files. Unlisted folders are denied, and the most specific rule wins.",
          "format": "json",
          "if": "{{ is config.folder_policy true }}",
          "label": "Folder access JSON",
          "multiline": true,
          "order": 2,
          "required": true,
          "type": "string"
        }
      },
      "auth": {
        "oauth": {
          "account": {
            "headers": {
              "Authorization": {
                "value": "Bearer {{auth.oauth.access_token}}"
              }
            },
            "label": "/email",
            "method": "POST",
            "url": "https://api.dropboxapi.com/2/users/get_current_account"
          },
          "authorize_params": {
            "token_access_type": "offline"
          },
          "authorize_url": "https://www.dropbox.com/oauth2/authorize",
          "client_auth": "body",
          "client_id": "{{publisher.client_id}}",
          "client_secret": "{{publisher.client_secret}}",
          "label": "Connect with Dropbox",
          "brand": "dropbox",
          "pkce": "S256",
          "require_refresh": true,
          "scopes": [
            {
              "values": [
                "account_info.read"
              ]
            },
            {
              "if": "{{ allows access.files \"read\" }}",
              "values": [
                "files.metadata.read",
                "files.content.read"
              ]
            },
            {
              "if": "{{ allows access.sharing \"read\" }}",
              "values": [
                "sharing.read"
              ]
            },
            {
              "if": "{{ allows access.file_requests \"read\" }}",
              "values": [
                "file_requests.read"
              ]
            },
            {
              "if": "{{ allows access.files \"write\" }}",
              "values": [
                "files.content.write"
              ]
            },
            {
              "if": "{{ allows access.sharing \"write\" }}",
              "values": [
                "sharing.write"
              ]
            },
            {
              "if": "{{ allows access.file_requests \"write\" }}",
              "values": [
                "file_requests.write"
              ]
            }
          ],
          "token_url": "https://api.dropboxapi.com/oauth2/token",
          "type": "oauth2"
        }
      },
      "publisher": {
        "client_id": {
          "label": "Dropbox app key",
          "order": 1,
          "required": true,
          "type": "string"
        },
        "client_secret": {
          "label": "Dropbox app secret",
          "order": 2,
          "required": true,
          "type": "secret"
        }
      },
      "proxy": [
        {
          "action": {
            "headers": {
              "set": {
                "Authorization": "Bearer {{auth.oauth.access_token}}"
              }
            }
          },
          "match": {
            "host": [
              "api.dropboxapi.com",
              "content.dropboxapi.com"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/2/*"
            ],
            "protocol": "http"
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • lib
    • policy.luau
      -- Folder permissions use Dropbox's canonical paths; continuation tokens retain their original query boundary.
      type Object = {[string]: any}
      type Grant = {path: string, access: "read-only" | "read-write"}
      local DENIED = "Dropbox path is outside the permitted folder access"
      local specs: {[string]: {fields: string, kind: string}} = {
      	getMetadata = {fields = "path include_media_info include_deleted", kind = "read"},
      	listFolder = {fields = "path recursive limit include_deleted include_media_info include_mounted_folders include_non_downloadable_files", kind = "list"},
      	listFolderContinue = {fields = "cursor", kind = "continue"},
      	listFolderGetLatestCursor = {fields = "path recursive include_deleted include_media_info include_mounted_folders include_non_downloadable_files", kind = "list"},
      	search = {fields = "query options match_field_options include_highlights", kind = "search"},
      	searchContinue = {fields = "cursor", kind = "continue"},
      	listRevisions = {fields = "path limit before_rev include_restorable_info", kind = "read"},
      	getTemporaryLink = {fields = "path", kind = "read"},
      	download = {fields = "path session_path", kind = "read"},
      	downloadZip = {fields = "path session_path", kind = "read"},
      	export = {fields = "path export_format session_path", kind = "read"},
      	getPreview = {fields = "path session_path", kind = "read"},
      	getThumbnail = {fields = "path format size mode session_path", kind = "read"},
      	createFolder = {fields = "path autorename", kind = "write"},
      	upload = {fields = "path session_path mode autorename mute client_modified strict_conflict content_hash", kind = "write"},
      	move = {fields = "from_path to_path autorename", kind = "move"},
      	copy = {fields = "from_path to_path autorename", kind = "copy"},
      	delete = {fields = "path parent_rev", kind = "delete"},
      	restore = {fields = "path rev", kind = "restore"},
      }
      
      local function ordinary(value: any, root: boolean?): string
      	assert(type(value) == "string", "Dropbox path must be a string")
      	if value == "" and root then return value end
      	assert(string.sub(value, 1, 1) == "/" and value ~= "/" and string.sub(value, -1) ~= "/", "Folder limits require an absolute Dropbox path; use '' for the root")
      	assert(utf8.len(value) ~= nil and not string.find(value, "[%z\1-\31\127\\]"), "Dropbox path contains invalid characters")
      	assert(not string.find(value, "//", 1, true), "Dropbox path contains an empty component")
      	for part in string.gmatch(value, "[^/]+") do
      		assert(part ~= "." and part ~= ".." and string.sub(part, -1) ~= " ", "Dropbox path contains a noncanonical component")
      	end
      	return value
      end
      
      local function within(path: string, root: string): boolean
      	return root == "" or path == root or string.sub(path, 1, #root + 1) == root .. "/"
      end
      
      local function denied(): never
      	error(DENIED, 0)
      end
      
      local function fields(value: any, allowed: string)
      	assert(type(value) == "table", "opts must be an object")
      	local permitted: {[string]: boolean} = {}
      	for key in string.gmatch(allowed, "%S+") do permitted[key] = true end
      	for key in value do assert(permitted[key] == true, "This option is unavailable with folder limits: " .. tostring(key)) end
      end
      
      return function(raw: string, metadata: (string) -> Object?): any
      	local parsed = json.decode(raw)
      	assert(type(parsed) == "table" and next(parsed) ~= nil, "Folder access must be a nonempty JSON object mapping paths to read-only or read-write")
      	local configured: {Grant} = {}
      	local writable = false
      	for path, access in parsed do
      		assert(type(path) == "string" and (access == "read-only" or access == "read-write"), "Folder access maps each absolute folder path to read-only or read-write")
      		table.insert(configured, {path = if path == "/" then "" else ordinary(path), access = access})
      		writable = writable or access == "read-write"
      	end
      	assert(#configured <= 64, "Folder access supports at most 64 folder rules")
      	table.sort(configured, function(a: Grant, b: Grant): boolean return a.path < b.path end)
      	local grants: {Grant}? = nil
      	local function rules(): {Grant}
      		if grants then return grants end
      		local resolved: {Grant} = {}
      		local seen: {[string]: boolean} = {}
      		for _, grant in configured do
      			local path = grant.path
      			if path ~= "" then
      				local info = metadata(path)
      				assert(info and info[".tag"] == "folder" and type(info.path_lower) == "string", "A configured Dropbox folder is missing or unavailable")
      				path = ordinary(info.path_lower)
      			end
      			assert(not seen[path], "Folder access contains two rules for the same Dropbox folder")
      			seen[path] = true
      			table.insert(resolved, {path = path, access = grant.access})
      		end
      		grants = resolved
      		return resolved
      	end
      	local function permission(path: string): string?
      		local selected: Grant? = nil
      		for _, grant in rules() do
      			if within(path, grant.path) and (selected == nil or #grant.path > #selected.path) then selected = grant end
      		end
      		return if selected then selected.access else nil
      	end
      	local function authorize(path: string, write: boolean, subtree: boolean?)
      		local access = permission(path)
      		if access == nil or (write and access ~= "read-write") then denied() end
      		if write and subtree then
      			for _, grant in rules() do
      				assert(not (grant.access == "read-only" and within(grant.path, path)), "This operation would change a read-only folder subtree")
      			end
      		end
      	end
      	local function lookup(path: string): Object?
      		local ok, info = pcall(metadata, path)
      		if not ok then denied() end
      		return info
      	end
      	local function metadataPath(info: Object): string
      		local ok, path = pcall(ordinary, info.path_lower)
      		if not ok then denied() end
      		return path
      	end
      	local function canonical(path: any, destination: boolean?): string
      		local original = ordinary(path, true)
      		rules()
      		if original == "" then return "" end
      		local info = lookup(original)
      		if info then
      			return metadataPath(info)
      		end
      		if not destination then denied() end
      		local parent, leaf = string.match(original, "^(.*)/([^/]+)$")
      		assert(parent ~= nil and leaf ~= nil, "Dropbox destination is invalid")
      		if parent == "" then return "/" .. leaf end
      		local folder = lookup(parent)
      		if not folder or folder[".tag"] ~= "folder" then denied() end
      		return metadataPath(folder :: Object) .. "/" .. leaf
      	end
      	local function resultPath(info: any, root: string?): string
      		assert(type(info) == "table" and type(info.path_lower) == "string", "Dropbox returned metadata without a verifiable folder path")
      		local path = ordinary(info.path_lower)
      		authorize(path, false)
      		assert(root == nil or within(path, root), "Dropbox returned metadata outside the requested folder")
      		return path
      	end
      	local function parent(path: string): string
      		return string.match(path, "^(.*)/[^/]+$") or ""
      	end
      	local policy: any = {writable = writable, supports = function(name: string): boolean return specs[name] ~= nil end}
      	local function prepare(name: string, value: any): (Object, Object)
      		local spec = specs[name]
      		assert(spec, "Operation is unavailable with folder limits")
      		fields(value, spec.fields)
      		local args = table.clone(value)
      		local context: Object = {}
      		if spec.kind == "continue" then
      			local token = houston.unseal(args.cursor)
      			assert(type(token) == "table" and token.operation == name and type(token.cursor) == "string", "Invalid Dropbox continuation token")
      			context.root = ordinary(token.root, true)
      			authorize(context.root, false)
      			args.cursor = token.cursor
      			return args, context
      		end
      		assert(args.autorename == nil or args.autorename == false, "Autorename is unavailable with folder limits; choose an explicit destination")
      		if spec.kind == "search" then
      			fields(args.options, "path max_results order_by file_status filename_only file_extensions file_categories")
      			args.options = table.clone(args.options)
      			context.root = canonical(args.options.path)
      			authorize(context.root, false)
      			args.options.path = context.root
      		elseif spec.kind == "move" or spec.kind == "copy" then
      			args.from_path = canonical(args.from_path)
      			args.to_path = canonical(args.to_path, true)
      			authorize(args.from_path, spec.kind == "move", spec.kind == "move")
      			authorize(args.to_path, true, true)
      			context.root = parent(args.to_path)
      		else
      			local write = spec.kind == "write" or spec.kind == "delete" or spec.kind == "restore"
      			args.path = canonical(args.path, spec.kind == "write" or spec.kind == "restore")
      			authorize(args.path, write, write)
      			context.root = if spec.kind == "write" or spec.kind == "restore" then parent(args.path) else args.path
      			if spec.kind == "restore" then
      				assert(type(args.rev) == "string" and string.match(args.rev, "^[0-9a-f]+$"), "rev must be a Dropbox revision")
      				local revision = lookup("rev:" .. args.rev)
      				if not revision then denied() end
      				authorize(metadataPath(revision :: Object), false)
      			end
      		end
      		return args, context
      	end
      	policy.prepare = function(name: string, value: any): (Object, Object)
      		local ok, args, context = pcall(prepare, name, value)
      		if not ok then
      			if string.find(tostring(args), DENIED, 1, true) then denied() end
      			error(args, 0)
      		end
      		return args, context
      	end
      	policy.result = function(name: string, result: any, context: Object): any
      		assert(type(result) == "table", "Dropbox returned an invalid result")
      		if name == "listFolder" or name == "listFolderContinue" or name == "listFolderGetLatestCursor" then
      			if name ~= "listFolderGetLatestCursor" then
      				assert(type(result.entries) == "table" and type(result.has_more) == "boolean", "Dropbox returned an invalid folder page")
      				for _, entry in result.entries do resultPath(entry, context.root) end
      			end
      			assert(type(result.cursor) == "string", "Dropbox returned no folder cursor")
      			result.cursor = houston.seal({operation = "listFolderContinue", root = context.root, cursor = result.cursor})
      		elseif name == "search" or name == "searchContinue" then
      			assert(type(result.matches) == "table" and type(result.has_more) == "boolean", "Dropbox returned an invalid search page")
      			for _, match in result.matches do
      				assert(type(match.metadata) == "table", "Dropbox returned invalid search metadata")
      				resultPath(match.metadata.metadata, context.root)
      			end
      			if result.cursor ~= nil then
      				assert(type(result.cursor) == "string", "Dropbox returned an invalid search cursor")
      				result.cursor = houston.seal({operation = "searchContinue", root = context.root, cursor = result.cursor})
      			end
      		elseif name == "listRevisions" then
      			assert(type(result.entries) == "table", "Dropbox returned invalid revisions")
      			for _, entry in result.entries do resultPath(entry, context.root) end
      		elseif name == "getTemporaryLink" or name == "downloadZip" or name == "createFolder" or name == "move" or name == "copy" or name == "delete" then
      			resultPath(result.metadata, context.root)
      		elseif name == "export" then
      			resultPath(result.file_metadata, context.root)
      		else
      			resultPath(result, context.root)
      		end
      		return result
      	end
      	policy.help = function(): string
      		local lines = {"Limited to folders: unlisted paths are denied; the most specific configured folder wins."}
      		for _, grant in configured do
      			table.insert(lines, (if grant.path == "" then "/" else grant.path) .. ": " .. grant.access)
      		end
      		table.insert(lines, "Folder rules must name existing folders in this account's member root. Paths are checked using Dropbox's canonical metadata, including Unicode names. Use ordinary absolute paths, not IDs, namespace aliases or revision paths. Parent folders must exist before creating a child. Search requires options.path. Pagination cursors are Houston tokens, tied to this connection and its current settings; keep them intact. Moves and deletes cannot change a read-only subtree. Autorename, revision downloads, batch/jobs, sharing, file requests and account-wide operations are unavailable in this mode.")
      		return table.concat(lines, "\n")
      	end
      	policy.examplePath = function(write: boolean?): string
      		for _, grant in configured do
      			if not write or grant.access == "read-write" then return grant.path end
      		end
      		return configured[1].path
      	end
      	-- Shape the reference with the same allowlist used by prepare, without resolving customer metadata.
      	policy.schema = function(name: string, input: Object): Object
      		local result = json.decode(json.encode(input))
      		local permitted: {[string]: boolean} = {}
      		for field in string.gmatch(specs[name].fields, "%S+") do permitted[field] = true end
      		for field in result.properties do
      			if not permitted[field] then result.properties[field] = nil end
      		end
      		result.additionalProperties = false
      		local pathSchema = {type = "string", pattern = "^(/[^/].*|)$", description = "Ordinary absolute Dropbox path inside a configured folder; IDs, revision paths and namespace aliases are not accepted. Empty root requires a '/' grant; see folderAccess."}
      		for _, field in {"path", "from_path", "to_path"} do
      			if result.properties[field] then result.properties[field] = pathSchema end
      		end
      		if result.properties.autorename then result.properties.autorename = {const = false, description = "Choose an explicit destination with folder limits."} end
      		if name == "search" then
      			table.insert(result.required, "options")
      			result.properties.options.required = {"path"}
      			result.properties.options.properties.path = pathSchema
      			result.properties.options.properties.account_id = nil
      			result.properties.options.additionalProperties = false
      		end
      		local root = policy.examplePath(specs[name].kind == "write" or specs[name].kind == "move" or specs[name].kind == "copy" or specs[name].kind == "delete" or specs[name].kind == "restore")
      		local function paths(value: Object)
      			for key, item in value do
      				if type(item) == "table" then paths(item)
      				elseif type(item) == "string" and string.sub(item, 1, 8) == "/Reports" then
      					value[key] = root .. string.sub(item, 9)
      				end
      			end
      		end
      		for _, example in result.examples do
      			for field in example do if not permitted[field] then example[field] = nil end end
      			paths(example)
      		end
      		return result
      	end
      	return policy
      end
      
  • README.md
    ---
    description: Find, read and organize your Dropbox files.
    ---
    
    # Dropbox
    
    Search and read files, download folders, and manage sharing and file requests.
    Choose **Write** for **Files** to upload and organize files, or turn on **Limit
    to folders** to restrict file access to the folders you list.
    
    Connect by signing in to Dropbox using the shared app.
    
  • SETUP.md
    # Connect Dropbox
    
    Choose **None**, **Read** or **Write** for **Files**, **Sharing** and **File
    requests**, then authorize your Dropbox account. No app setup is needed for the
    standard sign-in.
    
    ## Advanced
    
    ### Folder permissions
    
    **Limit to folders** applies to existing folders, with **Read** or **Write**
    for **Files**. Give each folder `read-only` or `read-write`; `read-write`
    folders also need **Write** for **Files**. Unlisted folders are denied, and the
    most specific rule wins. Houston enforces these limits; Dropbox itself grants
    broader app permissions. Sharing, file requests and batch operations are
    unavailable in this mode. Restart any ongoing file listing after changing
    permissions.
    
    ### Limits and reconnecting
    
    Uploads support files up to 150 MiB. Full team-space traversal is not supported.
    Raising an access level requires signing in again. Remove access anytime in
    [Dropbox connected apps](https://www.dropbox.com/account/connected_apps).
    
  • tests
    • arguments.luau
      return {
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth"},
      	access = {files = "write", sharing = "write", file_requests = "write"},
      	configure = function()
      		requests = {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader('{".tag":"async_job_id","async_job_id":"job"}')})
      		end}
      	end,
      	run = function(c)
      		for _, case in {
      			{"getMetadata", {}}, {"listFolder", {}}, {"listFolderContinue", {cursor = false}},
      			{"search", {query = 42}}, {"getAccount", {account_id = {}}},
      			{"download", {session_path = "unused"}}, {"upload", {session_path = "unused"}},
      			{"move", {from_path = "/a"}}, {"moveBatch", {entries = "bad"}},
      			{"modifySharedLinkSettings", {url = "https://dropbox.com/s/a", settings = false}},
      			{"updateFolderMember", {shared_folder_id = "1", member = true, access_level = "viewer"}},
      			{"removeFolderMember", {shared_folder_id = "1", member = {['.tag'] = "email", email = "[email protected]"}}},
      			{"getFileRequest", {id = json.null}}, {"createFileRequest", {title = "Uploads"}},
      			{"deleteFileRequest", {ids = 4}}, {"listFolder", {"/a"}},
      		} do
      			assert(not pcall(c[case[1]], case[2]), "accepted invalid arguments for " .. case[1])
      		end
      		assert(#requests == 0, "invalid arguments reached Dropbox")
      		-- False is a required value, and Dropbox union strings/objects and empty arrays survive encoding.
      		c.removeFolderMember({shared_folder_id = "1", member = {['.tag'] = "email", email = "[email protected]"}, leave_a_copy = false})
      		assert(json.decode(requests[1].body).leave_a_copy == false)
      		c.updateFolderMember({shared_folder_id = "1", member = {['.tag'] = "dropbox_id", dropbox_id = "dbid:a"}, access_level = "viewer"})
      		assert(json.decode(requests[2].body).access_level == "viewer")
      		c.deleteFileRequest({ids = json.decode('[]')})
      		assert(json.encode(json.decode(requests[3].body).ids) == "[]")
      	end,
      }
      
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = {},
      				config = {},
      				endpoint = { "POST", "https://api.dropboxapi.com/2/files/list_folder" },
      				expected = "Bearer synthetic-oauth-token",
      				header = "Authorization",
      				method = "oauth",
      				oauth = true,
      				publisher = {
      					client_id = "synthetic-public-client",
      					client_secret = "synthetic-client-secret",
      				},
      				scopes = true,
      			},
      		})
      	end,
      }
      
    • errors.luau
      return {
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", auth_config = {}},
      	access = {files = "write", sharing = "write", file_requests = "write"},
      	configure = function()
      		requests, responses = {}, {}
      		fs = fixture.files()
      		http = {request = function(req)
      			table.insert(requests, req)
      			for name in req.headers or {} do assert(string.lower(name) ~= "authorization", "credentials belong to the proxy") end
      			if req.body ~= nil and type(req.body) ~= "string" then
      				local source = req.body
      				assert(await(source:readAll()) == "upload")
      				await(source:close())
      			end
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local response = table.remove(responses, 1)
      			return fixture.operation({statusCode = response.status or 200, headers = {}, body = fixture.reader(response.body)})
      		end}
      	end,
      	run = function(c)
      		-- Error snippets stay bounded even when the upstream response exceeds readAll's limit.
      		responses = {{status = 503, body = "service unavailable: " .. string.rep("x", 8 * 1024 * 1024) .. "UNREAD_TAIL"}}
      		local ok, err = pcall(c.getMetadata, {path = "/report"})
      		local message = tostring(err)
      		assert(not ok and string.find(message, "Dropbox HTTP 503: service unavailable:", 1, true), message)
      		assert(string.find(message, '"retryable":true', 1, true) and string.find(message, '"upstream_status":503', 1, true), message)
      		assert(#message < 1500 and not string.find(message, "UNREAD_TAIL", 1, true), "upstream error body was not bounded")
      
      		local input = fs.open("upload.txt", "w")
      		input:write("upload")
      		await(input:close())
      		-- Ordinary RPC and upload results must contain structured JSON, never a fabricated success.
      		for _, body in {"", " \n\t", "null", "42", "true", '"ok"'} do
      			for _, name in {"getMetadata", "upload"} do
      				responses = {{body = body}}
      				local args = if name == "upload" then {path = "/upload.txt", session_path = "upload.txt"} else {path = "/report"}
      				ok, err = pcall(c[name], args)
      				message = tostring(err)
      				assert(not ok and string.find(message, "Dropbox returned invalid JSON", 1, true), name .. " accepted " .. body .. ": " .. message)
      				assert(string.find(message, '"retryable":false', 1, true) and string.find(message, '"upstream_status":200', 1, true), message)
      			end
      		end
      
      		-- Only these documented void-result routes turn JSON null into a success object.
      		for name, args in {
      			revokeSharedLink = {url = "https://www.dropbox.com/s/abc/report.txt"},
      			addFolderMember = {shared_folder_id = "123", members = {{member = {[".tag"] = "email", email = "[email protected]"}, access_level = "viewer"}}},
      			unmountFolder = {shared_folder_id = "123"},
      			unshareFile = {file = "id:report"},
      			relinquishFileMembership = {file = "id:report"},
      		} do
      			responses = {{body = " \nnull\t "}}
      			assert(c[name](args).success == true, name .. " rejected its null result")
      			responses = {{body = ""}}
      			assert(not pcall(c[name], args), name .. " accepted a missing result")
      		end
      		assert(#responses == 0)
      	end,
      }
      
    • exports.luau
      return {
      	contract = function(m)
      		for _, case in
      			{
      				{ scopes = {}, exports = {} },
      				{ scopes = { "account_info.read" }, exports = { "getCurrentAccount", "getSpaceUsage" } },
      				{
      					scopes = { "files.metadata.read" },
      					exports = {
      						"getMetadata",
      						"listFolder",
      						"listFolderContinue",
      						"listFolderGetLatestCursor",
      						"listRevisions",
      						"search",
      						"searchContinue",
      						"statFile",
      					},
      				},
      				-- Rows gate exports even when the token holds broader scopes.
      				{
      					scopes = { "account_info.read", "files.metadata.read", "files.content.read", "file_requests.read", "file_requests.write", "sharing.read" },
      					access = { files = "none", sharing = "none", file_requests = "write" },
      					exports = {
      						"createFileRequest",
      						"deleteFileRequest",
      						"getCurrentAccount",
      						"getFileRequest",
      						"getSpaceUsage",
      						"listFileRequests",
      						"listFileRequestsContinue",
      						"updateFileRequest",
      					},
      				},
      			}
      		do
      			local access = case.access or { files = "write", sharing = "write", file_requests = "write" }
      			local result, err = m.exports({}, "oauth", case.scopes, nil, access)
      			assert(result and not err, tostring(err))
      			if #case.exports == 0 then
      				assert(
      					result.type == "error"
      						and string.find(result.error, "configured bundle has no exports", 1, true),
      					"empty grant exposed operations"
      				)
      			else
      				assert(
      					result.type == "result" and m.equal(result.exports, case.exports),
      					"wrong configured exports"
      				)
      				-- Discovery validates structured records against this exact export set;
      				-- m.exports returns only the introductory text in result.help.
      			end
      		end
      	end,
      }
      
    • folders.luau
      return {
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", auth_config = {}},
      	access = {files = "write"},
      	config = {folder_policy = true, path_access = '{"/Reports":"read-only","/Incoming":"read-write","/Incoming/Approved":"read-only","/Équipe":"read-write","/Incoming/k":"read-only"}'},
      	configure = function()
      		requests, responses, metadataOverride = {}, {}, nil
      		fs = fixture.files()
      		local native = houston
      		local tokens, count = {}, 0
      		houston = table.clone(native)
      		houston.seal = function(value)
      			count += 1
      			local token = "protected:" .. tostring(count)
      			tokens[token] = json.encode(value)
      			return token
      		end
      		houston.unseal = function(token)
      			assert(type(token) == "string" and tokens[token], "Invalid continuation token")
      			return json.decode(tokens[token])
      		end
      		local folders = {["/reports"] = true, ["/incoming"] = true, ["/incoming/approved"] = true, ["/incoming/k"] = true, ["/équipe"] = true, ["/outside"] = true}
      		local files = {["/reports/report.txt"] = true, ["/incoming/draft.txt"] = true, ["/incoming/approved/approved.txt"] = true,
      			["/incoming/k/secret.txt"] = true, ["/équipe/café.txt"] = true, ["/outside/secret.txt"] = true}
      		http = {request = function(req)
      			if type(req.body) == "userdata" then req.body = await(req.body:readAll()) end
      			table.insert(requests, req)
      			local response
      			if string.find(req.url, "files/get_metadata", 1, true) then
      				local path = json.decode(req.body).path
      				path = string.gsub(string.gsub(string.lower(path), "É", "é"), "K", "k")
      				if metadataOverride then response = metadataOverride(path)
      				elseif path == "rev:abcdef123" then response = {body = '{".tag":"file","path_lower":"/reports/report.txt","name":"report.txt","id":"id:report","size":6}'}
      				elseif path == "rev:deadbeef123" then response = {body = '{".tag":"file","path_lower":"/outside/secret.txt","name":"secret.txt","id":"id:secret","size":6}'}
      				elseif folders[path] or files[path] then response = {body = json.encode({[".tag"] = if folders[path] then "folder" else "file", path_lower = path, name = string.match(path, "[^/]+$"), id = "id:" .. path, size = if files[path] then 6 else nil})}
      				else response = {status = 409, body = '{"error_summary":"path/not_found/.."}'} end
      			else
      				assert(#responses > 0, "Unexpected request: " .. req.url)
      				response = table.remove(responses, 1)
      			end
      			return fixture.operation({statusCode = response.status or 200, headers = response.headers or {}, body = fixture.reader(response.body or "")})
      		end}
      	end,
      	run = function(c)
      		local makePolicy = require("lib/policy.luau")
      		for _, raw in {"{", "{}", "[]", '["read-only"]', '{"/Reports":"write"}', '{"/Reports":true}', '{"relative":"read-only"}', '{"/Reports/":"read-only"}'} do
      			assert(not pcall(makePolicy, raw, function() error("Invalid config reached Dropbox") end), "Accepted invalid folder policy " .. raw)
      		end
      		local aliases = makePolicy('{"/Reports":"read-write","/REPORTS":"read-only"}', function() return {[".tag"] = "folder", path_lower = "/reports"} end)
      		assert(not pcall(aliases.prepare, "listFolder", {path = "/Reports"}), "Accepted conflicting case aliases")
      		local missing = makePolicy('{"/Missing":"read-only"}', function() return nil end)
      		assert(not pcall(missing.prepare, "listFolder", {path = "/Missing"}), "Accepted an unavailable policy root")
      		local readOnly = makePolicy('{"/Reports":"read-only"}', function() error("Pure policy construction reached Dropbox") end)
      		assert(not readOnly.writable, "All-read-only folder policy exports writes")
      		local expected = {}
      		for _, name in {"getMetadata", "statFile", "listFolder", "listFolderContinue", "listFolderGetLatestCursor", "search", "searchContinue", "listRevisions",
      			"getTemporaryLink", "download", "downloadZip", "export", "getPreview", "getThumbnail", "createFolder", "upload", "move", "copy", "delete", "restore"} do
      			expected[name] = true
      			assert(type(c[name]) == "function", "Missing scoped operation " .. name)
      		end
      		for name in c do assert(expected[name], "Folder-limited connection exposes " .. name) end
      		local function reject(fn, args)
      			assert(not pcall(fn, args), "Unsafe folder-limited operation succeeded")
      		end
      		for _, fn in {c.getMetadata, c.delete, c.upload, c.createFolder} do
      			local errors = {}
      			for _, path in {"/Outside/secret.txt", "/Outside/missing.txt", "/Missing/child/file.txt"} do
      				local ok, err = pcall(fn, {path = path, session_path = if fn == c.upload then "source.txt" else nil})
      				assert(not ok)
      				table.insert(errors, tostring(err))
      			end
      			assert(errors[1] == errors[2] and errors[1] == errors[3], "Folder denial revealed whether an outside path exists")
      		end
      		local revisionErrors = {}
      		for _, rev in {"deadbeef123", "abcdef999"} do
      			local ok, err = pcall(c.restore, {path = "/Incoming/new.txt", rev = rev})
      			assert(not ok)
      			table.insert(revisionErrors, tostring(err))
      		end
      		assert(revisionErrors[1] == revisionErrors[2], "Restore denial revealed whether an outside revision exists")
      		local function mutations()
      			local count = 0
      			for _, req in requests do
      				if not string.find(req.url, "files/get_metadata", 1, true) then count += 1 end
      			end
      			return count
      		end
      		local report = c.statFile("/REPORTS/report.txt")
      		assert(report.name == "report.txt" and report.size == 6)
      		assert(c.statFile("/Équipe/café.txt").name == "café.txt")
      		for _, path in {"", "/", "/Outside/secret.txt", "/ReportsElsewhere/x", "id:secret", "ns:123/reports/report.txt", "rev:abcdef123", "/Incoming/../Outside/secret.txt", "/Incoming//draft.txt", "/Incoming /draft.txt", "/Incoming\\draft.txt"} do reject(c.getMetadata, {path = path}) end
      		for _, path in {"/Reports/report.txt", "/Incoming/Approved/approved.txt", "/Incoming/K/secret.txt", "/Incoming", "/Outside/secret.txt"} do reject(c.delete, {path = path}) end
      		reject(c.move, {from_path = "/Incoming", to_path = "/Équipe/archive"})
      		reject(c.copy, {from_path = "/Reports", to_path = "/Incoming"})
      		reject(c.move, {from_path = "/Reports/report.txt", to_path = "/Incoming/report.txt"})
      		reject(c.upload, {path = "/Incoming/Approved/new.txt", session_path = "source.txt"})
      		reject(c.createFolder, {path = "/Incoming/new/deep"})
      		reject(c.createFolder, {path = "/Incoming/new", autorename = true})
      		reject(c.listFolder, {path = "/Reports", shared_link = {url = "https://dropbox.test/shared"}})
      		reject(c.search, {query = "secret"})
      		reject(c.search, {query = "secret", options = {path = "/Outside"}})
      		reject(c.search, {query = "secret", options = {path = "/Reports", account_id = "other"}})
      		reject(c.download, {path = "/Reports/report.txt", rev = "deadbeef123", session_path = "bad.txt"})
      		reject(c.listRevisions, {path = "/Reports/report.txt", mode = "id"})
      		reject(c.restore, {path = "/Incoming/new.txt", rev = "deadbeef123"})
      		reject(c.listFolderContinue, {cursor = "raw-dropbox-cursor"})
      		assert(mutations() == 0, "Unsafe input reached a content or mutation endpoint")
      
      		responses = {{body = '{"entries":[{".tag":"file","path_lower":"/reports/report.txt","id":"id:report","name":"report.txt","size":6}],"cursor":"provider-list-1","has_more":true}'}}
      		local page = c.listFolder({path = "/Reports", recursive = true, include_deleted = true})
      		assert(page.entries[1].name == "report.txt" and page.cursor ~= "provider-list-1")
      		local listToken = page.cursor
      		reject(c.listFolderContinue, {cursor = listToken .. "tampered"})
      		reject(c.searchContinue, {cursor = listToken})
      		responses = {{body = '{"entries":[],"cursor":"provider-list-2","has_more":false}'}}
      		page = c.listFolderContinue({cursor = listToken})
      		assert(json.decode(requests[#requests].body).cursor == "provider-list-1" and json.encode(page.entries) == "[]")
      		responses = {{body = '{"entries":[{".tag":"file","path_lower":"/outside/secret.txt","name":"secret.txt"}],"cursor":"provider-list-3","has_more":false}'}}
      		reject(c.listFolderContinue, {cursor = page.cursor})
      		responses = {{body = '{"entries":[{".tag":"file","path_lower":"/incoming/draft.txt","name":"draft.txt"}],"cursor":"provider-list-3","has_more":false}'}}
      		reject(c.listFolderContinue, {cursor = page.cursor})
      		responses = {{body = '{"cursor":"latest-provider"}'}}
      		local latest = c.listFolderGetLatestCursor({path = "/Reports"})
      		assert(latest.cursor ~= "latest-provider")
      		responses = {{body = '{"matches":[{"metadata":{".tag":"metadata","metadata":{".tag":"file","path_lower":"/reports/report.txt","name":"report.txt"}}}],"cursor":"search-provider","has_more":true}'}}
      		local search = c.search({query = "report", options = {path = "/Reports"}})
      		assert(search.cursor ~= "search-provider" and search.matches[1].metadata.metadata.name == "report.txt")
      		responses = {{body = '{"matches":[],"has_more":false}'}}
      		assert(c.searchContinue({cursor = search.cursor}).has_more == false)
      		responses = {{body = '{"entries":[{".tag":"file","path_lower":"/reports/report.txt","rev":"abcdef123"}],"is_deleted":false,"has_more":false}'}}
      		assert(c.listRevisions({path = "/Reports/report.txt"}).entries[1].rev == "abcdef123")
      
      		local source = fs.open("source.txt", "w")
      		source:write("source")
      		await(source:close())
      		responses = {{body = '{".tag":"file","path_lower":"/incoming/new.txt","name":"new.txt","id":"id:new","size":6}'}}
      		assert(c.upload({path = "/Incoming/NEW.txt", session_path = "source.txt"}).name == "new.txt")
      		assert(json.decode(requests[#requests].headers["Dropbox-API-Arg"][1]).path == "/incoming/NEW.txt")
      		responses = {{body = '{"metadata":{".tag":"folder","path_lower":"/incoming/new","name":"new","id":"id:new"}}'}}
      		assert(c.createFolder({path = "/Incoming/New"}).metadata.name == "new")
      		for _, name in {"move", "copy"} do
      			responses = {{body = '{"metadata":{".tag":"file","path_lower":"/équipe/draft.txt","name":"draft.txt","id":"id:draft","size":6}}'}}
      			assert(c[name]({from_path = "/Incoming/draft.txt", to_path = "/Équipe/draft.txt"}).metadata.name == "draft.txt")
      		end
      		responses = {{body = '{"metadata":{".tag":"file","path_lower":"/incoming/draft.txt","name":"draft.txt","id":"id:draft","size":6}}'}}
      		assert(c.delete({path = "/Incoming/draft.txt"}).metadata.name == "draft.txt")
      		responses = {{body = '{".tag":"file","path_lower":"/incoming/restored.txt","name":"restored.txt","id":"id:restored","size":6}'}}
      		assert(c.restore({path = "/Incoming/restored.txt", rev = "abcdef123"}).name == "restored.txt")
      		responses = {{body = '{"metadata":{".tag":"file","path_lower":"/reports/report.txt","name":"report.txt"},"link":"https://dropbox.test/download"}'}}
      		assert(c.getTemporaryLink({path = "/Reports/report.txt"}).link == "https://dropbox.test/download")
      		for _, name in {"download", "getPreview", "getThumbnail"} do
      			responses = {{headers = {["dropbox-api-result"] = {'{".tag":"file","path_lower":"/reports/report.txt","name":"report.txt"}'}}, body = "secret"}}
      			assert(c[name]({path = "/Reports/report.txt", session_path = name .. ".txt"}).size == 6)
      		end
      		responses = {{headers = {["dropbox-api-result"] = {'{"metadata":{".tag":"folder","path_lower":"/reports","name":"Reports"}}'}}, body = "zip"}}
      		assert(c.downloadZip({path = "/Reports", session_path = "reports.zip"}).size == 3)
      		responses = {{headers = {["dropbox-api-result"] = {'{"file_metadata":{".tag":"file","path_lower":"/reports/report.txt","name":"report.txt"},"export_metadata":{"name":"report.md"}}'}}, body = "text"}}
      		assert(c.export({path = "/Reports/report.txt", session_path = "report.md"}).size == 4)
      		responses = {{headers = {["dropbox-api-result"] = {'{".tag":"file","path_lower":"/outside/secret.txt","name":"secret.txt"}'}}, body = "MUST NOT ESCAPE"}}
      		reject(c.download, {path = "/Reports/report.txt", session_path = "refused.txt"})
      		assert(not await(fs.exists("refused.txt")), "Unauthorized bytes escaped to the session filesystem")
      		-- Generated examples choose a granted root and retain policy-specific options.
      		responses = {{body = '{"metadata":{".tag":"folder","path_lower":"/incoming/new folder","name":"New folder","id":"id:example"}}'}}
      		assert(fixture.example("createFolder").metadata.id == "id:example")
      		assert(json.decode(requests[#requests].body).path == "/incoming/New folder")
      		responses = {{body = '{"cursor":"example-cursor"}'}}
      		assert(fixture.example("listFolderGetLatestCursor").cursor ~= "example-cursor")
      		assert(json.decode(requests[#requests].body).path == "/incoming")
      		responses = {{body = '{"matches":[],"has_more":false}'}}
      		assert(fixture.example("search").has_more == false)
      		assert(json.decode(requests[#requests].body).options.path == "/incoming")
      		assert(#responses == 0)
      	end,
      }
      
    • folders_read_access.luau
      return {
      	-- Files stays at Read: folder limits apply, and a read-write folder still gets no writes.
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", auth_config = {}},
      	config = {folder_policy = true, path_access = '{"/Reports":"read-only","/Incoming":"read-write"}'},
      	configure = function()
      		http = {request = function(req)
      			assert(req.url == "https://api.dropboxapi.com/2/files/get_metadata")
      			local path = string.lower(json.decode(req.body).path)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(json.encode({[".tag"] = "folder", path_lower = path, name = "folder", id = "id:" .. path}))})
      		end}
      	end,
      	run = function(c)
      		for _, name in {"upload", "createFolder", "move", "copy", "delete", "restore", "getCurrentAccount", "listSharedLinks", "listFileRequests"} do assert(c[name] == nil, "Read folder limits expose " .. name) end
      		assert(type(c.listFolder) == "function" and type(c.download) == "function", "Read folder limits lack reads")
      		assert(c.getMetadata({path = "/Incoming"}).path_lower == "/incoming", "Read folder limits denied a configured folder")
      		assert(fixture.example("getMetadata").path_lower == "/incoming/report.pdf", "example must use a configured folder")
      		local stat = fixture.example("statFile")
      		assert(stat.id == "id:/incoming/report.pdf" and stat.isFolder, "positional example must use a configured folder")
      		assert(not pcall(c.getMetadata, {path = "/Outside"}), "Read folder limits reached an unlisted folder")
      	end,
      }
      
    • folders_read_only_rules.luau
      return {
      	-- Files is at Write, but no folder is read-write, so no write is exported.
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", auth_config = {}},
      	access = {files = "write"},
      	config = {folder_policy = true, path_access = '{"/Reports":"read-only","/Incoming":"read-only"}'},
      	configure = function()
      		requests = {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(req.url == "https://api.dropboxapi.com/2/files/get_metadata")
      			local path = string.lower(json.decode(req.body).path)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(json.encode({[".tag"] = "folder", path_lower = path, name = "folder", id = "id:" .. path}))})
      		end}
      	end,
      	run = function(c)
      		for _, name in {"upload", "createFolder", "move", "copy", "delete", "restore", "getCurrentAccount", "listSharedLinks", "listFileRequests"} do assert(c[name] == nil, "All-read-only folder rules expose " .. name) end
      		assert(c.getMetadata({path = "/Incoming"}).path_lower == "/incoming", "Read-only folder policy denied a configured folder")
      		assert(fixture.example("getMetadata").path_lower == "/incoming/report.pdf", "example must respect read-only folder rules")
      		assert(not pcall(c.getMetadata, {path = "/Outside"}), "Read-only folder policy reached an unlisted folder")
      	end,
      }
      
    • help_examples.luau
      -- Execute generated reference calls, checking options, nesting and streamed file behavior.
      return {
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", auth_config = {}},
      	access = {files = "write", sharing = "write", file_requests = "write"},
      	configure = function()
      		requests = {}
      		responses = {}
      		fs = fixture.files()
      		http = {request = function(request)
      			table.insert(requests, request)
      			local response = table.remove(responses, 1)
      			assert(response, "unexpected request")
      			return fixture.operation({statusCode = 200, headers = response.headers or {}, body = fixture.reader(response.body)})
      		end}
      	end,
      	run = function()
      		responses = {{body = '{"entries":[{".tag":"file","name":"report.pdf","path_lower":"/reports/report.pdf"}],"cursor":"next-page","has_more":true}'}}
      		local page = fixture.example("listFolder")
      		assert(page.entries[1].name == "report.pdf" and page.has_more and page.cursor == "next-page")
      		local request = requests[#requests]
      		local args = json.decode(request.body)
      		assert(request.url == "https://api.dropboxapi.com/2/files/list_folder" and args.path == "/Reports" and args.limit == 100 and args.recursive == false)
      
      		responses = {{body = '{"metadata":{".tag":"folder","name":"New folder"}}'}}
      		assert(fixture.example("createFolder").metadata.name == "New folder")
      		request = requests[#requests]
      		assert(request.url == "https://api.dropboxapi.com/2/files/create_folder_v2" and json.decode(request.body).path == "/Reports/New folder")
      
      		local file = fs.open("upload.txt", "w")
      		file:write("quarterly report")
      		await(file:close())
      		responses = {{body = '{".tag":"file","name":"upload.txt","id":"id:upload","size":16}'}}
      		assert(fixture.example("upload").id == "id:upload")
      		request = requests[#requests]
      		args = json.decode(request.headers["Dropbox-API-Arg"][1])
      		assert(request.url == "https://content.dropboxapi.com/2/files/upload" and args.path == "/Reports/upload.txt" and args.mode == "add" and args.session_path == nil)
      		assert(await(request.body:readAll()) == "quarterly report")
      		await(request.body:close())
      
      		responses = {{headers = {["dropbox-api-result"] = {'{".tag":"file","name":"report.pdf"}'}}, body = "PDF bytes"}}
      		local downloaded = fixture.example("download")
      		assert(downloaded.session_path == "downloads/report.pdf" and downloaded.size == 9 and downloaded.result.name == "report.pdf")
      		assert(downloaded.url == "https://houston.test/downloads/report.pdf")
      
      		responses = {{body = '{"matches":[],"has_more":false}'}}
      		assert(#fixture.example("search").matches == 0)
      		args = json.decode(requests[#requests].body)
      		assert(args.query == "report" and args.options.path == "/Reports" and args.options.max_results == 20)
      
      		responses = {{body = "null"}}
      		assert(fixture.example("addFolderMember").success)
      		args = json.decode(requests[#requests].body)
      		assert(args.shared_folder_id == "84528192421" and args.quiet == true)
      		assert(args.members[1].member[".tag"] == "email" and args.members[1].member.email == "[email protected]" and args.members[1].access_level == "viewer")
      
      		responses = {{body = '{".tag":"file","id":"id:report","name":"report.pdf","size":9}'}}
      		local stat = fixture.example("statFile")
      		assert(stat.id == "id:report" and stat.size == 9 and not stat.isFolder)
      		assert(json.decode(requests[#requests].body).path == "/Reports/report.pdf")
      
      		responses = {{body = '{"account_id":"dbid:account","email":"[email protected]"}'}}
      		assert(fixture.example("getCurrentAccount").email == "[email protected]")
      		assert(requests[#requests].body == nil, "zero-argument example must preserve the void RPC body")
      
      		responses = {{body = '{"id":"oaCAVmEyrqYnkZX9955Y","is_open":false}'}}
      		assert(fixture.example("updateFileRequest").is_open == false)
      		assert(json.decode(requests[#requests].body).open == false)
      		assert(#responses == 0)
      	end,
      }
      
    • manifest.luau
      return {
      	contract = function(m)
      		-- TestDropboxScopesAndRoutes
      		do
      			local readScopes = {
      				"account_info.read",
      				"files.metadata.read",
      				"files.content.read",
      				"sharing.read",
      				"file_requests.read",
      			}
      			local writeScopes = { "files.content.write", "sharing.write", "file_requests.write" }
      			local method = "oauth"
      			-- The default and full matrices request exactly the v1 Read-only and Read and write scopes.
      			for _, case in
      				{
      					{ access = nil, scopes = readScopes },
      					{ access = { files = "write", sharing = "write", file_requests = "write" }, scopes = m.concat(readScopes, writeScopes) },
      					{ access = { files = "none", sharing = "none", file_requests = "none" }, scopes = { "account_info.read" } },
      					{
      						access = { files = "write", sharing = "none", file_requests = "read" },
      						scopes = {
      							"account_info.read",
      							"files.metadata.read",
      							"files.content.read",
      							"file_requests.read",
      							"files.content.write",
      						},
      					},
      					{ access = { files = "none", sharing = "write" }, scopes = { "account_info.read", "sharing.read", "file_requests.read", "sharing.write" } },
      				}
      			do
      				local publisher = { client_id = "publisher-key", client_secret = "publisher-secret" }
      				local r, err = m.resolve(publisher, {}, nil, method, case.access)
      				assert(not err, tostring(err))
      				if not (m.equal(r.Scopes, case.scopes)) then
      					m.fail("access=%s scopes %s", case.access and json.encode(case.access) or "default", r.Scopes)
      				end
      				r.Context.Auth[method].access_token = "fixture-token"
      				m.routes(r, "Bearer fixture-token", true, {
      					"POST https://api.dropboxapi.com/2/files/list_folder",
      					"POST https://api.dropboxapi.com/2/sharing/revoke_shared_link",
      					"POST https://content.dropboxapi.com/2/files/download",
      					"POST https://content.dropboxapi.com/2/files/upload",
      				})
      				m.routes(r, "Bearer fixture-token", false, {
      					"POST https://api.dropboxapi.com/oauth2/token",
      					"GET https://api.dropboxapi.com/2/files/list_folder",
      					"POST https://notify.dropboxapi.com/2/files/list_folder/longpoll",
      					"GET https://dl.dropboxusercontent.com/apitl/1/file",
      					"POST https://api.dropboxapi.com.evil.test/2/files/list_folder",
      				})
      			end
      		end
      		-- TestDropboxPublisherClient
      		do
      			local publisher = { client_id = "publisher-key", client_secret = "publisher-secret" }
      			local r, err = m.resolve(publisher, nil, nil, "oauth")
      			assert(not err, tostring(err))
      			local client, err = m.render(m.raw.auth["oauth"].client_id, r.Context)
      			if
      				((err ~= nil) or (client ~= "publisher-key")) or not (m.publisherClient(m.raw.auth["oauth"]))
      			then
      				m.fail("wrong OAuth client: %s %s", client, err)
      			end
      			for _, field in r.ConnectionFields do
      				if
      					((field.name == "client_id") or (field.name == "client_secret"))
      					or (field.name == "own_app")
      				then
      					m.fail("connection exposes app credentials")
      				end
      			end
      			for _, missing in { "client_id", "client_secret" } do
      				local inputs = table.clone(publisher)
      				inputs[missing] = nil
      				do
      					local _, err = m.resolve(inputs, nil, nil, "oauth")
      					if err == nil then
      						m.fail("missing %s accepted", missing)
      					end
      				end
      			end
      		end
      	end,
      }
      
    • read_only.luau
      return {
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", auth_config = {}},
      	run = function(c)
      		local reads = {}
      		for _, name in {
      			"getCurrentAccount", "getSpaceUsage", "getAccount", "statFile",
      			"getMetadata", "listFolder", "listFolderContinue", "listFolderGetLatestCursor", "search", "searchContinue", "listRevisions",
      			"getTemporaryLink", "download", "downloadZip", "export", "getPreview", "getThumbnail",
      			"listSharedLinks", "getSharedLinkMetadata", "getSharedLinkFile",
      			"listSharedFolders", "listSharedFoldersContinue", "listMountableFolders", "listMountableFoldersContinue",
      			"getSharedFolderMetadata", "listFolderMembers", "listFolderMembersContinue",
      			"listReceivedFiles", "listReceivedFilesContinue", "getSharedFileMetadata", "listFileMembers", "listFileMembersContinue",
      			"listFileRequests", "listFileRequestsContinue", "getFileRequest",
      		} do
      			reads[name] = true
      			assert(type(c[name]) == "function", "read-only lacks " .. name)
      		end
      		for name in c do
      			assert(name == "help" or reads[name], "read-only exposes " .. name)
      		end
      	end,
      }
      
    • reads.luau
      return {
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", auth_config = {}},
      	configure = function()
      		requests, responses = {}, {}
      		fs = fixture.files()
      		http = {request = function(req)
      			for name in req.headers or {} do assert(string.lower(name) ~= "authorization", "credentials belong to the proxy") end
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local response = table.remove(responses, 1)
      			return fixture.operation({statusCode = response.status or 200, headers = response.headers or {}, body = fixture.reader(response.body or "")})
      		end}
      	end,
      	run = function(c)
      		local API = "https://api.dropboxapi.com/2/"
      
      		-- RPC routes POST the options as JSON and return Dropbox's JSON unchanged.
      		responses = {{body = '{"entries":[{".tag":"file","name":"a.txt","id":"id:a"}],"cursor":"c1","has_more":true}'}, {body = '{"entries":[],"cursor":"c2","has_more":false}'}}
      		local page = c.listFolder({path = "", recursive = true})
      		local req = requests[1]
      		assert(req.method == "POST" and req.url == API .. "files/list_folder" and req.headers["Content-Type"][1] == "application/json")
      		local sent = json.decode(req.body)
      		assert(sent.path == "" and sent.recursive == true)
      		assert(page.entries[1].id == "id:a" and page.entries[1][".tag"] == "file" and page.cursor == "c1")
      		local last = c.listFolderContinue({cursor = "c1"})
      		assert(requests[2].url == API .. "files/list_folder/continue" and json.decode(requests[2].body).cursor == "c1")
      		assert(json.encode(last.entries) == "[]", "empty entries must stay an array")
      
      		-- Routes without arguments send no body.
      		responses = {{body = '{"account_id":"dbid:1","email":"[email protected]"}'}}
      		assert(c.getCurrentAccount().email == "[email protected]")
      		assert(requests[3].url == API .. "users/get_current_account" and requests[3].body == nil and requests[3].headers == nil)
      		assert(not pcall(c.getCurrentAccount, {extra = true}))
      		assert(not pcall(c.listFolder, "/path"), "options must be a table")
      		assert(#requests == 3, "invalid options reached Dropbox")
      
      		-- Errors carry Dropbox's summary, user message and retry hint.
      		responses = {
      			{status = 409, body = '{"error_summary":"path/not_found/..","error":{".tag":"path","path":{".tag":"not_found"}},"user_message":{"text":"Nothing here","locale":"en"}}'},
      			{status = 400, body = 'Error in call to API function "files/list_folder": request body: path: Specify the root folder as an empty string rather than as "/".'},
      			{status = 429, headers = {["retry-after"] = {"7"}}, body = '{"error_summary":"too_many_requests/..","error":{"reason":{".tag":"too_many_requests"},"retry_after":7}}'},
      		}
      		local ok, err = pcall(c.getMetadata, {path = "/missing"})
      		assert(not ok and string.find(tostring(err), "Dropbox HTTP 409: path/not_found/.. (Nothing here)", 1, true), tostring(err))
      		assert(string.find(tostring(err), '"retryable":false', 1, true) and string.find(tostring(err), '"upstream_status":409', 1, true), tostring(err))
      		ok, err = pcall(c.listFolder, {path = "/"})
      		assert(not ok and string.find(tostring(err), "Specify the root folder", 1, true), tostring(err))
      		ok, err = pcall(c.search, {query = "report"})
      		assert(not ok and string.find(tostring(err), "too_many_requests", 1, true) and string.find(tostring(err), "Retry-After: 7", 1, true), tostring(err))
      		assert(string.find(tostring(err), '"retryable":true', 1, true), tostring(err))
      		responses = {{body = "<html>"}}
      		assert(not pcall(c.getMetadata, {path = "/a"}), "accepted invalid JSON")
      
      		-- statFile keeps the shared storage contract.
      		assert(not pcall(c.statFile, ""))
      		assert(not pcall(c.statFile, 42))
      		assert(not pcall(c.statFile, "id:a", "extra"))
      		assert(not pcall(c.statFile))
      		local before = #requests
      		responses = {{body = '{".tag":"file","id":"id:a","name":"a.txt","size":42}'}, {body = '{".tag":"folder","id":"id:d","name":"Docs"}'}}
      		local file = c.statFile("id:a")
      		assert(#requests == before + 1 and requests[#requests].url == API .. "files/get_metadata" and json.decode(requests[#requests].body).path == "id:a")
      		assert(file.id == "id:a" and file.name == "a.txt" and file.size == 42 and file.isFolder == false)
      		local folder = c.statFile("/Docs")
      		assert(folder.isFolder and folder.size == nil)
      		for _, size in {',"size":-1', ',"size":0.5', ',"size":9007199254740992', ',"size":"42"', ""} do
      			responses = {{body = '{".tag":"file","id":"id:b","name":"b"' .. size .. '}'}}
      			assert(not pcall(c.statFile, "id:b"), "accepted size " .. size)
      		end
      
      		-- Downloads stream to the session path; arguments travel in a header-safe Dropbox-API-Arg.
      		local bytes = string.char(0, 255, 13, 10) .. "binary payload"
      		responses = {{headers = {["dropbox-api-result"] = {'{"name":"Caf\\u00e9.txt","id":"id:c","size":18}'}}, body = bytes}}
      		local saved = c.download({path = "/Café/😀\127.txt", session_path = "downloads/cafe.txt"})
      		req = requests[#requests]
      		assert(req.method == "POST" and req.url == "https://content.dropboxapi.com/2/files/download" and req.body == nil and req.headers["Content-Type"] == nil)
      		local arg = req.headers["Dropbox-API-Arg"][1]
      		assert(not string.find(arg, "[\127-\255]"), "Dropbox-API-Arg must be ASCII: " .. arg)
      		assert(string.find(arg, "\\u00e9", 1, true) and string.find(string.lower(arg), "\\ud83d\\ude00\\u007f", 1, true), arg)
      		local decoded = json.decode(arg)
      		assert(decoded.path == "/Café/😀\127.txt" and decoded.session_path == nil)
      		assert(saved.session_path == "downloads/cafe.txt" and saved.url == "https://houston.test/downloads/cafe.txt" and saved.size == #bytes)
      		assert(saved.result.name == "Café.txt" and saved.result.id == "id:c")
      		local fd = fs.open("downloads/cafe.txt", "r")
      		assert(await(fd:readAll()) == bytes)
      		await(fd:close())
      
      		responses = {{headers = {["dropbox-api-result"] = {'{"export_metadata":{"name":"Notes.md"}}'}}, body = "# Notes"}}
      		local exported = c.export({path = "/Notes.paper", export_format = "markdown", session_path = "notes.md"})
      		assert(requests[#requests].url == "https://content.dropboxapi.com/2/files/export" and exported.size == 7 and exported.result.export_metadata.name == "Notes.md")
      		responses = {{body = "no metadata"}}
      		assert(not pcall(c.download, {path = "/a", session_path = "a"}), "accepted a download without Dropbox-API-Result")
      		responses = {{status = 409, body = '{"error_summary":"path/not_file/.."}'}}
      		ok, err = pcall(c.download, {path = "/Docs", session_path = "docs"})
      		assert(not ok and string.find(tostring(err), "path/not_file", 1, true), tostring(err))
      		-- The session file system refuses the path before anything reaches Dropbox.
      		before = #requests
      		ok, err = pcall(c.download, {path = "/a", session_path = "../outside"})
      		assert(not ok and type(err) == "table" and err.code == "permission_denied", "accepted a session path outside the session")
      		assert(#requests == before, "a refused session path reached Dropbox")
      		assert(not pcall(c.download, {path = "/a"}), "download requires a session_path")
      		assert(#requests == before)
      		-- Opening a directory fails asynchronously and must not start an HTTP request.
      		local seed = fs.open("blocked/seed", "w")
      		await(seed:close())
      		assert(not pcall(c.download, {path = "/a", session_path = "blocked"}))
      		assert(#requests == before, "failed file opening reached Dropbox")
      		-- A transport failure must release the destination's writer reservation.
      		local original = http.request
      		http.request = function() error("request failed", 0) end
      		ok, err = pcall(c.download, {path = "/a", session_path = "failed-download"})
      		assert(not ok and string.find(tostring(err), "request failed", 1, true), tostring(err))
      		local retry = fs.open("failed-download", "w")
      		await(retry:close())
      		http.request = original
      		assert(#responses == 0)
      	end,
      }
      
    • scopes_narrowed.luau
      return {
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", granted_scopes = {"files.content.read","sharing.write",}},
      	run = function(c)
      		local expected = {}
      		expected.getTemporaryLink = true
      		expected.download = true
      		expected.downloadZip = true
      		expected.export = true
      		expected.getPreview = true
      		expected.getThumbnail = true
      		for name in expected do assert(type(c[name]) == "function", "missing permitted export: " .. name) end
      		for name in c do assert(name == "help" or expected[name], "unexpected export: " .. name) end
      	end,
      }
      
    • scopes_partial.luau
      return {
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", granted_scopes = {"files.metadata.read","sharing.read","files.content.write",}},
      	access = {files = "write", sharing = "write", file_requests = "write"},
      	run = function(c)
      		local expected = {}
      		expected.getAccount = true
      		expected.getMetadata = true
      		expected.listFolder = true
      		expected.listFolderContinue = true
      		expected.listFolderGetLatestCursor = true
      		expected.search = true
      		expected.searchContinue = true
      		expected.listRevisions = true
      		expected.createFolder = true
      		expected.upload = true
      		expected.saveUrl = true
      		expected.saveUrlCheckJobStatus = true
      		expected.move = true
      		expected.copy = true
      		expected.delete = true
      		expected.restore = true
      		expected.moveBatch = true
      		expected.moveBatchCheck = true
      		expected.copyBatch = true
      		expected.copyBatchCheck = true
      		expected.deleteBatch = true
      		expected.deleteBatchCheck = true
      		expected.listSharedLinks = true
      		expected.getSharedLinkMetadata = true
      		expected.getSharedLinkFile = true
      		expected.listSharedFolders = true
      		expected.listSharedFoldersContinue = true
      		expected.listMountableFolders = true
      		expected.listMountableFoldersContinue = true
      		expected.getSharedFolderMetadata = true
      		expected.listFolderMembers = true
      		expected.listFolderMembersContinue = true
      		expected.listReceivedFiles = true
      		expected.listReceivedFilesContinue = true
      		expected.getSharedFileMetadata = true
      		expected.listFileMembers = true
      		expected.listFileMembersContinue = true
      		expected.statFile = true
      		for name in expected do assert(type(c[name]) == "function", "missing permitted export: " .. name) end
      		for name in c do assert(name == "help" or expected[name], "unexpected export: " .. name) end
      	end,
      }
      
    • transfers.luau
      return {
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", auth_config = {}},
      	access = {files = "write", sharing = "write", file_requests = "write"},
      	configure = function()
      		requests, responses = {}, {}
      		fs = fixture.files()
      		local stat = fs.stat
      		fs.stat = function(path)
      			if path == "oversized.bin" then return fixture.operation({isFile = true, size = 150 * 1024 * 1024 + 1}) end
      			return stat(path)
      		end
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local body = table.remove(responses, 1)
      			return fixture.operation({statusCode = 200, headers = {["dropbox-api-result"] = {'{"id":"id:large","name":"large.bin"}'}}, body = body})
      		end}
      	end,
      	run = function(c)
      		-- A file larger than readAll's default limit must flow through native Reader/File streaming.
      		local size = 8 * 1024 * 1024 + 17
      		responses = {fixture.reader(string.rep("d", size))}
      		local saved = c.download({path = "/large.bin", session_path = "large.bin"})
      		assert(saved.size == size and saved.result.id == "id:large")
      		assert(requests[1].url == "https://content.dropboxapi.com/2/files/download")
      		local file = fs.open("large.bin", "r")
      		local total = 0
      		while true do
      			local chunk = await(file:read(1024 * 1024))
      			if chunk.done then break end
      			assert(chunk.data == string.rep("d", #chunk.data), "downloaded bytes changed")
      			total += #chunk.data
      		end
      		await(file:close())
      		assert(total == size)
      
      		local before = #requests
      		local ok, err = pcall(c.upload, {path = "/oversized.bin", session_path = "oversized.bin"})
      		assert(not ok and string.find(tostring(err), "at most 150 MiB", 1, true), tostring(err))
      		assert(#requests == before, "oversized upload reached Dropbox")
      
      		-- A native source failure surfaces at final close rather than returning a download URL.
      		responses = {gzip.decode(fixture.reader("not a gzip stream"))}
      		ok, err = pcall(c.download, {path = "/broken.bin", session_path = "broken.bin"})
      		assert(not ok, "a failed stream returned a successful download")
      		assert(#requests == before + 1 and #responses == 0)
      	end,
      }
      
    • writes.luau
      return {
      	scenario = {publisher = {client_id = "fixture-app-key", client_secret = "fixture-private-secret"}, auth_method = "oauth", granted_scopes = {"account_info.read", "files.metadata.read", "files.content.read", "sharing.read", "file_requests.read", "files.content.write", "sharing.write", "file_requests.write"}},
      	access = {files = "write", sharing = "write", file_requests = "write"},
      	configure = function()
      		requests, responses = {}, {}
      		fs = fixture.files()
      		http = {request = function(req)
      			for name in req.headers or {} do assert(string.lower(name) ~= "authorization", "credentials belong to the proxy") end
      			table.insert(requests, req)
      			if req.body ~= nil and type(req.body) ~= "string" then
      				local captured = fs.open("captured-upload", "w")
      				captured:write(req.body)
      				await(captured:close())
      				local input = fs.open("captured-upload", "r")
      				req.body = await(input:readAll())
      				await(input:close())
      			end
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			local response = table.remove(responses, 1)
      			return fixture.operation({statusCode = response.status or 200, headers = response.headers or {}, body = fixture.reader(response.body or "")})
      		end}
      	end,
      	run = function(c)
      		local API = "https://api.dropboxapi.com/2/"
      		local expected = {}
      		for _, name in {
      			"getCurrentAccount", "getSpaceUsage", "getAccount", "getMetadata",
      			"listFolder", "listFolderContinue", "listFolderGetLatestCursor", "search",
      			"searchContinue", "listRevisions", "getTemporaryLink", "download",
      			"downloadZip", "export", "getPreview", "getThumbnail",
      			"createFolder", "upload", "saveUrl", "saveUrlCheckJobStatus",
      			"move", "copy", "delete", "restore",
      			"moveBatch", "moveBatchCheck", "copyBatch", "copyBatchCheck",
      			"deleteBatch", "deleteBatchCheck", "listSharedLinks", "getSharedLinkMetadata",
      			"getSharedLinkFile", "createSharedLinkWithSettings", "modifySharedLinkSettings", "revokeSharedLink",
      			"listSharedFolders", "listSharedFoldersContinue", "listMountableFolders", "listMountableFoldersContinue",
      			"getSharedFolderMetadata", "listFolderMembers", "listFolderMembersContinue", "shareFolder",
      			"checkShareJobStatus", "addFolderMember", "updateFolderMember", "removeFolderMember",
      			"checkRemoveMemberJobStatus", "unshareFolder", "checkJobStatus", "mountFolder",
      			"unmountFolder", "relinquishFolderMembership", "listReceivedFiles", "listReceivedFilesContinue",
      			"getSharedFileMetadata", "listFileMembers", "listFileMembersContinue", "addFileMember",
      			"removeFileMember", "unshareFile", "relinquishFileMembership", "listFileRequests",
      			"listFileRequestsContinue", "getFileRequest", "createFileRequest", "updateFileRequest",
      			"deleteFileRequest", "statFile",
      		} do
      			expected[name] = true
      			assert(type(c[name]) == "function", "read-write lacks " .. name)
      		end
      		for name in c do assert(name == "help" or expected[name], "read-write exposes " .. name) end
      
      		-- Uploads stream the session file with the arguments in Dropbox-API-Arg.
      		local bytes = string.char(0, 255) .. "report"
      		local input = fs.open("uploads/report.pdf", "w")
      		input:write(bytes)
      		await(input:close())
      		responses = {{body = '{"id":"id:up","name":"report.pdf","rev":"015f"}'}}
      		local uploaded = c.upload({path = "/Reports/report.pdf", mode = "overwrite", session_path = "uploads/report.pdf"})
      		local req = requests[1]
      		assert(uploaded.id == "id:up")
      		assert(req.method == "POST" and req.url == "https://content.dropboxapi.com/2/files/upload" and req.body == bytes)
      		assert(req.headers["Content-Type"][1] == "application/octet-stream")
      		local arg = json.decode(req.headers["Dropbox-API-Arg"][1])
      		assert(arg.path == "/Reports/report.pdf" and arg.mode == "overwrite" and arg.session_path == nil)
      		assert(not pcall(c.upload, {path = "/Reports/report.pdf"}), "upload requires a session_path")
      		assert(not pcall(c.upload, {path = "/Reports", session_path = "uploads"}), "uploaded a directory")
      		assert(#requests == 1)
      
      		-- Writes post Dropbox's arguments unchanged, including nested unions and arrays.
      		responses = {{body = '{".tag":"async_job_id","async_job_id":"job-1"}'}, {body = '{".tag":"complete","entries":[]}'}}
      		local job = c.moveBatch({entries = {{from_path = "/a", to_path = "/b/a"}}, autorename = true})
      		assert(requests[2].url == API .. "files/move_batch_v2" and job.async_job_id == "job-1")
      		local sent = json.decode(requests[2].body)
      		assert(sent.entries[1].from_path == "/a" and sent.entries[1].to_path == "/b/a" and sent.autorename == true)
      		local status = c.moveBatchCheck({async_job_id = "job-1"})
      		assert(requests[3].url == API .. "files/move_batch/check_v2" and status[".tag"] == "complete" and json.encode(status.entries) == "[]")
      
      		-- A null result is a success; a list result stays a list.
      		responses = {{body = "null"}, {body = '[{"member":{".tag":"email","email":"[email protected]"},"result":{".tag":"success"}}]'}}
      		assert(c.revokeSharedLink({url = "https://www.dropbox.com/s/abc/a.txt"}).success == true)
      		assert(requests[4].url == API .. "sharing/revoke_shared_link")
      		local added = c.addFileMember({file = "id:a", members = {{[".tag"] = "email", email = "[email protected]"}}, quiet = true})
      		assert(added[1].result[".tag"] == "success" and added[1].member.email == "[email protected]")
      		sent = json.decode(requests[5].body)
      		assert(sent.members[1][".tag"] == "email" and sent.quiet == true)
      
      		responses = {{status = 409, body = '{"error_summary":"shared_link_already_exists/..","error":{".tag":"shared_link_already_exists"}}'}}
      		local ok, err = pcall(c.createSharedLinkWithSettings, {path = "/a.txt"})
      		assert(not ok and string.find(tostring(err), "shared_link_already_exists", 1, true), tostring(err))
      		-- Dropbox asks callers to retry contended writes.
      		responses = {{status = 409, body = '{"error_summary":"path/too_many_write_operations/.."}'}}
      		ok, err = pcall(c.move, {from_path = "/a", to_path = "/b"})
      		assert(not ok and string.find(tostring(err), '"retryable":true', 1, true), tostring(err))
      		assert(#responses == 0)
      	end,
      }