diff --git a/Cargo.lock b/Cargo.lock index d6ef499938..9d5b164ed6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7725,19 +7725,24 @@ dependencies = [ "csv", "flate2", "futures", + "getrandom 0.3.4", + "hmac 0.13.0", "num-bigint 0.4.8", "percent-encoding", "proptest", + "regex", "rust_xlsxwriter", "rustix", "rustls-pki-types", "secrecy", "serde", "serde_json", + "sha2 0.11.0", "sqlparser", "thiserror 2.0.20", "tokio", "tokio-util", + "unicode-segmentation", "unicode-width", "uuid", "winapi-util", @@ -7956,6 +7961,8 @@ dependencies = [ "futures", "russh", "secrecy", + "serde_json", + "tablepro-account", "tablepro-core", "tablepro-driver-cassandra", "tablepro-driver-clickhouse", diff --git a/Cargo.toml b/Cargo.toml index 98d254b261..d1fe00c6dd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,6 +61,7 @@ async-trait = "0.1" thiserror = "2" serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["raw_value"] } +regex = "1" # Edits a TOML config file and keeps its comments and layout. toml_edit = "0.25.15" sqlparser = { version = "0.63", default-features = false, features = ["std"] } @@ -106,6 +107,8 @@ comfy-table = "8.0" unicode-width = "0.2" # Folds accents out of a name for the Finder-like order the Apple apps sort a library by. unicode-normalization = "0.1.25" +# Extended grapheme clusters, the characters a masking rule and a mask count in, as Swift counts them. +unicode-segmentation = "1.13" # No zlib feature: it pulls libz-sys, and the pure-Rust deflate keeps # the build free of another C dependency. Constant memory lets a sheet # spill its rows to a temporary file instead of holding them. @@ -168,13 +171,15 @@ glib-build-tools = "0.22" uuid = { version = "1", features = ["v4", "serde"] } url = "2" percent-encoding = "2" -# The Windows Credential Manager, where the core keeps secrets on Windows, and the -# owning process of a loopback connection, from GetExtendedTcpTable. +# The Windows Credential Manager, where the core keeps secrets on Windows, the +# owning process of a loopback connection, from GetExtendedTcpTable, and the +# MachineGuid the TablePro account derives the machine ID from. windows-sys = { version = "0.61", features = [ "Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security_Credentials", + "Win32_System_Registry", ] } # What other apps' saved connections are kept in: binary and XML property # lists, XML, and the fixed-key ciphers those apps use for passwords. @@ -187,6 +192,8 @@ salsa20 = "0.10" chacha20 = "0.9" sha1 = "0.11" sha2 = "0.11" +# A masked value's Stable Hash, HMAC-SHA256 as the macOS app computes it. +hmac = "0.13" hex = "0.4" flate2 = { version = "1", default-features = false, features = ["rust_backend"] } zeroize = "1.9" diff --git a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml index fb565cf1e3..830c571e32 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml +++ b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml @@ -13,3 +13,7 @@ filter: - issue-entitlement - list-library-changes - push-library-changes + - get-share-limits + - list-shares + - delete-share + - get-shared diff --git a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json index a3af459ea3..9bb6346f8f 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json +++ b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json @@ -112,6 +112,83 @@ ], "type": "object" }, + "CreateShareBody": { + "additionalProperties": false, + "properties": { + "allow_download": { + "description": "Defaults to true; false needs Pro", + "type": "boolean" + }, + "dialect": { + "description": "The SQL dialect, for display", + "maxLength": 40, + "type": "string" + }, + "expiry": { + "$ref": "#/components/schemas/ShareExpiry", + "description": "Omit for the plan's default_expiry" + }, + "hide_sql": { + "description": "Only with kind result", + "type": "boolean" + }, + "kind": { + "$ref": "#/components/schemas/ShareKind" + }, + "note": { + "maxLength": 2000, + "type": "string" + }, + "password": { + "description": "Needs Pro", + "maxLength": 128, + "type": "string" + }, + "snapshot": { + "$ref": "#/components/schemas/SnapshotBody", + "description": "Required with kind result, refused with kind query" + }, + "sql": { + "description": "Always stored; the viewer hides it with hide_sql. May be empty for a result share, which then shares its data alone", + "maxLength": 262144, + "type": "string" + }, + "team_id": { + "description": "Team TypeID for a team link; needs Pro, a seat, and a team that allows public links", + "type": "string" + }, + "title": { + "maxLength": 200, + "type": "string" + } + }, + "required": [ + "kind", + "sql" + ], + "type": "object" + }, + "CreatedShare": { + "properties": { + "share": { + "$ref": "#/components/schemas/ShareView" + }, + "token": { + "description": "The raw link token, 43 base62 characters", + "type": "string" + }, + "url": { + "description": "SHARE_BASE_URL/token", + "type": "string" + } + }, + "required": [ + "share", + "token", + "url" + ], + "type": "object" + }, "Cycle": { "enum": [ "monthly", @@ -174,15 +251,17 @@ "type": "string" }, "platform": { - "description": "Extensible enum: macos, linux", + "description": "Extensible enum: macos, linux, windows", "examples": [ "macos", - "linux" + "linux", + "windows" ], "type": "string", "x-extensible-enum": [ "macos", - "linux" + "linux", + "windows" ] } }, @@ -772,19 +851,23 @@ "type": "string" }, "source": { - "description": "Extensible enum: subscription, order, manual, legacy", + "description": "Extensible enum: subscription, order, manual, legacy, redeem_code, education", "examples": [ "subscription", "order", "manual", - "legacy" + "legacy", + "redeem_code", + "education" ], "type": "string", "x-extensible-enum": [ "subscription", "order", "manual", - "legacy" + "legacy", + "redeem_code", + "education" ] }, "status": { @@ -867,15 +950,17 @@ "type": "string" }, "platform": { - "description": "Extensible enum: macos, linux", + "description": "Extensible enum: macos, linux, windows", "examples": [ "macos", - "linux" + "linux", + "windows" ], "type": "string", "x-extensible-enum": [ "macos", - "linux" + "linux", + "windows" ] } }, @@ -1046,7 +1131,7 @@ "NewsletterStats": { "properties": { "subscribers": { - "description": "Contacts in the newsletter segment who have not unsubscribed, counted at most once an hour", + "description": "Subscribers no suppression holds back, counted at most once an hour", "format": "int64", "minimum": 0, "type": "integer" @@ -1060,6 +1145,11 @@ "NewsletterSubscriptionRequest": { "additionalProperties": false, "properties": { + "consent_version": { + "description": "Names the consent text the form showed", + "maxLength": 32, + "type": "string" + }, "email": { "format": "email", "maxLength": 254, @@ -1070,6 +1160,11 @@ "maxLength": 16, "type": "string" }, + "source": { + "description": "URL of the page whose form was sent; kept in the consent log when it is on the public site, else the public site's origin is", + "maxLength": 2048, + "type": "string" + }, "turnstile_token": { "description": "Token from the Turnstile widget, action newsletter", "maxLength": 2048, @@ -1190,7 +1285,8 @@ "Platform": { "enum": [ "macos", - "linux" + "linux", + "windows" ], "type": "string" }, @@ -1203,6 +1299,9 @@ ], "type": "string" }, + "education": { + "$ref": "#/components/schemas/PricingEducation" + }, "plans": { "items": { "$ref": "#/components/schemas/PlanPrice" @@ -1212,7 +1311,20 @@ }, "required": [ "country", - "plans" + "plans", + "education" + ], + "type": "object" + }, + "PricingEducation": { + "properties": { + "open": { + "description": "Whether students and teachers can claim Pro free with a school address now", + "type": "boolean" + } + }, + "required": [ + "open" ], "type": "object" }, @@ -1244,6 +1356,11 @@ "null" ] }, + "live_limit": { + "description": "With share_limit_reached: the most live links the plan allows", + "format": "int64", + "type": "integer" + }, "status": { "description": "HTTP status code", "format": "int64", @@ -1267,220 +1384,2331 @@ ], "type": "object" }, - "Seats": { - "properties": { - "available": { - "description": "total minus used and reserved; below zero when the pool shrank under what is in use", - "format": "int64", - "type": "integer" - }, - "reserved": { - "description": "Pending invitations that include a seat, expired ones included", - "format": "int64", - "minimum": 0, - "type": "integer" - }, - "total": { - "description": "Seats on the team's active licenses", - "format": "int64", - "minimum": 0, - "type": "integer" - }, - "used": { - "description": "Members holding a seat", - "format": "int64", - "minimum": 0, - "type": "integer" - } - }, - "required": [ - "total", - "used", - "reserved", - "available" - ], - "type": "object" - }, - "Team": { + "PublicColumn": { "properties": { - "has_seat": { - "description": "Whether the caller holds one of the team's seats", - "type": "boolean" - }, - "id": { - "description": "Team TypeID", + "masked": { + "description": "Extensible enum: full, lastFour, email, hash, null. How the app masked the column's values before sharing; absent for an unmasked column", "examples": [ - "team_01jbvh7pn9e3sv4bzq4rqk4kzh" + "full", + "lastFour", + "email", + "hash", + "null" ], - "type": "string" + "type": "string", + "x-extensible-enum": [ + "full", + "lastFour", + "email", + "hash", + "null" + ] }, "name": { - "examples": [ - "Acme" - ], "type": "string" }, - "role": { - "description": "Extensible enum: owner, admin, member. The caller's role", - "examples": [ - "owner", - "admin", - "member" - ], - "type": "string", - "x-extensible-enum": [ - "owner", - "admin", - "member" - ] + "type": { + "type": "string" } }, "required": [ - "id", "name", - "role", - "has_seat" + "type" ], "type": "object" }, - "TeamDetail": { + "PublicShare": { "properties": { - "has_seat": { - "description": "Whether the caller holds a seat; absent for a team API token", + "allow_download": { "type": "boolean" }, - "id": { - "description": "Team TypeID", - "examples": [ - "team_01jbvh7pn9e3sv4bzq4rqk4kzh" - ], + "created_at": { + "format": "date-time", "type": "string" }, - "name": { - "examples": [ - "Acme" - ], + "dialect": { "type": "string" }, - "role": { - "description": "Extensible enum: owner, admin, member. The caller's role; absent for a team API token", + "expires_at": { + "format": "date-time", + "type": "string" + }, + "kind": { + "description": "Extensible enum: query, result", "examples": [ - "owner", - "admin", - "member" + "query", + "result" ], "type": "string", "x-extensible-enum": [ - "owner", - "admin", - "member" + "query", + "result" ] }, - "seats": { - "$ref": "#/components/schemas/Seats" + "made_with": { + "description": "Attribution the viewer page shows", + "type": "string" + }, + "note": { + "type": "string" + }, + "snapshot": { + "$ref": "#/components/schemas/PublicSnapshot" + }, + "sql": { + "description": "Absent when the owner hid it", + "type": "string" + }, + "title": { + "type": "string" } }, "required": [ - "id", - "name", - "seats" + "kind", + "title", + "note", + "dialect", + "created_at", + "allow_download", + "made_with" ], "type": "object" }, - "TeamList": { + "PublicSnapshot": { "properties": { - "data": { + "columns": { "items": { - "$ref": "#/components/schemas/Team" + "$ref": "#/components/schemas/PublicColumn" }, "type": "array" }, - "next_cursor": { - "description": "Pass as cursor for the next page; absent on the last page", - "type": "string" + "row_count": { + "description": "The rows the query returned, which may be more than those shown; null when the app cut the result without knowing its total", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "rows": { + "description": "An integer outside plus or minus 2^53-1 arrives as a string of its digits", + "items": { + "items": {}, + "type": [ + "array", + "null" + ] + }, + "type": "array" + }, + "truncated": { + "type": "boolean" } }, "required": [ - "data" + "columns", + "rows", + "row_count", + "truncated" ], "type": "object" }, - "TeamRef": { + "ReportAccepted": { + "type": "object" + }, + "ReportShareBody": { + "additionalProperties": false, "properties": { - "id": { - "description": "Team TypeID", - "examples": [ - "team_01jbvh7pn9e3sv4bzq4rqk4kzh" - ], + "contact_email": { + "description": "Where staff may answer; optional", + "maxLength": 254, "type": "string" }, - "name": { - "examples": [ - "Acme" - ], + "details": { + "maxLength": 2000, + "type": "string" + }, + "reason": { + "$ref": "#/components/schemas/ShareReportReason" + }, + "turnstile_token": { + "description": "The token of the viewer's Turnstile widget, rendered with the action share_report; a missing or rejected one answers human_check_failed", + "maxLength": 2048, "type": "string" } }, "required": [ - "id", - "name" + "reason" ], "type": "object" - } - }, - "securitySchemes": { - "oauth": { - "description": "An access token from the TablePro app's sign-in.", - "flows": { - "authorizationCode": { - "authorizationUrl": "https://account.tablepro.app/oauth/authorize", - "refreshUrl": "https://account.tablepro.app/oauth/token", - "scopes": { - "app": "Use the API as the TablePro app" - }, - "tokenUrl": "https://account.tablepro.app/oauth/token" + }, + "Seats": { + "properties": { + "available": { + "description": "total minus used and reserved; below zero when the pool shrank under what is in use", + "format": "int64", + "type": "integer" + }, + "reserved": { + "description": "Pending invitations that include a seat, expired ones included", + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "total": { + "description": "Seats on the team's active licenses", + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "used": { + "description": "Members holding a seat", + "format": "int64", + "minimum": 0, + "type": "integer" } }, - "type": "oauth2" - }, - "team_token": { - "bearerFormat": "tpt_...", + "required": [ + "total", + "used", + "reserved", + "available" + ], + "type": "object" + }, + "ShareExpiry": { + "enum": [ + "1d", + "7d", + "30d", + "never" + ], + "type": "string" + }, + "ShareKind": { + "enum": [ + "query", + "result" + ], + "type": "string" + }, + "ShareLimits": { + "properties": { + "default_expiry": { + "description": "Extensible enum: 1d, 7d, 30d, never. The expiry a create without one gets", + "examples": [ + "1d", + "7d", + "30d", + "never" + ], + "type": "string", + "x-extensible-enum": [ + "1d", + "7d", + "30d", + "never" + ] + }, + "disable_download": { + "description": "The plan allows turning viewer downloads off", + "type": "boolean" + }, + "email_verified": { + "description": "false: every create answers email_unverified", + "type": "boolean" + }, + "expiries": { + "description": "The expiries the plan allows", + "items": { + "description": "Extensible enum: 1d, 7d, 30d, never", + "examples": [ + "1d", + "7d", + "30d", + "never" + ], + "type": "string", + "x-extensible-enum": [ + "1d", + "7d", + "30d", + "never" + ] + }, + "type": "array" + }, + "live": { + "description": "The account's live personal links", + "format": "int64", + "type": "integer" + }, + "live_limit": { + "description": "The most live personal links the plan allows", + "format": "int64", + "type": "integer" + }, + "max_rows": { + "description": "The most snapshot rows the plan keeps; the server cuts the rest", + "format": "int64", + "type": "integer" + }, + "password": { + "description": "The plan allows a link password", + "type": "boolean" + }, + "plan": { + "description": "Extensible enum: free, pro", + "examples": [ + "free", + "pro" + ], + "type": "string", + "x-extensible-enum": [ + "free", + "pro" + ] + }, + "sharing_disabled": { + "description": "true: every create answers sharing_disabled", + "type": "boolean" + }, + "team": { + "description": "The plan allows team links", + "type": "boolean" + }, + "teams": { + "description": "The teams the caller holds a seat in, for a team link; empty on Free", + "items": { + "$ref": "#/components/schemas/ShareTeam" + }, + "type": "array" + } + }, + "required": [ + "plan", + "live", + "live_limit", + "max_rows", + "expiries", + "default_expiry", + "password", + "disable_download", + "team", + "email_verified", + "sharing_disabled", + "teams" + ], + "type": "object" + }, + "ShareList": { + "properties": { + "data": { + "description": "Newest first", + "items": { + "$ref": "#/components/schemas/ShareView" + }, + "type": "array" + }, + "next_cursor": { + "description": "Pass as cursor for the next page; absent on the last page", + "type": "string" + } + }, + "required": [ + "data" + ], + "type": "object" + }, + "ShareListState": { + "enum": [ + "live", + "all" + ], + "type": "string" + }, + "ShareMaskStyle": { + "enum": [ + "full", + "lastFour", + "email", + "hash", + "null" + ], + "type": "string" + }, + "ShareReportReason": { + "enum": [ + "illegal", + "malware_phishing", + "personal_data", + "spam", + "copyright", + "other" + ], + "type": "string" + }, + "ShareTeam": { + "properties": { + "id": { + "description": "Team TypeID, the create's team_id", + "type": "string" + }, + "live": { + "description": "The team's live links", + "format": "int64", + "type": "integer" + }, + "live_limit": { + "description": "The most live links a team may hold", + "format": "int64", + "type": "integer" + }, + "name": { + "type": "string" + }, + "public_links": { + "description": "false: the team turned public links off, and a team link answers team_sharing_disabled", + "type": "boolean" + } + }, + "required": [ + "id", + "name", + "live", + "live_limit", + "public_links" + ], + "type": "object" + }, + "ShareView": { + "properties": { + "allow_download": { + "description": "The viewer offers CSV and JSON downloads", + "type": "boolean" + }, + "created_at": { + "format": "date-time", + "type": "string" + }, + "dialect": { + "description": "The SQL dialect, for display", + "type": "string" + }, + "expires_at": { + "description": "Absent for a link that never expires", + "format": "date-time", + "type": "string" + }, + "has_password": { + "type": "boolean" + }, + "has_snapshot": { + "description": "true for a result share", + "type": "boolean" + }, + "hide_sql": { + "description": "The viewer shows the result without its SQL", + "type": "boolean" + }, + "id": { + "description": "Share TypeID", + "examples": [ + "shr_01jbvh7pn9e3sv4bzq4rqk4kzh" + ], + "type": "string" + }, + "kind": { + "description": "Extensible enum: query, result", + "examples": [ + "query", + "result" + ], + "type": "string", + "x-extensible-enum": [ + "query", + "result" + ] + }, + "note": { + "type": "string" + }, + "removed_at": { + "format": "date-time", + "type": "string" + }, + "removed_reason": { + "description": "With state removed: why TablePro removed the link", + "type": "string" + }, + "revoked_at": { + "format": "date-time", + "type": "string" + }, + "row_count": { + "description": "With a snapshot: the rows the query returned, which may be more than those shared; null when the app cut the result without knowing its total", + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "scope": { + "description": "Extensible enum: account, team. account: a personal link; team: a team link", + "examples": [ + "account", + "team" + ], + "type": "string", + "x-extensible-enum": [ + "account", + "team" + ] + }, + "sql": { + "description": "Only in the answer for one share, never in a list", + "type": "string" + }, + "state": { + "description": "Extensible enum: live, expired, revoked, removed. live, or why the link no longer resolves", + "examples": [ + "live", + "expired", + "revoked", + "removed" + ], + "type": "string", + "x-extensible-enum": [ + "live", + "expired", + "revoked", + "removed" + ] + }, + "suspended": { + "description": "true while the team turned public links off or staff turned the creator's sharing off: the link does not resolve and has no url, and comes back when the switch is on again", + "type": "boolean" + }, + "suspended_by": { + "description": "Extensible enum: account, team, team_deleted. With suspended: account (staff turned the creator's sharing off), team (the team turned public links off) or team_deleted (its owner deleted the team); team_deleted wins, then account", + "examples": [ + "account", + "team", + "team_deleted" + ], + "type": "string", + "x-extensible-enum": [ + "account", + "team", + "team_deleted" + ] + }, + "team_id": { + "description": "Team TypeID, for a team link", + "type": "string" + }, + "title": { + "type": "string" + }, + "truncated": { + "description": "With a snapshot: true when the server kept fewer rows than row_count", + "type": "boolean" + }, + "updated_at": { + "format": "date-time", + "type": "string" + }, + "url": { + "description": "The link; present only for a caller who manages the share, and only while the server can rebuild it", + "type": "string" + }, + "view_count": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "id", + "kind", + "scope", + "title", + "note", + "dialect", + "has_snapshot", + "hide_sql", + "allow_download", + "has_password", + "state", + "suspended", + "view_count", + "created_at", + "updated_at" + ], + "type": "object" + }, + "SnapshotBody": { + "additionalProperties": false, + "properties": { + "columns": { + "items": { + "$ref": "#/components/schemas/SnapshotColumnBody" + }, + "maxItems": 100, + "minItems": 1, + "type": "array" + }, + "more_rows": { + "description": "The app holds rows past those sent; with no row_count above them, the total is stored as unknown", + "type": "boolean" + }, + "row_count": { + "description": "The rows the query returned, when more than those sent", + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "rows": { + "description": "One array per row, one value per column. The server keeps the plan's max_rows and cuts the rest", + "items": { + "items": {}, + "type": [ + "array", + "null" + ] + }, + "type": "array" + } + }, + "required": [ + "columns", + "rows" + ], + "type": "object" + }, + "SnapshotColumnBody": { + "additionalProperties": false, + "properties": { + "masked": { + "$ref": "#/components/schemas/ShareMaskStyle", + "description": "How the app masked the column's values before sharing; omit for an unmasked column" + }, + "name": { + "maxLength": 256, + "type": "string" + }, + "type": { + "description": "The column's database type, for display and alignment", + "maxLength": 256, + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "Team": { + "properties": { + "has_seat": { + "description": "Whether the caller holds one of the team's seats", + "type": "boolean" + }, + "id": { + "description": "Team TypeID", + "examples": [ + "team_01jbvh7pn9e3sv4bzq4rqk4kzh" + ], + "type": "string" + }, + "name": { + "examples": [ + "Acme" + ], + "type": "string" + }, + "role": { + "description": "Extensible enum: owner, admin, member. The caller's role", + "examples": [ + "owner", + "admin", + "member" + ], + "type": "string", + "x-extensible-enum": [ + "owner", + "admin", + "member" + ] + } + }, + "required": [ + "id", + "name", + "role", + "has_seat" + ], + "type": "object" + }, + "TeamDetail": { + "properties": { + "has_seat": { + "description": "Whether the caller holds a seat; absent for a team API token", + "type": "boolean" + }, + "id": { + "description": "Team TypeID", + "examples": [ + "team_01jbvh7pn9e3sv4bzq4rqk4kzh" + ], + "type": "string" + }, + "name": { + "examples": [ + "Acme" + ], + "type": "string" + }, + "role": { + "description": "Extensible enum: owner, admin, member. The caller's role; absent for a team API token", + "examples": [ + "owner", + "admin", + "member" + ], + "type": "string", + "x-extensible-enum": [ + "owner", + "admin", + "member" + ] + }, + "seats": { + "$ref": "#/components/schemas/Seats" + } + }, + "required": [ + "id", + "name", + "seats" + ], + "type": "object" + }, + "TeamList": { + "properties": { + "data": { + "items": { + "$ref": "#/components/schemas/Team" + }, + "type": "array" + }, + "next_cursor": { + "description": "Pass as cursor for the next page; absent on the last page", + "type": "string" + } + }, + "required": [ + "data" + ], + "type": "object" + }, + "TeamRef": { + "properties": { + "id": { + "description": "Team TypeID", + "examples": [ + "team_01jbvh7pn9e3sv4bzq4rqk4kzh" + ], + "type": "string" + }, + "name": { + "examples": [ + "Acme" + ], + "type": "string" + } + }, + "required": [ + "id", + "name" + ], + "type": "object" + }, + "UpdateShareBody": { + "additionalProperties": false, + "properties": { + "allow_download": { + "description": "false needs Pro", + "type": "boolean" + }, + "clear_password": { + "description": "Remove the password", + "type": "boolean" + }, + "expiry": { + "$ref": "#/components/schemas/ShareExpiry", + "description": "A new expiry from now. On an expired link it revives the link when a live slot is free" + }, + "hide_sql": { + "description": "Only on a result share", + "type": "boolean" + }, + "note": { + "maxLength": 2000, + "type": "string" + }, + "password": { + "description": "A new password; needs Pro", + "maxLength": 128, + "minLength": 1, + "type": "string" + }, + "title": { + "maxLength": 200, + "type": "string" + } + }, + "type": "object" + } + }, + "securitySchemes": { + "oauth": { + "description": "An access token from the TablePro app's sign-in.", + "flows": { + "authorizationCode": { + "authorizationUrl": "https://account.tablepro.app/oauth/authorize", + "refreshUrl": "https://account.tablepro.app/oauth/token", + "scopes": { + "app": "Use the API as the TablePro app" + }, + "tokenUrl": "https://account.tablepro.app/oauth/token" + } + }, + "type": "oauth2" + }, + "team_token": { + "bearerFormat": "tpt_...", "description": "A team API token, created by the team's owner or admins in the portal.", "scheme": "bearer", "type": "http" } - } - }, - "info": { - "title": "TablePro API", - "version": "2" - }, - "openapi": "3.1.0", - "paths": { - "/checkouts": { - "post": { - "description": "Creates Polar's checkout for a guest. The price is the catalog's, less the discount code's discount or, without a code, the regional discount GET /pricing shows; tax and currency follow the caller's IP address.", - "operationId": "create-checkout", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CheckoutRequest" + } + }, + "info": { + "title": "TablePro API", + "version": "2" + }, + "openapi": "3.1.0", + "paths": { + "/checkouts": { + "post": { + "description": "Creates Polar's checkout for a guest. The price is the catalog's, less the discount code's discount or, without a code, the regional discount GET /pricing shows; tax and currency follow the caller's IP address.", + "operationId": "create-checkout", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CheckoutRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Checkout" + } + } + }, + "description": "Created", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "summary": "Start a checkout", + "tags": [ + "Checkout" + ] + } + }, + "/devices": { + "get": { + "description": "Every device that was not removed, oldest first.", + "operationId": "list-devices", + "parameters": [ + { + "description": "Devices per page", + "explode": false, + "in": "query", + "name": "limit", + "schema": { + "default": 50, + "description": "Devices per page", + "format": "int64", + "maximum": 200, + "minimum": 1, + "type": "integer" + } + }, + { + "description": "next_cursor of the previous page; absent for the first page", + "explode": false, + "in": "query", + "name": "cursor", + "schema": { + "description": "next_cursor of the previous page; absent for the first page", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeviceList" + } + } + }, + "description": "OK", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "type": "https://api.tablepro.app/problems/unauthorized", + "title": "Unauthorized", + "status": 401, + "code": "unauthorized", + "detail": "The token is invalid or has expired." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "The token lacks the app scope." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation_failed": { + "summary": "Validation failed", + "value": { + "type": "https://api.tablepro.app/problems/validation-failed", + "title": "Validation failed", + "status": 422, + "code": "validation_failed", + "detail": "validation failed", + "errors": [ + { + "message": "expected the next_cursor of a previous page", + "location": "query.cursor", + "value": "abc" + } + ] + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "type": "https://api.tablepro.app/problems/rate-limited", + "title": "Rate limited", + "status": 429, + "code": "rate_limited", + "detail": "Too many requests. Try again later." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "The account's devices", + "tags": [ + "Devices" + ] + }, + "post": { + "description": "Registers the machine the app runs on, or updates the account's device for it, and binds the refresh token family of the caller's sign-in to the device: access tokens refreshed afterwards carry dev, which the entitlement needs. Answers 201 for a new device and 200 when the machine was registered already. A sign-in already bound to another device is refused. 10 an hour per account.", + "operationId": "register-device", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeviceRegistration" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Device" + } + } + }, + "description": "The machine was registered already; its name, platform and versions are updated", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Device" + } + } + }, + "description": "Created", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "type": "https://api.tablepro.app/problems/unauthorized", + "title": "Unauthorized", + "status": 401, + "code": "unauthorized", + "detail": "The token is invalid or has expired." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "The token lacks the app scope." + } + }, + "forbidden_2": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "This sign-in belongs to another device. Sign in again on this one." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation_failed": { + "summary": "Validation failed", + "value": { + "type": "https://api.tablepro.app/problems/validation-failed", + "title": "Validation failed", + "status": 422, + "code": "validation_failed", + "detail": "validation failed", + "errors": [ + { + "message": "expected string to match pattern ^[0-9a-f]{64}$", + "location": "body.machine_id", + "value": "MAC-1" + } + ] + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "type": "https://api.tablepro.app/problems/rate-limited", + "title": "Rate limited", + "status": 429, + "code": "rate_limited", + "detail": "Too many requests. Try again later." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "Register this device", + "tags": [ + "Devices" + ] + } + }, + "/devices/{device_id}": { + "delete": { + "description": "Frees its license slot and revokes its refresh tokens, so the app on it signs out at its next refresh. Its entitlement stays valid until it expires. A device with an offline file that has not expired (offline_until) keeps its slot until its last valid file expires and is refused with offline_file_active.", + "operationId": "delete-device", + "parameters": [ + { + "description": "Device TypeID", + "in": "path", + "name": "device_id", + "required": true, + "schema": { + "description": "Device TypeID", + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "No Content", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "type": "https://api.tablepro.app/problems/unauthorized", + "title": "Unauthorized", + "status": 401, + "code": "unauthorized", + "detail": "The token is invalid or has expired." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "The token lacks the app scope." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/problem+json": { + "examples": { + "not_found": { + "summary": "Not found", + "value": { + "type": "https://api.tablepro.app/problems/not-found", + "title": "Not found", + "status": 404, + "code": "not_found", + "detail": "This account has no such device." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "409": { + "content": { + "application/problem+json": { + "examples": { + "offline_file_active": { + "summary": "Offline file active", + "value": { + "type": "https://api.tablepro.app/problems/offline-file-active", + "title": "Offline file active", + "status": 409, + "code": "offline_file_active", + "detail": "This device's offline file has not expired, so it keeps its license slot until offline_until." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Conflict" + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "type": "https://api.tablepro.app/problems/rate-limited", + "title": "Rate limited", + "status": 429, + "code": "rate_limited", + "detail": "Too many requests. Try again later." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "Remove a device", + "tags": [ + "Devices" + ] + }, + "patch": { + "operationId": "update-device", + "parameters": [ + { + "description": "Device TypeID", + "in": "path", + "name": "device_id", + "required": true, + "schema": { + "description": "Device TypeID", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeviceUpdate" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Device" + } + } + }, + "description": "OK", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "type": "https://api.tablepro.app/problems/unauthorized", + "title": "Unauthorized", + "status": 401, + "code": "unauthorized", + "detail": "The token is invalid or has expired." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "The token lacks the app scope." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/problem+json": { + "examples": { + "not_found": { + "summary": "Not found", + "value": { + "type": "https://api.tablepro.app/problems/not-found", + "title": "Not found", + "status": 404, + "code": "not_found", + "detail": "This account has no such device." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "validation_failed": { + "summary": "Validation failed", + "value": { + "type": "https://api.tablepro.app/problems/validation-failed", + "title": "Validation failed", + "status": 422, + "code": "validation_failed", + "detail": "validation failed", + "errors": [ + { + "message": "expected a name of 1 to 100 characters", + "location": "body.name", + "value": "\t" + } + ] + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "type": "https://api.tablepro.app/problems/rate-limited", + "title": "Rate limited", + "status": 429, + "code": "rate_limited", + "detail": "Too many requests. Try again later." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "Rename a device", + "tags": [ + "Devices" + ] + } + }, + "/devices/{device_id}/entitlement": { + "post": { + "description": "Answers only for the device the caller's token is bound to: register the device, refresh the token, then ask. When the account has a license and the device holds none of its 3 slots, the device takes one, or the answer is device_limit_reached with the devices that hold them. An account without licenses gets a token with no features.", + "operationId": "issue-entitlement", + "parameters": [ + { + "description": "Device TypeID; must be the device the caller's token is bound to (its dev claim)", + "in": "path", + "name": "device_id", + "required": true, + "schema": { + "description": "Device TypeID; must be the device the caller's token is bound to (its dev claim)", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EntitlementRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Entitlement" + } + } + }, + "description": "OK", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "type": "https://api.tablepro.app/problems/unauthorized", + "title": "Unauthorized", + "status": 401, + "code": "unauthorized", + "detail": "The token is invalid or has expired." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "account_locked": { + "summary": "Account locked", + "value": { + "type": "https://api.tablepro.app/problems/account-locked", + "title": "Account locked", + "status": 403, + "code": "account_locked", + "detail": "This account is locked." + } + }, + "device_revoked": { + "summary": "Device revoked", + "value": { + "type": "https://api.tablepro.app/problems/device-revoked", + "title": "Device revoked", + "status": 403, + "code": "device_revoked", + "detail": "This device was removed from the account. Sign in again to use it." + } + }, + "forbidden": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "The token lacks the app scope." + } + }, + "forbidden_2": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "This token is not bound to that device. Register this device, refresh the token, and ask again." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "409": { + "content": { + "application/problem+json": { + "examples": { + "device_limit_reached": { + "summary": "Device limit reached", + "value": { + "type": "https://api.tablepro.app/problems/device-limit-reached", + "title": "Device limit reached", + "status": 409, + "code": "device_limit_reached", + "detail": "The license is already used on 3 devices.", + "devices": [ + { + "id": "dev_01k8djrfaefw08m00000000001", + "machine_id": "0000000000000000000000000000000000000000000000000000000000000001", + "platform": "macos", + "name": "Ada's MacBook Pro", + "app_version": "2.0.0", + "os_version": "26.0", + "licensed_at": "2026-10-01T09:00:00Z", + "created_at": "2026-10-01T09:00:00Z", + "last_seen_at": "2026-10-21T09:00:00Z" + }, + { + "id": "dev_01k8djrfaefw08m00000000002", + "machine_id": "0000000000000000000000000000000000000000000000000000000000000002", + "platform": "macos", + "name": "Studio", + "app_version": "2.0.0", + "os_version": "26.0", + "licensed_at": "2026-10-02T09:00:00Z", + "offline_until": "2027-10-02T09:00:00Z", + "created_at": "2026-10-02T09:00:00Z", + "last_seen_at": "2026-10-22T09:00:00Z" + }, + { + "id": "dev_01k8djrfaefw08m00000000003", + "machine_id": "0000000000000000000000000000000000000000000000000000000000000003", + "platform": "linux", + "name": "Workstation", + "app_version": "2.0.0", + "os_version": "Fedora 43", + "licensed_at": "2026-10-03T09:00:00Z", + "created_at": "2026-10-03T09:00:00Z", + "last_seen_at": "2026-10-23T09:00:00Z" + } + ] + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Conflict" + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "type": "https://api.tablepro.app/problems/rate-limited", + "title": "Rate limited", + "status": 429, + "code": "rate_limited", + "detail": "Too many requests. Try again later." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "An entitlement for this device", + "tags": [ + "Devices" + ] + } + }, + "/discounts/preview": { + "post": { + "description": "Answers whether checkout would apply the code, and how much it takes off. An unknown code is not an error.", + "operationId": "preview-discount", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiscountPreviewRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiscountPreview" + } + } + }, + "description": "OK", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "summary": "Check a discount code", + "tags": [ + "Checkout" + ] + } + }, + "/me": { + "get": { + "description": "The account, the teams it belongs to with its role and seat in each, and the licenses whose features it can use.", + "operationId": "get-me", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Me" + } + } + }, + "description": "OK", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/problem+json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "type": "https://api.tablepro.app/problems/unauthorized", + "title": "Unauthorized", + "status": 401, + "code": "unauthorized", + "detail": "The token is invalid or has expired." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "The token lacks the app scope." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "429": { + "content": { + "application/problem+json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "type": "https://api.tablepro.app/problems/rate-limited", + "title": "Rate limited", + "status": 429, + "code": "rate_limited", + "detail": "Too many requests. Try again later." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "The signed-in account", + "tags": [ + "Account" + ] + } + }, + "/newsletter/stats": { + "get": { + "operationId": "get-newsletter-stats", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewsletterStats" + } + } + }, + "description": "OK" + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Service Unavailable" + } + }, + "summary": "Count the newsletter's subscribers", + "tags": [ + "Newsletter" + ] + } + }, + "/newsletter/subscriptions": { + "post": { + "description": "Emails a confirmation link. Answers 202 whether or not the address is subscribed and whether or not the Turnstile check passed, so it reveals nothing.", + "operationId": "create-newsletter-subscription", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewsletterSubscriptionRequest" + } + } + }, + "required": true + }, + "responses": { + "202": { + "description": "Accepted", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "summary": "Sign up for the newsletter", + "tags": [ + "Newsletter" + ] + } + }, + "/pricing": { + "get": { + "description": "What checkout charges the caller without a discount code, regional discount included. Answered for the caller's country, so it is never cached.", + "operationId": "get-pricing", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pricing" + } + } + }, + "description": "OK", + "headers": { + "Cache-Control": { + "schema": { + "type": "string" + } } } }, - "required": true + "422": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } }, + "summary": "Prices in the caller's country", + "tags": [ + "Checkout" + ] + } + }, + "/share-limits": { + "get": { + "description": "What the share sheet offers: the plan, its live link count and limit, row cap, expiries and options, and whether the account may create at all.", + "operationId": "get-share-limits", "responses": { - "201": { + "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Checkout" + "$ref": "#/components/schemas/ShareLimits" } } }, - "description": "Created", + "description": "OK", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -1493,19 +3721,65 @@ } } }, - "422": { + "401": { "content": { "application/problem+json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "type": "https://api.tablepro.app/problems/unauthorized", + "title": "Unauthorized", + "status": 401, + "code": "unauthorized", + "detail": "The token is invalid or has expired." + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Unprocessable Entity" + "description": "Unauthorized" + }, + "403": { + "content": { + "application/problem+json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "The token lacks the app scope." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" }, "429": { "content": { "application/problem+json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "type": "https://api.tablepro.app/problems/rate-limited", + "title": "Rate limited", + "status": 429, + "code": "rate_limited", + "detail": "Too many requests. Try again later." + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } @@ -1538,38 +3812,40 @@ "description": "Internal Server Error" } }, - "summary": "Start a checkout", + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "The caller's plan limits for shared links", "tags": [ - "Checkout" + "Shares" ] } }, - "/devices": { + "/shared/{token}": { "get": { - "description": "Every device that was not removed, oldest first.", - "operationId": "list-devices", + "description": "No authentication. An unknown, revoked, removed, expired or suspended link, a malformed token and a deleted team's link all answer 404 alike. Password guesses are limited per link and client, and per link.", + "operationId": "get-shared", "parameters": [ { - "description": "Devices per page", - "explode": false, - "in": "query", - "name": "limit", + "description": "The link token", + "in": "path", + "name": "token", + "required": true, "schema": { - "default": 50, - "description": "Devices per page", - "format": "int64", - "maximum": 200, - "minimum": 1, - "type": "integer" + "description": "The link token", + "type": "string" } }, { - "description": "next_cursor of the previous page; absent for the first page", - "explode": false, - "in": "query", - "name": "cursor", + "description": "The link password, for a password-protected link", + "in": "header", + "name": "X-Share-Password", "schema": { - "description": "next_cursor of the previous page; absent for the first page", + "description": "The link password, for a password-protected link", "type": "string" } } @@ -1579,11 +3855,11 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeviceList" + "$ref": "#/components/schemas/PublicShare" } } }, - "description": "OK", + "description": "The shared link", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -1600,14 +3876,24 @@ "content": { "application/problem+json": { "examples": { - "unauthorized": { - "summary": "Unauthorized", + "share_password_required": { + "summary": "Share password required", "value": { - "type": "https://api.tablepro.app/problems/unauthorized", - "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/share-password-required", + "title": "Share password required", "status": 401, - "code": "unauthorized", - "detail": "The token is invalid or has expired." + "code": "share_password_required", + "detail": "This link is password protected." + } + }, + "share_password_wrong": { + "summary": "Share password wrong", + "value": { + "type": "https://api.tablepro.app/problems/share-password-wrong", + "title": "Share password wrong", + "status": 401, + "code": "share_password_wrong", + "detail": "That password is not correct." } } }, @@ -1618,18 +3904,18 @@ }, "description": "Unauthorized" }, - "403": { + "404": { "content": { "application/problem+json": { "examples": { - "forbidden": { - "summary": "Forbidden", + "not_found": { + "summary": "Not found", "value": { - "type": "https://api.tablepro.app/problems/forbidden", - "title": "Forbidden", - "status": 403, - "code": "forbidden", - "detail": "The token lacks the app scope." + "type": "https://api.tablepro.app/problems/not-found", + "title": "Not found", + "status": 404, + "code": "not_found", + "detail": "No such share." } } }, @@ -1638,30 +3924,11 @@ } } }, - "description": "Forbidden" + "description": "Not Found" }, "422": { "content": { "application/problem+json": { - "examples": { - "validation_failed": { - "summary": "Validation failed", - "value": { - "type": "https://api.tablepro.app/problems/validation-failed", - "title": "Validation failed", - "status": 422, - "code": "validation_failed", - "detail": "validation failed", - "errors": [ - { - "message": "expected the next_cursor of a previous page", - "location": "query.cursor", - "value": "abc" - } - ] - } - } - }, "schema": { "$ref": "#/components/schemas/Problem" } @@ -1714,64 +3981,72 @@ } }, "description": "Internal Server Error" + }, + "503": { + "content": { + "application/problem+json": { + "examples": { + "service_unavailable": { + "summary": "Service unavailable", + "value": { + "type": "https://api.tablepro.app/problems/service-unavailable", + "title": "Service unavailable", + "status": 503, + "code": "service_unavailable", + "detail": "This shared result is busy. Try again in a moment." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Service Unavailable" } }, - "security": [ - { - "oauth": [ - "app" - ] - } - ], - "summary": "The account's devices", + "summary": "Read a shared link", "tags": [ - "Devices" + "Shares" ] - }, + } + }, + "/shared/{token}/report": { "post": { - "description": "Registers the machine the app runs on, or updates the account's device for it, and binds the refresh token family of the caller's sign-in to the device: access tokens refreshed afterwards carry dev, which the entitlement needs. Answers 201 for a new device and 200 when the machine was registered already. A sign-in already bound to another device is refused. 10 an hour per account.", - "operationId": "register-device", + "description": "No authentication; a Turnstile token instead. Answers 202 for any token, so a report never tells whether a link exists. 10 an hour per client.", + "operationId": "report-shared", + "parameters": [ + { + "description": "The link token", + "in": "path", + "name": "token", + "required": true, + "schema": { + "description": "The link token", + "type": "string" + } + } + ], "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeviceRegistration" + "$ref": "#/components/schemas/ReportShareBody" } } }, "required": true }, "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Device" - } - } - }, - "description": "The machine was registered already; its name, platform and versions are updated", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - } - }, - "201": { + "202": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Device" + "$ref": "#/components/schemas/ReportAccepted" } } }, - "description": "Created", + "description": "Accepted", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -1784,50 +4059,18 @@ } } }, - "401": { - "content": { - "application/problem+json": { - "examples": { - "unauthorized": { - "summary": "Unauthorized", - "value": { - "type": "https://api.tablepro.app/problems/unauthorized", - "title": "Unauthorized", - "status": 401, - "code": "unauthorized", - "detail": "The token is invalid or has expired." - } - } - }, - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Unauthorized" - }, "403": { "content": { "application/problem+json": { "examples": { - "forbidden": { - "summary": "Forbidden", - "value": { - "type": "https://api.tablepro.app/problems/forbidden", - "title": "Forbidden", - "status": 403, - "code": "forbidden", - "detail": "The token lacks the app scope." - } - }, - "forbidden_2": { - "summary": "Forbidden", + "human_check_failed": { + "summary": "Human check failed", "value": { - "type": "https://api.tablepro.app/problems/forbidden", - "title": "Forbidden", + "type": "https://api.tablepro.app/problems/human-check-failed", + "title": "Human check failed", "status": 403, - "code": "forbidden", - "detail": "This sign-in belongs to another device. Sign in again on this one." + "code": "human_check_failed", + "detail": "The check that a person is reporting did not pass. Complete it again, then send the report." } } }, @@ -1841,25 +4084,6 @@ "422": { "content": { "application/problem+json": { - "examples": { - "validation_failed": { - "summary": "Validation failed", - "value": { - "type": "https://api.tablepro.app/problems/validation-failed", - "title": "Validation failed", - "status": 422, - "code": "validation_failed", - "detail": "validation failed", - "errors": [ - { - "message": "expected string to match pattern ^[0-9a-f]{64}$", - "location": "body.machine_id", - "value": "MAC-1" - } - ] - } - } - }, "schema": { "$ref": "#/components/schemas/Problem" } @@ -1914,38 +4138,73 @@ "description": "Internal Server Error" } }, - "security": [ - { - "oauth": [ - "app" - ] - } - ], - "summary": "Register this device", + "summary": "Report a shared link", "tags": [ - "Devices" + "Shares" ] } }, - "/devices/{device_id}": { - "delete": { - "description": "Frees its license slot and revokes its refresh tokens, so the app on it signs out at its next refresh. Its entitlement stays valid until it expires. A device with an offline file that has not expired (offline_until) keeps its slot until its last valid file expires and is refused with offline_file_active.", - "operationId": "delete-device", + "/shares": { + "get": { + "description": "The caller's personal links, or with team a team's links: every one for its owner and admins, its own for a seated member, seat_required for a member without a seat. Newest first, without sql.", + "operationId": "list-shares", "parameters": [ { - "description": "Device TypeID", - "in": "path", - "name": "device_id", - "required": true, + "description": "Team TypeID: that team's links, every one for its owner and admins, a seated member's own for a member; omit for the caller's personal links", + "explode": false, + "in": "query", + "name": "team", "schema": { - "description": "Device TypeID", + "description": "Team TypeID: that team's links, every one for its owner and admins, a seated member's own for a member; omit for the caller's personal links", + "maxLength": 64, + "type": "string" + } + }, + { + "description": "live: only live links; all: every state", + "explode": false, + "in": "query", + "name": "state", + "schema": { + "$ref": "#/components/schemas/ShareListState", + "default": "all", + "description": "live: only live links; all: every state" + } + }, + { + "description": "next_cursor of the previous page; absent for the first page", + "explode": false, + "in": "query", + "name": "cursor", + "schema": { + "description": "next_cursor of the previous page; absent for the first page", + "maxLength": 64, "type": "string" } + }, + { + "explode": false, + "in": "query", + "name": "limit", + "schema": { + "default": 50, + "format": "int64", + "maximum": 200, + "minimum": 1, + "type": "integer" + } } ], "responses": { - "204": { - "description": "No Content", + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareList" + } + } + }, + "description": "OK", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -1993,6 +4252,16 @@ "code": "forbidden", "detail": "The token lacks the app scope." } + }, + "seat_required": { + "summary": "Seat required", + "value": { + "type": "https://api.tablepro.app/problems/seat-required", + "title": "Seat required", + "status": 403, + "code": "seat_required", + "detail": "A team link needs a seat in the team." + } } }, "schema": { @@ -2013,7 +4282,7 @@ "title": "Not found", "status": 404, "code": "not_found", - "detail": "This account has no such device." + "detail": "No such share." } } }, @@ -2024,18 +4293,24 @@ }, "description": "Not Found" }, - "409": { + "422": { "content": { "application/problem+json": { "examples": { - "offline_file_active": { - "summary": "Offline file active", + "validation_failed": { + "summary": "Validation failed", "value": { - "type": "https://api.tablepro.app/problems/offline-file-active", - "title": "Offline file active", - "status": 409, - "code": "offline_file_active", - "detail": "This device's offline file has not expired, so it keeps its license slot until offline_until." + "type": "https://api.tablepro.app/problems/validation-failed", + "title": "Validation failed", + "status": 422, + "code": "validation_failed", + "detail": "validation failed", + "errors": [ + { + "message": "expected the next_cursor of the previous page", + "location": "query.cursor" + } + ] } } }, @@ -2044,16 +4319,6 @@ } } }, - "description": "Conflict" - }, - "422": { - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, "description": "Unprocessable Entity" }, "429": { @@ -2110,45 +4375,34 @@ ] } ], - "summary": "Remove a device", + "summary": "List shared links", "tags": [ - "Devices" + "Shares" ] }, - "patch": { - "operationId": "update-device", - "parameters": [ - { - "description": "Device TypeID", - "in": "path", - "name": "device_id", - "required": true, - "schema": { - "description": "Device TypeID", - "type": "string" - } - } - ], + "post": { + "description": "Needs a verified email. Free allows 5 live personal links, expiry 1d, 7d or 30d and no password, no team and no download switch; Pro allows 1,000 and every option. Rows past the plan's max_rows are cut and truncated is set. 60 an hour and 300 a day per account.", + "operationId": "create-share", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeviceUpdate" + "$ref": "#/components/schemas/CreateShareBody" } } }, "required": true }, "responses": { - "200": { + "201": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Device" + "$ref": "#/components/schemas/CreatedShare" } } }, - "description": "OK", + "description": "Created", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -2187,6 +4441,16 @@ "content": { "application/problem+json": { "examples": { + "email_unverified": { + "summary": "Email unverified", + "value": { + "type": "https://api.tablepro.app/problems/email-unverified", + "title": "Email unverified", + "status": 403, + "code": "email_unverified", + "detail": "Verify your email address to share links." + } + }, "forbidden": { "summary": "Forbidden", "value": { @@ -2196,6 +4460,46 @@ "code": "forbidden", "detail": "The token lacks the app scope." } + }, + "pro_required": { + "summary": "Pro required", + "value": { + "type": "https://api.tablepro.app/problems/pro-required", + "title": "Pro required", + "status": 403, + "code": "pro_required", + "detail": "This option needs TablePro Pro." + } + }, + "seat_required": { + "summary": "Seat required", + "value": { + "type": "https://api.tablepro.app/problems/seat-required", + "title": "Seat required", + "status": 403, + "code": "seat_required", + "detail": "A team link needs a seat in the team." + } + }, + "sharing_disabled": { + "summary": "Sharing disabled", + "value": { + "type": "https://api.tablepro.app/problems/sharing-disabled", + "title": "Sharing disabled", + "status": 403, + "code": "sharing_disabled", + "detail": "Sharing is turned off for this account." + } + }, + "team_sharing_disabled": { + "summary": "Team sharing disabled", + "value": { + "type": "https://api.tablepro.app/problems/team-sharing-disabled", + "title": "Team sharing disabled", + "status": 403, + "code": "team_sharing_disabled", + "detail": "Public links are turned off for this team." + } } }, "schema": { @@ -2216,7 +4520,7 @@ "title": "Not found", "status": 404, "code": "not_found", - "detail": "This account has no such device." + "detail": "No such share." } } }, @@ -2227,25 +4531,41 @@ }, "description": "Not Found" }, + "409": { + "content": { + "application/problem+json": { + "examples": { + "share_limit_reached": { + "summary": "Share limit reached", + "value": { + "type": "https://api.tablepro.app/problems/share-limit-reached", + "title": "Share limit reached", + "status": 409, + "code": "share_limit_reached", + "detail": "You have reached your plan's live link limit.", + "live_limit": 5 + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Conflict" + }, "422": { "content": { "application/problem+json": { "examples": { - "validation_failed": { - "summary": "Validation failed", + "snapshot_too_large": { + "summary": "Snapshot too large", "value": { - "type": "https://api.tablepro.app/problems/validation-failed", - "title": "Validation failed", + "type": "https://api.tablepro.app/problems/snapshot-too-large", + "title": "Snapshot too large", "status": 422, - "code": "validation_failed", - "detail": "validation failed", - "errors": [ - { - "message": "expected a name of 1 to 100 characters", - "location": "body.name", - "value": "\t" - } - ] + "code": "snapshot_too_large", + "detail": "This result is too large to share." } } }, @@ -2269,6 +4589,16 @@ "code": "rate_limited", "detail": "Too many requests. Try again later." } + }, + "rate_limited_2": { + "summary": "Rate limited", + "value": { + "type": "https://api.tablepro.app/problems/rate-limited", + "title": "Rate limited", + "status": 429, + "code": "rate_limited", + "detail": "Too many requests. Try again later." + } } }, "schema": { @@ -2310,48 +4640,32 @@ ] } ], - "summary": "Rename a device", + "summary": "Create a shared link", "tags": [ - "Devices" + "Shares" ] } }, - "/devices/{device_id}/entitlement": { - "post": { - "description": "Answers only for the device the caller's token is bound to: register the device, refresh the token, then ask. When the account has a license and the device holds none of its 3 slots, the device takes one, or the answer is device_limit_reached with the devices that hold them. An account without licenses gets a token with no features.", - "operationId": "issue-entitlement", + "/shares/{share_id}": { + "delete": { + "description": "The link stops working at once. Revoking a revoked link changes nothing.", + "operationId": "delete-share", "parameters": [ { - "description": "Device TypeID; must be the device the caller's token is bound to (its dev claim)", + "description": "Share TypeID", "in": "path", - "name": "device_id", + "name": "share_id", "required": true, "schema": { - "description": "Device TypeID; must be the device the caller's token is bound to (its dev claim)", + "description": "Share TypeID", + "maxLength": 64, "type": "string" } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EntitlementRequest" - } - } - }, - "required": true - }, "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Entitlement" - } - } - }, - "description": "OK", + "204": { + "description": "No Content", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -2390,26 +4704,6 @@ "content": { "application/problem+json": { "examples": { - "account_locked": { - "summary": "Account locked", - "value": { - "type": "https://api.tablepro.app/problems/account-locked", - "title": "Account locked", - "status": 403, - "code": "account_locked", - "detail": "This account is locked." - } - }, - "device_revoked": { - "summary": "Device revoked", - "value": { - "type": "https://api.tablepro.app/problems/device-revoked", - "title": "Device revoked", - "status": 403, - "code": "device_revoked", - "detail": "This device was removed from the account. Sign in again to use it." - } - }, "forbidden": { "summary": "Forbidden", "value": { @@ -2419,16 +4713,6 @@ "code": "forbidden", "detail": "The token lacks the app scope." } - }, - "forbidden_2": { - "summary": "Forbidden", - "value": { - "type": "https://api.tablepro.app/problems/forbidden", - "title": "Forbidden", - "status": 403, - "code": "forbidden", - "detail": "This token is not bound to that device. Register this device, refresh the token, and ask again." - } } }, "schema": { @@ -2438,54 +4722,18 @@ }, "description": "Forbidden" }, - "409": { + "404": { "content": { "application/problem+json": { "examples": { - "device_limit_reached": { - "summary": "Device limit reached", + "not_found": { + "summary": "Not found", "value": { - "type": "https://api.tablepro.app/problems/device-limit-reached", - "title": "Device limit reached", - "status": 409, - "code": "device_limit_reached", - "detail": "The license is already used on 3 devices.", - "devices": [ - { - "id": "dev_01k8djrfaefw08m00000000001", - "machine_id": "0000000000000000000000000000000000000000000000000000000000000001", - "platform": "macos", - "name": "Ada's MacBook Pro", - "app_version": "2.0.0", - "os_version": "26.0", - "licensed_at": "2026-10-01T09:00:00Z", - "created_at": "2026-10-01T09:00:00Z", - "last_seen_at": "2026-10-21T09:00:00Z" - }, - { - "id": "dev_01k8djrfaefw08m00000000002", - "machine_id": "0000000000000000000000000000000000000000000000000000000000000002", - "platform": "macos", - "name": "Studio", - "app_version": "2.0.0", - "os_version": "26.0", - "licensed_at": "2026-10-02T09:00:00Z", - "offline_until": "2027-10-02T09:00:00Z", - "created_at": "2026-10-02T09:00:00Z", - "last_seen_at": "2026-10-22T09:00:00Z" - }, - { - "id": "dev_01k8djrfaefw08m00000000003", - "machine_id": "0000000000000000000000000000000000000000000000000000000000000003", - "platform": "linux", - "name": "Workstation", - "app_version": "2.0.0", - "os_version": "Fedora 43", - "licensed_at": "2026-10-03T09:00:00Z", - "created_at": "2026-10-03T09:00:00Z", - "last_seen_at": "2026-10-23T09:00:00Z" - } - ] + "type": "https://api.tablepro.app/problems/not-found", + "title": "Not found", + "status": 404, + "code": "not_found", + "detail": "No such share." } } }, @@ -2494,7 +4742,7 @@ } } }, - "description": "Conflict" + "description": "Not Found" }, "422": { "content": { @@ -2560,32 +4808,32 @@ ] } ], - "summary": "An entitlement for this device", + "summary": "Revoke a shared link", "tags": [ - "Devices" + "Shares" ] - } - }, - "/discounts/preview": { - "post": { - "description": "Answers whether checkout would apply the code, and how much it takes off. An unknown code is not an error.", - "operationId": "preview-discount", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/DiscountPreviewRequest" - } + }, + "get": { + "operationId": "get-share", + "parameters": [ + { + "description": "Share TypeID", + "in": "path", + "name": "share_id", + "required": true, + "schema": { + "description": "Share TypeID", + "maxLength": 64, + "type": "string" } - }, - "required": true - }, + } + ], "responses": { "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DiscountPreview" + "$ref": "#/components/schemas/ShareView" } } }, @@ -2602,95 +4850,62 @@ } } }, - "422": { - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Unprocessable Entity" - }, - "429": { + "401": { "content": { "application/problem+json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "type": "https://api.tablepro.app/problems/unauthorized", + "title": "Unauthorized", + "status": 401, + "code": "unauthorized", + "detail": "The token is invalid or has expired." + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Too Many Requests", - "headers": { - "Retry-After": { - "$ref": "#/components/headers/Retry-After" - }, - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - } + "description": "Unauthorized" }, - "500": { + "403": { "content": { "application/problem+json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "The token lacks the app scope." + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Internal Server Error" - } - }, - "summary": "Check a discount code", - "tags": [ - "Checkout" - ] - } - }, - "/me": { - "get": { - "description": "The account, the teams it belongs to with its role and seat in each, and the licenses whose features it can use.", - "operationId": "get-me", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Me" - } - } - }, - "description": "OK", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - } + "description": "Forbidden" }, - "401": { + "404": { "content": { "application/problem+json": { "examples": { - "unauthorized": { - "summary": "Unauthorized", + "not_found": { + "summary": "Not found", "value": { - "type": "https://api.tablepro.app/problems/unauthorized", - "title": "Unauthorized", - "status": 401, - "code": "unauthorized", - "detail": "The token is invalid or has expired." + "type": "https://api.tablepro.app/problems/not-found", + "title": "Not found", + "status": 404, + "code": "not_found", + "detail": "No such share." } } }, @@ -2699,29 +4914,17 @@ } } }, - "description": "Unauthorized" + "description": "Not Found" }, - "403": { + "422": { "content": { "application/problem+json": { - "examples": { - "forbidden": { - "summary": "Forbidden", - "value": { - "type": "https://api.tablepro.app/problems/forbidden", - "title": "Forbidden", - "status": 403, - "code": "forbidden", - "detail": "The token lacks the app scope." - } - } - }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Forbidden" + "description": "Unprocessable Entity" }, "429": { "content": { @@ -2777,70 +4980,47 @@ ] } ], - "summary": "The signed-in account", + "summary": "Get one shared link, with its SQL", "tags": [ - "Account" + "Shares" ] - } - }, - "/newsletter/stats": { - "get": { - "operationId": "get-newsletter-stats", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/NewsletterStats" - } - } - }, - "description": "OK" - }, - "500": { - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Internal Server Error" - }, - "503": { - "content": { - "application/problem+json": { - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Service Unavailable" + }, + "patch": { + "description": "Title, note, expiry, password, downloads and hide_sql, under the same plan rules as create. Works on an expired link without reviving it; a new expiry revives it when a live slot is free.", + "operationId": "update-share", + "parameters": [ + { + "description": "Share TypeID", + "in": "path", + "name": "share_id", + "required": true, + "schema": { + "description": "Share TypeID", + "maxLength": 64, + "type": "string" + } } - }, - "summary": "Count the newsletter's subscribers", - "tags": [ - "Newsletter" - ] - } - }, - "/newsletter/subscriptions": { - "post": { - "description": "Emails a confirmation link. Answers 202 whether or not the address is subscribed and whether or not the Turnstile check passed, so it reveals nothing.", - "operationId": "create-newsletter-subscription", + ], "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NewsletterSubscriptionRequest" + "$ref": "#/components/schemas/UpdateShareBody" } } }, "required": true }, "responses": { - "202": { - "description": "Accepted", + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareView" + } + } + }, + "description": "OK", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -2853,88 +5033,210 @@ } } }, - "422": { + "401": { "content": { "application/problem+json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "type": "https://api.tablepro.app/problems/unauthorized", + "title": "Unauthorized", + "status": 401, + "code": "unauthorized", + "detail": "The token is invalid or has expired." + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Unprocessable Entity" + "description": "Unauthorized" }, - "429": { + "403": { "content": { "application/problem+json": { + "examples": { + "email_unverified": { + "summary": "Email unverified", + "value": { + "type": "https://api.tablepro.app/problems/email-unverified", + "title": "Email unverified", + "status": 403, + "code": "email_unverified", + "detail": "Verify your email address to share links." + } + }, + "forbidden": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "The token lacks the app scope." + } + }, + "pro_required": { + "summary": "Pro required", + "value": { + "type": "https://api.tablepro.app/problems/pro-required", + "title": "Pro required", + "status": 403, + "code": "pro_required", + "detail": "This option needs TablePro Pro." + } + }, + "seat_required": { + "summary": "Seat required", + "value": { + "type": "https://api.tablepro.app/problems/seat-required", + "title": "Seat required", + "status": 403, + "code": "seat_required", + "detail": "A team link needs a seat in the team." + } + }, + "sharing_disabled": { + "summary": "Sharing disabled", + "value": { + "type": "https://api.tablepro.app/problems/sharing-disabled", + "title": "Sharing disabled", + "status": 403, + "code": "sharing_disabled", + "detail": "Sharing is turned off for this account." + } + }, + "team_sharing_disabled": { + "summary": "Team sharing disabled", + "value": { + "type": "https://api.tablepro.app/problems/team-sharing-disabled", + "title": "Team sharing disabled", + "status": 403, + "code": "team_sharing_disabled", + "detail": "Public links are turned off for this team." + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Too Many Requests", - "headers": { - "Retry-After": { - "$ref": "#/components/headers/Retry-After" - }, - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - } + "description": "Forbidden" }, - "500": { + "404": { "content": { "application/problem+json": { + "examples": { + "not_found": { + "summary": "Not found", + "value": { + "type": "https://api.tablepro.app/problems/not-found", + "title": "Not found", + "status": 404, + "code": "not_found", + "detail": "No such share." + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Internal Server Error" - } - }, - "summary": "Sign up for the newsletter", - "tags": [ - "Newsletter" - ] - } - }, - "/pricing": { - "get": { - "description": "What checkout charges the caller without a discount code, regional discount included. Answered for the caller's country, so it is never cached.", - "operationId": "get-pricing", - "responses": { - "200": { + "description": "Not Found" + }, + "409": { "content": { - "application/json": { + "application/problem+json": { + "examples": { + "share_limit_reached": { + "summary": "Share limit reached", + "value": { + "type": "https://api.tablepro.app/problems/share-limit-reached", + "title": "Share limit reached", + "status": 409, + "code": "share_limit_reached", + "detail": "You have reached your plan's live link limit.", + "live_limit": 5 + } + }, + "share_removed": { + "summary": "Share removed", + "value": { + "type": "https://api.tablepro.app/problems/share-removed", + "title": "Share removed", + "status": 409, + "code": "share_removed", + "detail": "TablePro removed this link." + } + }, + "share_revoked": { + "summary": "Share revoked", + "value": { + "type": "https://api.tablepro.app/problems/share-revoked", + "title": "Share revoked", + "status": 409, + "code": "share_revoked", + "detail": "This link was revoked." + } + } + }, "schema": { - "$ref": "#/components/schemas/Pricing" + "$ref": "#/components/schemas/Problem" } } }, - "description": "OK", - "headers": { - "Cache-Control": { + "description": "Conflict" + }, + "422": { + "content": { + "application/problem+json": { "schema": { - "type": "string" + "$ref": "#/components/schemas/Problem" } } - } + }, + "description": "Unprocessable Entity" }, - "422": { + "429": { "content": { "application/problem+json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "type": "https://api.tablepro.app/problems/rate-limited", + "title": "Rate limited", + "status": 429, + "code": "rate_limited", + "detail": "Too many requests. Try again later." + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Unprocessable Entity" + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } }, "500": { "content": { @@ -2947,9 +5249,16 @@ "description": "Internal Server Error" } }, - "summary": "Prices in the caller's country", + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "Change a shared link", "tags": [ - "Checkout" + "Shares" ] } }, diff --git a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift index 9c31d291c2..81e0ff81c9 100644 --- a/apple/TablePro/Core/Coordinators/FilterCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/FilterCoordinator.swift @@ -284,6 +284,66 @@ final class FilterCoordinator: ObservableObject { normalizeLogicModeIfNeeded(at: tabIndex) let tab = parent.tabManager.tabs[tabIndex] + let built = tableQuery( + for: tab, + tableName: tableName, + limit: tab.pagination.pageSize, + offset: tab.pagination.currentOffset + ) + + parent.tabManager.mutate(at: tabIndex) { + $0.content.query = built.query + if built.isRefused { + $0.filterState.commit = nil + } + $0.filterState.executedFilters = built.executed + $0.filterState.executedLogicMode = $0.filterState.commit == nil ? nil : built.logicMode + } + } + + // The table tab's view, its filters, search and sort, read from the first row: what Share Result reads. + func viewQuery(for tab: QueryTab, limit: Int) -> String? { + guard let tableName = tab.tableContext.tableName else { return nil } + return tableQuery(for: tab, tableName: tableName, limit: limit, offset: 0).query + } + + // The same view with no LIMIT or OFFSET, as a shared link shows it; nil when the host cannot write it as SQL. + func viewSQL(for tab: QueryTab) -> String? { + guard parent.queryBuilder.writesSQL, + let tableName = tab.tableContext.tableName, + activeBrowseSearch(for: tab.filterState) == nil + else { return nil } + let rerun = tab.filterState.rerunFilters + let (columns, columnTypes) = parent.queryColumns(for: tab) + guard !rerun.filters.isEmpty else { + return parent.queryBuilder.buildBaseQuery( + tableName: tableName, + schemaName: tab.tableContext.schemaName, + sortState: querySortState(for: tab), + columns: columns, + selectColumns: parent.selectColumns(for: tab), + window: false + ) + } + return parent.queryBuilder.buildFilteredQuery( + tableName: tableName, + schemaName: tab.tableContext.schemaName, + filters: rerun.filters, + logicMode: parent.supportsMatchAnyFilters ? rerun.logicMode : .and, + sortState: querySortState(for: tab), + columns: columns, + columnTypes: columnTypes, + selectColumns: parent.selectColumns(for: tab), + window: false + ) + } + + private func tableQuery( + for tab: QueryTab, + tableName: String, + limit: Int, + offset: Int + ) -> (query: String, executed: [TableFilter], isRefused: Bool, logicMode: FilterLogicMode) { let rerun = tab.filterState.rerunFilters let logicMode = parent.supportsMatchAnyFilters ? rerun.logicMode : .and let (columns, columnTypes) = parent.queryColumns(for: tab) @@ -300,8 +360,8 @@ final class FilterCoordinator: ObservableObject { columns: columns, selectColumns: parent.selectColumns(for: tab), unloadedValues: parent.unloadedValuePlan(for: tab), - limit: tab.pagination.pageSize, - offset: tab.pagination.currentOffset + limit: limit, + offset: offset ) } else if rerun.filters.isEmpty { filteredQuery = nil @@ -316,33 +376,25 @@ final class FilterCoordinator: ObservableObject { columnTypes: columnTypes, selectColumns: parent.selectColumns(for: tab), unloadedValues: parent.unloadedValuePlan(for: tab), - limit: tab.pagination.pageSize, - offset: tab.pagination.currentOffset + limit: limit, + offset: offset ) } let isRefused = filteredQuery == nil && !rerun.filters.isEmpty if isRefused { executed = [] } - let newQuery = filteredQuery ?? parent.queryBuilder.buildBaseQuery( + let query = filteredQuery ?? parent.queryBuilder.buildBaseQuery( tableName: tableName, schemaName: tab.tableContext.schemaName, sortState: querySortState(for: tab), columns: columns, selectColumns: parent.selectColumns(for: tab), unloadedValues: parent.unloadedValuePlan(for: tab), - limit: tab.pagination.pageSize, - offset: tab.pagination.currentOffset + limit: limit, + offset: offset ) - - parent.tabManager.mutate(at: tabIndex) { - $0.content.query = newQuery - if isRefused { - $0.filterState.commit = nil - } - $0.filterState.executedFilters = executed - $0.filterState.executedLogicMode = $0.filterState.commit == nil ? nil : logicMode - } + return (query, executed, isRefused, logicMode) } // MARK: - Filter State diff --git a/apple/TablePro/Core/Coordinators/PaginationCoordinator+CappedRead.swift b/apple/TablePro/Core/Coordinators/PaginationCoordinator+CappedRead.swift new file mode 100644 index 0000000000..afa93ef2e0 --- /dev/null +++ b/apple/TablePro/Core/Coordinators/PaginationCoordinator+CappedRead.swift @@ -0,0 +1,55 @@ +// +// PaginationCoordinator+CappedRead.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +extension PaginationCoordinator { + // Fetch All's gate and driver read, capped and handed back rather than installed, for a reader such as Share + // Result that needs more rows than the grid holds without changing what the grid shows. + internal func readRows( + tabId: UUID, + query: String, + parameters: [TypedParameterValue?]?, + rowCap: Int, + operationDescription: String + ) async throws -> QueryResult { + guard let tab = parent.tabManager.tabs.first(where: { $0.id == tabId }), + let scope = parent.scope(for: tab) + else { throw DatabaseError.notConnected } + + + let workToken = parent.tabExecution.beginUnclaimedWork(for: tabId) + defer { parent.tabExecution.endUnclaimedWork(workToken, for: tabId) } + + let decision = await parent.executionGate.authorize(OperationRequest( + connectionId: scope.connectionId, + databaseType: parent.connection.type, + sql: query, + kind: .readQuery, + caller: .userInterface, + capabilities: .interactiveUser, + operationDescription: operationDescription, + scope: scope + )) + if let denial = decision.denialError { throw denial } + + let isTableTab = tab.tabType == .table + let lengthColumns = isTableTab ? parent.unloadedValueLengthColumns(for: tab) : [] + let safeModeIsReadOnly = parent.runsAtReadOnly + return try await parent.withExecutionDriver(scope: scope, isTableTab: isTableTab, lease: DriverLeaseOwner()) { driver in + let values = parameters.map { $0.map { $0 as Any? } } + let result: QueryResult + if let context = driver.readOnlyRunContext(safeModeIsReadOnly: safeModeIsReadOnly) { + result = try await driver.executeUserQuery( + query: query, rowCap: rowCap, parameters: values, context: context + ) + } else { + result = try await driver.executeUserQuery(query: query, rowCap: rowCap, parameters: values) + } + return result.foldingUnloadedValues(lengthColumns: lengthColumns) + } + } +} diff --git a/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift b/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift index 7844ea8b62..0cecfd6ad8 100644 --- a/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift +++ b/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift @@ -12,6 +12,7 @@ enum DataGridCommand: Hashable, CaseIterable { case hideColumns case showRowsAsJSON case exportResults + case shareResult case clearResults case searchAllRows case navigateForeignKey @@ -95,6 +96,7 @@ protocol DataGridActions: AnyObject { func gridNavigateForeignKey(value: String, info: ForeignKeyInfo, intent: ReferenceOpenIntent) func gridShowRowsAsJSON(_ rowIDs: [RowID]) func gridExportResults() + func gridShareResult() func gridClearResults() func gridSearchAllRows(term: String) func gridSetCheckbox(_ isOn: Bool, rowIDs: [RowID], column: DataGridColumn) @@ -127,6 +129,7 @@ extension DataGridActions { func gridNavigateForeignKey(value: String, info: ForeignKeyInfo, intent: ReferenceOpenIntent) {} func gridShowRowsAsJSON(_ rowIDs: [RowID]) {} func gridExportResults() {} + func gridShareResult() {} func gridClearResults() {} func gridSearchAllRows(term: String) {} func gridSetCheckbox(_ isOn: Bool, rowIDs: [RowID], column: DataGridColumn) {} diff --git a/apple/TablePro/Core/Menu/AppDelegate+MainMenuActions.swift b/apple/TablePro/Core/Menu/AppDelegate+MainMenuActions.swift index c4ac12a895..2009631011 100644 --- a/apple/TablePro/Core/Menu/AppDelegate+MainMenuActions.swift +++ b/apple/TablePro/Core/Menu/AppDelegate+MainMenuActions.swift @@ -1,4 +1,5 @@ import AppKit +import TableProHTTP /// Commands that belong to the app rather than to any one window. They sit on the /// app delegate because it is the last link in the responder chain, so they stay @@ -24,6 +25,10 @@ extension AppDelegate: NSMenuItemValidation { UpdateCenter.shared.performPrimaryAction() } + @objc func manageSharedLinks(_ sender: Any?) { + _ = WebPageOpener.open(AccountServices.shared.configuration.portalSharedLinks, scope: .httpsOrLoopbackHTTP) + } + @objc func openMCPActivity(_ sender: Any?) { WindowOpener.shared.openIntegrationsActivity() } diff --git a/apple/TablePro/Core/Menu/FileMenuBuilder.swift b/apple/TablePro/Core/Menu/FileMenuBuilder.swift index 2ce0f5d02b..0be99d922c 100644 --- a/apple/TablePro/Core/Menu/FileMenuBuilder.swift +++ b/apple/TablePro/Core/Menu/FileMenuBuilder.swift @@ -126,6 +126,19 @@ enum FileMenuBuilder { importSubmenu(keyboard: keyboard), exportSubmenu(keyboard: keyboard), MenuItemFactory.separator, + MenuItemFactory.item( + String(localized: "Share Query…"), + action: #selector(MainSplitViewController.shareQuery(_:)) + ), + MenuItemFactory.item( + String(localized: "Share Result…"), + action: #selector(MainSplitViewController.shareQueryResult(_:)) + ), + MenuItemFactory.item( + String(localized: "Manage Shared Links…"), + action: #selector(AppDelegate.manageSharedLinks(_:)) + ), + MenuItemFactory.separator, MenuItemFactory.item( String(localized: "Backup Dump…"), action: #selector(MainSplitViewController.backupDatabase(_:)) diff --git a/apple/TablePro/Core/Services/Account/AccountAPI.swift b/apple/TablePro/Core/Services/Account/AccountAPI.swift index d228807de4..86c0859a56 100644 --- a/apple/TablePro/Core/Services/Account/AccountAPI.swift +++ b/apple/TablePro/Core/Services/Account/AccountAPI.swift @@ -20,6 +20,15 @@ internal enum AccountAPI { ) } + // No bearer: the public share read answers a recipient who may not be signed in. + static func publicClient(configuration: AccountConfiguration, transport: any ClientTransport) -> Client { + Client( + serverURL: configuration.apiServerURL, + configuration: Configuration(dateTranscoder: RFC3339DateTranscoder()), + transport: transport + ) + } + static func transport(session: URLSession) -> any ClientTransport { URLSessionTransport(configuration: .init(session: session)) } diff --git a/apple/TablePro/Core/Services/Account/AccountConfiguration.swift b/apple/TablePro/Core/Services/Account/AccountConfiguration.swift index f4d292a19c..2dc43bad94 100644 --- a/apple/TablePro/Core/Services/Account/AccountConfiguration.swift +++ b/apple/TablePro/Core/Services/Account/AccountConfiguration.swift @@ -81,6 +81,10 @@ extension AccountConfiguration { accountURL.appendingPathComponent("devices") } + var portalSharedLinks: URL { + accountURL.appendingPathComponent("shared-links") + } + func portalTeam(_ teamID: String) -> URL { accountURL.appendingPathComponent("teams").appendingPathComponent(teamID) } diff --git a/apple/TablePro/Core/Services/Account/AccountServices.swift b/apple/TablePro/Core/Services/Account/AccountServices.swift index 298881d777..74d1fc2933 100644 --- a/apple/TablePro/Core/Services/Account/AccountServices.swift +++ b/apple/TablePro/Core/Services/Account/AccountServices.swift @@ -51,6 +51,7 @@ internal final class AccountServices { let devices: DeviceRegistry let access: FeatureAccess let api: any APIProtocol + let shares: any ShareService let events = PassthroughSubject() private let entitlements: EntitlementStore private let legacy: LegacyLicenseStore @@ -92,6 +93,15 @@ internal final class AccountServices { onRefused: { Task { @MainActor in refusals.services?.sessionWasRefused() } } ) self.api = AccountAPI.client(configuration: configuration, transport: transport, session: session) + self.shares = CloudShareService( + api: api, + publicAPI: AccountAPI.publicClient(configuration: configuration, transport: transport), + createRequest: ShareCreateRequest( + serverURL: configuration.apiServerURL, + transport: transport, + middlewares: [BearerTokenMiddleware(session: session)] + ) + ) self.devices = DeviceRegistry(api: api, machine: machine) self.entitlements = EntitlementStore( fileURL: entitlementFile, diff --git a/apple/TablePro/Core/Services/Infrastructure/AppActivationPolicy.swift b/apple/TablePro/Core/Services/Infrastructure/AppActivationPolicy.swift index 323be30207..992aa712c1 100644 --- a/apple/TablePro/Core/Services/Infrastructure/AppActivationPolicy.swift +++ b/apple/TablePro/Core/Services/Infrastructure/AppActivationPolicy.swift @@ -80,6 +80,7 @@ internal extension LaunchIntent { .openDatabaseFile, .openDataFile, .openConnectionShare, + .openSharedLink, .pairIntegration, .openDatabaseURL, .installPlugin, diff --git a/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift b/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift index 236defed2d..9b8723395b 100644 --- a/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift +++ b/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift @@ -65,11 +65,24 @@ internal enum DeeplinkParser { return parseIntegrations(url) case "settings": return parseSettings(url) + case "share": + return parseSharedLink(url) default: return .failure(.unknownHost(host)) } } + private static func parseSharedLink(_ url: URL) -> Result { + let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] + guard let token = items.first(where: { $0.name == "token" })?.value, !token.isEmpty else { + return .failure(.missingRequiredParam("token")) + } + guard ShareToken.isValid(token) else { + return .failure(.invalidParameter("token")) + } + return .success(.openSharedLink(token: token)) + } + /// Never fails: an unknown id or extra segments open the last-used pane, so a link to a pane /// or section added later still opens Settings on an older app. private static func parseSettings(_ url: URL) -> Result { diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchEnvironment.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchEnvironment.swift index 3dae771af1..7e479c827e 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchEnvironment.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchEnvironment.swift @@ -83,6 +83,8 @@ internal final class LiveLaunchEnvironment: LaunchEnvironment { internal func dismissWelcomeIfMainWindowVisible() { guard NSApp.windows.contains(where: { AppLaunchCoordinator.isMainWindow($0) && $0.isVisible }) else { return } + // Welcome is up to pick a connection for a shared link that had none to open in. + guard WelcomeRouter.shared.pendingSharedQueries.isEmpty else { return } WindowOpener.shared.closeWelcome() } diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift index c7cb643940..37ba828a0c 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift @@ -23,6 +23,7 @@ internal enum LaunchIntent: @unchecked Sendable { case openDatabaseFile(URL, DatabaseType) case openDataFile(URL) case openConnectionShare(URL) + case openSharedLink(token: String) case pairIntegration(PairingRequest) case startMCPServer /// nil opens the last-used pane. @@ -46,6 +47,7 @@ internal enum LaunchIntent: @unchecked Sendable { .openSQLFile, .importConnection, .openConnectionShare, + .openSharedLink, .pairIntegration, .startMCPServer, .openSettings, diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift index 5842ab53a5..0e7f89087a 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift @@ -33,6 +33,9 @@ internal final class LaunchIntentRouter { case .openConnectionShare(let url): WelcomeRouter.shared.routeShare(url) + case .openSharedLink(let token): + await SharedLinkOpener.shared.open(token: token) + case .pairIntegration(let request): try await MCPPairingService.shared.startPairing(request) @@ -163,7 +166,7 @@ internal final class LaunchIntentRouter { title = String(localized: "Connection Failed") case .openSQLFile, .openDataFile: title = String(localized: "Could Not Open File") - case .importConnection, .openConnectionShare, .startMCPServer, .openSettings: + case .importConnection, .openConnectionShare, .openSharedLink, .startMCPServer, .openSettings: title = String(localized: "Action Failed") } if presentRecoverableError(error, for: intent, title: title) { return } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+FileMenuActions.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+FileMenuActions.swift index 2d23bcea46..25a1313869 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+FileMenuActions.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+FileMenuActions.swift @@ -126,6 +126,15 @@ extension MainSplitViewController { commandActions?.exportQueryResults() } + // The Favorites list answers this first when it has focus and a saved query selected. + @objc func shareQuery(_ sender: Any?) { + commandActions?.shareQuery() + } + + @objc func shareQueryResult(_ sender: Any?) { + commandActions?.shareQueryResult() + } + @objc func importData(_ sender: Any?) { commandActions?.importData() } diff --git a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift index a63ab93d2c..b48868df7c 100644 --- a/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift +++ b/apple/TablePro/Core/Services/Infrastructure/MainSplitViewController+MenuValidation.swift @@ -211,6 +211,11 @@ extension MainSplitViewController: NSMenuItemValidation { return context.isConnected && context.isQueryTab case #selector(exportQueryResults(_:)): return context.isConnected && (context.hasResultRows || context.hasTableHealthFindings) + // A share reads the loaded rows and the editor text, so neither waits on the connection. + case #selector(shareQueryResult(_:)): + return context.hasResultRows + case #selector(shareQuery(_:)): + return context.isQueryTab && context.hasQueryText case #selector(exportDataDictionary(_:)): return context.isConnected && context.canExportDataDictionary @@ -546,6 +551,8 @@ extension MainSplitViewController: NSMenuItemValidation { #selector(discardChanges(_:)), #selector(exportTables(_:)), #selector(exportQueryResults(_:)), + #selector(shareQuery(_:)), + #selector(shareQueryResult(_:)), #selector(exportDataDictionary(_:)), #selector(importData(_:)), #selector(importDataFormat(_:)), diff --git a/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift b/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift index 4c917cc3e1..dba6c9b115 100644 --- a/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift @@ -141,6 +141,7 @@ internal final class TabRouter { } private func openConnection(id: UUID, transientConnection: DatabaseConnection? = nil) async throws { + WelcomeRouter.shared.claimPendingSharedQueries(for: id) let connection: DatabaseConnection if let stored = ConnectionStorage.shared.loadConnections().first(where: { $0.id == id }) { connection = stored @@ -495,6 +496,30 @@ internal final class TabRouter { AppActivationPolicyController.shared.activate(ignoringOtherApps: true) } + // False when no connection is up to open it in; the caller holds it until one connects. + @discardableResult + internal func openSharedQuery(_ query: SharedQueryOpen) -> Bool { + let target = Self.sqlFileConnectionId( + shownConnectionId: WindowManager.shared.frontmostHost()?.workspaces.selectedConnectionId, + lastActiveConnectionId: DatabaseManager.shared.lastActiveSessionId, + activeSessionIds: Set(DatabaseManager.shared.activeSessions.keys) + ) + guard let target else { return false } + openSharedQuery(query, in: target) + return true + } + + internal func openSharedQuery(_ query: SharedQueryOpen, in connectionId: UUID) { + WindowManager.shared.openTab(payload: EditorTabPayload( + connectionId: connectionId, + tabType: .query, + initialQuery: query.sql, + forcesNewTab: true, + tabTitle: query.title + )) + AppActivationPolicyController.shared.activate(ignoringOtherApps: true) + } + /// The connection on screen, so the script lands where the user is looking. The last one to /// connect is only a fallback for when no window shows a connected one: switching to a /// connection that is already up never updates it. diff --git a/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift b/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift index bc6e9d7ee3..320ff5a8b9 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift @@ -43,25 +43,65 @@ internal final class WelcomeRouter: ObservableObject { @Published private(set) var pendingImport: ConnectionBundle? @Published private(set) var pendingConnectionShare: URL? @Published private(set) var pendingSQLFiles: [URL] = [] + @Published private(set) var pendingSharedQueries: [SharedQueryOpen] = [] + // Taken by a connection opened while they waited; they open once that connection is up. + private(set) var claimedSharedQueries: [UUID: [SharedQueryOpen]] = [:] @Published private(set) var pendingError: PendingConnectionError? @Published private(set) var pendingPluginInstall: DatabaseConnection? private var databaseDidConnectCancellable: AnyCancellable? - - internal init(appEvents: AppEvents = .shared) { + private var connectionPhaseCancellable: AnyCancellable? + private let workspacePhases: @MainActor (UUID) -> [ConnectionWindowPhase] + + internal init( + appEvents: AppEvents = .shared, + workspacePhases: @escaping @MainActor (UUID) -> [ConnectionWindowPhase] = { id in + WindowManager.shared.workspaces(for: id).map(\.phase) + } + ) { + self.workspacePhases = workspacePhases databaseDidConnectCancellable = appEvents.databaseDidConnect .receive(on: RunLoop.main) - .sink { [weak self] _ in + .sink { [weak self] event in self?.drainPendingSQLFiles() + self?.drainSharedQueries(connectedTo: event.connectionId) + } + connectionPhaseCancellable = appEvents.connectionPhaseChanged + .receive(on: RunLoop.main) + .sink { [weak self] connectionId in + self?.releaseSharedQueriesIfConnectEnded(connectionId) } } + // A connect that failed, was cancelled or lost its window hands its shared queries back, so they open in the next + // connection to come up rather than when this one is reconnected much later. + private func releaseSharedQueriesIfConnectEnded(_ connectionId: UUID) { + guard claimedSharedQueries[connectionId] != nil else { return } + let ended = workspacePhases(connectionId).allSatisfy { phase in + switch phase { + case .unavailable, .closing: true + case .idle, .connecting, .connected: false + } + } + guard ended, let released = claimedSharedQueries.removeValue(forKey: connectionId) else { return } + pendingSharedQueries += released + } + private func drainPendingSQLFiles() { let urls = consumePendingSQLFiles() guard !urls.isEmpty else { return } AppCommands.shared.openSQLFiles.send(urls) } + private func drainSharedQueries(connectedTo connectionId: UUID) { + for query in claimedSharedQueries.removeValue(forKey: connectionId) ?? [] { + TabRouter.shared.openSharedQuery(query, in: connectionId) + } + guard !pendingSharedQueries.isEmpty else { return } + let queries = consumePendingSharedQueries() + pendingSharedQueries = queries.filter { !TabRouter.shared.openSharedQuery($0) } + } + internal func route(_ request: WelcomeRequest) { pendingRequest = request showWelcomeWindow() @@ -97,6 +137,28 @@ internal final class WelcomeRouter: ObservableObject { pendingSQLFiles.append(url) } + // A shared link opened with no connection up waits for the next one to connect. + internal func enqueueSharedQuery(_ query: SharedQueryOpen) { + pendingSharedQueries.append(query) + showWelcomeWindow() + } + + internal func claimPendingSharedQueries(for connectionId: UUID) { + guard !pendingSharedQueries.isEmpty else { return } + claimedSharedQueries[connectionId, default: []] += consumePendingSharedQueries() + } + + // Closed with no connection taking them: a tab must not open hours later off an unrelated connect. + internal func welcomeDidClose() { + pendingSharedQueries.removeAll() + } + + internal func consumePendingSharedQueries() -> [SharedQueryOpen] { + let value = pendingSharedQueries + pendingSharedQueries.removeAll() + return value + } + internal func consumePendingImport() -> ConnectionBundle? { let value = pendingImport pendingImport = nil diff --git a/apple/TablePro/Core/Services/Masking/MaskingPolicy.swift b/apple/TablePro/Core/Services/Masking/MaskingPolicy.swift index f0fac9b9eb..3c41124af6 100644 --- a/apple/TablePro/Core/Services/Masking/MaskingPolicy.swift +++ b/apple/TablePro/Core/Services/Masking/MaskingPolicy.swift @@ -116,7 +116,7 @@ struct MaskingPolicy: Equatable, Sendable { } // A result names `TINYINT(1)`, `BIT(8)` or `Nullable(String)` where the rule says `tinyint`, `bit` or `string`. - private static func baseTypeName(_ typeName: String) -> String { + static func baseTypeName(_ typeName: String) -> String { let unwrapped = ColumnType.unwrappedTypeName(typeName) ?? typeName return unwrapped.prefix { $0 != "(" }.trimmingCharacters(in: .whitespaces) } @@ -177,6 +177,15 @@ struct ColumnMasks: Equatable, Sendable { styles[column] != nil } + func strictest(with other: ColumnMasks) -> ColumnMasks { + guard !other.isEmpty else { return self } + var merged = styles + for (column, style) in other.styles { + merged[column] = MaskingStyle.strictest(merged[column], style) + } + return ColumnMasks(styles: merged) + } + func value(_ value: PluginCellValue, column: Int) -> PluginCellValue { guard let style = styles[column] else { return value } return MaskedValue.mask(value, style: style) diff --git a/apple/TablePro/Core/Services/Masking/MaskingRule.swift b/apple/TablePro/Core/Services/Masking/MaskingRule.swift index 53008bbf4a..bed240cbe1 100644 --- a/apple/TablePro/Core/Services/Masking/MaskingRule.swift +++ b/apple/TablePro/Core/Services/Masking/MaskingRule.swift @@ -80,4 +80,15 @@ struct MaskingRule: Codable, Hashable, Identifiable, Sendable { var trimmedPattern: String { pattern.trimmingCharacters(in: .whitespacesAndNewlines) } + + // What the rule does, without its id: a rule stored without one gets a new id on every read. + struct Effect: Equatable, Sendable { + let pattern: String + let target: MaskingTarget + let style: MaskingStyle + } + + var effect: Effect { + Effect(pattern: pattern, target: target, style: style) + } } diff --git a/apple/TablePro/Core/Services/Query/TableQueryBuilder.swift b/apple/TablePro/Core/Services/Query/TableQueryBuilder.swift index d0e2714120..83767ad2cd 100644 --- a/apple/TablePro/Core/Services/Query/TableQueryBuilder.swift +++ b/apple/TablePro/Core/Services/Query/TableQueryBuilder.swift @@ -85,9 +85,10 @@ struct TableQueryBuilder { selectColumns: [String]? = nil, unloadedValues: UnloadedValuePlan? = nil, limit: Int = 200, - offset: Int = 0 + offset: Int = 0, + window: Bool = true ) -> String { - if let pluginDriver { + if window, let pluginDriver { let targetColumns = selectColumns ?? columns let sortCols = SortColumnResolver.resolvedIndices( for: sortState, displayColumns: columns, targetColumns: targetColumns @@ -102,15 +103,15 @@ struct TableQueryBuilder { let quotedTable = qualifiedTable(tableName, schema: schemaName) var query = "SELECT \(selectClause(selectColumns, unloadedValues: unloadedValues)) FROM \(quotedTable)" - - if let orderBy = orderByOrOffsetFetchDefault(sortState: sortState, columns: columns) { - query += " \(orderBy)" - } - - query += " \(buildPaginationClause(limit: limit, offset: offset))" + appendOrderAndWindow(to: &query, sortState: sortState, columns: columns, limit: limit, offset: offset, window: window) return query } + // A dialect is what lets the host write the statement itself, the only kind that can leave its window off. + var writesSQL: Bool { + dialect != nil + } + func buildFilteredQuery( tableName: String, schemaName: String? = nil, @@ -122,7 +123,8 @@ struct TableQueryBuilder { selectColumns: [String]? = nil, unloadedValues: UnloadedValuePlan? = nil, limit: Int = 200, - offset: Int = 0 + offset: Int = 0, + window: Bool = true ) -> String? { // A driver that writes its own SQL takes a raw condition as given, so the boundary check the // host's generator applies has to run before the driver is asked. @@ -134,7 +136,7 @@ struct TableQueryBuilder { // A driver reads a column named like the raw row as a raw condition, so a comparison on such a // column is written by the host's generator, or by no one. let reachesDriver = !filters.contains { $0.isEnabled && $0.namesRawConditionColumn } - if let pluginDriver, reachesDriver { + if window, let pluginDriver, reachesDriver { let targetColumns = selectColumns ?? columns let sortCols = SortColumnResolver.resolvedIndices( for: sortState, displayColumns: columns, targetColumns: targetColumns @@ -169,12 +171,7 @@ struct TableQueryBuilder { if !whereClause.isEmpty { query += " \(whereClause)" } - - if let orderBy = orderByOrOffsetFetchDefault(sortState: sortState, columns: columns) { - query += " \(orderBy)" - } - - query += " \(buildPaginationClause(limit: limit, offset: offset))" + appendOrderAndWindow(to: &query, sortState: sortState, columns: columns, limit: limit, offset: offset, window: window) return query } @@ -254,6 +251,26 @@ struct TableQueryBuilder { return selectColumns.map { quote($0) }.joined(separator: ", ") } + // Without a window only the person's own sort goes in: the default ORDER BY exists for OFFSET ... FETCH. + private func appendOrderAndWindow( + to query: inout String, + sortState: SortState?, + columns: [String], + limit: Int, + offset: Int, + window: Bool + ) { + let orderBy = window + ? orderByOrOffsetFetchDefault(sortState: sortState, columns: columns) + : buildOrderByClause(sortState: sortState, columns: columns) + if let orderBy { + query += " \(orderBy)" + } + if window { + query += " \(buildPaginationClause(limit: limit, offset: offset))" + } + } + private func buildPaginationClause(limit: Int, offset: Int) -> String { guard pagination.allowsSeeking else { return "LIMIT \(pagination.clampedRowCount(limit))" diff --git a/apple/TablePro/Core/Services/Shares/CloudShareService.swift b/apple/TablePro/Core/Services/Shares/CloudShareService.swift new file mode 100644 index 0000000000..6893449577 --- /dev/null +++ b/apple/TablePro/Core/Services/Shares/CloudShareService.swift @@ -0,0 +1,217 @@ +// +// CloudShareService.swift +// TablePro +// + +import Foundation +import TableProCloudAPI + +// publicAPI carries no bearer: a signed-out recipient opens a shared link too. +internal struct CloudShareService: ShareService { + private static let pageSize: Int64 = 200 + private static let maxPages = 5 + + let api: any APIProtocol + let publicAPI: any APIProtocol + let createRequest: ShareCreateRequest + + func limits() async throws(ShareFailure) -> ShareLimits { + do { + switch try await api.getShareLimits() { + case .ok(let answer): + return Self.limits(try answer.body.json) + case .unauthorized(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .forbidden(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .tooManyRequests(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .internalServerError(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .undocumented(let status, _): + throw ShareFailure.httpStatus(status) + } + } catch { + throw Self.failure(from: error) + } + } + + func create(_ draft: ShareDraft) async throws(ShareFailure) -> CreatedShare { + let answer: (status: Int, contentType: String?, body: Data) + let body = await ShareBodyWriter.encoded(draft) + do { + answer = try await createRequest.send(body) + } catch { + throw Self.failure(from: error) + } + guard answer.status == 201 else { + let problem = try? JSONDecoder().decode(ProblemCode.self, from: answer.body) + throw ShareFailure.problem(status: answer.status, code: problem?.code) + } + guard let created = try? JSONDecoder().decode(CreatedLink.self, from: answer.body), + let url = URL(string: created.url) + else { throw ShareFailure.server } + return CreatedShare(id: created.share.id, url: url) + } + + func liveLinks(teamID: String?) async throws(ShareFailure) -> [ShareLink] { + var links: [ShareLink] = [] + var cursor: String? + var pages = 0 + do { + repeat { + pages += 1 + switch try await api.listShares(query: .init( + team: teamID, state: .live, cursor: cursor, limit: Self.pageSize + )) { + case .ok(let answer): + let page = try answer.body.json + links += page.data.map(Self.link) + cursor = page.nextCursor + case .unauthorized(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .forbidden(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .notFound(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .unprocessableContent(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .tooManyRequests(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .internalServerError(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .undocumented(let status, _): + throw ShareFailure.httpStatus(status) + } + } while cursor != nil && pages < Self.maxPages + } catch { + throw Self.failure(from: error) + } + return links.sorted { $0.createdAt < $1.createdAt } + } + + func revoke(id: String) async throws(ShareFailure) { + do { + switch try await api.deleteShare(path: .init(shareId: id)) { + case .noContent: + return + case .unauthorized(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .forbidden(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .notFound(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .unprocessableContent(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .tooManyRequests(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .internalServerError(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .undocumented(let status, _): + throw ShareFailure.httpStatus(status) + } + } catch { + throw Self.failure(from: error) + } + } + + func fetchShared(token: String, password: String?) async throws(ShareFailure) -> SharedQuery { + do { + switch try await publicAPI.getShared(path: .init(token: token), headers: .init(xSharePassword: password)) { + case .ok(let answer): + let shared = try answer.body.json + return SharedQuery(kind: ShareKind(rawValue: shared.kind) ?? .query, title: shared.title, sql: shared.sql) + case .unauthorized(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .notFound(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .unprocessableContent: + throw ShareFailure.notFound + case .tooManyRequests(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .internalServerError(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .serviceUnavailable(let answer): + throw Self.failure(try answer.body.applicationProblemJson) + case .undocumented(let status, _): + throw ShareFailure.httpStatus(status) + } + } catch { + throw Self.failure(from: error) + } + } + + // MARK: - Mapping + + static func limits(_ wire: Components.Schemas.ShareLimits) -> ShareLimits { + let expiries = wire.expiries.compactMap(ShareExpiry.init(rawValue:)) + return ShareLimits( + plan: SharePlan(rawValue: wire.plan) ?? .free, + live: Int(wire.live), + liveLimit: Int(wire.liveLimit), + maxRows: Int(wire.maxRows), + expiries: expiries, + defaultExpiry: ShareExpiry(rawValue: wire.defaultExpiry) ?? expiries.last ?? .thirtyDays, + allowsPassword: wire.password, + allowsDisablingDownload: wire.disableDownload, + allowsTeamLinks: wire.team, + emailVerified: wire.emailVerified, + sharingDisabled: wire.sharingDisabled, + teams: wire.teams.map { team in + ShareTeam( + id: team.id, + name: team.name, + live: Int(team.live), + liveLimit: Int(team.liveLimit), + allowsPublicLinks: team.publicLinks + ) + } + ) + } + + static func link(_ view: Components.Schemas.ShareView) -> ShareLink { + ShareLink( + id: view.id, + title: view.title, + kind: ShareKind(rawValue: view.kind) ?? .query, + createdAt: view.createdAt, + expiresAt: view.expiresAt, + isSuspended: view.suspended + ) + } + + private static func failure(_ problem: Components.Schemas.Problem) -> ShareFailure { + ShareFailure.problem(status: Int(problem.status), code: problem.code) + } + + // Only a URL load that did not finish is offline; anything else that is not the server's answer is the app's. + static func failure(from error: any Error) -> ShareFailure { + switch error { + case let failure as ShareFailure: + return failure + case let error as ClientError: + return failure(from: error.underlyingError) + case let error as AccountError: + return ShareFailure.from(error) + case is CancellationError: + return .canceled + case let error as URLError: + return error.code == .cancelled ? .canceled : .offline + default: + return .server + } + } +} + +private struct ProblemCode: Decodable { + let code: String? +} + +private struct CreatedLink: Decodable { + struct Share: Decodable { + let id: String + } + + let share: Share + let url: String +} diff --git a/apple/TablePro/Core/Services/Shares/SecretScanner.swift b/apple/TablePro/Core/Services/Shares/SecretScanner.swift new file mode 100644 index 0000000000..5b827aaf9a --- /dev/null +++ b/apple/TablePro/Core/Services/Shares/SecretScanner.swift @@ -0,0 +1,201 @@ +// +// SecretScanner.swift +// TablePro +// + +import Foundation + +internal enum SecretKind: String, CaseIterable, Equatable, Sendable { + case awsAccessKey + case privateKey + case jsonWebToken + case gitHubToken + case slackToken + case stripeSecretKey + case googleAPIKey + case urlCredentials + case passwordLiteral + + var displayName: String { + switch self { + case .awsAccessKey: String(localized: "AWS access key") + case .privateKey: String(localized: "private key") + case .jsonWebToken: String(localized: "JSON Web Token") + case .gitHubToken: String(localized: "GitHub token") + case .slackToken: String(localized: "Slack token") + case .stripeSecretKey: String(localized: "Stripe secret key") + case .googleAPIKey: String(localized: "Google API key") + case .urlCredentials: String(localized: "URL with a password") + case .passwordLiteral: String(localized: "password value") + } + } +} + +internal struct SecretHit: Equatable, Sendable { + let kind: SecretKind + // 1-based. + let line: Int +} + +// Warns before a share goes public and never blocks one. The patterns are the core's (secret_scan.rs), in the regex +// features both engines share; `\p{White_Space}` is what Rust means by `\s`. +internal enum SecretScanner { + private enum Starts { + case anywhere + // A word that runs into `://`. + case wordBeforeScheme + // A word holding a password-like name. + case wordWithKeyword + } + + private static let keywords = "(?:password|passwd|pwd|secret|token|api_key)" + + private static let patterns: [(SecretKind, String, Starts)] = [ + (.awsAccessKey, "AKIA[0-9A-Z]{16}", .anywhere), + (.privateKey, "-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----", .anywhere), + (.jsonWebToken, "eyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+", .anywhere), + (.gitHubToken, "gh[pousr]_[A-Za-z0-9]{36,}", .anywhere), + (.slackToken, "xox[abprs]-", .anywhere), + (.stripeSecretKey, "sk_live_", .anywhere), + (.googleAPIKey, "AIza[0-9A-Za-z_-]{35}", .anywhere), + (.urlCredentials, "\\w+://[^\\p{White_Space}:/@]+:[^\\p{White_Space}@]+@", .wordBeforeScheme), + // A name may close its own quote or bracket, as in JSON or T-SQL; the value closes with the quote it opened with. + ( + .passwordLiteral, + "(?i)\\w*\(keywords)\\w*[\"'`\\]]?\\p{White_Space}*(?:=>|:=|=|:)\\p{White_Space}*(?:'[^']+'|\"[^\"]+\")", + .wordWithKeyword + ), + ] + + private static let compiled: [(SecretKind, NSRegularExpression, Starts)] = patterns.compactMap { kind, pattern, starts in + (try? NSRegularExpression(pattern: pattern)).map { (kind, $0, starts) } + } + + private static let wordRun = try? NSRegularExpression(pattern: "\\w+") + private static let keyword = try? NSRegularExpression(pattern: "(?i)" + keywords) + + private static let sensitiveColumnTerms = [ + "password", "passwd", "secret", "token", "apikey", "ssn", "creditcard", "cardnumber" + ] + + static func scanSQL(_ sql: String) -> [SecretHit] { + let text = sql as NSString + let starts = lineStarts(in: text) + let words = wordRuns(in: text) + var hits: [SecretHit] = [] + for (kind, expression, rule) in compiled { + let lines = Set(matchLocations(expression, in: text, starts: rule, words: words).map { + lineNumber(of: $0, starts: starts) + }) + hits += lines.map { SecretHit(kind: kind, line: $0) } + } + return hits.sorted { ($0.line, $0.kind.sortOrder) < ($1.line, $1.kind.sortOrder) } + } + + // ICU backtracks where Rust's automaton does not, so a long word would cost a pass per character. Only the places + // a match can begin are tried, which finds the same matches: a leading `\w*` or `\w+` reaches back to its word's + // start, and a word never runs across the end of an earlier match. + private static func matchLocations( + _ expression: NSRegularExpression, + in text: NSString, + starts rule: Starts, + words: [NSRange] + ) -> [Int] { + let length = text.length + let candidates: [Int] + switch rule { + case .anywhere: + return expression.matches(in: text as String, range: NSRange(location: 0, length: length)).map(\.range.location) + case .wordBeforeScheme: + candidates = words.compactMap { run in + let end = NSMaxRange(run) + guard end + 3 <= length, text.character(at: end) == 0x3A, text.character(at: end + 1) == 0x2F, + text.character(at: end + 2) == 0x2F + else { return nil } + return run.location + } + case .wordWithKeyword: + guard let keyword else { return [] } + var starts: Set = [] + for found in keyword.matches(in: text as String, range: NSRange(location: 0, length: length)) { + if let word = word(containing: found.range.location, in: words) { + starts.insert(word.location) + } + } + candidates = starts.sorted() + } + var locations: [Int] = [] + var searchFrom = 0 + for candidate in candidates where candidate >= searchFrom { + let range = NSRange(location: candidate, length: length - candidate) + guard let match = expression.firstMatch(in: text as String, options: .anchored, range: range) else { continue } + locations.append(match.range.location) + searchFrom = max(NSMaxRange(match.range), candidate + 1) + } + return locations + } + + private static func word(containing location: Int, in words: [NSRange]) -> NSRange? { + var low = 0 + var high = words.count + while low < high { + let middle = (low + high) / 2 + if NSMaxRange(words[middle]) <= location { low = middle + 1 } else { high = middle } + } + guard low < words.count, NSLocationInRange(location, words[low]) else { return nil } + return words[low] + } + + private static func wordRuns(in text: NSString) -> [NSRange] { + guard let wordRun else { return [] } + return wordRun.matches(in: text as String, range: NSRange(location: 0, length: text.length)).map(\.range) + } + + static func scanColumns(_ names: [String]) -> [String] { + var seen: Set = [] + return names.filter { name in + guard isSensitiveColumn(name), !seen.contains(name) else { return false } + seen.insert(name) + return true + } + } + + // Whole words as the share sheet's detectors split a name, so api_key, apiKey and API-KEY read alike and + // class_name holds no "ssn". + static func isSensitiveColumn(_ name: String) -> Bool { + SensitiveDataDetector.longestTerm(in: SensitiveDataDetector.words(in: name), terms: sensitiveColumnTerms) != nil + } + + // UTF-16 offsets where each line starts; a CRLF pair is one break. + private static func lineStarts(in text: NSString) -> [Int] { + var starts = [0] + var index = 0 + while index < text.length { + let unit = text.character(at: index) + if unit == 0x0D, index + 1 < text.length, text.character(at: index + 1) == 0x0A { + index += 2 + starts.append(index) + } else { + index += 1 + if unit == 0x0A || unit == 0x0D { starts.append(index) } + } + } + return starts + } + + private static func lineNumber(of location: Int, starts: [Int]) -> Int { + var low = 0 + var high = starts.count + while low < high { + let middle = (low + high) / 2 + if starts[middle] <= location { low = middle + 1 } else { high = middle } + } + return low + } +} + +private extension SecretKind { + var sortOrder: Int { + Self.allCases.firstIndex(of: self) ?? 0 + } +} diff --git a/apple/TablePro/Core/Services/Shares/SensitiveDataDetector.swift b/apple/TablePro/Core/Services/Shares/SensitiveDataDetector.swift new file mode 100644 index 0000000000..ae6a98a516 --- /dev/null +++ b/apple/TablePro/Core/Services/Shares/SensitiveDataDetector.swift @@ -0,0 +1,647 @@ +// +// SensitiveDataDetector.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +// What a column's name says it holds. Every TablePro app lists the same terms in the same order. +internal enum SensitiveNameKind: CaseIterable, Equatable, Sendable { + case email + case phone + case secret + case nationalID + case cardOrAccount + case address + case birthDate + case ipAddress + case personName + + var terms: [String] { + switch self { + case .email: ["email", "mail"] + case .phone: ["phone", "mobile", "tel", "telephone", "fax", "msisdn"] + case .secret: + ["password", "passwd", "pwd", "secret", "token", "apikey", "accesskey", "privatekey", "credential"] + case .nationalID: ["ssn", "socialsecurity", "nationalid", "passport", "taxid", "tin"] + case .cardOrAccount: + ["creditcard", "cardnumber", "ccnumber", "pan", "iban", "accountnumber", "routingnumber"] + case .address: ["address", "street", "zip", "zipcode", "postcode", "postal"] + case .birthDate: ["dob", "birthdate", "dateofbirth", "birthday"] + case .ipAddress: ["ip", "ipaddress", "ipv4", "ipv6"] + case .personName: ["firstname", "lastname", "fullname", "surname", "givenname"] + } + } + + var style: MaskingStyle { + switch self { + case .email: .email + case .phone, .nationalID, .cardOrAccount: .lastFour + case .secret, .address, .birthDate, .personName: .full + case .ipAddress: .hash + } + } + + var displayName: String { + switch self { + case .email: String(localized: "email address") + case .phone: String(localized: "phone number") + case .secret: String(localized: "password or secret") + case .nationalID: String(localized: "ID number") + case .cardOrAccount: String(localized: "card or account number") + case .address: String(localized: "postal address") + case .birthDate: String(localized: "date of birth") + case .ipAddress: String(localized: "IP address") + case .personName: String(localized: "person's name") + } + } +} + +// What a column's values look like, in the order that decides between two kinds. +internal enum SensitiveValueKind: CaseIterable, Equatable, Sendable { + case card + case iban + case jsonWebToken + case apiKey + case email + case phone + case ipAddress + + // One such value flags the column; the others need at least half of its values. + var flagsOnAnyValue: Bool { + switch self { + case .card, .iban, .jsonWebToken, .apiKey: true + case .email, .phone, .ipAddress: false + } + } + + var style: MaskingStyle { + switch self { + case .card, .iban, .phone: .lastFour + case .jsonWebToken, .apiKey: .full + case .email: .email + case .ipAddress: .hash + } + } + + var displayName: String { + switch self { + case .card: String(localized: "card number") + case .iban: "IBAN" + case .jsonWebToken: String(localized: "JSON Web Token") + case .apiKey: String(localized: "API key") + case .email: String(localized: "email address") + case .phone: String(localized: "phone number") + case .ipAddress: String(localized: "IP address") + } + } + + // The kinds a quoted literal in the SQL can show. + static let inSQL: [SensitiveValueKind] = [.card, .iban, .jsonWebToken, .apiKey, .email, .phone] +} + +internal enum SensitiveDetection: Equatable, Sendable { + case name(SensitiveNameKind) + case values(SensitiveValueKind) + + var style: MaskingStyle { + switch self { + case .name(let kind): kind.style + case .values(let kind): kind.style + } + } + + var displayName: String { + switch self { + case .name(let kind): kind.displayName + case .values(let kind): kind.displayName + } + } +} + +// Finds what looks like personal data before a share leaves the machine (PLAN-MASKING 8.3 and 8.3.1). The Rust core +// runs the same rules, and DETECTOR-FIXTURES.md pins both to one table. +internal enum SensitiveDataDetector { + // MARK: - Column names + + // In table order, so a tie goes to the earlier term. + private static let nameTerms: [(term: String, kind: SensitiveNameKind)] = SensitiveNameKind.allCases.flatMap { kind in + kind.terms.map { ($0, kind) } + } + + static func nameKind(_ column: String) -> SensitiveNameKind? { + let found = longestTerm(in: words(in: column), terms: nameTerms.map(\.term), singleWord: ["mail"]) + return found.map { nameTerms[$0].kind } + } + + // The index of the term that equals one word or several consecutive words joined, never part of a word: the one + // covering the most words, a tie going to the earlier term. + static func longestTerm(in words: [String], terms: [String], singleWord: Set = []) -> Int? { + let longest = terms.map(\.count).max() ?? 0 + var best: (span: Int, index: Int)? + for start in words.indices { + var joined = "" + for end in start.. span || (current.span == span && current.index <= index) { + continue + } + best = (span, index) + } + } + return best?.index + } + + // Split on `_ - . space`, where a lower-case letter meets an upper-case one, and where letters meet digits. + static func words(in name: String) -> [String] { + var words: [String] = [] + var current = String.UnicodeScalarView() + var previous: Unicode.Scalar? + func flush() { + if !current.isEmpty { + words.append(String(current).lowercased()) + } + current = String.UnicodeScalarView() + } + for scalar in name.unicodeScalars { + if scalar == "_" || scalar == "-" || scalar == "." || scalar == " " { + flush() + previous = nil + continue + } + if let previous, isBoundary(previous, scalar) { + flush() + } + current.append(scalar) + previous = scalar + } + flush() + return words + } + + private static func isBoundary(_ previous: Unicode.Scalar, _ next: Unicode.Scalar) -> Bool { + if previous.properties.isLowercase, next.properties.isUppercase { return true } + let previousIsDigit = isDigit(previous) + let nextIsDigit = isDigit(next) + return (previousIsDigit && next.properties.isAlphabetic) || (nextIsDigit && previous.properties.isAlphabetic) + } + + // MARK: - Column types + + private static let nonTextBaseType = try? NSRegularExpression( + pattern: "\\A(?:u?int[0-9]*|tinyint|smallint|mediumint|bigint|integer|serial|smallserial|bigserial|numeric" + + "|decimal[0-9]*|number|real|float[0-9]*|double|money|smallmoney|bool|boolean|bit|date[0-9]*|datetime[0-9]*" + + "|smalldatetime|datetimeoffset|time|timetz|timestamp|timestamptz|interval|year|uuid|uniqueidentifier)" + + "(?: .*)?\\z" + ) + + // Value patterns run only where a value can be free text; an unknown type can. + static func isTextLike(_ rawType: String?) -> Bool { + guard let rawType, let expression = nonTextBaseType else { return true } + let base = MaskingPolicy.baseTypeName(rawType).lowercased() + guard !base.isEmpty else { return true } + return !hasMatch(expression, base) + } + + // MARK: - Values + + // Nil too once the caller's task is cancelled, which the caller checks. + static func valueKind(of values: some Sequence) -> SensitiveValueKind? { + var nonNull = 0 + var read = 0 + var flagged: SensitiveValueKind? + var counts: [SensitiveValueKind: Int] = [:] + for value in values { + read += 1 + if read % 256 == 0, Task.isCancelled { return nil } + let text: String + switch value { + case .null: + continue + case .bytes: + nonNull += 1 + continue + case .text(let string): + nonNull += 1 + text = string + } + for kind in SensitiveValueKind.allCases where kind.flagsOnAnyValue { + if let flagged, flagged.order <= kind.order { break } + if matches(kind, text) { + flagged = kind + break + } + } + if flagged == .card { return .card } + guard flagged == nil else { continue } + for kind in SensitiveValueKind.allCases where !kind.flagsOnAnyValue && matches(kind, text) { + counts[kind, default: 0] += 1 + } + } + if let flagged { return flagged } + guard nonNull > 0 else { return nil } + return SensitiveValueKind.allCases.first { !$0.flagsOnAnyValue && counts[$0, default: 0] * 2 >= nonNull } + } + + static func matches(_ kind: SensitiveValueKind, _ text: String) -> Bool { + switch kind { + case .card: isCardNumber(text) + case .iban: isIBAN(text) + case .jsonWebToken: text.hasPrefix("eyJ") && hasMatch(jsonWebToken, text) + case .apiKey: mayHoldAPIKey(text) && hasMatch(apiKey, text) + case .email: isEmail(text) + case .phone: isPhoneNumber(text) + case .ipAddress: isIPv4(text) || isIPv6(text) + } + } + + private static let jsonWebToken = try? NSRegularExpression( + pattern: "\\AeyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\z" + ) + private static let apiKey = try? NSRegularExpression( + pattern: "AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{36,}|xox[abprs]-|sk_live_|AIza[0-9A-Za-z_-]{35}" + ) + private static let ibanShape = try? NSRegularExpression(pattern: "\\A[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}\\z") + + // `\A[^\s@]+@[^\s@]+\.[^\s@]+\z` with `\s` as White_Space, in one pass: ICU backtracks over a long domain that + // never matches. One `@` after at least one scalar, and a dot in the domain with a scalar on each side. + static func isEmail(_ text: String) -> Bool { + var local = 0 + var seenAt = false + var domain = 0 + var dotWaitsForScalar = false + var hasInnerDot = false + for scalar in text.unicodeScalars { + if scalar.properties.isWhitespace { return false } + if scalar == "@" { + guard !seenAt, local > 0 else { return false } + seenAt = true + continue + } + guard seenAt else { + local += 1 + continue + } + if dotWaitsForScalar { hasInnerDot = true } + if scalar == ".", domain > 0 { dotWaitsForScalar = true } + domain += 1 + } + return seenAt && hasInnerDot + } + + static func isCardNumber(_ text: String) -> Bool { + var digits: [UInt8] = [] + digits.reserveCapacity(19) + for byte in text.utf8 { + switch byte { + case 0x30...0x39: + digits.append(byte - 0x30) + guard digits.count <= 19 else { return false } + case 0x20, 0x2D: + continue + default: + return false + } + } + guard digits.count >= 13 else { return false } + var sum = 0 + for (offset, digit) in digits.reversed().enumerated() { + var value = Int(digit) + if offset % 2 == 1 { + value *= 2 + if value > 9 { value -= 9 } + } + sum += value + } + return sum % 10 == 0 + } + + static func isIBAN(_ text: String) -> Bool { + guard let first = text.utf8.first(where: { $0 != 0x20 }), (0x41...0x5A).contains(first) else { return false } + let compact = String(String.UnicodeScalarView(text.unicodeScalars.filter { $0 != " " })) + guard hasMatch(ibanShape, compact) else { return false } + let bytes = Array(compact.utf8) + var remainder = 0 + for byte in bytes[4...] + bytes[..<4] { + if byte >= 0x41 { + remainder = (remainder * 100 + Int(byte - 0x41 + 10)) % 97 + } else { + remainder = (remainder * 10 + Int(byte - 0x30)) % 97 + } + } + return remainder == 1 + } + + static func isPhoneNumber(_ text: String) -> Bool { + var digits = 0 + var hasSeparator = false + for (offset, byte) in text.utf8.enumerated() { + switch byte { + case 0x30...0x39: + digits += 1 + case 0x2B where offset == 0: + hasSeparator = true + case 0x28, 0x29, 0x20, 0x2E, 0x2D: + hasSeparator = true + default: + return false + } + } + guard (7...15).contains(digits), hasSeparator else { return false } + return !isIPv4(text) && !startsWithISODate(text) && !isPlainDecimal(text) + } + + // `^[0-9]{4}-[0-9]{2}-[0-9]{2}` + private static func startsWithISODate(_ text: String) -> Bool { + let bytes = Array(text.utf8.prefix(10)) + guard bytes.count == 10 else { return false } + return bytes.indices.allSatisfy { offset in + offset == 4 || offset == 7 ? bytes[offset] == 0x2D : isDigit(bytes[offset]) + } + } + + // `^[+-]?[0-9]+\.[0-9]+$` + private static func isPlainDecimal(_ text: String) -> Bool { + var bytes = Array(text.utf8) + if let sign = bytes.first, sign == 0x2B || sign == 0x2D { + bytes.removeFirst() + } + guard let dot = bytes.firstIndex(of: 0x2E) else { return false } + let whole = bytes[.. Bool { + var text = text + return text.withUTF8 { bytes in + guard bytes.count >= 4 else { return false } + for index in 0..<(bytes.count - 3) { + let next = (bytes[index + 1], bytes[index + 2], bytes[index + 3]) + switch bytes[index] { + case UInt8(ascii: "A") where next == (0x4B, 0x49, 0x41) || next == (0x49, 0x7A, 0x61): return true + case UInt8(ascii: "g") where next.0 == UInt8(ascii: "h") && next.2 == UInt8(ascii: "_"): return true + case UInt8(ascii: "x") where next.0 == UInt8(ascii: "o") && next.1 == UInt8(ascii: "x"): return true + case UInt8(ascii: "s") where next == (0x6B, 0x5F, 0x6C): return true + default: continue + } + } + return false + } + } + + static func isIPv4(_ text: String) -> Bool { + var parser = AddressParser(text) + return parser.readIPv4() && parser.isAtEnd + } + + static func isIPv6(_ text: String) -> Bool { + var parser = AddressParser(text) + return parser.readIPv6() && parser.isAtEnd + } + + // MARK: - SQL + + struct PersonalDataHit: Equatable, Sendable { + let kind: SensitiveValueKind + // The line the literal starts on, from 1; CR, LF and CRLF each end a line. + let line: Int + } + + // Each literal takes the first kind it shows; each kind once per line, by line. + static func personalDataHits(inSQL sql: String) -> [PersonalDataHit] { + var hits: [PersonalDataHit] = [] + for literal in quotedLiterals(in: sql) { + guard let kind = SensitiveValueKind.inSQL.first(where: { matches($0, literal.text) }) else { continue } + let hit = PersonalDataHit(kind: kind, line: literal.line) + if !hits.contains(hit) { + hits.append(hit) + } + } + return hits.sorted { ($0.line, $0.kind.order) < ($1.line, $1.kind.order) } + } + + // The kinds the SQL's literals show, in table order. + static func personalData(inSQL sql: String) -> [SensitiveValueKind] { + let found = Set(personalDataHits(inSQL: sql).map(\.kind)) + return SensitiveValueKind.inSQL.filter(found.contains) + } + + // Closed single-quoted literals, `''` read as a quote inside one. Double-quoted text is a name, `--` to the end of + // the line and `/* */` are comments, all skipped, so an apostrophe there opens nothing; a literal left open is not + // read. + static func quotedLiterals(in sql: String) -> [(line: Int, text: String)] { + var literals: [(line: Int, text: String)] = [] + let scalars = Array(sql.unicodeScalars) + var line = 1 + var index = 0 + func advance() { + let scalar = scalars[index] + index += 1 + let endsLine = scalar == "\n" || (scalar == "\r" && (index == scalars.count || scalars[index] != "\n")) + if endsLine { line += 1 } + } + func next(is scalar: Unicode.Scalar) -> Bool { + index < scalars.count && scalars[index] == scalar + } + while index < scalars.count { + let opener = scalars[index] + let startLine = line + advance() + if opener == "-", next(is: "-") { + while index < scalars.count, scalars[index] != "\n", scalars[index] != "\r" { + advance() + } + } else if opener == "/", next(is: "*") { + advance() + while index < scalars.count { + let closes = scalars[index] == "*" && index + 1 < scalars.count && scalars[index + 1] == "/" + advance() + if closes { + advance() + break + } + } + } else if opener == "\"" { + while index < scalars.count { + let closes = scalars[index] == "\"" + advance() + if closes { break } + } + } else if opener == "'" { + var literal: [Unicode.Scalar] = [] + var closed = false + while index < scalars.count { + let scalar = scalars[index] + advance() + guard scalar == "'" else { + literal.append(scalar) + continue + } + if index < scalars.count, scalars[index] == "'" { + literal.append("'") + advance() + } else { + closed = true + break + } + } + if closed { + literals.append((startLine, String(String.UnicodeScalarView(literal)))) + } + } + } + return literals + } + + // MARK: - A result + + // Each window is a count of leading rows, read on its own with its own thresholds; a column any window flags is + // flagged, with the first kind in table order. Nil once the caller's task is cancelled. Columns the connection's + // rules mask get nothing: their values are gone. + static func detections(in source: ShareResultSource, windows: [Int]) -> [Int: SensitiveDetection]? { + var detections: [Int: SensitiveDetection] = [:] + let counts = Set(windows.map { min(max(0, $0), source.rows.count) }).filter { $0 > 0 } + for index in source.columns.indices where !source.masks.isMasked(index) { + if Task.isCancelled { return nil } + if let kind = nameKind(source.columns[index]) { + detections[index] = .name(kind) + continue + } + let rawType = source.columnTypes.indices.contains(index) ? source.columnTypes[index].rawType : nil + guard isTextLike(rawType) else { continue } + var found: SensitiveValueKind? + for count in counts { + let values = source.rows.prefix(count).lazy.map { $0.indices.contains(index) ? $0[index] : .null } + let kind = valueKind(of: values) + if Task.isCancelled { return nil } + if let kind, found.map({ kind.order < $0.order }) ?? true { + found = kind + } + } + if let found { + detections[index] = .values(found) + } + } + return detections + } + + // MARK: - Helpers + + private static func isDigit(_ scalar: Unicode.Scalar) -> Bool { + ("0"..."9").contains(scalar) + } + + private static func isDigit(_ byte: UInt8) -> Bool { + (0x30...0x39).contains(byte) + } + + private static func hasMatch(_ expression: NSRegularExpression?, _ text: String) -> Bool { + guard let expression else { return false } + return expression.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) != nil + } +} + +private extension SensitiveValueKind { + var order: Int { + Self.allCases.firstIndex(of: self) ?? 0 + } +} + +// Rust's `std::net` address parser, step for step, so both apps agree on every edge. +private struct AddressParser { + private let bytes: [UInt8] + private var position = 0 + + init(_ text: String) { + bytes = Array(text.utf8) + } + + var isAtEnd: Bool { + position == bytes.count + } + + mutating func readIPv4() -> Bool { + let start = position + for part in 0..<4 { + guard part == 0 || read(0x2E), let value = readNumber(radix: 10, maxDigits: 3, allowsZeroPrefix: false), + value <= 255 + else { + position = start + return false + } + } + return true + } + + mutating func readIPv6() -> Bool { + let start = position + let head = readGroups(limit: 8) + if head.count == 8 { return true } + guard !head.endsInIPv4, read(0x3A), read(0x3A) else { + position = start + return false + } + _ = readGroups(limit: 8 - (head.count + 1)) + return true + } + + private mutating func readGroups(limit: Int) -> (count: Int, endsInIPv4: Bool) { + for index in 0.. Int? { + let start = position + let hasLeadingZero = position < bytes.count && bytes[position] == 0x30 + var value = 0 + var digits = 0 + while position < bytes.count, let digit = Self.digit(bytes[position], radix: radix) { + position += 1 + value = value * radix + digit + digits += 1 + if digits > maxDigits { + position = start + return nil + } + } + if digits == 0 || (!allowsZeroPrefix && hasLeadingZero && digits > 1) { + position = start + return nil + } + return value + } + + private mutating func read(_ byte: UInt8) -> Bool { + guard position < bytes.count, bytes[position] == byte else { return false } + position += 1 + return true + } + + private static func digit(_ byte: UInt8, radix: Int) -> Int? { + switch byte { + case 0x30...0x39: return Int(byte - 0x30) + case 0x61...0x66 where radix == 16: return Int(byte - 0x61 + 10) + case 0x41...0x46 where radix == 16: return Int(byte - 0x41 + 10) + default: return nil + } + } +} diff --git a/apple/TablePro/Core/Services/Shares/ShareColumnChoice.swift b/apple/TablePro/Core/Services/Shares/ShareColumnChoice.swift new file mode 100644 index 0000000000..9d1aa2c285 --- /dev/null +++ b/apple/TablePro/Core/Services/Shares/ShareColumnChoice.swift @@ -0,0 +1,140 @@ +// +// ShareColumnChoice.swift +// TablePro +// + +import Foundation + +// What a share does with one column of the result: send it as it is, mask it, or leave it out. +internal struct ShareColumnChoice: Identifiable, Equatable, Sendable { + enum Action: String, CaseIterable, Identifiable, Sendable { + case keep + case mask + case remove + + var id: String { rawValue } + + var displayName: String { + switch self { + case .keep: String(localized: "Keep") + case .mask: String(localized: "Mask") + case .remove: String(localized: "Remove") + } + } + } + + // The column's position in the share source. + let index: Int + let name: String + // The connection's rules mask this column for everything leaving the app, so it is never sent as it is. + let ruleStyle: MaskingStyle? + // Masked whole only because nothing traced it to a table column, whatever the rules say. + let isUntraced: Bool + let detection: SensitiveDetection? + private(set) var action: Action + private(set) var style: MaskingStyle + + var id: Int { index } + + init(index: Int, name: String, ruleStyle: MaskingStyle?, detection: SensitiveDetection?, isUntraced: Bool = false) { + self.index = index + self.name = name + self.ruleStyle = ruleStyle + self.isUntraced = isUntraced + self.detection = detection + if let ruleStyle { + action = .mask + style = ruleStyle + } else if let detection { + action = .mask + style = detection.style + } else { + action = .keep + style = .full + } + } + + var allowsKeep: Bool { + ruleStyle == nil + } + + // Under a rule only a style that hides at least as much: the rule's own, Full or NULL. + var allowedStyles: [MaskingStyle] { + MaskingStyle.allCases.filter { MaskingStyle.strictest(ruleStyle, $0) == $0 } + } + + func choosing(_ action: Action) -> ShareColumnChoice? { + guard action != .keep || allowsKeep else { return nil } + var choice = self + choice.action = action + return choice + } + + func choosing(style: MaskingStyle) -> ShareColumnChoice? { + guard allowedStyles.contains(style) else { return nil } + var choice = self + choice.style = style + return choice + } + + var maskedStyle: MaskingStyle? { + action == .mask ? style : nil + } + + // Nil when the column is left out. A rule's own style is already on the values, so it is not applied twice. + var sharedColumn: ShareSnapshotBuilder.SharedColumn? { + switch action { + case .remove: nil + case .keep: ShareSnapshotBuilder.SharedColumn(source: index, applying: nil, masked: nil) + case .mask: ShareSnapshotBuilder.SharedColumn(source: index, applying: style == ruleStyle ? nil : style, masked: style) + } + } + + // Nil once the caller's task is cancelled. + static func defaults(for source: ShareResultSource, windows: [Int]) -> [ShareColumnChoice]? { + guard let detections = SensitiveDataDetector.detections(in: source, windows: windows) else { return nil } + return source.columns.indices.map { index in + ShareColumnChoice( + index: index, + name: source.columns[index], + ruleStyle: source.masks.styles[index], + detection: detections[index], + isUntraced: source.untracedColumns.contains(index) + ) + } + } + + // What the person chose before the rows were read again, matched by column name and held to what each column allows. + static func carryingOver(_ previous: [ShareColumnChoice], onto defaults: [ShareColumnChoice]) -> [ShareColumnChoice] { + guard !previous.isEmpty else { return defaults } + var unmatched = previous + return defaults.map { choice in + guard let match = unmatched.firstIndex(where: { $0.name == choice.name }) else { return choice } + let earlier = unmatched.remove(at: match) + var carried = choice.choosing(style: earlier.style) ?? choice + carried = carried.choosing(earlier.action) ?? carried + return carried + } + } + + // Detection reads the first max_rows rows and the rows a keep-everything snapshot sends, as the core does, so neither + // the body budget nor a short sensitive run hides a column. Nil once the caller's task is cancelled. + static func prepare(_ source: ShareResultSource, maxRows: Int, keeping previous: [ShareColumnChoice]) -> SharePreparation? { + let rowCap = max(0, maxRows) + guard let everything = ShareSnapshotBuilder.build(source, maxRows: rowCap) else { return nil } + let sentWhole = if case .snapshot(let snapshot) = everything { snapshot.rows.count } else { 0 } + guard let defaults = defaults(for: source, windows: [rowCap, sentWhole]) else { return nil } + let columns = carryingOver(previous, onto: defaults) + guard let built = ShareSnapshotBuilder.build(source, maxRows: rowCap, columns: columns.compactMap(\.sharedColumn)) + else { return nil } + return SharePreparation(columns: columns, rowCap: rowCap, snapshot: built) + } +} + +// What a share sheet starts from once the rows are read. +internal struct SharePreparation: Sendable { + let columns: [ShareColumnChoice] + // The rows the detectors read, which the snapshot never goes past. + let rowCap: Int + let snapshot: ShareSnapshotOutcome +} diff --git a/apple/TablePro/Core/Services/Shares/ShareCreateRequest.swift b/apple/TablePro/Core/Services/Shares/ShareCreateRequest.swift new file mode 100644 index 0000000000..c39ef93bae --- /dev/null +++ b/apple/TablePro/Core/Services/Shares/ShareCreateRequest.swift @@ -0,0 +1,136 @@ +// +// ShareCreateRequest.swift +// TablePro +// + +import Foundation +import TableProCloudAPI + +// POST /v2/shares with a body written here: the generated client's JSONEncoder cannot write a number with more digits +// than a Double holds, nor keep a JSON column's key order, and a snapshot needs both. +internal struct ShareCreateRequest: Sendable { + let serverURL: URL + let transport: any ClientTransport + let middlewares: [any ClientMiddleware] + + private static let operationID = "create-share" + private static let maxResponseBytes = 1_048_576 + + func send(_ body: Data) async throws -> (status: Int, contentType: String?, body: Data) { + var request = HTTPRequest(method: .post, scheme: nil, authority: nil, path: "/shares") + request.headerFields[.contentType] = "application/json; charset=utf-8" + request.headerFields[.accept] = "application/json, application/problem+json" + + let transport = transport + var next: @concurrent @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?) = { request, body, url in + try await transport.send(request, body: body, baseURL: url, operationID: Self.operationID) + } + for middleware in middlewares.reversed() { + let inner = next + next = { request, body, url in + try await middleware.intercept(request, body: body, baseURL: url, operationID: Self.operationID, next: inner) + } + } + let (response, responseBody) = try await next(request, HTTPBody(body), serverURL) + var data = Data() + if let responseBody { + data = try await Data(collecting: responseBody, upTo: Self.maxResponseBytes) + } + return (response.status.code, response.headerFields[.contentType], data) + } +} + +// The create body as the contract names it (api/v2.json, CreateShareBody). +internal enum ShareBodyWriter { + // The contract's maxLength for a dialect, and for a column's name and type, in Unicode scalars. + static let dialectLimit = 40 + static let columnTextLimit = 256 + + // A snapshot body runs to 4.5 MB, too much to write on the main actor at Create. + @concurrent + static func encoded(_ draft: ShareDraft) async -> Data { + body(draft) + } + + static func body(_ draft: ShareDraft) -> Data { + var json = "{" + var first = true + func field(_ name: String, _ value: String) { + json += (first ? "" : ",") + quoted(name) + ":" + value + first = false + } + field("kind", quoted(draft.kind.rawValue)) + field("sql", quoted(draft.sql)) + if !draft.title.isEmpty { field("title", quoted(draft.title)) } + if let note = draft.note { field("note", quoted(note)) } + if let dialect = draft.dialect { field("dialect", quoted(clipped(dialect, to: dialectLimit))) } + field("expiry", quoted(draft.expiry.rawValue)) + if let hidesSQL = draft.hidesSQL { field("hide_sql", hidesSQL ? "true" : "false") } + if let allowsDownload = draft.allowsDownload { field("allow_download", allowsDownload ? "true" : "false") } + if let password = draft.password { field("password", quoted(password)) } + if let teamID = draft.teamID { field("team_id", quoted(teamID)) } + if let snapshot = draft.snapshot { field("snapshot", self.snapshot(snapshot)) } + json += "}" + return Data(json.utf8) + } + + static func snapshot(_ snapshot: ShareSnapshot) -> String { + let columns = snapshot.columns.map { column in + var object = "{\"name\":" + quoted(clipped(column.name, to: columnTextLimit)) + if let type = column.type { + object += ",\"type\":" + quoted(clipped(type, to: columnTextLimit)) + } + // The style names are the contract's ShareMaskStyle values. + if let masked = column.masked { + object += ",\"masked\":" + quoted(masked.rawValue) + } + return object + "}" + } + let rows = snapshot.rows.map { row in "[" + row.map(cell).joined(separator: ",") + "]" } + var json = "{\"columns\":[" + columns.joined(separator: ",") + "],\"rows\":[" + rows.joined(separator: ",") + "]" + // The count when more rows exist than were sent; more_rows when they exist and nobody counted them. + if let total = snapshot.rowCount { + if total > snapshot.rows.count { + json += ",\"row_count\":\(total)" + } + } else { + json += ",\"more_rows\":true" + } + return json + "}" + } + + static func cell(_ cell: ShareCell) -> String { + switch cell { + case .null: return "null" + case .bool(let flag): return flag ? "true" : "false" + case .number(let token), .document(let token): return token + case .string(let text): return quoted(text) + case .array(let cells): return "[" + cells.map(self.cell).joined(separator: ",") + "]" + } + } + + static func quoted(_ text: String) -> String { + var result = "\"" + result.unicodeScalars.reserveCapacity(text.unicodeScalars.count + 2) + for scalar in text.unicodeScalars { + switch scalar { + case "\"": result += "\\\"" + case "\\": result += "\\\\" + case "\n": result += "\\n" + case "\r": result += "\\r" + case "\t": result += "\\t" + default: + if scalar.value < 0x20 { + result += String(format: "\\u%04x", scalar.value) + } else { + result.unicodeScalars.append(scalar) + } + } + } + return result + "\"" + } + + private static func clipped(_ text: String, to limit: Int) -> String { + String(String.UnicodeScalarView(text.unicodeScalars.prefix(limit))) + } +} diff --git a/apple/TablePro/Core/Services/Shares/ShareModels.swift b/apple/TablePro/Core/Services/Shares/ShareModels.swift new file mode 100644 index 0000000000..8d9f248882 --- /dev/null +++ b/apple/TablePro/Core/Services/Shares/ShareModels.swift @@ -0,0 +1,251 @@ +// +// ShareModels.swift +// TablePro +// + +import Foundation + +internal enum SharePlan: String, Equatable, Sendable { + case free + case pro +} + +internal enum ShareKind: String, Equatable, Sendable { + case query + case result +} + +internal enum ShareExpiry: String, CaseIterable, Identifiable, Equatable, Sendable { + case oneDay = "1d" + case sevenDays = "7d" + case thirtyDays = "30d" + case never + + var id: String { rawValue } + + var displayName: String { + switch self { + case .oneDay: String(localized: "1 day") + case .sevenDays: String(localized: "7 days") + case .thirtyDays: String(localized: "30 days") + case .never: String(localized: "Never") + } + } +} + +internal struct ShareLimits: Equatable, Sendable { + let plan: SharePlan + let live: Int + let liveLimit: Int + let maxRows: Int + let expiries: [ShareExpiry] + let defaultExpiry: ShareExpiry + let allowsPassword: Bool + let allowsDisablingDownload: Bool + let allowsTeamLinks: Bool + let emailVerified: Bool + let sharingDisabled: Bool + // The teams the account holds a seat in; empty on Free. + var teams: [ShareTeam] = [] + + var isAtCap: Bool { + live >= liveLimit + } + + func allows(_ expiry: ShareExpiry) -> Bool { + expiries.contains(expiry) + } + + func team(_ id: String) -> ShareTeam? { + teams.first { $0.id == id } + } +} + +internal struct ShareTeam: Identifiable, Equatable, Sendable { + let id: String + let name: String + var live: Int + let liveLimit: Int + let allowsPublicLinks: Bool + + var isAtCap: Bool { + live >= liveLimit + } +} + +// Who a new link belongs to: the account, or one of its teams. +internal enum ShareTarget: Hashable, Sendable { + case personal + case team(String) + + var teamID: String? { + guard case .team(let id) = self else { return nil } + return id + } +} + +// A cell as the core writes it: numbers and JSON documents go as their exact text, never through a Double. +internal enum ShareCell: Equatable, Sendable { + case null + case bool(Bool) + // A JSON number token, digits exactly as the database gave them. + case number(String) + case string(String) + // A JSON document, written as its own text so its key order and digits survive. + case document(String) + case array([ShareCell]) +} + +internal struct ShareSnapshot: Equatable, Sendable { + struct Column: Equatable, Sendable { + let name: String + let type: String? + var masked: MaskingStyle? + } + + let columns: [Column] + let rows: [[ShareCell]] + // The result's true total, at least rows.count; nil when more rows exist and nobody counted them. + let rowCount: Int? + + var isTruncated: Bool { + guard let rowCount else { return true } + return rowCount > rows.count + } +} + +internal struct ShareDraft: Equatable, Sendable { + let kind: ShareKind + let sql: String + let title: String + let note: String? + let dialect: String? + let expiry: ShareExpiry + // Sent only for a result; a query share always shows its SQL. + let hidesSQL: Bool? + // Sent only to turn downloads off, which needs Pro. + let allowsDownload: Bool? + let password: String? + let teamID: String? + let snapshot: ShareSnapshot? +} + +internal struct CreatedShare: Equatable, Sendable { + let id: String + let url: URL +} + +internal struct ShareLink: Identifiable, Equatable, Sendable { + let id: String + let title: String + let kind: ShareKind + let createdAt: Date + let expiresAt: Date? + // Still live and holding a slot, but it does not resolve while the team or staff has sharing off. + let isSuspended: Bool +} + +internal struct SharedQuery: Equatable, Sendable { + let kind: ShareKind + let title: String + // Nil when the owner hid the SQL of a result share. + let sql: String? +} + +internal enum ShareFailure: Error, Equatable, Sendable { + case signedOut + case emailUnverified + case proRequired + case sharingDisabled + case teamSharingDisabled + case seatRequired + case notFound + case limitReached + case revoked + case removed + case snapshotTooLarge + case invalid + case rateLimited + case passwordRequired + case passwordWrong + case offline + case canceled + case server + + static func problem(status: Int, code: String?) -> ShareFailure { + switch code { + case "unauthorized": return .signedOut + case "email_unverified": return .emailUnverified + case "pro_required": return .proRequired + case "sharing_disabled": return .sharingDisabled + case "team_sharing_disabled": return .teamSharingDisabled + case "seat_required": return .seatRequired + case "not_found": return .notFound + case "share_limit_reached": return .limitReached + case "share_revoked": return .revoked + case "share_removed": return .removed + case "snapshot_too_large": return .snapshotTooLarge + case "validation_failed": return .invalid + case "rate_limited": return .rateLimited + case "share_password_required": return .passwordRequired + case "share_password_wrong": return .passwordWrong + default: return httpStatus(status) + } + } + + static func httpStatus(_ status: Int) -> ShareFailure { + switch status { + case 401: return .signedOut + case 404: return .notFound + case 409: return .limitReached + case 413: return .snapshotTooLarge + case 422: return .invalid + case 429: return .rateLimited + default: return .server + } + } + + static func from(_ error: AccountError) -> ShareFailure { + switch error { + case .canceled: + return .canceled + case .signedOut: + return .signedOut + case .network: + return .offline + case .server(let status, let code): + return problem(status: status, code: code) + case .oauth("invalid_grant", _): + return .signedOut + case .oauth, .invalidResponse, .stateMismatch, .entitlementRejected: + return .server + } + } + + // What a create or a load shows, or nil when there is nothing to say. + var message: String? { + switch self { + case .canceled: + return nil + case .signedOut: + return String(localized: "Sign in to your TablePro account to share links.") + case .emailUnverified: + return String(localized: "Verify your email address to share links.") + case .proRequired: + return String(localized: "This option needs TablePro Pro.") + case .sharingDisabled: + return String(localized: "Sharing is turned off for this account.") + case .teamSharingDisabled: + return String(localized: "Public links are turned off for this team.") + case .snapshotTooLarge: + return String(localized: "This result is too large to share.") + case .rateLimited: + return String(localized: "Too many links just now. Try again in a moment.") + case .offline: + return String(localized: "You appear to be offline. Try again once you're connected.") + case .seatRequired, .notFound, .limitReached, .revoked, .removed, .invalid, + .passwordRequired, .passwordWrong, .server: + return String(localized: "The link couldn't be created. Try again.") + } + } +} diff --git a/apple/TablePro/Core/Services/Shares/ShareService.swift b/apple/TablePro/Core/Services/Shares/ShareService.swift new file mode 100644 index 0000000000..52f47b1aaa --- /dev/null +++ b/apple/TablePro/Core/Services/Shares/ShareService.swift @@ -0,0 +1,27 @@ +// +// ShareService.swift +// TablePro +// + +import Foundation + +internal protocol ShareService: Sendable { + func limits() async throws(ShareFailure) -> ShareLimits + func create(_ draft: ShareDraft) async throws(ShareFailure) -> CreatedShare + // The live links of the account, or of the team named, oldest first. + func liveLinks(teamID: String?) async throws(ShareFailure) -> [ShareLink] + func revoke(id: String) async throws(ShareFailure) + // The public read a tablepro://share link opens; needs no session. + func fetchShared(token: String, password: String?) async throws(ShareFailure) -> SharedQuery +} + +internal enum ShareToken { + static let length = 43 + + // 43 characters of base62, the only shape the server ever issues. + static func isValid(_ token: String) -> Bool { + token.utf8.count == length && token.utf8.allSatisfy { byte in + (0x30...0x39).contains(byte) || (0x41...0x5A).contains(byte) || (0x61...0x7A).contains(byte) + } + } +} diff --git a/apple/TablePro/Core/Services/Shares/ShareSnapshotBuilder.swift b/apple/TablePro/Core/Services/Shares/ShareSnapshotBuilder.swift new file mode 100644 index 0000000000..be92753a9a --- /dev/null +++ b/apple/TablePro/Core/Services/Shares/ShareSnapshotBuilder.swift @@ -0,0 +1,251 @@ +// +// ShareSnapshotBuilder.swift +// TablePro +// + +import Foundation +import TableProPluginKit + +// The rows a Share Result sheet works from: visible columns in grid order, display order, masked values. +internal struct ShareResultSource: Sendable { + let columns: [String] + let columnTypes: [ColumnType] + let rows: [[PluginCellValue]] + // The result's true total, at least rows.count; nil when more rows exist and nobody counted them. + let totalRowCount: Int? + // The statement these rows came from. + let sql: String + // The columns whose values the connection's rules already masked, and how. + var masks: ColumnMasks = .none + // The masked columns nothing traced to a table column. + var untracedColumns: Set = [] +} + +internal enum ShareSnapshotOutcome: Equatable, Sendable { + case snapshot(ShareSnapshot) + case tooLarge + // Every column was removed. + case noColumns +} + +internal enum ShareSnapshotBuilder { + static let maxColumns = 100 + static let maxCellBytes = 256 * 1_024 + // Under the server's 5 MiB, so a size it counts differently never refuses a share the sheet offered. + static let maxBodyBytes = 4_500_000 + + // One column of the snapshot, read from a column of the source. + struct SharedColumn: Equatable, Sendable { + let source: Int + // Masked here, over what the source holds; nil sends the source's value. + let applying: MaskingStyle? + // What the snapshot tells the viewer the values were masked with. + let masked: MaskingStyle? + } + + // Every column of the source, its rule masks marked. + static func sharedColumns(of source: ShareResultSource) -> [SharedColumn] { + source.columns.indices.map { SharedColumn(source: $0, applying: nil, masked: source.masks.styles[$0]) } + } + + // Nil once the caller's task is cancelled. Past the server's column cap the first columns go, as from every app. + static func build(_ source: ShareResultSource, maxRows: Int, columns shared: [SharedColumn]? = nil) -> ShareSnapshotOutcome? { + guard !source.columns.isEmpty else { return .tooLarge } + let kept = (shared ?? sharedColumns(of: source)).filter { source.columns.indices.contains($0.source) } + guard !kept.isEmpty else { return .noColumns } + let shared = Array(kept.prefix(maxColumns)) + let columns = shared.map { column in + ShareSnapshot.Column( + name: source.columns[column.source], + type: typeLabel(source.columnTypes, at: column.source), + masked: column.masked + ) + } + + var rows: [[ShareCell]] = [] + rows.reserveCapacity(min(source.rows.count, max(0, maxRows))) + var bodyBytes = 2 + columns.reduce(0) { $0 + ShareCellEncoder.quotedByteCount($1.name) + 24 } + for row in source.rows { + guard rows.count < maxRows else { break } + if rows.count % 256 == 0, Task.isCancelled { return nil } + var cells: [ShareCell] = [] + cells.reserveCapacity(columns.count) + var rowBytes = 2 + max(0, columns.count - 1) + 1 + for column in shared { + var value = row.indices.contains(column.source) ? row[column.source] : .null + if let style = column.applying { + value = MaskedValue.mask(value, style: style) + } + // A masked value is text whatever the column held, so a hash of digits never reads as a number. + let type = column.masked == nil && source.columnTypes.indices.contains(column.source) + ? source.columnTypes[column.source] : .text(rawType: nil) + let cell = ShareCellEncoder.encode(value, type: type) + let size = ShareCellEncoder.jsonByteCount(cell) + guard size <= maxCellBytes else { return .tooLarge } + rowBytes += size + cells.append(cell) + } + if bodyBytes + rowBytes > maxBodyBytes { + guard !rows.isEmpty else { return .tooLarge } + break + } + bodyBytes += rowBytes + rows.append(cells) + } + + return .snapshot(ShareSnapshot( + columns: columns, + rows: rows, + rowCount: source.totalRowCount.map { max($0, rows.count) } + )) + } + + private static func typeLabel(_ types: [ColumnType], at index: Int) -> String? { + guard types.indices.contains(index) else { return nil } + return types[index].rawType ?? types[index].displayName.lowercased() + } +} + +// The core's snapshot cell rules (core/crates/core/src/export/snapshot.rs), so a result looks the same from any app. +internal enum ShareCellEncoder { + static func encode(_ cell: PluginCellValue, type: ColumnType) -> ShareCell { + switch cell { + case .null: + return .null + case .bytes(let data): + // Data, not interface text: every app and the viewer write the same words. + return .string("(binary, \(data.count) bytes)") + case .text(let value): + return encode(text: value, type: type) + } + } + + private static func encode(text value: String, type: ColumnType) -> ShareCell { + switch type { + case .boolean: + return boolean(value) + case .integer: + return JsonNumberNormalizer.integerLiteral(from: value).map(ShareCell.number) ?? .string(value) + case .decimal: + // NaN and Infinity have no JSON number, so they go as their names. + return JsonNumberNormalizer.numberLiteral(from: value).map(ShareCell.number) ?? .string(value) + case .json: + return document(value) ?? .string(value) + case .array(_, let element): + return array(value, element: element) + case .timestamp, .datetime: + return .string(isoTimestamp(value)) + case .text, .date, .blob, .enumType, .set, .spatial, .vector: + return .string(value) + } + } + + private static func boolean(_ value: String) -> ShareCell { + switch value.lowercased() { + case "true", "t", "1", "yes", "on": + return .bool(true) + case "false", "f", "0", "no", "off": + return .bool(false) + default: + // MySQL's BOOLEAN is TINYINT(1), which also stores 2 or -1. + return JsonNumberNormalizer.integerLiteral(from: value).map(ShareCell.number) ?? .string(value) + } + } + + private static func document(_ value: String) -> ShareCell? { + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, trimmed.isValidJson else { return nil } + return .document(trimmed) + } + + // A driver that writes arrays as JSON gives a document; PostgreSQL's literal is read element by element. + private static func array(_ value: String, element: ColumnType) -> ShareCell { + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.hasPrefix("["), let document = document(trimmed) { + return document + } + guard let elements = PostgresArrayLiteralCodec.parse(trimmed) else { return .string(value) } + return .array(elements.map { item in + if case .value(let text) = item { + return encode(text: text, type: element) + } + return .null + }) + } + + private static let timestampPattern = try? NSRegularExpression( + pattern: "^(-?\\d{4,}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?) ?(Z|[+-]\\d{2}(?::?\\d{2}){0,2})?( BC)?$" + ) + + // ISO 8601 as the core writes it: a T between date and time, and an offset as +HH:MM. + static func isoTimestamp(_ value: String) -> String { + let text = value as NSString + guard let pattern = timestampPattern, + let match = pattern.firstMatch(in: value, range: NSRange(location: 0, length: text.length)) + else { return value } + func group(_ index: Int) -> String? { + let range = match.range(at: index) + return range.location == NSNotFound ? nil : text.substring(with: range) + } + let date = group(1) ?? "" + let time = group(2) ?? "" + let offset = group(3).map(isoOffset) ?? "" + return date + "T" + time + offset + (group(4) ?? "") + } + + private static func isoOffset(_ offset: String) -> String { + guard offset != "Z" else { return "+00:00" } + let sign = offset.prefix(1) + let digits = offset.dropFirst().filter(\.isNumber) + let hours = digits.prefix(2) + let minutes = digits.dropFirst(2).prefix(2) + let seconds = digits.dropFirst(4).prefix(2) + var text = sign + hours + ":" + (minutes.isEmpty ? "00" : minutes) + if !seconds.isEmpty, seconds != "00" { + text += ":" + seconds + } + return String(text) + } + + static func jsonByteCount(_ cell: ShareCell) -> Int { + switch cell { + case .null: return 4 + case .bool(let value): return value ? 4 : 5 + case .number(let token): return token.utf8.count + case .document(let text): return text.utf8.count + case .string(let value): return quotedByteCount(value) + case .array(let cells): return cells.reduce(2 + max(0, cells.count - 1)) { $0 + jsonByteCount($1) } + } + } + + static func quotedByteCount(_ value: String) -> Int { + var count = 2 + for byte in value.utf8 { + switch byte { + case 0x22, 0x5C, 0x08, 0x0C, 0x0A, 0x0D, 0x09: count += 2 + case 0x00..<0x20, 0x3C, 0x3E, 0x26: count += 6 + default: count += 1 + } + } + return count + } + + // How the preview shows a cell, as one line. + static func previewText(_ cell: ShareCell) -> String { + switch cell { + case .null: return "" + case .bool(let flag): return flag ? "true" : "false" + case .number(let token): return token + case .string(let text), .document(let text): return text + case .array(let cells): return "[" + cells.map(previewElement).joined(separator: ", ") + "]" + } + } + + private static func previewElement(_ cell: ShareCell) -> String { + switch cell { + case .null: return "null" + case .string(let text): return "\"\(text)\"" + default: return previewText(cell) + } + } +} diff --git a/apple/TablePro/Core/Services/Shares/SharedLinkOpener.swift b/apple/TablePro/Core/Services/Shares/SharedLinkOpener.swift new file mode 100644 index 0000000000..9be3644de4 --- /dev/null +++ b/apple/TablePro/Core/Services/Shares/SharedLinkOpener.swift @@ -0,0 +1,211 @@ +// +// SharedLinkOpener.swift +// TablePro +// + +import AppKit +import Foundation +import SwiftUI + +internal struct SharedQueryOpen: Equatable, Sendable { + let sql: String + let title: String? +} + +// A shared link only ever fills a new query tab: it never runs the SQL and carries no connection details. +@MainActor +internal final class SharedLinkOpener { + enum PasswordPrompt: Equatable { + case required + case wrong + } + + struct Presentation { + var askPassword: @MainActor (PasswordPrompt) async -> String? + var openQuery: @MainActor (SharedQueryOpen) -> Void + var tell: @MainActor (String) async -> Void + var showProgress: @MainActor (_ cancel: @escaping @MainActor () -> Void) -> Void + var hideProgress: @MainActor () -> Void + // A launch that ends with nothing on screen leaves the person somewhere to go. + var fallBack: @MainActor () -> Void + } + + static let shared = SharedLinkOpener(service: { AccountServices.shared.shares }, presentation: .live) + + private let service: @MainActor () -> any ShareService + private let presentation: Presentation + private var openingTokens: Set = [] + private var fetch: Task, Never>? + + init(service: @escaping @MainActor () -> any ShareService, presentation: Presentation) { + self.service = service + self.presentation = presentation + } + + func open(token: String) async { + guard ShareToken.isValid(token), !openingTokens.contains(token) else { return } + openingTokens.insert(token) + defer { openingTokens.remove(token) } + + let service = service() + presentation.showProgress { [weak self] in self?.fetch?.cancel() } + var password: String? + while true { + let attempt = password + let task = Task { () async -> Result in + do throws(ShareFailure) { + return .success(try await service.fetchShared(token: token, password: attempt)) + } catch { + return .failure(error) + } + } + fetch = task + let result = await task.value + fetch = nil + switch result { + case .success(let shared): + presentation.hideProgress() + guard let sql = shared.sql, !sql.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + await finish(saying: String(localized: "This shared result hides its SQL, so there is nothing to open.")) + return + } + let title = shared.title.trimmingCharacters(in: .whitespacesAndNewlines) + presentation.openQuery(SharedQueryOpen(sql: sql, title: title.isEmpty ? nil : title)) + return + case .failure(.passwordRequired): + guard let entered = await presentation.askPassword(.required) else { return finishCancelled() } + password = entered + case .failure(.passwordWrong): + guard let entered = await presentation.askPassword(.wrong) else { return finishCancelled() } + password = entered + case .failure(let failure): + presentation.hideProgress() + guard let message = Self.message(for: failure) else { return finishCancelled() } + await finish(saying: message) + return + } + } + } + + private func finish(saying message: String) async { + await presentation.tell(message) + presentation.fallBack() + } + + private func finishCancelled() { + presentation.hideProgress() + presentation.fallBack() + } + + static func message(for failure: ShareFailure) -> String? { + switch failure { + case .canceled: + return nil + case .notFound, .revoked, .removed: + return String(localized: "This shared link is no longer available.") + case .offline: + return String(localized: "You appear to be offline. Try again once you're connected.") + case .rateLimited: + return String(localized: "Too many attempts. Try again in a moment.") + case .signedOut, .emailUnverified, .proRequired, .sharingDisabled, .teamSharingDisabled, .seatRequired, + .limitReached, .snapshotTooLarge, .invalid, .passwordRequired, .passwordWrong, .server: + return String(localized: "The shared link couldn't be opened. Try again.") + } + } +} + +extension SharedLinkOpener.Presentation { + @MainActor static var live: Self { + let progress = SharedLinkProgressPresenter() + return Self( + askPassword: { prompt in await SharedLinkPrompts.password(prompt, over: progress.window) }, + openQuery: { query in + guard !TabRouter.shared.openSharedQuery(query) else { return } + WelcomeRouter.shared.enqueueSharedQuery(query) + }, + tell: { message in await SharedLinkPrompts.tell(message) }, + showProgress: { cancel in progress.show(cancel: cancel) }, + hideProgress: { progress.hide() }, + fallBack: { + guard !NSApp.windows.contains(where: { AppLaunchCoordinator.isMainWindow($0) && $0.isVisible }) else { return } + WindowOpener.shared.openWelcome() + } + ) + } +} + +@MainActor +private enum SharedLinkPrompts { + static func password(_ prompt: SharedLinkOpener.PasswordPrompt, over window: NSWindow?) async -> String? { + let alert = NSAlert() + alert.messageText = prompt == .required + ? String(localized: "This link is password protected.") + : String(localized: "That password is not correct.") + alert.alertStyle = .informational + alert.addButton(withTitle: String(localized: "Open")) + AlertHelper.addCancelButton(to: alert, title: String(localized: "Cancel")) + + let field = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 260, height: 24)) + field.placeholderString = String(localized: "Password") + alert.accessoryView = field + alert.window.initialFirstResponder = field + + AppActivationPolicyController.shared.activate(ignoringOtherApps: true) + guard await AlertHelper.response(to: alert, in: window) == .alertFirstButtonReturn else { return nil } + return field.stringValue + } + + static func tell(_ message: String) async { + AppActivationPolicyController.shared.activate(ignoringOtherApps: true) + let alert = NSAlert() + alert.messageText = message + alert.alertStyle = .informational + alert.addButton(withTitle: String(localized: "OK")) + _ = await AlertHelper.response(to: alert, in: nil) + } +} + +// A small window while the link is read, so a link opened at launch never leaves the screen empty. +@MainActor +private final class SharedLinkProgressPresenter { + private(set) var window: NSWindow? + + func show(cancel: @escaping @MainActor () -> Void) { + guard window == nil else { return } + let hosting = NSHostingController(rootView: SharedLinkProgressView(cancel: cancel)) + hosting.sizingOptions = [.preferredContentSize] + let window = NSWindow.titled(String(localized: "Opening Shared Link"), contentViewController: hosting) + window.styleMask = [.titled] + window.isRestorable = false + window.center() + self.window = window + window.makeKeyAndOrderFront(nil) + AppActivationPolicyController.shared.activate(ignoringOtherApps: true) + } + + func hide() { + window?.orderOut(nil) + window = nil + } +} + +private struct SharedLinkProgressView: View { + let cancel: @MainActor () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 14) { + HStack(spacing: 10) { + ProgressView() + .controlSize(.small) + .accessibilityHidden(true) + Text("Opening the shared link…") + } + DialogFooter { + Button(String(localized: "Cancel"), role: .cancel) { cancel() } + .keyboardShortcut(.cancelAction) + } + } + .padding(20) + .frame(width: 320) + } +} diff --git a/apple/TablePro/Core/Services/SupportLinks.swift b/apple/TablePro/Core/Services/SupportLinks.swift index 8d3d69aa6e..9fc5ed8fcc 100644 --- a/apple/TablePro/Core/Services/SupportLinks.swift +++ b/apple/TablePro/Core/Services/SupportLinks.swift @@ -13,6 +13,7 @@ internal enum SupportReferrer: Equatable { case ask case blackFriday case welcome + case shareSheet case featureGate(ProFeature) internal var parameterValue: String { @@ -29,6 +30,8 @@ internal enum SupportReferrer: Equatable { return "app-black-friday" case .welcome: return "app-welcome" + case .shareSheet: + return "app-share" case .featureGate(let feature): return "app-gate-" + Self.slug(for: feature) } diff --git a/apple/TablePro/Core/Utilities/SQL/DisplayedResultReader.swift b/apple/TablePro/Core/Utilities/SQL/DisplayedResultReader.swift index a9463a1cb4..813fd67856 100644 --- a/apple/TablePro/Core/Utilities/SQL/DisplayedResultReader.swift +++ b/apple/TablePro/Core/Utilities/SQL/DisplayedResultReader.swift @@ -13,6 +13,8 @@ internal enum DisplayedResultReader { internal let columnTypes: [ColumnType] internal let rows: [[PluginCellValue]] internal let skippedDeletedCount: Int + // How the values in each projected column were masked. + internal var masks: ColumnMasks = .none } // Empty selectedDisplayIndices means every displayed row. A cell in defaultedCells has no value until the server @@ -47,7 +49,8 @@ internal enum DisplayedResultReader { columns: projection.columns(tableRows.columns), columnTypes: projection.columnTypes(tableRows.columnTypes), rows: rows, - skippedDeletedCount: skippedDeleted + skippedDeletedCount: skippedDeleted, + masks: projection.masks(tableRows.masks) ) } diff --git a/apple/TablePro/Models/Query/VisibleColumnProjection.swift b/apple/TablePro/Models/Query/VisibleColumnProjection.swift index 0dfada47d2..04070545d3 100644 --- a/apple/TablePro/Models/Query/VisibleColumnProjection.swift +++ b/apple/TablePro/Models/Query/VisibleColumnProjection.swift @@ -30,6 +30,15 @@ struct VisibleColumnProjection { return indices.map { all.indices.contains($0) ? all[$0] : .null } } + func masks(_ all: ColumnMasks) -> ColumnMasks { + guard let indices else { return all } + var styles: [Int: MaskingStyle] = [:] + for (position, index) in indices.enumerated() { + styles[position] = all.styles[index] + } + return ColumnMasks(styles: styles) + } + /// The positions, in the projected order, of the columns a row has no field for. func absentColumns(_ all: Set) -> Set { positions(of: all) diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index aa4f93e18d..72db702fbd 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -6512,6 +6512,86 @@ } } }, + "%1$@ · %2$lld of %3$lld links" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · %2$lld liens sur %3$lld" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · 링크 %2$lld/%3$lld개" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · %2$lld / %3$lld bağlantı" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · %2$lld/%3$lld liên kết" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · %2$lld/%3$lld 个链接" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · %2$lld/%3$lld 個連結" + } + } + } + }, + "%1$@ · Expires %2$@" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · Expire le %2$@" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · %2$@ 만료" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · Bitiş: %2$@" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · Hết hạn %2$@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · %2$@ 过期" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ · %2$@ 到期" + } + } + } + }, "%1$@ (%2$@)" : { "extractionState" : "manual", "generatesSymbol" : false, @@ -8292,6 +8372,128 @@ } } }, + "%1$lld columns masked, %2$lld removed." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%#@masked@, %2$lld removed." + }, + "substitutions" : { + "masked" : { + "argNum" : 1, + "formatSpecifier" : "lld", + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%arg column masked" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%arg columns masked" + } + } + } + } + } + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%#@masked@, %#@removed@." + }, + "substitutions" : { + "masked" : { + "argNum" : 1, + "formatSpecifier" : "lld", + "variations" : { + "plural" : { + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "%arg colonnes masquées" + } + }, + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%arg colonne masquée" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%arg colonnes masquées" + } + } + } + } + }, + "removed" : { + "argNum" : 2, + "formatSpecifier" : "lld", + "variations" : { + "plural" : { + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "%arg supprimées" + } + }, + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "%arg supprimée" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "%arg supprimées" + } + } + } + } + } + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "열 %1$lld개 마스킹됨, %2$lld개 제거됨." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$lld sütun maskelendi, %2$lld kaldırıldı." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đã che %1$lld cột, đã gỡ %2$lld cột." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已遮盖 %1$lld 列,已移除 %2$lld 列。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "已遮蓋 %1$lld 欄,已移除 %2$lld 欄。" + } + } + } + }, "%1$lld commands failed inside the Redis transaction: %2$@" : { "extractionState" : "manual", "generatesSymbol" : false, @@ -16667,6 +16869,86 @@ } } }, + "A password can be up to %lld characters." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Un mot de passe peut contenir jusqu’à %lld caractères." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "암호는 최대 %lld자까지 가능합니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Parola en fazla %lld karakter olabilir." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Mật khẩu có thể dài tối đa %lld ký tự." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "密码最多可包含 %lld 个字符。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "密碼最多可包含 %lld 個字元。" + } + } + } + }, + "A password can't be only spaces or tabs." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Un mot de passe ne peut pas contenir uniquement des espaces ou des tabulations." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "비밀번호는 공백이나 탭으로만 이루어질 수 없습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Parola yalnızca boşluk veya sekmelerden oluşamaz." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Mật khẩu không thể chỉ gồm dấu cách hoặc tab." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "密码不能只包含空格或制表符。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "密碼不能只包含空格或定位字元。" + } + } + } + }, "A password is sent only over TLS, and SSL Mode is Disabled. Set SSL Mode to Verify Identity, or clear the password if the cluster has no authentication." : { "extractionState" : "manual", "generatesSymbol" : false, @@ -23746,6 +24028,46 @@ }, "Allow this only if you trust where the connection signs in." : { + }, + "Allow viewers to download" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Autoriser les lecteurs à télécharger" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "보는 사람의 다운로드 허용" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Görüntüleyenlerin indirmesine izin ver" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cho phép người xem tải xuống" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "允许查看者下载" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "允許檢視者下載" + } + } + } }, "Allowed Connections" : { "localizations" : { @@ -25882,8 +26204,88 @@ } } }, + "Anyone with the link can no longer open it. This can't be undone." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Plus personne ne pourra ouvrir ce lien. Cette action est irréversible." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크가 있는 누구도 더 이상 열 수 없습니다. 이 작업은 되돌릴 수 없습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantıya sahip olan hiç kimse artık onu açamaz. Bu işlem geri alınamaz." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Không ai có liên kết này còn mở được nữa. Không thể hoàn tác thao tác này." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "持有链接的任何人都将无法再打开它。此操作无法撤销。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "持有連結的任何人都將無法再開啟它。此動作無法復原。" + } + } + } + }, "Anything already imported may stay." : { + }, + "API key" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "clé d’API" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "API 키" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "API anahtarı" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "khóa API" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "API 密钥" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "API 金鑰" + } + } + } }, "API Key" : { "extractionState" : "manual", @@ -30432,6 +30834,46 @@ }, "Avro single-object encoding: schema fingerprint %@" : { + }, + "AWS access key" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "clé d’accès AWS" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "AWS 액세스 키" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "AWS erişim anahtarı" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "khóa truy cập AWS" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "AWS 访问密钥" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "AWS 存取金鑰" + } + } + } }, "AWS answered without the Redshift user and password." : { @@ -35274,6 +35716,86 @@ } } }, + "card number" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "numéro de carte" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "카드 번호" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "kart numarası" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "số thẻ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "卡号" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "卡號" + } + } + } + }, + "card or account number" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "numéro de carte ou de compte" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "카드 또는 계좌 번호" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "kart veya hesap numarası" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "số thẻ hoặc số tài khoản" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "卡号或账号" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "卡號或帳號" + } + } + } + }, "caret" : { "extractionState" : "manual", "localizations" : { @@ -38978,6 +39500,46 @@ } } }, + "Choose another expiry to create the link." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Choisissez une autre expiration pour créer le lien." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크를 만들려면 다른 만료 기간을 선택하세요." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantıyı oluşturmak için başka bir süre seçin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chọn thời hạn khác để tạo liên kết." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "请选择其他有效期以创建链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "請選擇其他有效期限以建立連結。" + } + } + } + }, "Choose Another Folder…" : { "localizations" : { "fr" : { @@ -40746,6 +41308,46 @@ } } }, + "Clear the password to create the link." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Effacez le mot de passe pour créer le lien." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크를 만들려면 비밀번호를 지우세요." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantıyı oluşturmak için parolayı temizleyin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Xóa mật khẩu để tạo liên kết." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "清除密码以创建链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "清除密碼以建立連結。" + } + } + } + }, "Clear the queries shown here" : { "localizations" : { "fr" : { @@ -56365,6 +56967,46 @@ } } }, + "Create Link" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Créer le lien" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크 생성" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantı Oluştur" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tạo liên kết" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "创建链接" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "建立連結" + } + } + } + }, "Create New Group" : { "extractionState" : "stale", "localizations" : { @@ -57022,6 +57664,46 @@ }, "creating database '%@'" : { + }, + "Creating the link" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Création du lien" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크 생성 중" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantı oluşturuluyor" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đang tạo liên kết" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在创建链接" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在建立連結" + } + } + } }, "Creating…" : { "extractionState" : "stale", @@ -61158,6 +61840,46 @@ } } }, + "date of birth" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "date de naissance" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "생년월일" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "doğum tarihi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "ngày sinh" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "出生日期" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "出生日期" + } + } + } + }, "Date Range" : { "localizations" : { "fr" : { @@ -71684,7 +72406,84 @@ } }, "Email" : { - + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "E-mail" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이메일" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "E-posta" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Email" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "电子邮件" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "電子郵件" + } + } + } + }, + "email address" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "adresse e-mail" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이메일 주소" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "e-posta adresi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "địa chỉ email" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "电子邮件地址" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "電子郵件地址" + } + } + } }, "Email:" : { "extractionState" : "stale", @@ -86435,6 +87234,86 @@ }, "Free" : { + }, + "Free · %1$lld of %2$lld links · first %3$lld rows" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Gratuit · %1$lld liens sur %2$lld · %3$lld premières lignes" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "무료 · 링크 %1$lld/%2$lld개 · 처음 %3$lld개 행" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ücretsiz · %1$lld / %2$lld bağlantı · ilk %3$lld satır" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Miễn phí · %1$lld/%2$lld liên kết · %3$lld hàng đầu tiên" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "免费 · %1$lld/%2$lld 个链接 · 前 %3$lld 行" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "免費 · %1$lld/%2$lld 個連結 · 前 %3$lld 列" + } + } + } + }, + "Free allows %lld. Revoke one to share another." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "L’offre Gratuite en autorise %lld. Révoquez-en un pour en partager un autre." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "무료 플랜은 %lld개까지 허용합니다. 하나를 철회해야 새로 공유할 수 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ücretsiz plan %lld bağlantıya izin verir. Yenisini paylaşmak için birini iptal edin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Gói Miễn phí cho phép %lld. Thu hồi một liên kết để chia sẻ liên kết khác." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "免费版最多允许 %lld 个。撤销一个即可分享新的链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "免費版最多允許 %lld 個。撤銷一個即可分享新的連結。" + } + } + } }, "FreeTDS could not set up the login." : { "extractionState" : "manual", @@ -86516,7 +87395,44 @@ } }, "Full" : { - + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Complet" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "전체" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tam" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Toàn bộ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "完全" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "完全" + } + } + } }, "FULL (rewrites the whole object, blocks access)" : { "extractionState" : "manual", @@ -87855,6 +88771,46 @@ } } }, + "GitHub token" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "jeton GitHub" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "GitHub 토큰" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "GitHub belirteci" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "token GitHub" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "GitHub 令牌" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "GitHub 權杖" + } + } + } + }, "Give %1$@ a value. Left at its default, the call also matches another overload of %2$@." : { "extractionState" : "manual", "generatesSymbol" : false @@ -88153,6 +89109,46 @@ } } }, + "Google API key" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "clé d’API Google" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "Google API 키" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Google API anahtarı" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "khóa API Google" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Google API 密钥" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Google API 金鑰" + } + } + } + }, "Google Cloud globally distributed SQL" : { "localizations" : { "fr" : { @@ -90085,6 +91081,46 @@ } } }, + "Hide SQL" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Masquer le SQL" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "SQL 숨기기" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "SQL’i Gizle" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ẩn SQL" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "隐藏 SQL" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "隱藏 SQL" + } + } + } + }, "Hide TablePro" : { "localizations" : { "fr" : { @@ -90206,8 +91242,45 @@ } } }, - "Hides matching values in the grid, copies, exports, the AI assistant and MCP. A pattern is table.column or column, with * as a wildcard, such as *.email. Filters and sorts still run on the stored values, so masking does not replace database permissions." : { - + "Hides matching values in the grid, copies, exports, shared links, the AI assistant and MCP. A pattern is table.column or column, with * as a wildcard, such as *.email. Filters and sorts still run on the stored values, so masking does not replace database permissions." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Masque les valeurs correspondantes dans la grille, les copies, les exportations, les liens partagés, l’assistant IA et MCP. Un motif s’écrit table.column ou column, avec * comme caractère générique, par exemple *.email. Les filtres et les tris portent toujours sur les valeurs stockées : le masquage ne remplace donc pas les autorisations de la base de données." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "그리드, 복사, 내보내기, 공유 링크, AI 어시스턴트와 MCP에서 일치하는 값을 숨깁니다. 패턴은 table.column 또는 column 형식이며 *를 와일드카드로 쓸 수 있습니다(예: *.email). 필터와 정렬은 여전히 저장된 값으로 실행되므로 마스킹이 데이터베이스 권한을 대신하지는 않습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Eşleşen değerleri ızgarada, kopyalarda, dışa aktarmalarda, paylaşılan bağlantılarda, AI asistanında ve MCP'de gizler. Bir desen table.column veya column biçimindedir; * joker karakterdir, örneğin *.email. Filtreler ve sıralamalar yine saklanan değerler üzerinde çalışır, bu yüzden maskeleme veritabanı izinlerinin yerini tutmaz." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Che các giá trị khớp trong lưới, khi sao chép, khi xuất, trong liên kết chia sẻ, trợ lý AI và MCP. Mẫu có dạng table.column hoặc column, dùng * làm ký tự đại diện, ví dụ *.email. Bộ lọc và sắp xếp vẫn chạy trên giá trị đã lưu, nên che dữ liệu không thay thế được quyền truy cập cơ sở dữ liệu." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "在表格、复制、导出、共享链接、AI 助手和 MCP 中隐藏匹配的值。模式为 table.column 或 column,可用 * 作通配符,例如 *.email。筛选和排序仍基于存储的值运行,因此遮盖不能替代数据库权限。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "在表格、複製、匯出、共享連結、AI 助理和 MCP 中隱藏相符的值。模式為 table.column 或 column,可用 * 作萬用字元,例如 *.email。篩選和排序仍以儲存的值執行,因此遮蓋無法取代資料庫權限。" + } + } + } }, "High" : { "localizations" : { @@ -91796,6 +92869,46 @@ } } }, + "ID number" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "numéro d’identité" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "신분증 번호" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "kimlik numarası" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "số định danh" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "身份证件号码" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "身分證件號碼" + } + } + } + }, "Id of the check that reported it" : { }, @@ -98215,6 +99328,46 @@ } } }, + "IP address" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "adresse IP" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "IP 주소" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "IP adresi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "địa chỉ IP" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "IP 地址" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "IP 位址" + } + } + } + }, "is empty" : { "localizations" : { "fr" : { @@ -99015,6 +100168,46 @@ } } }, + "JSON Web Token" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "JSON Web Token" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "JSON 웹 토큰" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "JSON Web Token" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "JSON Web Token" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "JSON Web Token" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "JSON Web Token" + } + } + } + }, "JSON-style document database" : { "localizations" : { "fr" : { @@ -99364,6 +100557,46 @@ }, "KB" : { + }, + "Keep" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Conserver" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "유지" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Koru" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Giữ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "保留" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "保留" + } + } + } }, "Keep a Table Open" : { "localizations" : { @@ -99622,6 +100855,46 @@ } } }, + "Keep or mask at least one column to share." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Conservez ou masquez au moins une colonne pour partager." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "공유하려면 열을 하나 이상 유지하거나 마스킹하세요." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Paylaşmak için en az bir sütunu koruyun veya maskeleyin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hãy giữ hoặc che ít nhất một cột để chia sẻ." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "请至少保留或遮盖一列才能分享。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "請至少保留或遮蓋一欄才能分享。" + } + } + } + }, "Keep Restoring" : { "localizations" : { "fr" : { @@ -101259,7 +102532,44 @@ }, "Last 4 Characters" : { - + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "4 derniers caractères" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "마지막 4자" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Son 4 karakter" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "4 ký tự cuối" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "最后 4 个字符" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "最後 4 個字元" + } + } + } }, "Last 4 Weeks" : { "localizations" : { @@ -104048,6 +105358,46 @@ } } }, + "Link copied" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Lien copié" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크를 복사했습니다" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantı kopyalandı" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đã sao chép liên kết" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "链接已复制" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "連結已複製" + } + } + } + }, "Linked" : { "localizations" : { "fr" : { @@ -106261,6 +107611,46 @@ } } }, + "Loading" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chargement" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "불러오는 중" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Yükleniyor" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đang tải" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在载入" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在載入" + } + } + } + }, "Loading %@…" : { "localizations" : { "fr" : { @@ -107254,6 +108644,46 @@ } } }, + "Looks like: %@" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ressemble à : %@" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "감지됨: %@" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Şuna benziyor: %@" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Trông giống: %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "看似:%@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "看似:%@" + } + } + } + }, "Loops" : { "comment" : "Label for the number of loops in a query plan.", "isCommentAutoGenerated" : true, @@ -108089,6 +109519,46 @@ } } }, + "Manage Shared Links…" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Gérer les liens partagés…" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "공유 링크 관리…" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Paylaşılan Bağlantıları Yönet…" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Quản lý liên kết đã chia sẻ…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "管理共享链接…" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "管理共享連結…" + } + } + } + }, "Manage Storage…" : { "extractionState" : "manual", "generatesSymbol" : false @@ -108328,19 +109798,213 @@ }, "Mask" : { - + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Masquer" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "마스킹" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Maskele" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Che" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "遮盖" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "遮蓋" + } + } + } + }, + "Mask style for %@" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Style de masquage pour %@" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ 마스킹 방식" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ için maskeleme stili" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Kiểu che cho %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ 的遮盖方式" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ 的遮蓋方式" + } + } + } }, "masked" : { }, "Masked" : { - + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Masqué" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "마스킹됨" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Maskelendi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đã che" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已遮盖" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "已遮蓋" + } + } + } }, "Masked %@: this connection has masking rules, and TablePro could not trace these columns to a table column." : { + }, + "Masked because TablePro cannot tell which table column this comes from." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Masquée, car TablePro ne peut pas déterminer de quelle colonne de table elle provient." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro가 어떤 테이블 열에서 온 값인지 알 수 없어 마스킹되었습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro bunun hangi tablo sütunundan geldiğini anlayamadığı için maskelendi." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đã che vì TablePro không xác định được cột này lấy từ cột nào của bảng." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已遮盖,因为 TablePro 无法确定它来自哪一列。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "已遮蓋,因為 TablePro 無法確定它來自哪一欄。" + } + } + } }, "Masked by a masking rule" : { + }, + "Masked by this connection's rules" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Masquée par les règles de cette connexion" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 연결의 규칙으로 마스킹됨" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu bağlantının kurallarıyla maskelendi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đã che theo quy tắc của kết nối này" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已按此连接的规则遮盖" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "已依此連線的規則遮蓋" + } + } + } }, "Masked every column: this connection has masking rules, and TablePro could not trace any of them to a table column." : { @@ -124777,6 +126441,46 @@ } } }, + "Note" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Note" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "메모" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Not" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ghi chú" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "备注" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "備註" + } + } + } + }, "Notes" : { "localizations" : { "fr" : { @@ -128526,6 +130230,46 @@ } } }, + "Open Account" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ouvrir le compte" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "계정 열기" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hesabı Aç" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Mở tài khoản" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "打开账户" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "開啟帳號" + } + } + } + }, "Open Account Settings…" : { }, @@ -129027,6 +130771,46 @@ } } }, + "Open in Browser" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ouvrir dans le navigateur" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "브라우저에서 열기" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tarayıcıda Aç" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Mở trong trình duyệt" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "在浏览器中打开" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "在瀏覽器中開啟" + } + } + } + }, "Open in Editor" : { "localizations" : { "fr" : { @@ -130189,6 +131973,46 @@ }, "Open-source vector search engine" : { + }, + "Opening Shared Link" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ouverture du lien partagé" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "공유 링크 여는 중" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Paylaşılan Bağlantı Açılıyor" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đang mở liên kết chia sẻ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在打开共享链接" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在開啟共享連結" + } + } + } }, "Opening the connection" : { "localizations" : { @@ -130230,6 +132054,46 @@ } } }, + "Opening the shared link…" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ouverture du lien partagé…" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "공유 링크를 여는 중…" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Paylaşılan bağlantı açılıyor…" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đang mở liên kết chia sẻ…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在打开共享链接…" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在開啟共享連結…" + } + } + } + }, "Opening your browser to sign in…" : { "localizations" : { "fr" : { @@ -130349,6 +132213,46 @@ } } }, + "Opens the Pro plan details in your browser." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ouvre les détails de l’offre Pro dans votre navigateur." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "브라우저에서 Pro 플랜 정보를 엽니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro plan ayrıntılarını tarayıcınızda açar." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Mở thông tin gói Pro trong trình duyệt." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "在浏览器中打开 Pro 方案详情。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "在瀏覽器中開啟 Pro 方案詳細資訊。" + } + } + } + }, "Opens the TablePro pricing page" : { "localizations" : { "fr" : { @@ -133891,6 +135795,46 @@ } } }, + "password or secret" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "mot de passe ou secret" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "비밀번호 또는 비밀 값" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "parola veya gizli bilgi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "mật khẩu hoặc bí mật" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "密码或密钥" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "密碼或密鑰" + } + } + } + }, "Password Required" : { "localizations" : { "fr" : { @@ -133941,6 +135885,46 @@ } } }, + "password value" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "valeur de mot de passe" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "암호 값" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "parola değeri" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "giá trị mật khẩu" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "密码值" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "密碼值" + } + } + } + }, "Password:" : { "localizations" : { "fr" : { @@ -135002,13 +136986,130 @@ "extractionState" : "manual", "generatesSymbol" : false }, + "person's name" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "nom de personne" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "사람 이름" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "kişi adı" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "tên người" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "人名" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "人名" + } + } + } + }, "Personal" : { - + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Personnel" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "개인" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Kişisel" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cá nhân" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "个人" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "個人" + } + } + } }, "Phone" : { "extractionState" : "manual", "generatesSymbol" : false }, + "phone number" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "numéro de téléphone" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "전화번호" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "telefon numarası" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "số điện thoại" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "电话号码" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "電話號碼" + } + } + } + }, "Phone Number" : { }, @@ -136911,6 +139012,46 @@ }, "Post-Disconnect Script" : { + }, + "postal address" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "adresse postale" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "우편 주소" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "posta adresi" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "địa chỉ bưu chính" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "邮寄地址" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "郵寄地址" + } + } + } }, "PostgreSQL %1$@ needs %2$@ %3$@ or later." : { "localizations" : { @@ -138987,6 +141128,46 @@ } } }, + "private key" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "clé privée" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "개인 키" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "özel anahtar" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "khóa riêng tư" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "私钥" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "私密金鑰" + } + } + } + }, "Private Key" : { "extractionState" : "manual", "generatesSymbol" : false, @@ -139314,6 +141495,162 @@ } } }, + "Pro · %lld links" : { + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro · %lld link" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro · %lld links" + } + } + } + } + }, + "fr" : { + "variations" : { + "plural" : { + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro · %lld liens" + } + }, + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro · %lld lien" + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro · %lld liens" + } + } + } + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro · 링크 %lld개" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro · %lld bağlantı" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro · %lld liên kết" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro · %lld 个链接" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro · %lld 個連結" + } + } + } + }, + "Pro allows %lld. Revoke one to share another." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "L’offre Pro en autorise %lld. Révoquez-en un pour en partager un autre." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro 플랜은 %lld개까지 허용합니다. 하나를 철회해야 새로 공유할 수 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro plan %lld bağlantıya izin verir. Yenisini paylaşmak için birini iptal edin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Gói Pro cho phép %lld. Thu hồi một liên kết để chia sẻ liên kết khác." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro 版最多允许 %lld 个。撤销一个即可分享新的链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro 版最多允許 %lld 個。撤銷一個即可分享新的連結。" + } + } + } + }, + "Pro allows up to 1,000." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "L’offre Pro en autorise jusqu’à 1 000." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro 플랜은 최대 1,000개까지 허용합니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro plan 1.000 bağlantıya kadar izin verir." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Gói Pro cho phép tối đa 1.000." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro 版最多允许 1,000 个。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pro 版最多允許 1,000 個。" + } + } + } + }, "Pro feature" : { "extractionState" : "stale", "localizations" : { @@ -140581,6 +142918,86 @@ } } }, + "Public links are off for this team." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Les liens publics sont désactivés pour cette équipe." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 팀은 공개 링크가 꺼져 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu ekip için herkese açık bağlantılar kapalı." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nhóm này đã tắt liên kết công khai." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此团队已关闭公开链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此團隊已關閉公開連結。" + } + } + } + }, + "Public links are turned off for this team." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Les liens publics sont désactivés pour cette équipe." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 팀은 공개 링크를 사용하지 않도록 설정했습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu ekip herkese açık bağlantıları kapattı." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nhóm này đã tắt liên kết công khai." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此团队已关闭公开链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此團隊已關閉公開連結。" + } + } + } + }, "Publish" : { "localizations" : { "fr" : { @@ -153530,6 +155947,86 @@ } } }, + "Revoke “%@”?" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Révoquer « %@ » ?" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "“%@”을(를) 철회하시겠습니까?" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "“%@” iptal edilsin mi?" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Thu hồi “%@”?" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "要撤销“%@”吗?" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "要撤銷「%@」嗎?" + } + } + } + }, + "Revoke %@" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Révoquer %@" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ 철회" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ İptal Et" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Thu hồi %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "撤销 %@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "撤銷 %@" + } + } + } + }, "Revoke %1$@ on %2$@" : { "localizations" : { "fr" : { @@ -155624,6 +158121,46 @@ } } }, + "Rows that will be shared" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Lignes qui seront partagées" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "공유될 행" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Paylaşılacak satırlar" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Các hàng sẽ được chia sẻ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "将分享的行" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "將分享的列" + } + } + } + }, "Rows the engine reported inserting" : { "localizations" : { "fr" : { @@ -166152,6 +168689,46 @@ } } }, + "Share as" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Partager en tant que" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "공유 주체" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Şu olarak paylaş" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chia sẻ dưới danh nghĩa" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享身份" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享身分" + } + } + } + }, "Share connections and saved queries with your team through your account. Passwords are never included." : { "localizations" : { "fr" : { @@ -166192,6 +168769,166 @@ } } }, + "Share Query" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Partager la requête" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "쿼리 공유" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sorguyu Paylaş" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chia sẻ truy vấn" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享查询" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享查詢" + } + } + } + }, + "Share Query…" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Partager la requête…" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "쿼리 공유…" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sorguyu Paylaş…" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chia sẻ truy vấn…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享查询…" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享查詢…" + } + } + } + }, + "Share Result" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Partager le résultat" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "결과 공유" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sonucu Paylaş" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chia sẻ kết quả" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享结果" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享結果" + } + } + } + }, + "Share Result…" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Partager le résultat…" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "결과 공유…" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sonucu Paylaş…" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chia sẻ kết quả…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享结果…" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享結果…" + } + } + } + }, "Share usage data" : { "localizations" : { "fr" : { @@ -166234,6 +168971,286 @@ }, "Share Used" : { + }, + "Share…" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Partager…" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "공유…" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Paylaş…" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chia sẻ…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享…" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享…" + } + } + } + }, + "Shares the first %1$lld of %2$lld rows." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Partage les %1$lld premières lignes sur %2$lld." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "전체 %2$lld개 행 중 처음 %1$lld개를 공유합니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%2$lld satırın ilk %1$lld tanesini paylaşır." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chia sẻ %1$lld hàng đầu tiên trong số %2$lld hàng." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享 %2$lld 行中的前 %1$lld 行。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享 %2$lld 列中的前 %1$lld 列。" + } + } + } + }, + "Shares the first %lld columns." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Partage les %lld premières colonnes." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "처음 %lld개 열을 공유합니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "İlk %lld sütunu paylaşır." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chia sẻ %lld cột đầu tiên." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享前 %lld 列。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享前 %lld 欄。" + } + } + } + }, + "Shares the first %lld rows of a larger result." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Partage les %lld premières lignes d’un résultat plus grand." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "더 큰 결과 중 처음 %lld개 행을 공유합니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Daha büyük bir sonucun ilk %lld satırını paylaşır." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chia sẻ %lld hàng đầu tiên của một kết quả lớn hơn." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享更大结果中的前 %lld 行。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "分享更大結果中的前 %lld 列。" + } + } + } + }, + "Sharing for %@" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Partage de %@" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ 공유 방식" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ için paylaşım" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cách chia sẻ %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ 的分享方式" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ 的分享方式" + } + } + } + }, + "Sharing is turned off for this account." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Le partage est désactivé pour ce compte." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 계정은 공유가 꺼져 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu hesap için paylaşım kapalı." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tài khoản này đã tắt chia sẻ." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此账户已关闭分享。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此帳號已關閉分享。" + } + } + } + }, + "Sharing isn't available right now. Try again." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Le partage n’est pas disponible pour le moment. Réessayez." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "지금은 공유를 사용할 수 없습니다. 다시 시도하십시오." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Paylaşım şu anda kullanılamıyor. Tekrar deneyin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hiện không thể chia sẻ. Hãy thử lại." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "目前无法分享。请重试。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "目前無法分享。請再試一次。" + } + } + } }, "Sheet" : { "localizations" : { @@ -169347,6 +172364,46 @@ }, "Sign in to Vault with your browser?" : { + }, + "Sign in to your TablePro account to share links." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Connectez-vous à votre compte TablePro pour partager des liens." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크를 공유하려면 TablePro 계정에 로그인하십시오." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantı paylaşmak için TablePro hesabınıza giriş yapın." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đăng nhập tài khoản TablePro để chia sẻ liên kết." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "登录你的 TablePro 账户以分享链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "登入你的 TablePro 帳號以分享連結。" + } + } + } }, "Sign In With" : { @@ -169489,6 +172546,46 @@ } } }, + "Sign In…" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Se connecter…" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "로그인…" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Giriş Yap…" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Đăng nhập…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "登录…" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "登入…" + } + } + } + }, "Sign it again with: codesign --force --sign - %@" : { "extractionState" : "manual", "generatesSymbol" : false, @@ -170656,6 +173753,46 @@ }, "Skipped: %@" : { + }, + "Slack token" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "jeton Slack" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "Slack 토큰" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Slack belirteci" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "token Slack" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Slack 令牌" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Slack 權杖" + } + } + } }, "slash" : { "extractionState" : "manual", @@ -171348,6 +174485,46 @@ } } }, + "Some columns may hold secrets: %@." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Certaines colonnes peuvent contenir des secrets : %@." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "일부 열에 비밀 정보가 있을 수 있습니다: %@." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bazı sütunlar gizli bilgi içerebilir: %@." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Một số cột có thể chứa thông tin bí mật: %@." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "某些列可能包含机密信息:%@。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "某些欄位可能包含機密資訊:%@。" + } + } + } + }, "Some documents hold both %1$@ and %2$@. Remove one of the two from those documents first." : { "extractionState" : "manual", "generatesSymbol" : false, @@ -174595,7 +177772,44 @@ }, "Stable Hash" : { - + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hachage stable" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "고정 해시" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Sabit karma" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hash ổn định" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "稳定哈希" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "穩定雜湊" + } + } + } }, "Stable metric id" : { @@ -177329,6 +180543,46 @@ } } }, + "Stripe secret key" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "clé secrète Stripe" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "Stripe 비밀 키" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Stripe gizli anahtarı" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "khóa bí mật Stripe" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Stripe 密钥" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Stripe 秘密金鑰" + } + } + } + }, "Structure" : { "extractionState" : "manual", "generatesSymbol" : false, @@ -182923,6 +186177,46 @@ }, "TablePro is turned off in %1$@. Turn it on in %1$@'s MCP settings to use it." : { + }, + "TablePro masked columns that look sensitive. Check them before sharing." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro a masqué les colonnes qui semblent sensibles. Vérifiez-les avant de partager." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro가 민감해 보이는 열을 마스킹했습니다. 공유하기 전에 확인하세요." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro hassas görünen sütunları maskeledi. Paylaşmadan önce kontrol edin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro đã che các cột có vẻ nhạy cảm. Hãy kiểm tra trước khi chia sẻ." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro 已遮盖看似敏感的列。分享前请检查。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "TablePro 已遮蓋看似敏感的欄。分享前請檢查。" + } + } + } }, "TablePro moved" : { @@ -184530,6 +187824,46 @@ }, "Teams" : { + }, + "Teams allow %lld. Revoke one to share another." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Les équipes en autorisent %lld. Révoquez-en un pour en partager un autre." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "팀은 %lld개까지 허용합니다. 하나를 철회해야 새로 공유할 수 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ekipler %lld bağlantıya izin verir. Yenisini paylaşmak için birini iptal edin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nhóm được phép có %lld. Thu hồi một liên kết để chia sẻ liên kết khác." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "团队最多允许 %lld 个。撤销一个即可分享新的链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "團隊最多允許 %lld 個。撤銷一個即可分享新的連結。" + } + } + } }, "Template" : { "extractionState" : "stale", @@ -185761,6 +189095,46 @@ } } }, + "That password is not correct." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ce mot de passe est incorrect." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "암호가 올바르지 않습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Parola yanlış." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Mật khẩu không đúng." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "密码不正确。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "密碼不正確。" + } + } + } + }, "That result is no longer open. Choose another one." : { }, @@ -190783,6 +194157,86 @@ } } }, + "The link couldn't be created. Try again." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Impossible de créer le lien. Réessayez." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크를 생성할 수 없습니다. 다시 시도하십시오." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantı oluşturulamadı. Tekrar deneyin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Không thể tạo liên kết. Hãy thử lại." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "无法创建链接。请重试。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法建立連結。請再試一次。" + } + } + } + }, + "The link shares the first %lld columns." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Le lien partage les %lld premières colonnes." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크는 처음 %lld개 열을 공유합니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantı ilk %lld sütunu paylaşır." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Liên kết chia sẻ %lld cột đầu tiên." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此链接分享前 %lld 列。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此連結分享前 %lld 欄。" + } + } + } + }, "The list of allowed values is not carried over." : { "localizations" : { "fr" : { @@ -194405,6 +197859,46 @@ }, "The settings it was created with could not be read, so it gets the target's own." : { + }, + "The shared link couldn't be opened. Try again." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Impossible d’ouvrir le lien partagé. Réessayez." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "공유 링크를 열 수 없습니다. 다시 시도하십시오." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Paylaşılan bağlantı açılamadı. Tekrar deneyin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Không thể mở liên kết chia sẻ. Hãy thử lại." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "无法打开共享链接。请重试。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法開啟共享連結。請再試一次。" + } + } + } }, "The shell drops a field named __proto__ from a new document. Remove the field, then set it on the saved document." : { "extractionState" : "manual", @@ -201688,6 +205182,46 @@ } } }, + "This link is password protected." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ce lien est protégé par un mot de passe." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 링크는 암호로 보호되어 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu bağlantı parola korumalı." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Liên kết này được bảo vệ bằng mật khẩu." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此链接受密码保护。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此連結受密碼保護。" + } + } + } + }, "This list is a capped preview. Apply covers every difference, not only the rows listed here." : { "localizations" : { "fr" : { @@ -202014,6 +205548,46 @@ }, "This operation is not the one that was approved." : { + }, + "This option needs TablePro Pro." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cette option nécessite TablePro Pro." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 옵션은 TablePro Pro가 필요합니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu seçenek TablePro Pro gerektirir." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Tùy chọn này cần TablePro Pro." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此选项需要 TablePro Pro。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此選項需要 TablePro Pro。" + } + } + } }, "This Oracle server is older than release 11.1, which the database driver does not support." : { "extractionState" : "manual", @@ -202524,6 +206098,126 @@ }, "This query calls a function that can change data" : { + }, + "This query contains what looks like personal data (%@). Turn on Hide SQL to keep the query private." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cette requête contient ce qui ressemble à des données personnelles (%@). Activez Masquer le SQL pour garder la requête privée." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 쿼리에 개인 정보로 보이는 내용(%@)이 있습니다. 쿼리를 비공개로 유지하려면 SQL 숨기기를 켜세요." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu sorgu kişisel veri gibi görünen bir şey içeriyor (%@). Sorguyu gizli tutmak için SQL’i Gizle’yi açın." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Truy vấn này có nội dung trông giống dữ liệu cá nhân (%@). Bật Ẩn SQL để giữ kín truy vấn." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此查询包含看似个人数据的内容(%@)。打开“隐藏 SQL”以保持查询私密。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此查詢包含看似個人資料的內容(%@)。開啟「隱藏 SQL」以保持查詢私密。" + } + } + } + }, + "This query is too long to share. A link holds up to %@ of SQL." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cette requête est trop longue pour être partagée. Un lien contient au plus %@ de SQL." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 쿼리는 너무 길어 공유할 수 없습니다. 링크에는 최대 %@의 SQL을 담을 수 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu sorgu paylaşmak için çok uzun. Bir bağlantı en fazla %@ SQL tutabilir." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Truy vấn này quá dài để chia sẻ. Một liên kết chứa tối đa %@ SQL." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此查询过长,无法分享。一个链接最多可包含 %@ 的 SQL。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此查詢過長,無法分享。一個連結最多可包含 %@ 的 SQL。" + } + } + } + }, + "This query is too long to share. A link holds up to %lld characters." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cette requête est trop longue pour être partagée. Un lien contient au plus %lld caractères." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 쿼리는 너무 길어 공유할 수 없습니다. 링크에는 최대 %lld자까지 담을 수 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu sorgu paylaşmak için çok uzun. Bir bağlantı en fazla %lld karakter tutabilir." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Truy vấn này quá dài để chia sẻ. Một liên kết chứa tối đa %lld ký tự." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此查询太长,无法分享。链接最多可包含 %lld 个字符。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此查詢太長,無法分享。連結最多可包含 %lld 個字元。" + } + } + } }, "This query language has no formatter." : { "localizations" : { @@ -202535,6 +206229,46 @@ } } }, + "This query may contain a secret (%@). Anyone with the link can read it." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cette requête contient peut-être un secret (%@). Toute personne disposant du lien peut le lire." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 쿼리에 비밀 정보(%@)가 있을 수 있습니다. 링크가 있는 누구나 읽을 수 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu sorgu gizli bir bilgi (%@) içerebilir. Bağlantıya sahip herkes okuyabilir." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Truy vấn này có thể chứa thông tin bí mật (%@). Bất kỳ ai có liên kết đều đọc được." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此查询可能包含机密信息(%@)。任何持有链接的人都能读取。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此查詢可能包含機密資訊(%@)。任何持有連結的人都能讀取。" + } + } + } + }, "This record cannot be found again from what was read. Refresh and try again." : { "extractionState" : "manual", "generatesSymbol" : false @@ -202589,6 +206323,86 @@ } } }, + "This result is no longer open, so there are no rows to share." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ce résultat n’est plus ouvert, il n’y a donc aucune ligne à partager." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 결과가 더 이상 열려 있지 않아 공유할 행이 없습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu sonuç artık açık değil, bu yüzden paylaşılacak satır yok." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Kết quả này không còn mở, nên không có hàng nào để chia sẻ." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此结果已不再打开,因此没有可分享的行。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此結果已不再開啟,因此沒有可分享的列。" + } + } + } + }, + "This result is too large to share." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ce résultat est trop volumineux pour être partagé." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 결과는 너무 커서 공유할 수 없습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu sonuç paylaşmak için çok büyük." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Kết quả này quá lớn để chia sẻ." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此结果太大,无法分享。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此結果太大,無法分享。" + } + } + } + }, "This routine sets client_min_messages to %@, which hides the notice the debugger starts with." : { "extractionState" : "manual", "generatesSymbol" : false @@ -203187,6 +207001,86 @@ } } }, + "This shared link is no longer available." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ce lien partagé n’est plus disponible." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 공유 링크는 더 이상 사용할 수 없습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu paylaşılan bağlantı artık kullanılamıyor." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Liên kết chia sẻ này không còn khả dụng." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此共享链接已不可用。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此共享連結已無法使用。" + } + } + } + }, + "This shared result hides its SQL, so there is nothing to open." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ce résultat partagé masque son SQL : il n’y a rien à ouvrir." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 공유 결과는 SQL을 숨기므로 열 내용이 없습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu paylaşılan sonuç SQL’ini gizliyor, bu yüzden açılacak bir şey yok." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Kết quả chia sẻ này ẩn SQL nên không có gì để mở." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此共享结果隐藏了 SQL,因此没有可打开的内容。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此共享結果隱藏了 SQL,因此沒有可開啟的內容。" + } + } + } + }, "This shortcut is reserved by macOS and cannot be assigned." : { "localizations" : { "fr" : { @@ -203422,6 +207316,122 @@ } } }, + "This table view has no SQL to share, so the link shares its rows only." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cette vue de table n’a pas de SQL à partager : le lien ne partage que ses lignes." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 테이블 보기에는 공유할 SQL이 없으므로 링크는 행만 공유합니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu tablo görünümünün paylaşılacak SQL’i yok, bu yüzden bağlantı yalnızca satırlarını paylaşır." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chế độ xem bảng này không có SQL để chia sẻ, nên liên kết chỉ chia sẻ các hàng." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此表视图没有可分享的 SQL,因此链接只分享其中的行。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此表格檢視沒有可分享的 SQL,因此連結只分享其中的列。" + } + } + } + }, + "This team has %lld live links." : { + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "This team has %lld live link." + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "This team has %lld live links." + } + } + } + } + }, + "fr" : { + "variations" : { + "plural" : { + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cette équipe a %lld liens actifs." + } + }, + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cette équipe a %lld lien actif." + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "Cette équipe a %lld liens actifs." + } + } + } + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 팀에는 활성 링크가 %lld개 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu ekibin %lld etkin bağlantısı var." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nhóm này có %lld liên kết đang hoạt động." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此团队有 %lld 个有效链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "此團隊有 %lld 個有效連結。" + } + } + } + }, "This token will not be shown again" : { "localizations" : { "fr" : { @@ -205795,6 +209805,46 @@ }, "Too large to save (%@)" : { + }, + "Too many attempts. Try again in a moment." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Trop de tentatives. Réessayez dans un instant." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "시도 횟수가 너무 많습니다. 잠시 후 다시 시도하십시오." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Çok fazla deneme. Biraz sonra tekrar deneyin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Quá nhiều lần thử. Hãy thử lại sau giây lát." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "尝试次数过多。请稍后重试。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "嘗試次數過多。請稍後再試。" + } + } + } }, "Too many lines differ to compare line by line." : { "localizations" : { @@ -205836,6 +209886,46 @@ } } }, + "Too many links just now. Try again in a moment." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Trop de liens à la fois. Réessayez dans un instant." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "방금 링크를 너무 많이 만들었습니다. 잠시 후 다시 시도하십시오." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Az önce çok fazla bağlantı oluşturuldu. Biraz sonra tekrar deneyin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Vừa tạo quá nhiều liên kết. Hãy thử lại sau giây lát." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "刚才创建的链接过多。请稍后重试。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "剛才建立的連結過多。請稍後再試。" + } + } + } + }, "Too many pending pairing codes. Try again later." : { "localizations" : { "fr" : { @@ -207922,6 +212012,46 @@ } } }, + "Turn downloads back on to create the link." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Réactivez les téléchargements pour créer le lien." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크를 만들려면 다운로드를 다시 켜세요." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantıyı oluşturmak için indirmeleri yeniden açın." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bật lại tải xuống để tạo liên kết." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "重新开启下载以创建链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "重新開啟下載以建立連結。" + } + } + } + }, "Turn loaded query results into native bar, line, area, and scatter charts." : { "localizations" : { "fr" : { @@ -208044,6 +212174,46 @@ }, "Turned off" : { + }, + "Turns on Hide SQL for this link." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Active Masquer le SQL pour ce lien." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "이 링크에 SQL 숨기기를 켭니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bu bağlantı için SQL’i Gizle’yi açar." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bật Ẩn SQL cho liên kết này." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "为此链接打开“隐藏 SQL”。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "為此連結開啟「隱藏 SQL」。" + } + } + } }, "Two columns are both named “%@”. Rename one, then save again." : { "localizations" : { @@ -211793,6 +215963,46 @@ "extractionState" : "manual", "generatesSymbol" : false }, + "URL with a password" : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "URL avec mot de passe" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "암호가 포함된 URL" + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "parola içeren URL" + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "URL có mật khẩu" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "含密码的 URL" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "含密碼的 URL" + } + } + } + }, "US Long (12/31/2024 11:59:59 PM)" : { "localizations" : { "fr" : { @@ -214899,6 +219109,46 @@ } } }, + "Verify your email address to share links." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Vérifiez votre adresse e-mail pour partager des liens." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "링크를 공유하려면 이메일 주소를 인증하십시오." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bağlantı paylaşmak için e-posta adresinizi doğrulayın." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Xác minh địa chỉ email để chia sẻ liên kết." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "验证你的电子邮件地址以分享链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "驗證你的電子郵件地址以分享連結。" + } + } + } + }, "Verify your plan soon" : { }, @@ -219590,6 +223840,122 @@ } } }, + "You appear to be offline. Try again once you're connected." : { + "localizations" : { + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Vous semblez hors ligne. Réessayez une fois connecté." + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "오프라인 상태인 것 같습니다. 연결된 후 다시 시도하십시오." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Çevrimdışı görünüyorsunuz. Bağlandıktan sonra tekrar deneyin." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Có vẻ bạn đang ngoại tuyến. Hãy thử lại khi đã kết nối." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "你似乎已离线。连接后请重试。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "你似乎已離線。連線後請再試一次。" + } + } + } + }, + "You have %lld live links." : { + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "You have %lld live link." + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "You have %lld live links." + } + } + } + } + }, + "fr" : { + "variations" : { + "plural" : { + "many" : { + "stringUnit" : { + "state" : "translated", + "value" : "Vous avez %lld liens actifs." + } + }, + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "Vous avez %lld lien actif." + } + }, + "other" : { + "stringUnit" : { + "state" : "translated", + "value" : "Vous avez %lld liens actifs." + } + } + } + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "활성 링크가 %lld개 있습니다." + } + }, + "tr" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld etkin bağlantınız var." + } + }, + "vi" : { + "stringUnit" : { + "state" : "translated", + "value" : "Bạn có %lld liên kết đang hoạt động." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "你有 %lld 个有效链接。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "你有 %lld 個有效連結。" + } + } + } + }, "You have no saved queries to publish." : { "localizations" : { "fr" : { diff --git a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift b/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift index 7107e4813a..9fb743d3d1 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/OptionsPaneView.swift @@ -496,7 +496,7 @@ private struct MaskingRulesSection: View { Text(String(localized: "Masking")) } footer: { Text(String(localized: """ - Hides matching values in the grid, copies, exports, the AI assistant and MCP. \ + Hides matching values in the grid, copies, exports, shared links, the AI assistant and MCP. \ A pattern is table.column or column, with * as a wildcard, such as *.email. \ Filters and sorts still run on the stored values, so masking does not replace database permissions. """)) diff --git a/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowMenu.swift b/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowMenu.swift index 5b754272d6..1b6659bc92 100644 --- a/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowMenu.swift +++ b/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowMenu.swift @@ -209,6 +209,9 @@ extension DataGridViewController { if gridCommands.offers(.exportResults) { items.append(menuItem(String(localized: "Export Results…"), #selector(exportResultsFromMenu(_:)), context)) } + if gridCommands.offers(.shareResult) { + items.append(menuItem(String(localized: "Share Result…"), #selector(shareResultFromMenu(_:)), context)) + } if gridCommands.offers(.clearResults) { items.append(menuItem(String(localized: "Clear Results"), #selector(clearResultsFromMenu(_:)), context)) } @@ -238,6 +241,7 @@ extension DataGridViewController { #selector(DataGridViewController.applySetValueFromMenu(_:)), #selector(DataGridViewController.removeFieldFromMenu(_:)), #selector(DataGridViewController.exportResultsFromMenu(_:)), + #selector(DataGridViewController.shareResultFromMenu(_:)), #selector(DataGridViewController.clearResultsFromMenu(_:)), #selector(DataGridViewController.duplicateRowsFromMenu(_:)), #selector(DataGridViewController.copySummaryFigureFromMenu(_:)), @@ -265,6 +269,10 @@ extension DataGridViewController { model.actions?.gridExportResults() } + @objc func shareResultFromMenu(_ sender: Any?) { + model.actions?.gridShareResult() + } + @objc func clearResultsFromMenu(_ sender: Any?) { model.actions?.gridClearResults() } diff --git a/apple/TablePro/Views/Editor/AIEditorContextMenu.swift b/apple/TablePro/Views/Editor/AIEditorContextMenu.swift index adc76aef13..b5de758117 100644 --- a/apple/TablePro/Views/Editor/AIEditorContextMenu.swift +++ b/apple/TablePro/Views/Editor/AIEditorContextMenu.swift @@ -14,6 +14,7 @@ final class AIEditorContextMenu: NSMenu, NSMenuDelegate { var aiAvailability: (() -> AIQueryActionAvailability)? var onAIAction: ((AIQueryAction) -> Void)? var onSaveAsFavorite: ((String) -> Void)? + var onShareQuery: ((String) -> Void)? var onFormatSQL: ((NSRange) -> Void)? var canFormatSQL: (() -> Bool)? /// Whether the cursor sits inside a collapsed fold. `nil` when there is no fold at the cursor. @@ -84,15 +85,29 @@ final class AIEditorContextMenu: NSMenu, NSMenuDelegate { } private var favoriteItems: [NSMenuItem] { - guard hasText, onSaveAsFavorite != nil else { return [] } - let item = NSMenuItem( - title: String(localized: "Save as Favorite…"), - action: #selector(handleSaveAsFavorite), - keyEquivalent: "" - ) - item.target = self - item.image = NSImage(systemSymbolName: "star", accessibilityDescription: nil) - return [item] + guard hasText else { return [] } + var items: [NSMenuItem] = [] + if onSaveAsFavorite != nil { + let item = NSMenuItem( + title: String(localized: "Save as Favorite…"), + action: #selector(handleSaveAsFavorite), + keyEquivalent: "" + ) + item.target = self + item.image = NSImage(systemSymbolName: "star", accessibilityDescription: nil) + items.append(item) + } + if onShareQuery != nil { + let item = NSMenuItem( + title: String(localized: "Share Query…"), + action: #selector(handleShareQuery), + keyEquivalent: "" + ) + item.target = self + item.image = NSImage(systemSymbolName: "square.and.arrow.up", accessibilityDescription: nil) + items.append(item) + } + return items } private var aiItems: [NSMenuItem] { @@ -133,4 +148,10 @@ final class AIEditorContextMenu: NSMenu, NSMenuDelegate { let selected = selection?().selectedText(in: text) onSaveAsFavorite?(selected ?? text) } + + @objc private func handleShareQuery() { + guard let text = fullText?(), !text.isEmpty else { return } + let selected = selection?().selectedText(in: text) + onShareQuery?(selected ?? text) + } } diff --git a/apple/TablePro/Views/Editor/SQLEditorController.swift b/apple/TablePro/Views/Editor/SQLEditorController.swift index f313b2d0b0..b0f49a3245 100644 --- a/apple/TablePro/Views/Editor/SQLEditorController.swift +++ b/apple/TablePro/Views/Editor/SQLEditorController.swift @@ -42,6 +42,7 @@ struct SQLEditorInput { var currentAIAvailability: (() -> AIQueryActionAvailability)? var onAIAction: ((AIQueryAction, AIQueryTarget) -> Void)? var onSaveAsFavorite: ((String) -> Void)? + var onShareQuery: ((String) -> Void)? } /// The SQL editor in AppKit, so the query tab hosts it with no SwiftUI host around it: each one above an editor @@ -193,6 +194,7 @@ final class SQLEditorController { coordinator.currentAIAvailability = input.currentAIAvailability coordinator.onAIAction = input.onAIAction coordinator.onSaveAsFavorite = input.onSaveAsFavorite + coordinator.onShareQuery = input.onShareQuery coordinator.schemaProvider = input.schemaProvider coordinator.databaseScope = input.databaseScope coordinator.databaseType = input.databaseType diff --git a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift index c912935495..24fa269596 100644 --- a/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift +++ b/apple/TablePro/Views/Editor/SQLEditorCoordinator.swift @@ -144,6 +144,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie var currentAIAvailability: (() -> AIQueryActionAvailability)? var onAIAction: ((AIQueryAction, AIQueryTarget) -> Void)? var onSaveAsFavorite: ((String) -> Void)? + var onShareQuery: ((String) -> Void)? var databaseType: DatabaseType? var tabID: UUID? var connectionId: UUID? @@ -358,6 +359,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie currentAIAvailability = nil onAIAction = nil onSaveAsFavorite = nil + onShareQuery = nil schemaProvider = nil controller?.textView?.menu = nil contextMenu = nil @@ -473,6 +475,7 @@ final class SQLEditorCoordinator: ObservableObject, TextViewCoordinator, TextVie self?.onAIAction?(action, Self.aiTarget(for: controller?.textView)) } menu.onSaveAsFavorite = { [weak self] text in self?.onSaveAsFavorite?(text) } + menu.onShareQuery = { [weak self] text in self?.onShareQuery?(text) } menu.onFormatSQL = { [weak self] range in self?.formatSQL(selectedRange: range) } menu.canFormatSQL = { [weak self] in QueryFormatterFactory.supportsFormatting(self?.databaseType) } menu.foldStateAtCursor = { [weak controller] in controller?.foldStateAtCursor() } diff --git a/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift b/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift index 0b608aae63..a463a7077b 100644 --- a/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift +++ b/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift @@ -184,6 +184,11 @@ final class DataTabGridAdapter: DataGridDataSource, DataGridActions { coordinator?.commandActions?.exportQueryResults() } + func gridShareResult() { + guard ownsWindowState else { return } + coordinator?.shareActiveResult() + } + func gridClearResults() { guard ownsWindowState else { return } coordinator?.clearActiveQueryResults() diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index aa10e55631..b8f6b3b0bf 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -1248,6 +1248,9 @@ extension MainEditorContentView { onSaveAsFavorite: { text in guard !text.isEmpty else { return } coordinator.favoriteDialogQuery = FavoriteDialogQuery(query: text) + }, + onShareQuery: { text in + coordinator.presentShareQuery(text, title: tab.title) } ) return QueryTabInput( diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift index 7dbdd9665a..e257f4de58 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift @@ -202,7 +202,7 @@ extension MainContentCoordinator { private func gridCommands(for tab: QueryTab, isSelected: Bool, isEditable: Bool) -> Set { var commands: Set = [ - .hideColumns, .showRowsAsJSON, .exportResults, .navigateForeignKey, + .hideColumns, .showRowsAsJSON, .exportResults, .shareResult, .navigateForeignKey, .highlightValues, .displayAs, .freezeColumns, .valueFilter ] let operations = isEditable ? (activeViewWriteTarget?.operations ?? .all) : [] diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Masking.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Masking.swift index 663fe1f4f4..3062dd7eda 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Masking.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Masking.swift @@ -47,15 +47,29 @@ extension MainContentCoordinator { return ServerErrorText.withheldMessage } + // A sync pull, a rename or a tag edit updates the connection too, and must not re-mask or make a Share sheet read + // its rows again. func observeMaskingRuleChanges() -> AnyCancellable { - services.appEvents.connectionUpdated + var applied = storedMaskingRules + return services.appEvents.connectionUpdated .filter { [connectionId] changed in changed == nil || changed == connectionId } .receive(on: RunLoop.main) - .sink { [weak self] _ in self?.maskLoadedResults() } + .sink { [weak self] _ in + guard let self else { return } + let rules = storedMaskingRules + guard rules != applied else { return } + applied = rules + maskLoadedResults() + maskingRulesApplied.send() + } + } + + private var storedMaskingRules: [MaskingRule.Effect]? { + services.databaseManager.connectionStorage.loadConnection(id: connectionId)?.maskingRules.map(\.effect) } - /// Masks the rows already on screen when a rule is saved, rather than waiting for the next run. Read from storage, - /// since the live session may adopt the saved record after this runs. + // Masks the rows already on screen when a rule is saved, rather than waiting for the next run. Read from storage, + // since the live session may adopt the saved record after this runs. func maskLoadedResults() { guard let stored = services.databaseManager.connectionStorage.loadConnection(id: connectionId) else { return } let policy = stored.maskingPolicy diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Share.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Share.swift new file mode 100644 index 0000000000..85089f30da --- /dev/null +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+Share.swift @@ -0,0 +1,340 @@ +// +// MainContentCoordinator+Share.swift +// TablePro +// + +import Combine +import Foundation +import os +import TableProEditorKit +import TableProPluginKit +import TableProSQLGrammar +import TableProUtilities + +extension MainContentCoordinator { + private static let shareLogger = Logger(subsystem: "com.TablePro", category: "ShareResult") + + // Share Result…: the active result as the grid shows it, masked the way rows leaving the app are masked. + func shareActiveResult() { + guard admitsSheetCommand(), let request = activeResultShareRequest() else { return } + activeSheet = .share(request) + } + + // Share Query…: the editor's selection, else all of its text. + func shareEditorQuery() { + guard let tabId = tabManager.selectedTabId else { return } + flushEditorText(forTab: tabId) + guard let tab = tabManager.selectedTab, tab.tabType == .query else { return } + let sql = Self.selectionOrWholeText(tab.content.query, selection: cursorPositions.first?.range) + presentShareQuery(sql, title: tab.title) + } + + func shareFavorite(_ favorite: SQLFavorite) { + presentShareQuery(favorite.query, title: favorite.name) + } + + func shareLinkedFavorite(_ favorite: LinkedSQLFavorite) { + guard let loaded = FileTextLoader.load(favorite.fileURL) else { return } + presentShareQuery(loaded.content, title: favorite.name) + } + + func presentShareQuery(_ sql: String, title: String) { + let trimmed = sql.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, admitsSheetCommand() else { return } + activeSheet = .share(.query(title: title, sql: trimmed, dialect: connection.type.rawValue)) + } + + func activeResultShareRequest() -> ShareRequest? { + guard let tab = tabManager.selectedTab, + !tabSessionRegistry.tableRows(for: tab.id).rows.isEmpty + else { return nil } + let tabId = tab.id + let key = shareResultKey(of: tab) + return .result( + title: tab.title, + sql: shareSQL(of: tab), + dialect: connection.type.rawValue, + sourceChanges: maskingRulesApplied.eraseToAnyPublisher() + ) { [weak self] maxRows in + await self?.shareSource(tabId: tabId, key: key, maxRows: maxRows) + } + } + + // MARK: - Rows + + // The rows of the result the sheet was opened on, or of a refresh of it; nil once the tab shows another statement + // or database. Rows the grid does not hold yet are read from the server, the grid itself left as it is. + func shareSource(tabId: UUID, key: ShareResultKey, maxRows: Int) async -> ShareResultSource? { + guard let tab = sharedTab(tabId, key: key) else { return nil } + if let read = shareRead(for: tab, maxRows: maxRows) { + do { + let result = try await paginationCoordinator.readRows( + tabId: tabId, + query: read.query, + parameters: read.parameters, + rowCap: maxRows, + operationDescription: String(localized: "Share Result") + ) + guard let current = sharedTab(tabId, key: key) else { return nil } + return await fetchedShareSource(result, tab: current, maxRows: maxRows) + } catch { + Self.shareLogger.notice("Share Result read failed, sharing the loaded rows: \(error.publicLogShape, privacy: .public)") + } + } + guard !Task.isCancelled, let current = sharedTab(tabId, key: key) else { return nil } + return await loadedShareSource(tab: current, maxRows: maxRows) + } + + // Auto Refresh and a reload install a new result for the same statement, so the share follows what the result is, + // never the result instance. + func shareResultKey(of tab: QueryTab) -> ShareResultKey { + let scope = scope(for: tab) + let statement = shareSQL(of: tab) + // A table view the host cannot write as SQL is told apart by what narrows and orders its rows. + let view = tab.tabType == .table && statement.isEmpty + ? ShareTableView(tab, search: filterCoordinator.activeBrowseSearch(for: tab.filterState)) + : nil + return ShareResultKey( + table: tab.tabType == .table ? tab.tableContext.tableName : nil, + statement: statement, + parameters: tab.tabType == .table ? nil : tab.display.activeResultSet?.baseQueryParameterValues, + database: scope?.database, + schema: scope?.schema, + view: view + ) + } + + private func sharedTab(_ tabId: UUID, key: ShareResultKey) -> QueryTab? { + guard let tab = tabManager.tabs.first(where: { $0.id == tabId }), shareResultKey(of: tab) == key else { return nil } + return tab + } + + // The statement to read, or nil when the grid already holds what the share needs or the result's own statement + // cannot safely run again. + private func shareRead(for tab: QueryTab, maxRows: Int) -> (query: String, parameters: [TypedParameterValue?]?)? { + // A value filter narrows the rows on screen, so the share is exactly those. + guard !tab.valueFilter.isActive, maxRows > 0 else { return nil } + let loaded = tabSessionRegistry.tableRows(for: tab.id).rows.count + if tab.tabType == .table { + let total = ShareTotals(tab).exact + let pageHoldsEnough = tab.pagination.currentOffset == 0 + && (loaded >= maxRows || (total.map { loaded >= $0 } ?? false)) + guard !pageHoldsEnough, let query = filterCoordinator.viewQuery(for: tab, limit: maxRows) else { return nil } + return (query, nil) + } + // A write that returned rows, such as UPDATE ... RETURNING, must not run again, as Reveal decides. + guard let result = tab.display.activeResultSet, result.isTruncated, loaded < maxRows, + let base = result.baseQuery, !wasReadElsewhere(result, in: tab), + QueryClassifier.classify(base, databaseType: connection.type).tier == .safe + else { return nil } + return (base, result.baseQueryParameterValues) + } + + private func fetchedShareSource(_ result: QueryResult, tab: QueryTab, maxRows: Int) async -> ShareResultSource? { + let policy = maskingPolicy + let table = tab.tabType == .table ? tab.tableContext.tableName : nil + let typeNames = result.columnTypes.map(\.rawType) + let masks = policy.columnMasks(table: table, columns: result.columns, typeNames: typeNames).strictest( + with: policy.externalColumnMasks( + table: table, columns: result.columns, typeNames: typeNames, origins: result.columnOrigins + ) + ) + let projection = VisibleColumnProjection.fromColumnLayout(tab.columnLayout, columns: result.columns) + let untraced = policy.untracedColumns(table: table, columns: result.columns, origins: result.columnOrigins) + return await Self.fetchedShareSource( + FetchedShareRows( + columns: result.columns, + columnTypes: result.columnTypes, + rows: result.rows, + absentCells: result.absentCells, + unloadedCells: result.unloadedCells, + isTruncated: result.isTruncated, + masks: masks, + projection: projection, + untracedColumns: projection.positions(of: Set(untraced)), + totals: ShareTotals(tab), + sql: shareSQL(of: tab) + ), + maxRows: maxRows + ) + } + + @concurrent + private static func fetchedShareSource(_ fetched: FetchedShareRows, maxRows: Int) async -> ShareResultSource? { + let shape = TableRows.RowShape(columns: fetched.columns, masks: fetched.masks, exportPolicy: .none, exportTable: nil) + let prepared = await TableRows.preparing( + fetched.rows, absentCells: fetched.absentCells, unloadedCells: fetched.unloadedCells, shape: shape + ) + guard prepared.isComplete, !Task.isCancelled else { return nil } + let read = DisplayedResultReader.read( + tableRows: TableRows.from(prepared: prepared, columnTypes: fetched.columnTypes), + displayIDs: nil, + selectedDisplayIndices: [], + columns: fetched.projection + ) + guard !Task.isCancelled else { return nil } + let more = fetched.isTruncated || read.rows.count >= maxRows + return ShareResultSource( + columns: read.columns, + columnTypes: read.columnTypes, + rows: read.rows, + totalRowCount: fetched.totals.total(rows: read.rows.count, more: more), + sql: fetched.sql, + masks: read.masks, + untracedColumns: fetched.untracedColumns + ) + } + + private func loadedShareSource(tab: QueryTab, maxRows: Int) async -> ShareResultSource? { + let tableRows = tabSessionRegistry.tableRows(for: tab.id) + let table = tab.tabType == .table ? tab.tableContext.tableName : nil + let untraced = maskingPolicy.untracedColumns(table: table, columns: tableRows.columns, origins: tableRows.columnOrigins) + let projection = VisibleColumnProjection.fromColumnLayout(tab.columnLayout, columns: tableRows.columns) + return await Self.loadedShareSource( + HeldShareRows( + tableRows: tableRows, + displayIDs: displayIDs(forTab: tab.id), + deletedRowIDs: changeManager.deletedRowIDs, + overlay: externalOverlay(forTab: tab.id), + projection: projection, + untracedColumns: projection.positions(of: Set(untraced)), + totals: ShareTotals(tab), + isValueFiltered: tab.valueFilter.isActive, + hasRowsElsewhere: tab.pagination.hasMoreRows || tab.display.activeResultSet?.isTruncated == true + || tab.pagination.currentOffset > 0, + sql: shareSQL(of: tab) + ), + maxRows: maxRows + ) + } + + // At most max_rows display positions are read and masked, so a large grid is never copied or masked whole. + @concurrent + private static func loadedShareSource(_ held: HeldShareRows, maxRows: Int) async -> ShareResultSource? { + guard !Task.isCancelled else { return nil } + let displayed = held.displayIDs?.count ?? held.tableRows.rows.count + let read = DisplayedResultReader.read( + tableRows: held.tableRows, + displayIDs: held.displayIDs, + selectedDisplayIndices: Set(0.. rows.count + total = held.totals.total(rows: rows.count, more: more) + } + return ShareResultSource( + columns: read.columns, + columnTypes: read.columnTypes, + rows: rows, + totalRowCount: total.map { max($0, rows.count) }, + sql: held.sql, + masks: read.masks.strictest(with: overlay), + untracedColumns: held.untracedColumns + ) + } + + // A table tab shares its view without the page's window, or no SQL when the host cannot write that view. + func shareSQL(of tab: QueryTab) -> String { + guard tab.tabType == .table else { return Self.resultSQL(of: tab) } + return filterCoordinator.viewSQL(for: tab) ?? "" + } + + private static func resultSQL(of tab: QueryTab) -> String { + let resultSet = tab.display.activeResultSet + return (resultSet?.namedParameterStatement?.sql ?? resultSet?.baseQuery ?? tab.content.query) + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + nonisolated static func selectionOrWholeText(_ text: String, selection: NSRange?) -> String { + let whole = text as NSString + guard let selection, selection.location != NSNotFound, selection.length > 0, + NSMaxRange(selection) <= whole.length + else { return text } + return whole.substring(with: selection) + } +} + +internal struct ShareResultKey: Equatable, Sendable { + let table: String? + let statement: String + let parameters: [TypedParameterValue?]? + let database: String? + let schema: String? + let view: ShareTableView? +} + +internal struct ShareTableView: Equatable, Sendable { + let filters: [TableFilter] + let logicMode: FilterLogicMode + let search: BrowseSearchState? + let sort: [SortColumn] + + @MainActor + init(_ tab: QueryTab, search: BrowseSearchState?) { + let rerun = tab.filterState.rerunFilters + filters = rerun.filters + logicMode = rerun.logicMode + self.search = search + sort = tab.sortState.columns + } +} + +// The tab's row count, taken on the main actor for the rows built off it. +private struct ShareTotals: Sendable { + let exact: Int? + let estimate: Int? + + @MainActor + init(_ tab: QueryTab) { + let pagination = tab.pagination + exact = pagination.isApproximateRowCount ? nil : pagination.totalRowCount + estimate = pagination.isApproximateRowCount ? pagination.totalRowCount : nil + } + + // The true total when counted; an estimate when it is above the rows held; else the rows, or nil if more exist. + func total(rows: Int, more: Bool) -> Int? { + if let exact { + return max(exact, rows) + } + if let estimate, estimate > rows { + return estimate + } + return more ? nil : rows + } +} + +private struct FetchedShareRows: Sendable { + let columns: [String] + let columnTypes: [ColumnType] + let rows: [[PluginCellValue]] + let absentCells: [Int: Set] + let unloadedCells: [Int: [Int: Int]] + let isTruncated: Bool + let masks: ColumnMasks + let projection: VisibleColumnProjection + let untracedColumns: Set + let totals: ShareTotals + let sql: String +} + +private struct HeldShareRows: Sendable { + let tableRows: TableRows + let displayIDs: [RowID]? + let deletedRowIDs: Set + // What the grid's own masks leave for a reader outside the app, by source column. + let overlay: ColumnMasks + let projection: VisibleColumnProjection + let untracedColumns: Set + let totals: ShareTotals + let isValueFiltered: Bool + let hasRowsElsewhere: Bool + let sql: String +} diff --git a/apple/TablePro/Views/Main/MainContentCommandActions.swift b/apple/TablePro/Views/Main/MainContentCommandActions.swift index c7c1904a51..f86a21a6c9 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions.swift @@ -1006,6 +1006,14 @@ final class MainContentCommandActions: ObservableObject { coordinator.openExportQueryResultsDialog() } + func shareQuery() { + coordinator?.shareEditorQuery() + } + + func shareQueryResult() { + coordinator?.shareActiveResult() + } + func importData() { guard coordinator?.admitsSheetCommand() == true else { return } coordinator?.openImportPanel() diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index 465beded46..c0edc94f0a 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -90,6 +90,7 @@ enum ActiveSheet: Identifiable { case searchDatabase(DatabaseSearchSession) case joinBuilder(JoinBuilderLaunchRequest) case generateRows(RowGenerationSession) + case share(ShareRequest) var id: String { switch self { @@ -123,6 +124,7 @@ enum ActiveSheet: Identifiable { case .searchDatabase(let session): "searchDatabase-\(session.id.uuidString)" case .joinBuilder(let launch): "joinBuilder-\(launch.id.uuidString)" case .generateRows(let session): "generateRows-\(session.id.uuidString)" + case .share(let request): "share-\(request.id.uuidString)" } } } @@ -359,6 +361,8 @@ final class MainContentCoordinator: ObservableObject { private var clearedEditsCancellable: AnyCancellable? private var gridRepaintCancellable: AnyCancellable? var maskingRulesCancellable: AnyCancellable? + // Sent once a saved rule has masked the rows on screen, so an open Share sheet reads them again. + let maskingRulesApplied = PassthroughSubject() private var browseContainerCancellable: AnyCancellable? @Published var fileConflictRequest: FileConflictRequest? diff --git a/apple/TablePro/Views/Main/MainContentView.swift b/apple/TablePro/Views/Main/MainContentView.swift index c1e5df3ff7..f31aeb43ac 100644 --- a/apple/TablePro/Views/Main/MainContentView.swift +++ b/apple/TablePro/Views/Main/MainContentView.swift @@ -236,6 +236,8 @@ struct MainContentView: View { } case .generateRows(let session): GenerateRowsSheet(session: session) + case .share(let request): + ShareSheet(model: .live(request)) case .exportDialog, .exportQueryResults, .exportDataSource, .importDialog, .rowImport, .rowImportBatch, .transferTables, .backupDatabase, .restoreDatabase: transferSheetContent(for: sheet, dismiss: dismissBinding) diff --git a/apple/TablePro/Views/Share/ShareRequest.swift b/apple/TablePro/Views/Share/ShareRequest.swift new file mode 100644 index 0000000000..e416ec3c88 --- /dev/null +++ b/apple/TablePro/Views/Share/ShareRequest.swift @@ -0,0 +1,40 @@ +// +// ShareRequest.swift +// TablePro +// + +import Combine +import Foundation + +// Reads up to the plan's row limit once the sheet knows it; nil when the result is no longer open. +internal typealias ShareResultLoader = @MainActor @Sendable (_ maxRows: Int) async -> ShareResultSource? + +// What a Share sheet was opened for: a query, or a query with the result it produced. +internal struct ShareRequest: Identifiable { + let id = UUID() + let kind: ShareKind + let title: String + let sql: String + let dialect: String? + let loadResult: ShareResultLoader? + // Fires when the rows the loader reads were masked again, as after a masking rule is saved. + let sourceChanges: AnyPublisher? + + static func query(title: String, sql: String, dialect: String?) -> ShareRequest { + ShareRequest(kind: .query, title: title, sql: sql, dialect: dialect, loadResult: nil, sourceChanges: nil) + } + + static func result( + title: String, + sql: String, + dialect: String?, + sourceChanges: AnyPublisher? = nil, + load: @escaping ShareResultLoader + ) -> ShareRequest { + ShareRequest(kind: .result, title: title, sql: sql, dialect: dialect, loadResult: load, sourceChanges: sourceChanges) + } + + static func result(title: String, dialect: String?, source: ShareResultSource) -> ShareRequest { + result(title: title, sql: source.sql, dialect: dialect) { _ in source } + } +} diff --git a/apple/TablePro/Views/Share/ShareSheet.swift b/apple/TablePro/Views/Share/ShareSheet.swift new file mode 100644 index 0000000000..58d7fa28e2 --- /dev/null +++ b/apple/TablePro/Views/Share/ShareSheet.swift @@ -0,0 +1,651 @@ +// +// ShareSheet.swift +// TablePro +// + +import SwiftUI + +internal struct ShareSheet: View { + @StateObject private var model: ShareSheetModel + @State private var linkToRevoke: ShareLink? + @Environment(\.dismiss) private var dismiss + @Environment(\.openURL) private var openURL + + init(model: @autoclosure @escaping () -> ShareSheetModel) { + _model = StateObject(wrappedValue: model()) + } + + var body: some View { + VStack(spacing: 0) { + Text(model.isResult ? String(localized: "Share Result") : String(localized: "Share Query")) + .font(.headline) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 20) + .padding(.vertical, 14) + .accessibilityAddTraits(.isHeader) + + Divider() + + content + .frame(maxWidth: .infinity, maxHeight: .infinity) + + Divider() + + DialogFooter { + if let footer = model.footer { + Text(footer) + .font(.callout) + .foregroundStyle(.secondary) + .lineLimit(1) + .accessibilityIdentifier("share-sheet-usage") + } + } actions: { + actions + } + .padding(.horizontal, 20) + .padding(.vertical, 14) + } + .frame(width: 560, height: model.isResult ? 640 : 480) + .interactiveDismissDisabled(model.isCreating) + // Done and Close carry Return, so Esc closes these two through the window. + .onExitCommand { + switch model.phase { + case .created, .sharingDisabled: dismiss() + default: break + } + } + .task { await model.load() } + .onDisappear { model.close() } + .alert( + revokeTitle, + isPresented: Binding(get: { linkToRevoke != nil }, set: { if !$0 { linkToRevoke = nil } }), + presenting: linkToRevoke + ) { link in + Button(String(localized: "Revoke"), role: .destructive) { + Task { await model.revoke(link) } + } + Button(String(localized: "Cancel"), role: .cancel) {} + } message: { _ in + Text("Anyone with the link can no longer open it. This can't be undone.") + } + } + + private var revokeTitle: String { + let title = linkToRevoke.map(LiveLinkRow.displayTitle) ?? "" + return String(format: String(localized: "Revoke “%@”?"), title) + } + + // MARK: - Content + + @ViewBuilder + private var content: some View { + switch model.phase { + case .signedOut: + message( + String(localized: "Sign in to your TablePro account to share links."), + systemImage: "person.crop.circle" + ) + case .loading: + ProgressView() + .controlSize(.small) + .accessibilityLabel(Text("Loading")) + case .loadFailed(let text): + UnavailableStateView { + Label(text, systemImage: "wifi.exclamationmark") + } actions: { + Button(String(localized: "Try Again")) { + Task { await model.load() } + } + } + case .emailUnverified: + message(String(localized: "Verify your email address to share links."), systemImage: "envelope.badge") + case .sharingDisabled: + message(String(localized: "Sharing is turned off for this account."), systemImage: "nosign") + case .atCap: + atCapContent + case .form: + formContent + case .created(let url): + createdContent(url) + } + } + + private func message(_ text: String, systemImage: String) -> some View { + UnavailableStateView { + Label(text, systemImage: systemImage) + } + } + + @ViewBuilder + private var targetSection: some View { + if !model.teams.isEmpty { + Section { + Picker(String(localized: "Share as"), selection: $model.target) { + Text("Personal").tag(ShareTarget.personal) + ForEach(model.teams) { team in + TeamChoice(team: team) + .tag(ShareTarget.team(team.id)) + .disabled(!team.allowsPublicLinks) + } + } + .pickerStyle(.radioGroup) + .disabled(model.isCreating) + .accessibilityIdentifier("share-sheet-target") + } + } + } + + private var formContent: some View { + Form { + targetSection + + Section { + TextField(String(localized: "Title"), text: $model.title) + .accessibilityIdentifier("share-sheet-title") + TextField(String(localized: "Note"), text: $model.note, axis: .vertical) + .lineLimit(2...4) + .accessibilityIdentifier("share-sheet-note") + } + + Section { + expiryRow + if let message = model.expiryMessage { + NoticeLabel(message, severity: .error) + .accessibilityIdentifier("share-sheet-expiry-message") + } + if model.isResult, model.hasSharedSQL { + Toggle(String(localized: "Hide SQL"), isOn: $model.hidesSQL) + .accessibilityIdentifier("share-sheet-hide-sql") + if let suggestion = model.hideSQLSuggestion { + HStack(alignment: .firstTextBaseline, spacing: 8) { + NoticeLabel(suggestion) + Spacer(minLength: 8) + Button(String(localized: "Hide SQL")) { model.hidesSQL = true } + .accessibilityHint(Text("Turns on Hide SQL for this link.")) + .accessibilityIdentifier("share-sheet-hide-sql-suggestion") + } + } + } else if model.isResult { + Text("This table view has no SQL to share, so the link shares its rows only.") + .font(.callout) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + passwordRow + if let message = model.passwordMessage { + NoticeLabel(message, severity: .error) + .accessibilityIdentifier("share-sheet-password-message") + } + downloadRow + if let message = model.downloadMessage { + NoticeLabel(message, severity: .error) + .accessibilityIdentifier("share-sheet-download-message") + } + } + + if model.isResult { + previewSection + if !model.columns.isEmpty { + columnsSection + } + } + + if let message = model.sqlTooLongMessage { + Section { + NoticeLabel(message, severity: .error) + .accessibilityIdentifier("share-sheet-sql-too-long") + } + } + + if !model.secretWarnings.isEmpty || model.columnWarning != nil { + Section { + ForEach(model.secretWarnings, id: \.self) { warning in + NoticeLabel(warning) + } + if let warning = model.columnWarning { + NoticeLabel(warning) + } + } + } + + if let failure = model.failureMessage { + Section { + NoticeLabel(failure, severity: .error) + .accessibilityIdentifier("share-sheet-error") + } + } + } + .formStyle(.grouped) + .disabled(model.isCreating) + } + + private var expiryRow: some View { + LabeledContent { + Picker(String(localized: "Expires"), selection: $model.expiry) { + ForEach(ShareExpiry.allCases) { expiry in + Text(expiry.displayName) + .tag(expiry) + .disabled(!model.isAvailable(expiry)) + } + } + .labelsHidden() + .fixedSize() + .accessibilityIdentifier("share-sheet-expiry") + } label: { + proLabel(String(localized: "Expires"), showsTag: !model.isAvailable(.never)) + } + } + + private var passwordRow: some View { + LabeledContent { + // A password the plan no longer allows stays editable, so it can be cleared. + SecureField(String(localized: "Password"), text: $model.password) + .labelsHidden() + .frame(maxWidth: 220) + .disabled(!(model.limits?.allowsPassword ?? false) && model.password.isEmpty) + .accessibilityIdentifier("share-sheet-password") + } label: { + proLabel(String(localized: "Password"), showsTag: !(model.limits?.allowsPassword ?? false)) + } + } + + private var downloadRow: some View { + LabeledContent { + Toggle(String(localized: "Allow viewers to download"), isOn: $model.allowsDownload) + .labelsHidden() + .toggleStyle(.switch) + .disabled(!(model.limits?.allowsDisablingDownload ?? false) && model.allowsDownload) + .accessibilityIdentifier("share-sheet-allow-download") + } label: { + proLabel( + String(localized: "Allow viewers to download"), + showsTag: !(model.limits?.allowsDisablingDownload ?? false) + ) + } + } + + private func proLabel(_ title: String, showsTag: Bool) -> some View { + HStack(spacing: 6) { + Text(title) + if showsTag { + ProTag() + } + } + } + + private var previewSection: some View { + Section { + if let message = model.resultGoneMessage { + NoticeLabel(message, severity: .error) + .accessibilityIdentifier("share-sheet-result-gone") + } else if model.isSnapshotTooLarge { + NoticeLabel(String(localized: "This result is too large to share."), severity: .error) + } else if model.isEveryColumnRemoved { + NoticeLabel(String(localized: "Keep or mask at least one column to share."), severity: .error) + .accessibilityIdentifier("share-sheet-no-columns") + } else { + SharePreviewGrid(columns: model.previewColumns, rows: model.previewRows) + if let note = model.capNote { + Text(note) + .font(.callout) + .foregroundStyle(.secondary) + .accessibilityIdentifier("share-sheet-cap-note") + } + if let note = model.columnCapNote { + Text(note) + .font(.callout) + .foregroundStyle(.secondary) + .accessibilityIdentifier("share-sheet-column-cap-note") + } + } + } header: { + Text("Rows that will be shared") + } + } + + private var columnsSection: some View { + Section { + ForEach(model.columns) { column in + ShareColumnRow( + column: column, + action: Binding(get: { column.action }, set: { model.setAction($0, forColumn: column.index) }), + style: Binding(get: { column.style }, set: { model.setStyle($0, forColumn: column.index) }) + ) + } + } header: { + Text("Columns") + } footer: { + VStack(alignment: .leading, spacing: 4) { + Text(model.columnSummary) + .accessibilityIdentifier("share-sheet-column-summary") + if model.hasDetections { + Text("TablePro masked columns that look sensitive. Check them before sharing.") + .accessibilityIdentifier("share-sheet-detection-notice") + } + } + .font(.callout) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + private var atCapContent: some View { + Form { + targetSection + + Section { + if let text = model.atCapMessage { + Text(text) + .fixedSize(horizontal: false, vertical: true) + } + if model.showsProUpsell { + HStack(spacing: 6) { + Text("Pro allows up to 1,000.") + .foregroundStyle(.secondary) + ProTag() + } + } + } + + Section { + if model.isLoadingLinks, model.liveLinks.isEmpty { + ProgressView() + .controlSize(.small) + .frame(maxWidth: .infinity) + .accessibilityLabel(Text("Loading")) + } + ForEach(model.liveLinks) { link in + LiveLinkRow( + link: link, + isRevoking: model.revokingLinkIDs.contains(link.id), + revoke: { linkToRevoke = link } + ) + } + if let failure = model.linksFailure { + HStack { + NoticeLabel(failure, severity: .error) + Spacer(minLength: 8) + Button(String(localized: "Try Again")) { + Task { await model.loadLiveLinks() } + } + .disabled(model.isLoadingLinks) + } + } + } + } + .formStyle(.grouped) + } + + private func createdContent(_ url: URL) -> some View { + VStack(spacing: 14) { + Label { + Text("Link copied") + } icon: { + Image(systemName: "checkmark.circle.fill") + .foregroundStyle(.green) + } + .font(.title3.weight(.semibold)) + .accessibilityAddTraits(.isHeader) + + Text(verbatim: url.absoluteString) + .font(.body.monospaced()) + .textSelection(.enabled) + .lineLimit(2) + .truncationMode(.middle) + .multilineTextAlignment(.center) + .accessibilityIdentifier("share-sheet-url") + + if let note = model.createdColumnCapNote { + Text(note) + .font(.callout) + .foregroundStyle(.secondary) + .accessibilityIdentifier("share-sheet-created-column-cap-note") + } + + HStack(spacing: 10) { + Button(String(localized: "Copy")) { model.copyLink() } + Button(String(localized: "Open in Browser")) { openURL(url) } + } + } + .padding(.horizontal, 32) + } + + // MARK: - Buttons + + @ViewBuilder + private var actions: some View { + switch model.phase { + case .signedOut: + cancelButton + Button(String(localized: "Sign In…")) { SignInWindowController.present() } + .keyboardShortcut(.defaultAction) + case .emailUnverified: + cancelButton + Button(String(localized: "Open Account")) { + openURL(AccountServices.shared.configuration.accountURL) + } + .keyboardShortcut(.defaultAction) + case .form: + if model.isCreating { + ProgressView() + .controlSize(.small) + .accessibilityLabel(Text("Creating the link")) + } + // A create already sent finishes on the server whether or not the sheet stays. + cancelButton + .disabled(model.isCreating) + Button(String(localized: "Create Link")) { + Task { await model.create() } + } + .keyboardShortcut(.defaultAction) + .disabled(!model.canCreate) + .accessibilityIdentifier("share-sheet-create") + case .created: + Button(String(localized: "Done")) { dismiss() } + .keyboardShortcut(.defaultAction) + case .sharingDisabled: + Button(String(localized: "Close")) { dismiss() } + .keyboardShortcut(.defaultAction) + case .loading, .loadFailed, .atCap: + cancelButton + } + } + + private var cancelButton: some View { + Button(String(localized: "Cancel"), role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + } +} + +private struct TeamChoice: View { + let team: ShareTeam + + var body: some View { + if team.allowsPublicLinks { + Text(verbatim: team.name) + } else { + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: team.name) + Text("Public links are off for this team.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + } +} + +// Opens the plan details in the browser rather than a sheet over a sheet. +private struct ProTag: View { + @Environment(\.openURL) private var openURL + + var body: some View { + Button { + openURL(SupportLinks.pricing(.shareSheet)) + } label: { + Text("Pro") + .font(.caption2.weight(.semibold)) + .foregroundStyle(.secondary) + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(Capsule().fill(.quaternary)) + } + .buttonStyle(.plain) + .fixedSize() + .accessibilityHint(Text("Opens the Pro plan details in your browser.")) + } +} + +private struct LiveLinkRow: View { + let link: ShareLink + let isRevoking: Bool + let revoke: () -> Void + + static func displayTitle(_ link: ShareLink) -> String { + link.title.isEmpty ? String(localized: "Untitled") : link.title + } + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + if link.isSuspended { + Text("Suspended") + .foregroundStyle(.secondary) + } + Button(String(localized: "Revoke"), action: revoke) + .disabled(isRevoking) + .accessibilityLabel(Text(String(format: String(localized: "Revoke %@"), Self.displayTitle(link)))) + } + } label: { + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: Self.displayTitle(link)) + .lineLimit(1) + .truncationMode(.tail) + Text(detail) + .font(.caption) + .foregroundStyle(.secondary) + } + } + } + + private var detail: String { + let created = link.createdAt.formatted(date: .abbreviated, time: .omitted) + guard let expires = link.expiresAt else { return created } + return String( + format: String(localized: "%1$@ · Expires %2$@"), + created, + expires.formatted(date: .abbreviated, time: .omitted) + ) + } +} + +private struct ShareColumnRow: View { + let column: ShareColumnChoice + @Binding var action: ShareColumnChoice.Action + @Binding var style: MaskingStyle + + var body: some View { + LabeledContent { + HStack(spacing: 8) { + Picker(String(format: String(localized: "Sharing for %@"), column.name), selection: $action) { + ForEach(ShareColumnChoice.Action.allCases) { action in + Text(action.displayName) + .tag(action) + .disabled(action == .keep && !column.allowsKeep) + } + } + .labelsHidden() + .fixedSize() + if column.action == .mask { + Picker(String(format: String(localized: "Mask style for %@"), column.name), selection: $style) { + ForEach(column.allowedStyles) { style in + Text(style.displayName).tag(style) + } + } + .labelsHidden() + .fixedSize() + } + } + } label: { + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: column.name) + .lineLimit(1) + .truncationMode(.middle) + if let reason { + Text(reason) + .font(.caption) + .foregroundStyle(.secondary) + } + } + } + } + + private var reason: String? { + if column.isUntraced { + return String(localized: "Masked because TablePro cannot tell which table column this comes from.") + } + if column.ruleStyle != nil { + return String(localized: "Masked by this connection's rules") + } + guard let detection = column.detection else { return nil } + return String(format: String(localized: "Looks like: %@"), detection.displayName) + } +} + +private struct SharePreviewGrid: View { + let columns: [ShareSnapshot.Column] + let rows: [[ShareCell]] + + var body: some View { + ScrollView(.horizontal) { + Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 4) { + GridRow { + ForEach(columns.indices, id: \.self) { index in + HStack(spacing: 3) { + Text(verbatim: columns[index].name) + .lineLimit(1) + if columns[index].masked != nil { + Image(systemName: "eye.slash") + .foregroundStyle(.secondary) + .accessibilityLabel(Text("Masked")) + } + } + .font(.caption.weight(.semibold)) + } + } + Divider() + ForEach(rows.indices, id: \.self) { rowIndex in + GridRow { + ForEach(columns.indices, id: \.self) { index in + cell(rows[rowIndex].indices.contains(index) ? rows[rowIndex][index] : .null) + } + } + } + } + .padding(.vertical, 4) + } + .accessibilityElement(children: .contain) + .accessibilityLabel(Text("Rows that will be shared")) + .accessibilityIdentifier("share-sheet-preview") + } + + @ViewBuilder + private func cell(_ value: ShareCell) -> some View { + switch value { + case .null: + Text(verbatim: "NULL") + .font(.caption.monospaced()) + .foregroundStyle(.tertiary) + default: + Text(verbatim: Self.text(value)) + .font(.caption.monospaced()) + .lineLimit(1) + .truncationMode(.tail) + .frame(maxWidth: 200, alignment: .leading) + } + } + + private static func text(_ value: ShareCell) -> String { + let line = ShareCellEncoder.previewText(value).prefix(200) + return line.replacingOccurrences(of: "\n", with: " ", options: .literal) + } +} diff --git a/apple/TablePro/Views/Share/ShareSheetModel.swift b/apple/TablePro/Views/Share/ShareSheetModel.swift new file mode 100644 index 0000000000..e29ffdffe5 --- /dev/null +++ b/apple/TablePro/Views/Share/ShareSheetModel.swift @@ -0,0 +1,692 @@ +// +// ShareSheetModel.swift +// TablePro +// + +import Combine +import Foundation + +@MainActor +internal final class ShareSheetModel: ObservableObject { + enum Phase: Equatable { + case signedOut + case loading + case loadFailed(String) + case emailUnverified + case sharingDisabled + case atCap + case form + case created(URL) + } + + // The server's field caps (api/v2.json, CreateShareBody), counted as the server counts them: Unicode scalars, and + // UTF-8 bytes for the SQL. + static let titleLimit = 200 + static let noteLimit = 2_000 + static let passwordLimit = 128 + static let sqlLimit = 262_144 + static let previewRowCount = 5 + + let request: ShareRequest + + @Published private(set) var phase: Phase = .loading + @Published private(set) var limits: ShareLimits? + @Published private(set) var source: ShareResultSource? + @Published private(set) var snapshot: ShareSnapshotOutcome? + @Published private(set) var liveLinks: [ShareLink] = [] + @Published private(set) var isLoadingLinks = false + @Published private(set) var linksFailure: String? + @Published private(set) var revokingLinkIDs: Set = [] + @Published private(set) var isCreating = false + // Set when the created link holds only the first columns. + @Published private(set) var createdColumnCapNote: String? + @Published private(set) var failureMessage: String? + @Published private(set) var sqlSecretKinds: [SecretKind] = [] + @Published private(set) var sqlPersonalData: [SensitiveValueKind] = [] + @Published private(set) var columns: [ShareColumnChoice] = [] + // The loader found the result gone, as when its tab closed or shows another result. + @Published private(set) var isResultGone = false + // The rows were masked again since the snapshot was built, and are being read again. + @Published private(set) var isSourceStale = false + + @Published var title: String + @Published var note = "" + @Published var expiry: ShareExpiry = .thirtyDays + @Published var hidesSQL = false + @Published var password = "" + @Published var allowsDownload = true + @Published var target: ShareTarget = .personal { + didSet { + guard target != oldValue else { return } + settlePhase() + } + } + + private let service: any ShareService + private let isSignedIn: @MainActor () -> Bool + private let copyToClipboard: @MainActor (String) -> Void + private var signInObservation: AnyCancellable? + private var sourceObservation: AnyCancellable? + private var appliedDefaults = false + private var sourceMaxRows: Int? + // The row limit of the latest read asked for, done or still in flight, as during a reload as Free. + private var requestedMaxRows: Int? + // Moves on every read of the rows, so a read another one overtook is dropped. + private var sourceGeneration = 0 + private var sourceReload: Task? + // The rows the detectors read; a rebuild never sends past them. + private var rowCap: Int? + // The column choices the snapshot was built with; a snapshot built for others is never sent. + private var builtColumns: [ShareColumnChoice]? + private var rebuild: Task? + private var scannedSQL: String? + private var work: [Task] = [] + private var isClosed = false + + init( + request: ShareRequest, + service: any ShareService, + isSignedIn: @escaping @MainActor () -> Bool, + signInChanges: AnyPublisher, + copyToClipboard: @escaping @MainActor (String) -> Void + ) { + self.request = request + self.service = service + self.isSignedIn = isSignedIn + self.copyToClipboard = copyToClipboard + self.title = String(String.UnicodeScalarView(request.title.unicodeScalars.prefix(Self.titleLimit))) + signInObservation = signInChanges + .removeDuplicates() + .filter { $0 } + .sink { [weak self] _ in + guard let self, self.phase == .signedOut else { return } + self.track(Task { await self.load() }) + } + sourceObservation = request.sourceChanges?.sink { [weak self] in + self?.sourceChanged() + } + scanSQL(request.sql) + } + + // The sheet went away: nothing it started may finish into a closed sheet or onto the clipboard. + func close() { + isClosed = true + work.forEach { $0.cancel() } + work.removeAll() + } + + private func track(_ task: Task) { + work.removeAll { $0.isCancelled } + work.append(task) + } + + // MARK: - Loading + + func load() async { + guard isSignedIn() else { + phase = .signedOut + return + } + if limits == nil { + phase = .loading + } + do throws(ShareFailure) { + let limits = try await service.limits() + await loadSource(maxRows: limits.maxRows) + guard !isClosed else { return } + apply(limits) + } catch .signedOut { + phase = .signedOut + } catch .canceled { + return + } catch { + if limits == nil { + phase = .loadFailed(Self.loadMessage(error)) + } else { + failureMessage = error.message + } + } + } + + static func loadMessage(_ failure: ShareFailure) -> String { + if failure == .offline, let message = failure.message { + return message + } + return String(localized: "Sharing isn't available right now. Try again.") + } + + private func apply(_ limits: ShareLimits) { + self.limits = limits + if !appliedDefaults { + appliedDefaults = true + expiry = limits.allows(limits.defaultExpiry) ? limits.defaultExpiry : (limits.expiries.first ?? .thirtyDays) + } + if let teamID = target.teamID, limits.team(teamID)?.allowsPublicLinks != true { + // Settles the phase through didSet. + target = .personal + return + } + settlePhase() + } + + private func settlePhase() { + guard let limits else { return } + if !limits.emailVerified { + phase = .emailUnverified + } else if limits.sharingDisabled { + phase = .sharingDisabled + } else if isTargetAtCap { + phase = .atCap + liveLinks = [] + linksFailure = nil + track(Task { await loadLiveLinks() }) + } else if phase != .form { + phase = .form + } + } + + // Up to 10,000 rows of 100 columns: read, scanned and built off the main actor, once per row limit unless forced. + private func loadSource(maxRows: Int, force: Bool = false) async { + guard let load = request.loadResult, force || sourceMaxRows != maxRows else { return } + sourceGeneration += 1 + let generation = sourceGeneration + requestedMaxRows = maxRows + let loaded = await load(maxRows) + guard !Task.isCancelled, !isClosed, generation == sourceGeneration else { return } + guard let loaded else { + isResultGone = true + return + } + isResultGone = false + // The old snapshot and choices belong to the rows being replaced: nothing built from them is sent. + let previous = columns + rebuild?.cancel() + source = loaded + snapshot = nil + builtColumns = nil + rowCap = nil + columns = [] + scanSQL(loaded.sql) + let prepare = Task.detached(priority: .userInitiated) { + ShareColumnChoice.prepare(loaded, maxRows: maxRows, keeping: previous) + } + let prepared = await withTaskCancellationHandler { + await prepare.value + } onCancel: { + prepare.cancel() + } + guard let prepared, !isClosed, generation == sourceGeneration else { return } + sourceMaxRows = maxRows + isSourceStale = false + rowCap = prepared.rowCap + columns = prepared.columns + snapshot = prepared.snapshot + builtColumns = prepared.columns + } + + // A masking rule saved in another window masked the rows again: Create waits for them to be read once more. + private func sourceChanged() { + guard !isClosed, request.kind == .result, let maxRows = requestedMaxRows else { return } + isSourceStale = true + sourceReload?.cancel() + let task = Task { await loadSource(maxRows: maxRows, force: true) } + sourceReload = task + track(task) + } + + private func buildSnapshot() async { + guard let source, let rowCap else { return } + let generation = sourceGeneration + let choices = columns + let shared = choices.compactMap(\.sharedColumn) + let build = Task.detached(priority: .userInitiated) { + ShareSnapshotBuilder.build(source, maxRows: rowCap, columns: shared) + } + let built = await withTaskCancellationHandler { + await build.value + } onCancel: { + build.cancel() + } + guard let built, !Task.isCancelled, !isClosed, choices == columns, generation == sourceGeneration else { return } + snapshot = built + builtColumns = choices + } + + private func scanSQL(_ sql: String) { + guard sql != scannedSQL else { return } + scannedSQL = sql + let scan = Task.detached(priority: .utility) { + (SecretScanner.scanSQL(sql), SensitiveDataDetector.personalData(inSQL: sql)) + } + track(Task { [weak self] in + let (hits, personalData) = await withTaskCancellationHandler { await scan.value } onCancel: { scan.cancel() } + guard let self, self.scannedSQL == sql else { return } + var kinds: [SecretKind] = [] + for hit in hits where !kinds.contains(hit.kind) { + kinds.append(hit.kind) + } + self.sqlSecretKinds = kinds + self.sqlPersonalData = personalData + }) + } + + // MARK: - Columns + + func setAction(_ action: ShareColumnChoice.Action, forColumn index: Int) { + update(column: index) { $0.choosing(action) } + } + + func setStyle(_ style: MaskingStyle, forColumn index: Int) { + update(column: index) { $0.choosing(style: style) } + } + + private func update(column index: Int, _ change: (ShareColumnChoice) -> ShareColumnChoice?) { + guard let position = columns.firstIndex(where: { $0.index == index }), + let changed = change(columns[position]), changed != columns[position] + else { return } + columns[position] = changed + rebuild?.cancel() + let task = Task { await buildSnapshot() } + rebuild = task + track(task) + } + + func loadLiveLinks() async { + guard !isLoadingLinks else { return } + isLoadingLinks = true + defer { isLoadingLinks = false } + let teamID = target.teamID + do throws(ShareFailure) { + let links = try await service.liveLinks(teamID: teamID) + guard target.teamID == teamID else { return } + liveLinks = links.sorted { $0.createdAt < $1.createdAt } + linksFailure = nil + } catch .canceled { + return + } catch { + linksFailure = Self.loadMessage(error) + } + } + + // MARK: - At the cap + + var isTargetAtCap: Bool { + switch target { + case .personal: limits?.isAtCap ?? false + case .team(let id): limits?.team(id)?.isAtCap ?? false + } + } + + func revoke(_ link: ShareLink) async { + guard !revokingLinkIDs.contains(link.id) else { return } + revokingLinkIDs.insert(link.id) + defer { revokingLinkIDs.remove(link.id) } + do throws(ShareFailure) { + try await service.revoke(id: link.id) + } catch .notFound, .revoked, .removed { + // Already gone elsewhere: its slot is free either way. + } catch .canceled { + return + } catch { + linksFailure = Self.loadMessage(error) + return + } + linksFailure = nil + liveLinks.removeAll { $0.id == link.id } + adjustLive(by: -1) + if !isTargetAtCap, phase == .atCap { + phase = .form + } + } + + private func adjustLive(by delta: Int) { + guard let current = limits else { return } + var updated = current + switch target { + case .personal: + updated = ShareLimits( + plan: current.plan, + live: max(0, current.live + delta), + liveLimit: current.liveLimit, + maxRows: current.maxRows, + expiries: current.expiries, + defaultExpiry: current.defaultExpiry, + allowsPassword: current.allowsPassword, + allowsDisablingDownload: current.allowsDisablingDownload, + allowsTeamLinks: current.allowsTeamLinks, + emailVerified: current.emailVerified, + sharingDisabled: current.sharingDisabled, + teams: current.teams + ) + case .team(let id): + guard let index = current.teams.firstIndex(where: { $0.id == id }) else { return } + updated.teams[index].live = max(0, current.teams[index].live + delta) + } + limits = updated + } + + // MARK: - Creating + + var isSnapshotTooLarge: Bool { + snapshot == .tooLarge + } + + var isEveryColumnRemoved: Bool { + snapshot == .noColumns && builtColumns == columns + } + + // Also while a change to the columns or the rules is rebuilding the snapshot, so Create never sends values masked + // the old way. + var isPreparingRows: Bool { + request.kind == .result && (snapshot == nil || builtColumns != columns || isSourceStale) + } + + var resultGoneMessage: String? { + guard request.kind == .result, isResultGone else { return nil } + return String(localized: "This result is no longer open, so there are no rows to share.") + } + + var sharedSQL: String { + source?.sql ?? request.sql + } + + // A table view the host cannot write as SQL shares its rows alone. + var hasSharedSQL: Bool { + !sharedSQL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + + var sqlTooLongMessage: String? { + guard sharedSQL.utf8.count > Self.sqlLimit else { return nil } + return String( + format: String(localized: "This query is too long to share. A link holds up to %@ of SQL."), + ByteCountFormatter.string(fromByteCount: Int64(Self.sqlLimit), countStyle: .memory) + ) + } + + // Readers send the password in a header, where HTTP drops leading and trailing spaces and tabs. + static func sentPassword(_ typed: String) -> String { + typed.trimmingCharacters(in: CharacterSet(charactersIn: " \t")) + } + + // A password the plan no longer allows, as after a reload as Free, is never dropped silently. + var passwordMessage: String? { + guard !password.isEmpty else { return nil } + if let limits, !limits.allowsPassword { + return Self.sentences(Self.proRequired, String(localized: "Clear the password to create the link.")) + } + let sent = Self.sentPassword(password) + if sent.isEmpty { + return String(localized: "A password can't be only spaces or tabs.") + } + guard sent.unicodeScalars.count > Self.passwordLimit else { return nil } + return String( + format: String(localized: "A password can be up to %lld characters."), + locale: .current, + Int64(Self.passwordLimit) + ) + } + + var expiryMessage: String? { + guard let limits, !limits.allows(expiry) else { return nil } + return Self.sentences(Self.proRequired, String(localized: "Choose another expiry to create the link.")) + } + + var downloadMessage: String? { + guard !allowsDownload, let limits, !limits.allowsDisablingDownload else { return nil } + return Self.sentences(Self.proRequired, String(localized: "Turn downloads back on to create the link.")) + } + + private static var proRequired: String { + String(localized: "This option needs TablePro Pro.") + } + + var canCreate: Bool { + phase == .form && !isCreating && !isSnapshotTooLarge && !isEveryColumnRemoved && !isPreparingRows + && !isResultGone && sqlTooLongMessage == nil && passwordMessage == nil && expiryMessage == nil + && downloadMessage == nil + } + + func create() async { + guard canCreate, let draft = makeDraft() else { return } + isCreating = true + failureMessage = nil + defer { isCreating = false } + let capNote = isColumnCapped + ? String( + format: String(localized: "The link shares the first %lld columns."), + locale: .current, + Int64(ShareSnapshotBuilder.maxColumns) + ) + : nil + do throws(ShareFailure) { + let created = try await service.create(draft) + guard !isClosed else { return } + copyToClipboard(created.url.absoluteString) + adjustLive(by: 1) + createdColumnCapNote = capNote + phase = .created(created.url) + } catch .limitReached { + await load() + } catch .signedOut { + phase = .signedOut + } catch .emailUnverified { + phase = .emailUnverified + } catch .sharingDisabled { + phase = .sharingDisabled + } catch { + failureMessage = error.message + } + } + + func makeDraft() -> ShareDraft? { + guard limits != nil, !isSourceStale, !isResultGone, passwordMessage == nil, expiryMessage == nil, + downloadMessage == nil + else { return nil } + let snapshotValue: ShareSnapshot? + switch (request.kind, snapshot) { + case (.result, .snapshot(let built)) where builtColumns == columns: + snapshotValue = built + case (.result, _): + return nil + case (.query, _): + snapshotValue = nil + } + let trimmedNote = note.trimmingCharacters(in: .whitespacesAndNewlines) + let sentPassword = Self.sentPassword(password) + return ShareDraft( + kind: request.kind, + sql: sharedSQL, + title: Self.clipped(title.trimmingCharacters(in: .whitespacesAndNewlines), to: Self.titleLimit), + note: trimmedNote.isEmpty ? nil : Self.clipped(trimmedNote, to: Self.noteLimit), + dialect: request.dialect, + expiry: expiry, + hidesSQL: request.kind == .result && hasSharedSQL ? hidesSQL : nil, + allowsDownload: allowsDownload ? nil : false, + password: sentPassword.isEmpty ? nil : sentPassword, + teamID: target.teamID, + snapshot: snapshotValue + ) + } + + private static func clipped(_ text: String, to limit: Int) -> String { + String(String.UnicodeScalarView(text.unicodeScalars.prefix(limit))) + } + + func copyLink() { + guard case .created(let url) = phase else { return } + copyToClipboard(url.absoluteString) + } + + // MARK: - What the sheet shows + + var isResult: Bool { + request.kind == .result + } + + var isPro: Bool { + limits?.plan == .pro + } + + var teams: [ShareTeam] { + limits?.teams ?? [] + } + + func isAvailable(_ expiry: ShareExpiry) -> Bool { + limits?.allows(expiry) ?? false + } + + var previewColumns: [ShareSnapshot.Column] { + guard case .snapshot(let built) = snapshot else { return [] } + return built.columns + } + + var previewRows: [[ShareCell]] { + guard case .snapshot(let built) = snapshot else { return [] } + return Array(built.rows.prefix(Self.previewRowCount)) + } + + var capNote: String? { + guard case .snapshot(let built) = snapshot, built.isTruncated else { return nil } + guard let total = built.rowCount else { + return String( + format: String(localized: "Shares the first %lld rows of a larger result."), + locale: .current, + Int64(built.rows.count) + ) + } + return String( + format: String(localized: "Shares the first %1$lld of %2$lld rows."), + locale: .current, + Int64(built.rows.count), + Int64(total) + ) + } + + var footer: String? { + guard let limits else { return nil } + if let teamID = target.teamID, let team = limits.team(teamID) { + return String( + format: String(localized: "%1$@ · %2$lld of %3$lld links"), + locale: .current, + team.name, + Int64(team.live), + Int64(team.liveLimit) + ) + } + switch limits.plan { + case .free: + return String( + format: String(localized: "Free · %1$lld of %2$lld links · first %3$lld rows"), + locale: .current, + Int64(limits.live), + Int64(limits.liveLimit), + Int64(limits.maxRows) + ) + case .pro: + return String(format: String(localized: "Pro · %lld links"), locale: .current, Int64(limits.live)) + } + } + + var atCapMessage: String? { + guard let limits else { return nil } + if let teamID = target.teamID, let team = limits.team(teamID) { + return Self.sentences( + String(format: String(localized: "This team has %lld live links."), locale: .current, Int64(team.live)), + String( + format: String(localized: "Teams allow %lld. Revoke one to share another."), + locale: .current, + Int64(team.liveLimit) + ) + ) + } + let live = String(format: String(localized: "You have %lld live links."), locale: .current, Int64(limits.live)) + let allowance = switch limits.plan { + case .free: String(localized: "Free allows %lld. Revoke one to share another.") + case .pro: String(localized: "Pro allows %lld. Revoke one to share another.") + } + return Self.sentences(live, String(format: allowance, locale: .current, Int64(limits.liveLimit))) + } + + var showsProUpsell: Bool { + target == .personal && limits?.plan == .free + } + + private static func sentences(_ first: String, _ second: String) -> String { + first + " " + second + } + + // A query share always shows its SQL; a result share shows it unless Hide SQL is on. + var secretWarnings: [String] { + guard request.kind == .query || !hidesSQL else { return [] } + return sqlSecretKinds.map { kind in + String( + format: String(localized: "This query may contain a secret (%@). Anyone with the link can read it."), + kind.displayName + ) + } + } + + // Only columns sent as they are: a masked or removed one gives nothing away. + var columnWarning: String? { + let kept = SecretScanner.scanColumns(columns.filter { $0.action == .keep }.map(\.name)) + guard !kept.isEmpty else { return nil } + return String( + format: String(localized: "Some columns may hold secrets: %@."), + ListFormatter.localizedString(byJoining: kept) + ) + } + + // The first kept columns up to the server's cap; the rest are not sent. + private var sentColumns: ArraySlice { + columns.filter { $0.action != .remove }.prefix(ShareSnapshotBuilder.maxColumns) + } + + var isColumnCapped: Bool { + columns.filter { $0.action != .remove }.count > ShareSnapshotBuilder.maxColumns + } + + var columnCapNote: String? { + guard isColumnCapped else { return nil } + return String( + format: String(localized: "Shares the first %lld columns."), + locale: .current, + Int64(ShareSnapshotBuilder.maxColumns) + ) + } + + var columnSummary: String { + let masked = sentColumns.filter { $0.action == .mask }.count + let removed = columns.filter { $0.action == .remove }.count + return String( + format: String(localized: "%1$lld columns masked, %2$lld removed."), + locale: .current, + Int64(masked), + Int64(removed) + ) + } + + var hasDetections: Bool { + columns.contains { $0.detection != nil } + } + + // Only while Hide SQL is off and there is SQL to hide. + var hideSQLSuggestion: String? { + guard request.kind == .result, hasSharedSQL, !hidesSQL, !sqlPersonalData.isEmpty else { return nil } + return String( + format: String(localized: "This query contains what looks like personal data (%@). Turn on Hide SQL to keep the query private."), + ListFormatter.localizedString(byJoining: sqlPersonalData.map(\.displayName)) + ) + } +} + +extension ShareSheetModel { + static func live(_ request: ShareRequest) -> ShareSheetModel { + ShareSheetModel( + request: request, + service: AccountServices.shared.shares, + isSignedIn: { FeatureAccess.shared.state.isSignedIn }, + signInChanges: FeatureAccess.shared.$state.map(\.isSignedIn).eraseToAnyPublisher(), + copyToClipboard: { ClipboardService.shared.writeText($0) } + ) + } +} diff --git a/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift index ea9a7aec47..12397f05c4 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift @@ -306,6 +306,14 @@ internal final class FavoritesOutlineCoordinator: NSObject, NSOutline return favoriteNode.content.filePath } + internal var selectedShareCommand: FavoritesMenuCommand? { + guard case .query(let favoriteNode) = selectedNode()?.kind else { return nil } + if let favorite = favoriteNode.asFavorite { + return .shareFavorite(favorite) + } + return favoriteNode.asLinkedFavorite.map(FavoritesMenuCommand.shareLinkedFavorite) + } + internal func performMenuCommand(_ command: FavoritesMenuCommand) { owner.actions.performMenuCommand(command) } diff --git a/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift b/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift index 791943c252..abf3c9a47f 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift @@ -125,12 +125,20 @@ internal final class FavoritesNSOutlineView: SidebarOutlineView { favoritesCoordinator?.performMenuCommand(.copyRelativePath(relative)) } + // File > Share Query… on the selected saved query, ahead of the window's editor. + @objc internal func shareQuery(_ sender: Any?) { + guard let command = favoritesCoordinator?.selectedShareCommand else { return } + favoritesCoordinator?.performMenuCommand(command) + } + override internal func validateUserInterfaceItem(_ item: any NSValidatedUserInterfaceItem) -> Bool { switch item.action { case #selector(copyPath(_:)): return favoritesCoordinator?.selectedFilePath != nil case #selector(copyRelativePath(_:)): return favoritesCoordinator?.selectedFilePath?.relative != nil + case #selector(shareQuery(_:)): + return favoritesCoordinator?.selectedShareCommand != nil default: return super.validateUserInterfaceItem(item) } @@ -140,6 +148,8 @@ internal final class FavoritesNSOutlineView: SidebarOutlineView { @MainActor internal protocol FavoritesOutlineKeyHandling: AnyObject { var selectedFilePath: FavoriteFilePath? { get } + // Share… for the selected saved query or linked file, nil for anything else. + var selectedShareCommand: FavoritesMenuCommand? { get } func performPrimaryAction() func performDelete() func performMenuCommand(_ command: FavoritesMenuCommand) diff --git a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift index 1c56a97245..94fd803e48 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift @@ -635,6 +635,10 @@ internal struct FavoritesTabView: View { viewModel.deleteFavorite(favorite) case .showFavoriteHistory(let favorite): coordinator?.showVersionHistory(of: favorite) + case .shareFavorite(let favorite): + coordinator?.shareFavorite(favorite) + case .shareLinkedFavorite(let favorite): + coordinator?.shareLinkedFavorite(favorite) case .openLinkedFavorite(let favorite): coordinator?.openLinkedFavorite(favorite) case .editLinkedMetadata(let favorite): diff --git a/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuCommand.swift b/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuCommand.swift index a34512a5ea..52479d5fd1 100644 --- a/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuCommand.swift +++ b/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuCommand.swift @@ -26,6 +26,8 @@ internal enum FavoritesMenuCommand: Equatable { case moveFavorite(id: UUID, toFolder: UUID?) case deleteFavorite(SQLFavorite) case showFavoriteHistory(SQLFavorite) + case shareFavorite(SQLFavorite) + case shareLinkedFavorite(LinkedSQLFavorite) case openLinkedFavorite(LinkedSQLFavorite) case editLinkedMetadata(LinkedSQLFavorite) diff --git a/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift b/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift index c183ecf603..6fee2bfcf8 100644 --- a/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift +++ b/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift @@ -153,6 +153,7 @@ internal enum FavoritesMenuSpec { ) -> [FavoritesMenuSection] { var edits: [FavoritesMenuItem] = [ .command(String(localized: "Copy Query"), .copyText(favorite.query)), + .command(String(localized: "Share…"), .shareFavorite(favorite)), .command(String(localized: "Edit…"), .editFavorite(favorite)), .command(String(localized: "Show History"), .showFavoriteHistory(favorite)) ] @@ -212,7 +213,10 @@ internal enum FavoritesMenuSpec { ]), FavoritesMenuSection(gitItems(favorite, gitState: gitState, folderGitState: folderGitState)), FavoritesMenuSection( - [.command(String(localized: "Copy Query"), .copyLinkedFavoriteQuery(favorite))] + [ + .command(String(localized: "Copy Query"), .copyLinkedFavoriteQuery(favorite)), + .command(String(localized: "Share…"), .shareLinkedFavorite(favorite)) + ] + pathCommands + [.command(String(localized: "Show in Finder"), .revealLinkedFavorite(favorite))] ), diff --git a/apple/TablePro/Views/Welcome/WelcomeWindowController.swift b/apple/TablePro/Views/Welcome/WelcomeWindowController.swift index 49853c1912..4850ce47cd 100644 --- a/apple/TablePro/Views/Welcome/WelcomeWindowController.swift +++ b/apple/TablePro/Views/Welcome/WelcomeWindowController.swift @@ -97,6 +97,7 @@ internal final class WelcomeWindowController: NSWindowController, NSWindowDelega internal func windowWillClose(_ notification: Notification) { window?.saveFrame(usingAutosaveName: Self.frameAutosaveName) + WelcomeRouter.shared.welcomeDidClose() } // MARK: - Commands diff --git a/apple/TableProTests/Core/Services/Infrastructure/DeeplinkSharedLinkTests.swift b/apple/TableProTests/Core/Services/Infrastructure/DeeplinkSharedLinkTests.swift new file mode 100644 index 0000000000..d6ae49efde --- /dev/null +++ b/apple/TableProTests/Core/Services/Infrastructure/DeeplinkSharedLinkTests.swift @@ -0,0 +1,74 @@ +// +// DeeplinkSharedLinkTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct DeeplinkSharedLinkTests { + nonisolated private static let token = "Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7cDe0fGh3" + + private func parse(_ link: String) throws -> Result { + DeeplinkParser.parse(try #require(URL(string: link))) + } + + @Test("A share link carries its 43-character token") + func carriesToken() throws { + guard case .success(.openSharedLink(let token)) = try parse("tablepro://share?token=\(Self.token)") else { + Issue.record("Expected .openSharedLink") + return + } + #expect(token == Self.token) + } + + @Test("Other query items are ignored") + func ignoresOtherItems() throws { + guard case .success(.openSharedLink(let token)) = try parse("tablepro://share?ref=web&token=\(Self.token)") else { + Issue.record("Expected .openSharedLink") + return + } + #expect(token == Self.token) + } + + @Test("A link without a token names the missing parameter", arguments: [ + "tablepro://share", "tablepro://share?token=", "tablepro://share?t=abc" + ]) + func missingToken(link: String) throws { + guard case .failure(.missingRequiredParam("token")) = try parse(link) else { + Issue.record("Expected .missingRequiredParam(\"token\") for \(link)") + return + } + } + + @Test("A token that is not 43 characters of base62 is refused", arguments: [ + "short", + String(DeeplinkSharedLinkTests.token.dropLast()), + DeeplinkSharedLinkTests.token + "A", + String(DeeplinkSharedLinkTests.token.dropLast()) + "-", + String(DeeplinkSharedLinkTests.token.dropLast()) + "%2F" + ]) + func malformedToken(token: String) throws { + guard case .failure(.invalidParameter("token")) = try parse("tablepro://share?token=\(token)") else { + Issue.record("Expected .invalidParameter(\"token\") for \(token)") + return + } + } + + @Test("Opening a shared link puts something on screen and names no connection") + func intentShape() { + let intent = LaunchIntent.openSharedLink(token: Self.token) + #expect(intent.impliesUserInterface) + #expect(intent.targetConnectionId == nil) + } + + @Test("Token validation accepts exactly 43 base62 characters") + func tokenShape() { + #expect(ShareToken.isValid(Self.token)) + #expect(!ShareToken.isValid("")) + #expect(!ShareToken.isValid(String(repeating: "é", count: 43))) + #expect(!ShareToken.isValid(String(repeating: "a", count: 42) + "_")) + } +} diff --git a/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift b/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift index 56ee100c6c..123c04ef44 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift @@ -3,8 +3,10 @@ // TableProTests // +import Combine import Foundation @testable import TablePro +import TableProTestSupport import Testing @MainActor @@ -72,6 +74,51 @@ final class WelcomeRouterTests { #expect(selected == .mysql) } + @Test("A shared query a connection took waits for it, and closing Welcome keeps it") + func claimedSharedQueryOutlivesWelcome() { + let query = SharedQueryOpen(sql: "SELECT 1", title: "Report") + let connectionId = UUID() + router.enqueueSharedQuery(query) + router.claimPendingSharedQueries(for: connectionId) + + #expect(router.pendingSharedQueries.isEmpty) + #expect(router.claimedSharedQueries[connectionId] == [query]) + router.welcomeDidClose() + #expect(router.claimedSharedQueries[connectionId] == [query]) + } + + @Test("A connect that ends without connecting hands its shared queries back; one still connecting keeps them") + func endedConnectReleasesSharedQueries() async throws { + let events = AppEvents() + let failed = UUID() + let connecting = UUID() + let router = WelcomeRouter(appEvents: events) { id in + id == failed ? [.unavailable(.cancelled)] : [.connecting] + } + let first = SharedQueryOpen(sql: "SELECT 1", title: nil) + let second = SharedQueryOpen(sql: "SELECT 2", title: nil) + router.enqueueSharedQuery(first) + router.claimPendingSharedQueries(for: connecting) + router.enqueueSharedQuery(second) + router.claimPendingSharedQueries(for: failed) + + events.connectionPhaseChanged.send(connecting) + events.connectionPhaseChanged.send(failed) + try await waitUntil { router.claimedSharedQueries[failed] == nil } + + #expect(router.pendingSharedQueries == [second]) + #expect(router.claimedSharedQueries[connecting] == [first]) + router.welcomeDidClose() + } + + @Test("Closing Welcome drops a shared query no connection took") + func unclaimedSharedQueryDiesWithWelcome() { + router.enqueueSharedQuery(SharedQueryOpen(sql: "SELECT 1", title: nil)) + router.welcomeDidClose() + #expect(router.pendingSharedQueries.isEmpty) + #expect(router.claimedSharedQueries.isEmpty) + } + @Test func requestSlotIsIndependentOfTheOtherPendingSlots() { let connection = DatabaseConnection(name: "Test", type: .mysql) diff --git a/apple/TableProTests/Core/Services/Shares/CloudShareServiceTests.swift b/apple/TableProTests/Core/Services/Shares/CloudShareServiceTests.swift new file mode 100644 index 0000000000..a070de77ee --- /dev/null +++ b/apple/TableProTests/Core/Services/Shares/CloudShareServiceTests.swift @@ -0,0 +1,289 @@ +// +// CloudShareServiceTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProCloudAPI +import Testing + +struct CloudShareServiceTests { + private actor CannedTransport: ClientTransport { + struct Sent: Sendable { + let method: HTTPRequest.Method + let path: String + let headers: HTTPFields + let body: Data + } + + private var answers: [(HTTPResponse, HTTPBody?)] + private(set) var sent: [Sent] = [] + + init(_ answers: [(HTTPResponse, HTTPBody?)]) { + self.answers = answers + } + + func send( + _ request: HTTPRequest, + body: HTTPBody?, + baseURL: URL, + operationID: String + ) async throws -> (HTTPResponse, HTTPBody?) { + var data = Data() + if let body { + data = try await Data(collecting: body, upTo: 10 * 1_024 * 1_024) + } + sent.append(Sent(method: request.method, path: request.path ?? "", headers: request.headerFields, body: data)) + return answers.removeFirst() + } + } + + private static func service(_ transport: CannedTransport) -> CloudShareService { + let client = Client( + serverURL: URL(string: "https://api.example.test/v2")!, + configuration: Configuration(dateTranscoder: RFC3339DateTranscoder()), + transport: transport + ) + return CloudShareService( + api: client, + publicAPI: client, + createRequest: ShareCreateRequest( + serverURL: URL(string: "https://api.example.test/v2")!, + transport: transport, + middlewares: [] + ) + ) + } + + private static func limitsJSON() -> [String: Any] { + [ + "plan": "free", "live": 3, "live_limit": 5, "max_rows": 1_000, + "expiries": ["1d", "7d", "30d"], "default_expiry": "30d", + "password": false, "disable_download": false, "team": false, + "email_verified": true, "sharing_disabled": false, "teams": [[String: Any]]() + ] + } + + private static func shareView(id: String, created: String, suspended: Bool = false) -> [String: Any] { + [ + "id": id, "kind": "query", "scope": "account", "title": "T", "note": "", "dialect": "MySQL", + "has_snapshot": false, "hide_sql": false, "allow_download": true, "has_password": false, + "state": "live", "suspended": suspended, "view_count": 0, "created_at": created, "updated_at": created + ] + } + + @Test("Limits map every field the sheet reads") + func limitsMap() async throws { + let transport = CannedTransport([FakeAccountServer.json(status: .ok, Self.limitsJSON())]) + let limits = try await Self.service(transport).limits() + + #expect(limits == ShareLimits.free()) + #expect(await transport.sent.first?.path == "/share-limits") + } + + @Test("Create sends the draft as the contract names it and returns the link") + func createBody() async throws { + let created: [String: Any] = [ + "share": Self.shareView(id: "shr_1", created: "2026-11-13T10:00:00Z"), + "token": String(repeating: "a", count: 43), + "url": "https://s.tablepro.app/" + String(repeating: "a", count: 43) + ] + let transport = CannedTransport([FakeAccountServer.json(status: .created, created)]) + let draft = ShareDraft( + kind: .result, + sql: "SELECT id FROM t", + title: "T", + note: nil, + dialect: "PostgreSQL", + expiry: .sevenDays, + hidesSQL: true, + allowsDownload: nil, + password: nil, + teamID: "team_1", + snapshot: ShareSnapshot( + columns: [.init(name: "id", type: "int8"), .init(name: "doc", type: "jsonb")], + rows: [ + [.number("18446744073709551615"), .document("{\"b\":1,\"a\":2}")], + [.number("7"), .array([.number("1"), .null])], + [.null, .string("x\"y")] + ], + rowCount: 48_210 + ) + ) + + let link = try await Self.service(transport).create(draft) + #expect(link.id == "shr_1") + #expect(link.url.absoluteString.hasPrefix("https://s.tablepro.app/")) + + let sentRequest = try #require(await transport.sent.first) + #expect(sentRequest.method == .post) + #expect(sentRequest.path == "/shares") + let body = sentRequest.body + let text = try #require(String(data: body, encoding: .utf8)) + // Exact tokens and key order, which a Double or a dictionary would lose. + #expect(text.contains("[18446744073709551615,{\"b\":1,\"a\":2}]")) + #expect(text.contains("[7,[1,null]]")) + let sent = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + #expect(sent["kind"] as? String == "result") + #expect(sent["team_id"] as? String == "team_1") + #expect(sent["expiry"] as? String == "7d") + #expect(sent["hide_sql"] as? Bool == true) + #expect(sent["allow_download"] == nil) + #expect(sent["password"] == nil) + #expect(sent["note"] == nil) + let snapshot = try #require(sent["snapshot"] as? [String: Any]) + #expect((snapshot["row_count"] as? NSNumber)?.intValue == 48_210) + let rows = try #require(snapshot["rows"] as? [[Any]]) + #expect(rows[2][0] is NSNull) + #expect(rows[2][1] as? String == "x\"y") + } + + @Test("A snapshot that is not cut, or whose total nobody counted, sends no row_count", arguments: [1, nil] as [Int?]) + func noRowCountUnlessCounted(total: Int?) { + let text = ShareBodyWriter.snapshot(ShareSnapshot(columns: [.init(name: "a", type: nil)], rows: [[.number("1")]], rowCount: total)) + #expect(!text.contains("row_count")) + } + + @Test("A result with more rows and no count says so with more_rows; a counted one does not") + func moreRowsWhenUncounted() { + let columns = [ShareSnapshot.Column(name: "a", type: nil)] + let uncounted = ShareBodyWriter.snapshot(ShareSnapshot(columns: columns, rows: [[.number("1")]], rowCount: nil)) + #expect(uncounted.contains("\"more_rows\":true")) + let counted = ShareBodyWriter.snapshot(ShareSnapshot(columns: columns, rows: [[.number("1")]], rowCount: 40)) + #expect(!counted.contains("more_rows")) + #expect(counted.contains("\"row_count\":40")) + let whole = ShareBodyWriter.snapshot(ShareSnapshot(columns: columns, rows: [[.number("1")]], rowCount: 1)) + #expect(!whole.contains("more_rows")) + } + + @Test("A column's name and type are cut to the contract's 256 characters") + func columnTextIsCut() throws { + let column = ShareSnapshot.Column(name: String(repeating: "é", count: 300), type: String(repeating: "t", count: 300)) + let text = ShareBodyWriter.snapshot(ShareSnapshot(columns: [column], rows: [], rowCount: 0)) + let object = try #require(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any]) + let columns = try #require(object["columns"] as? [[String: String]]) + #expect(columns.first?["name"] == String(repeating: "é", count: 256)) + #expect(columns.first?["type"] == String(repeating: "t", count: 256)) + } + + @Test("A masked column names its style as the contract spells it, and an unmasked one sends no masked key") + func maskedColumns() throws { + // api/v2.json, ShareMaskStyle. + #expect(MaskingStyle.allCases.map(\.rawValue) == ["full", "lastFour", "email", "hash", "null"]) + let columns = [ + ShareSnapshot.Column(name: "email", type: "text", masked: .email), + ShareSnapshot.Column(name: "id", type: "int8") + ] + let text = ShareBodyWriter.snapshot(ShareSnapshot(columns: columns, rows: [], rowCount: 0)) + let object = try #require(try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any]) + let sent = try #require(object["columns"] as? [[String: String]]) + #expect(sent == [["name": "email", "type": "text", "masked": "email"], ["name": "id", "type": "int8"]]) + } + + @Test("Strings are escaped so the body stays valid JSON") + func stringsAreEscaped() throws { + let text = ShareBodyWriter.quoted("a\"b\\c\n\u{01}é") + #expect(text == "\"a\\\"b\\\\c\\n\\u0001é\"") + #expect(try JSONSerialization.jsonObject(with: Data(text.utf8), options: .fragmentsAllowed) as? String == "a\"b\\c\n\u{01}é") + } + + @Test("Only a URL load that did not finish reads as offline") + func offlineOnlyForURLErrors() { + #expect(CloudShareService.failure(from: URLError(.notConnectedToInternet)) == .offline) + #expect(CloudShareService.failure(from: URLError(.cancelled)) == .canceled) + #expect(CloudShareService.failure(from: CancellationError()) == .canceled) + #expect(CloudShareService.failure(from: DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: ""))) == .server) + #expect(CloudShareService.failure(from: AccountError.signedOut) == .signedOut) + } + + @Test("The limits carry the seated teams") + func limitsCarryTeams() async throws { + var json = Self.limitsJSON() + json["plan"] = "pro" + json["teams"] = [["id": "team_1", "name": "Acme", "live": 4, "live_limit": 1_000, "public_links": false]] + let transport = CannedTransport([FakeAccountServer.json(status: .ok, json)]) + let limits = try await Self.service(transport).limits() + #expect(limits.teams == [ShareTeam(id: "team_1", name: "Acme", live: 4, liveLimit: 1_000, allowsPublicLinks: false)]) + } + + @Test("Problem codes reach the sheet as their own failures", arguments: [ + (403, "email_unverified", ShareFailure.emailUnverified), + (403, "pro_required", .proRequired), + (403, "sharing_disabled", .sharingDisabled), + (403, "team_sharing_disabled", .teamSharingDisabled), + (409, "share_limit_reached", .limitReached), + (422, "snapshot_too_large", .snapshotTooLarge), + (429, "rate_limited", .rateLimited), + (401, "unauthorized", .signedOut) + ]) + func problemCodes(status: Int, code: String, failure: ShareFailure) async { + let transport = CannedTransport([FakeAccountServer.problem(status: status, code: code)]) + let draft = ShareDraft( + kind: .query, sql: "SELECT 1", title: "", note: nil, dialect: nil, expiry: .thirtyDays, + hidesSQL: nil, allowsDownload: nil, password: nil, teamID: nil, snapshot: nil + ) + await #expect(throws: failure) { + _ = try await Self.service(transport).create(draft) + } + } + + @Test("Live links ask for live ones only and come back oldest first") + func liveLinksOldestFirst() async throws { + let page: [String: Any] = ["data": [ + Self.shareView(id: "shr_new", created: "2026-11-13T10:00:00Z"), + Self.shareView(id: "shr_old", created: "2026-11-01T10:00:00Z", suspended: true) + ]] + let transport = CannedTransport([FakeAccountServer.json(status: .ok, page)]) + let links = try await Self.service(transport).liveLinks(teamID: nil) + + #expect(links.map(\.id) == ["shr_old", "shr_new"]) + #expect(links.map(\.isSuspended) == [true, false]) + let path = try #require(await transport.sent.first?.path) + #expect(path.hasPrefix("/shares?")) + #expect(path.contains("state=live")) + #expect(!path.contains("team=")) + } + + @Test("A team's live links are asked for by its ID") + func teamLiveLinks() async throws { + let transport = CannedTransport([FakeAccountServer.json(status: .ok, ["data": [[String: Any]]()])]) + _ = try await Self.service(transport).liveLinks(teamID: "team_1") + let path = try #require(await transport.sent.first?.path) + #expect(path.contains("team=team_1")) + } + + @Test("Revoke deletes the share by its ID") + func revokeDeletes() async throws { + let transport = CannedTransport([(HTTPResponse(status: .noContent), nil)]) + try await Self.service(transport).revoke(id: "shr_1") + let sent = try #require(await transport.sent.first) + #expect(sent.method == .delete) + #expect(sent.path == "/shares/shr_1") + } + + @Test("The public read sends the password header and tells required from wrong") + func publicReadPassword() async throws { + let shared: [String: Any] = [ + "kind": "result", "title": "Report", "note": "", "dialect": "MySQL", + "created_at": "2026-11-13T10:00:00Z", "allow_download": true, "made_with": "TablePro" + ] + let transport = CannedTransport([ + FakeAccountServer.problem(status: 401, code: "share_password_required"), + FakeAccountServer.problem(status: 401, code: "share_password_wrong"), + FakeAccountServer.json(status: .ok, shared) + ]) + let service = Self.service(transport) + let token = String(repeating: "b", count: 43) + + await #expect(throws: ShareFailure.passwordRequired) { _ = try await service.fetchShared(token: token, password: nil) } + await #expect(throws: ShareFailure.passwordWrong) { _ = try await service.fetchShared(token: token, password: "nope") } + let query = try await service.fetchShared(token: token, password: "right") + + #expect(query == SharedQuery(kind: .result, title: "Report", sql: nil)) + let sent = await transport.sent + #expect(sent[0].headers[HTTPField.Name("X-Share-Password")!] == nil) + #expect(sent[2].headers[HTTPField.Name("X-Share-Password")!] == "right") + #expect(sent[2].headers[.authorization] == nil) + } +} diff --git a/apple/TableProTests/Core/Services/Shares/SecretScannerTests.swift b/apple/TableProTests/Core/Services/Shares/SecretScannerTests.swift new file mode 100644 index 0000000000..ad38f2237f --- /dev/null +++ b/apple/TableProTests/Core/Services/Shares/SecretScannerTests.swift @@ -0,0 +1,181 @@ +// +// SecretScannerTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +struct SecretScannerTests { + private func kinds(_ sql: String) -> [SecretKind] { + SecretScanner.scanSQL(sql).map(\.kind) + } + + // Built at run time so no literal in this file reads as a live credential to a scanner. + private static let fakeGitHub = "ghp_" + String(repeating: "a1B2", count: 9) + private static let fakeGoogle = "AIza" + String(repeating: "x", count: 35) + private static let fakeAWS = "AKIA" + String(repeating: "Z", count: 16) + + @Test("Each provider pattern is recognised", arguments: [ + (SecretScannerTests.fakeAWS, SecretKind.awsAccessKey), + ("-----BEGIN RSA PRIVATE KEY-----", .privateKey), + ("-----BEGIN PRIVATE KEY-----", .privateKey), + ("-----BEGIN ENCRYPTED PRIVATE KEY-----", .privateKey), + ("-----BEGIN PKCS8 PRIVATE KEY-----", .privateKey), + ("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl", .jsonWebToken), + (SecretScannerTests.fakeGitHub, .gitHubToken), + ("xoxb-1234", .slackToken), + ("sk_live_abc", .stripeSecretKey), + (SecretScannerTests.fakeGoogle, .googleAPIKey), + ("postgres://admin:hunter2@db.internal/app", .urlCredentials) + ]) + func providerPatterns(token: String, kind: SecretKind) { + #expect(kinds("SELECT '\(token)'").contains(kind)) + } + + @Test("A quoted value assigned to a password-like name, bare or quoted in any style, is flagged", arguments: [ + "UPDATE users SET password = 'hunter2'", + "SELECT * FROM t WHERE api_key='abc'", + "SELECT * FROM t WHERE user_secret := 'abc'", + "SELECT '{\"token\": \"abc\"}'", + "SELECT * FROM t WHERE \"passwd\" = 'abc'", + "SELECT * FROM t WHERE 'password' = 'abc'", + "SET [db_passwd] = 'x'", + "WHERE `Api_Key`='x'", + "INSERT INTO t VALUES (secret => 'x')", + "SET @pwd := 'x'" + ]) + func passwordLiterals(sql: String) { + #expect(kinds(sql).contains(.passwordLiteral)) + } + + @Test("Ordinary SQL raises nothing", arguments: [ + "SELECT id, name FROM users WHERE id = 1", + "SELECT password_hash IS NULL FROM users", + "UPDATE users SET password = ''", + "UPDATE users SET password = \"\"", + "SELECT 'https://example.com/path' AS link", + "SELECT token_count FROM usage WHERE token_count > 10", + "SELECT 'password' AS label", + "SELECT * FROM users WHERE password = $1", + "SELECT * FROM users WHERE token = :token", + "SELECT '-----BEGIN PUBLIC KEY-----'" + ]) + func ordinarySQL(sql: String) { + #expect(SecretScanner.scanSQL(sql).isEmpty) + } + + @Test("Hits carry the line they start on, counting CRLF as one break") + func linesAreOneBased() { + let sql = "SELECT 1;\r\nSELECT 2;\n-- \(Self.fakeAWS)\nSELECT 'sk_live_x'" + #expect(SecretScanner.scanSQL(sql) == [ + SecretHit(kind: .awsAccessKey, line: 3), + SecretHit(kind: .stripeSecretKey, line: 4) + ]) + } + + @Test("A value that runs over lines is reported on the line its name starts") + func multiLineValue() { + #expect(SecretScanner.scanSQL("SELECT 1;\nUPDATE users SET password =\r\n'a\nb'") == [SecretHit(kind: .passwordLiteral, line: 2)]) + } + + @Test("Two hits of a kind on two lines are both reported, each on its own line") + func twoHitsOnTwoLines() { + #expect(SecretScanner.scanSQL("password='a'\npassword='b'") == [ + SecretHit(kind: .passwordLiteral, line: 1), + SecretHit(kind: .passwordLiteral, line: 2) + ]) + #expect(SecretScanner.scanSQL("-- postgres://app:pw@db1/x\r\n-- mysql://root:pw@db2/y") == [ + SecretHit(kind: .urlCredentials, line: 1), + SecretHit(kind: .urlCredentials, line: 2) + ]) + #expect(SecretScanner.scanSQL("-- postgres://app:pw@db1/x mysql://root:pw@db2/y") == [SecretHit(kind: .urlCredentials, line: 1)]) + } + + @Test("A kind found twice on one line is reported once") + func oneHitPerKindAndLine() { + #expect(SecretScanner.scanSQL("SELECT 'sk_live_a', 'sk_live_b'") == [SecretHit(kind: .stripeSecretKey, line: 1)]) + } + + @Test("A long run with no secret in it scans quickly") + func longRunsStayLinear() { + let run = String(repeating: "a", count: 200_000) + let hex = String(repeating: "0a1b2c3d", count: 25_000) + let started = ContinuousClock.now + #expect(SecretScanner.scanSQL("SELECT '\(run)://\(run)'").isEmpty) + #expect(SecretScanner.scanSQL("INSERT INTO t VALUES (X'\(hex)', '\(run) = 1')").isEmpty) + #expect(SecretScanner.scanSQL("SELECT \(run)password\(run) FROM t").isEmpty) + #expect(ContinuousClock.now - started < .seconds(5)) + } + + // DETECTOR-FIXTURES.md, Secret scan, SQL (core/crates/core/src/masking/detect/fixtures.rs). + static let fixtureRows: [(String, [String])] = [ + ("-- \(SensitiveDataDetectorTests.fakeAWS)", ["awsAccessKey:1"]), + ("-----BEGIN RSA PRIVATE KEY-----", ["privateKey:1"]), + ("-----BEGIN PRIVATE KEY-----", ["privateKey:1"]), + ("-----BEGIN OPENSSH PRIVATE KEY-----", ["privateKey:1"]), + ("-----BEGIN EC2 PRIVATE KEY-----", ["privateKey:1"]), + ("-----BEGIN ENCRYPTED PRIVATE KEY-----", []), + ("-----BEGIN rsa PRIVATE KEY-----", []), + ("-----BEGIN PUBLIC KEY-----", []), + ("-- \(SensitiveDataDetectorTests.jwt)", ["jsonWebToken:1"]), + ("-- \(SensitiveDataDetectorTests.fakeGitHub)", ["gitHubToken:1"]), + ("-- xoxb-123", ["slackToken:1"]), + ("-- sk_live_abc", ["stripeSecretKey:1"]), + ("-- \(SensitiveDataDetectorTests.fakeGoogle)", ["googleAPIKey:1"]), + ("-- postgres://app:hunter2@db.internal/shop", ["urlCredentials:1"]), + ("-- https://a@b:c@d", []), + ("https://tablepro.app/docs", []), + ("WHERE u.password = 'hunter2'", ["passwordLiteral:1"]), + ("SELECT '{\"token\": \"abc\"}'::jsonb", ["passwordLiteral:1"]), + ("WHERE \"password\" = 'x'", ["passwordLiteral:1"]), + ("WHERE 'password' = \"x\"", ["passwordLiteral:1"]), + ("SET `password` := 'x'", ["passwordLiteral:1"]), + ("VALUES ([db_passwd] => 'x')", ["passwordLiteral:1"]), + ("WHERE Api_Key: 'x'", ["passwordLiteral:1"]), + ("WHERE password = ''", []), + ("WHERE password = \"\"", []), + ("WHERE password = 'abc\" AND 1 = 1", []), + ("WHERE password = 'a\nb'", ["passwordLiteral:1"]), + ("SELECT password FROM users", []), + ("WHERE token = :token", []), + ("SELECT 'password' AS label", []), + ( + "SELECT '\(SensitiveDataDetectorTests.fakeAWS)', '\(SensitiveDataDetectorTests.otherAWS)';\nSELECT 'sk_live_a'", + ["awsAccessKey:1", "stripeSecretKey:2"] + ), + ("\r\rsk_live_x", ["stripeSecretKey:3"]), + ("\r\n\r\nsk_live_x", ["stripeSecretKey:3"]), + ("\n\rsk_live_x", ["stripeSecretKey:3"]) + ] + + @Test("Secret scan, fixture table", arguments: SecretScannerTests.fixtureRows) + func fixtures(sql: String, hits: [String]) { + #expect(SecretScanner.scanSQL(sql).map { "\($0.kind.rawValue):\($0.line)" } == hits) + } + + @Test("Secret columns, fixture table: whole words only") + func columnFixtures() { + #expect(SecretScanner.scanColumns([ + "id", "user_password", "PasswordHash", "access_token", "apiKey", "API-KEY", "client_secret", "ssn", "customerSSN", + "ssn_last4", "credit_card", "CardNumber", "class_name", "lesson", "id", "user_password" + ]) == [ + "user_password", "PasswordHash", "access_token", "apiKey", "API-KEY", "client_secret", "ssn", "customerSSN", + "ssn_last4", "credit_card", "CardNumber" + ]) + #expect(SecretScanner.scanColumns(["passwords", "tokens", "passwd", "secrets", "api_key_id"]) == ["passwd", "api_key_id"]) + } + + @Test("Column names that read like secrets are named, each once, in order") + func sensitiveColumns() { + let names = [ + "id", "password_hash", "apiKey", "API-KEY", "reset_token", "ssn", "user_ssn", "userSSN", + "credit_card", "CardNumber", "client_secret", "classname", "session", "password_hash" + ] + #expect(SecretScanner.scanColumns(names) == [ + "password_hash", "apiKey", "API-KEY", "reset_token", "ssn", "user_ssn", "userSSN", + "credit_card", "CardNumber", "client_secret" + ]) + } +} diff --git a/apple/TableProTests/Core/Services/Shares/SensitiveDataDetectorTests.swift b/apple/TableProTests/Core/Services/Shares/SensitiveDataDetectorTests.swift new file mode 100644 index 0000000000..cdd20667e7 --- /dev/null +++ b/apple/TableProTests/Core/Services/Shares/SensitiveDataDetectorTests.swift @@ -0,0 +1,280 @@ +// +// SensitiveDataDetectorTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +// The rows of DETECTOR-FIXTURES.md (core/crates/core/src/masking/detect/fixtures.rs), so the core and this app agree. +struct SensitiveDataDetectorTests { + // Built at run time so no literal in this file reads as a live credential to a scanner. + static let fakeAWS = "AKIA" + "IOSFODNN7EXAMPLE" + static let otherAWS = "AKIA" + "IOSFODNN7EXAMPLF" + static let fakeGitHub = "ghp_" + "0123456789abcdefghijABCDEFGHIJ012345" + static let fakeGoogle = "AIza" + "SyA1234567890abcdefghijklmnopqrstuv" + static let jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abc-DEF_123" + + static let nameRows: [(String, SensitiveNameKind?)] = [ + ("email", .email), ("E-Mail", .email), ("e_mail", .email), ("mail", .email), + ("work_mail", .email), ("ma_il", nil), ("email_address", .email), ("phone", .phone), ("mobilePhone", .phone), + ("mobile", .phone), ("tel_no", .phone), ("hotel", nil), ("fax", .phone), ("msisdn", .phone), + ("password_hash", .secret), ("passwords", nil), ("stripe_api_key", .secret), ("apiKey", .secret), + ("API-KEY", .secret), ("aws_access_key", .secret), ("PrivateKey", .secret), ("credential", .secret), + ("credentials", nil), ("refresh_token", .secret), ("ssn", .nationalID), ("customerSSN", .nationalID), + ("ssn4", .nationalID), ("classname", nil), ("class_name", nil), ("social_security_number", .nationalID), + ("national_id", .nationalID), ("tax_id", .nationalID), ("tin", .nationalID), + ("credit_card_number", .cardOrAccount), ("CardNumber", .cardOrAccount), ("pan", .cardOrAccount), + ("company", nil), ("iban", .cardOrAccount), ("routing_number", .cardOrAccount), ("street_address", .address), + ("street", .address), ("Address2Line", .address), ("zip", .address), ("zipcode", .address), + ("zip_code", .address), ("postal_code", .address), ("dob", .birthDate), ("date_of_birth", .birthDate), + ("birthday", .birthDate), ("ip", .ipAddress), ("ip_address", .ipAddress), ("IPAddress", .ipAddress), + ("ipv4", .ipAddress), ("client_ipv6", .ipAddress), ("ipv", nil), ("user_first_name", .personName), + ("lastName", .personName), ("surname", .personName), ("given_name", .personName), + ("home_phone_address", .phone), ("id", nil), ("", nil) + ] + + static let valueRows: [(String, [SensitiveValueKind])] = [ + ("4111 1111 1111 1111", [.card]), ("4111-1111-1111-1111", [.card]), ("4111111111111111", [.card]), + ("4222222222222", [.card]), ("4222 2222 22222", [.card, .phone]), ("4111111111111112", []), ("411111111111", []), + ("4111.1111.1111.1111", []), (" 4111111111111111", [.card]), ("GB82 WEST 1234 5698 7654 32", [.iban]), + ("GB82WEST12345698765432", [.iban]), ("DE89 3704 0044 0532 0130 00", [.iban]), + ("GB82 WEST 1234 5698 7654 33", []), ("gb82west12345698765432", []), ("GB82\tWEST12345698765432", []), + (SensitiveDataDetectorTests.jwt, [.jsonWebToken]), (" eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abc", []), + (SensitiveDataDetectorTests.fakeAWS, [.apiKey]), ("key=\(SensitiveDataDetectorTests.fakeAWS);", [.apiKey]), + (SensitiveDataDetectorTests.fakeGitHub, [.apiKey]), ("xoxb-123", [.apiKey]), ("sk_live_abc", [.apiKey]), + (SensitiveDataDetectorTests.fakeGoogle, [.apiKey]), ("sk_test_abc", []), ("ann@example.com", [.email]), + ("émile@exämple.fr", [.email]), ("a@b@c.com", []), ("ann@localhost", []), ("ann @example.com", []), + ("ann@example.com ", []), ("ann\u{a0}x@example.com", []), ("+1 555 0100", [.phone]), ("(555) 010-0100", [.phone]), + ("555.010.0100", [.phone]), ("+15550100", [.phone]), ("1.234.567", [.phone]), ("5550100", []), ("+123456", []), + ("+1234567890123456", []), ("555-0100 ext 2", []), ("2024-01-02", []), ("2024-01-0212345", []), + ("1234567.89", []), ("-1234567.89", []), ("12:30:45", []), ("192.168.100.200", [.ipAddress]), + ("192.168.1.1", [.ipAddress]), ("0.0.0.0", [.ipAddress]), ("192.168.01.1", [.phone]), ("256.1.1.1", []), + ("256.10.10.10", [.phone]), ("1.2.3", []), ("1.1.1.1 ", []), ("::1", [.ipAddress]), ("2001:db8::1", [.ipAddress]), + ("1:2:3:4:5:6:7:8", [.ipAddress]), ("::ffff:192.168.1.1", [.ipAddress]), ("fe80::1%eth0", []), ("[::1]", []), + ("2001:db8::1::2", []), ("12345::1", []), ("", []) + ] + + static let columnRows: [(String, [PluginCellValue], SensitiveValueKind?)] = [ + ("text", [.text("ann@example.com"), .text("bob@example.com"), .text("n/a"), .text("x")], .email), + ("text", [.text("ann@example.com"), .text("x"), .text("y")], nil), + ("text", [.text("ann@example.com"), .null, .null], .email), + ("text", [.text("ann@example.com"), .text(""), .text("")], nil), + ("text", [.text("ann@example.com"), .bytes(Data([1])), .bytes(Data([2]))], nil), + ("text", [.text("x"), .text("y"), .text("4111 1111 1111 1111")], .card), + ("text", [.text("ann@example.com"), .text(SensitiveDataDetectorTests.jwt)], .jsonWebToken), + ("text", [.text("192.168.1.1"), .text("10.0.0.1")], .ipAddress), + ("varchar(64)", [.text("+1 555 0100"), .text("x")], .phone), + ("", [.text("ann@example.com")], .email), + ("Nullable(String)", [.text("ann@example.com")], .email), + ("bigint", [.text("4111111111111111")], nil), + ("uuid", [.text("ann@example.com")], nil), + ("Nullable(UInt64)", [.text("4111111111111111")], nil), + ("timestamp with time zone", [.text("2024-01-02 10:00:00+00")], nil), + ("text", [.null, .null], nil), + ("text", [], nil) + ] + + static let sqlRows: [(String, [String])] = [ + ("SELECT * FROM users WHERE email = 'ann@example.com'", ["email:1"]), + ("SELECT \"ann@example.com\" FROM t", []), + ("WHERE note = 'call +1 555 0100'", []), + ("WHERE card = '4111-1111-1111-1111'", ["card:1"]), + ("WHERE iban = 'GB82 WEST 1234 5698 7654 32'", ["iban:1"]), + ("SET token = '\(SensitiveDataDetectorTests.jwt)'", ["jwt:1"]), + ("WHERE k = 'id \(SensitiveDataDetectorTests.fakeAWS)'", ["api_key:1"]), + ("SELECT 'o''brien@example.com'", ["email:1"]), + ("WHERE ip = '192.168.1.1'", []), + ("WHERE e = 'ann@example.com", []), + ("-- don't\nWHERE e = 'ann@example.com'", ["email:2"]), + ("SELECT /* it's */ 'ann@example.com'", ["email:1"]), + ("SELECT 1 -- 'ann@example.com'", []), + ("SELECT 1 /* 'ann@example.com' */", []), + ("/* 'ann@example.com'", []), + ("-- it's\r'ann@example.com'", ["email:2"]), + ("SELECT 'a--b@example.com'", ["email:1"]), + ("SELECT \"x--y\", 'ann@example.com'", ["email:1"]), + ("SELECT 1 - -1, 'ann@example.com'", ["email:1"]), + ("WHERE e = 'a@b.co' AND f = 'c@d.co'\nOR p = '(555) 010-0100'", ["email:1", "phone:2"]), + ("SELECT 1;\r\n\r\nSELECT '+1 555 0100'", ["phone:3"]), + ("SELECT 1", []) + ] + + // MARK: - Column names + + @Test("Column names, fixture table", arguments: SensitiveDataDetectorTests.nameRows) + func columnNames(name: String, kind: SensitiveNameKind?) { + #expect(SensitiveDataDetector.nameKind(name) == kind) + } + + @Test("Each name kind suggests its style") + func nameStyles() { + #expect(SensitiveNameKind.allCases.map(\.style) == [.email, .lastFour, .full, .lastFour, .lastFour, .full, .full, .hash, .full]) + } + + @Test("Words are lower-cased and split only where the rules say") + func wordSplitting() { + #expect(SensitiveDataDetector.words(in: "userFirstName2fa") == ["user", "first", "name", "2", "fa"]) + #expect(SensitiveDataDetector.words(in: "Address2Line") == ["address", "2", "line"]) + #expect(SensitiveDataDetector.words(in: "IPAddress") == ["ipaddress"]) + #expect(SensitiveDataDetector.words(in: "e.mail x") == ["e", "mail", "x"]) + #expect(SensitiveDataDetector.words(in: "e#mail") == ["e#mail"]) + #expect(SensitiveDataDetector.words(in: "__").isEmpty) + } + + // MARK: - Column types + + @Test("Text-like types, including unknown ones", arguments: [ + nil, "", "text", "varchar(255)", "jsonb", "String", "interval_text", "geometry", "inet", + "LowCardinality(Nullable(String))", "_int8" + ] as [String?]) + func textLikeTypes(type: String?) { + #expect(SensitiveDataDetector.isTextLike(type)) + } + + @Test("Number, date, boolean and UUID types are not text-like", arguments: [ + "int", "bigint unsigned", "UInt64", "Nullable(Int32)", "double precision", "timestamp with time zone", "Date32", + "DateTime64(3)", "numeric(10,2)", "uniqueidentifier", "BOOLEAN", "tinyint(1)", "uuid", "money", "year" + ]) + func nonTextTypes(type: String) { + #expect(!SensitiveDataDetector.isTextLike(type)) + } + + // MARK: - Values + + @Test("Values, fixture table: each kind tested alone", arguments: SensitiveDataDetectorTests.valueRows) + func values(value: String, kinds: [SensitiveValueKind]) { + #expect(SensitiveValueKind.allCases.filter { SensitiveDataDetector.matches($0, value) } == kinds) + } + + @Test("Email white space is Unicode White_Space, which ICU's \\s leaves partly out") + func emailWhiteSpace() { + #expect(!SensitiveDataDetector.matches(.email, "ann@example.com\u{0B}")) + #expect(!SensitiveDataDetector.matches(.email, "ann@example.com\u{85}")) + #expect(!SensitiveDataDetector.matches(.email, "ann@example.com\n")) + } + + @Test("An email check over a long domain that never matches stays linear") + func emailStaysLinear() { + let dots = String(repeating: ".", count: 100_000) + let started = ContinuousClock.now + #expect(!SensitiveDataDetector.matches(.email, "a@" + dots + " ")) + #expect(SensitiveDataDetector.matches(.email, "a@b" + dots + "c")) + // Dots are domain characters too, so this one matches the anchored pattern. + #expect(SensitiveDataDetector.matches(.email, "a@" + dots)) + #expect(ContinuousClock.now - started < .seconds(2)) + } + + @Test("IP addresses are what Rust's std::net parser accepts", arguments: [ + ("255.255.255.255", true), ("01.2.3.4", false), ("1.2.3.4.5", false), ("::", true), + ("2001:0DB8:0000:0000:0000:0000:0000:0001", true), ("::1.2.3.4", true), ("1:2:3:4:5:6:1.2.3.4", true), + ("1:2:3:4:5:6:7::", true), ("::1:2:3:4:5:6:7", true), ("1:2:3:4:5:6:7:8:9", false), + ("1:2:3:4:5:6:7:1.2.3.4", false), ("1.2.3.4::", false), ("::ffff:01.2.3.4", false), ("1:2:3:4:5:6:7:8::", false) + ]) + func ipAddressEdges(value: String, matches: Bool) { + #expect(SensitiveDataDetector.matches(.ipAddress, value) == matches) + } + + // MARK: - A column's values + + @Test("Columns, fixture table: thresholds and text-like types", arguments: SensitiveDataDetectorTests.columnRows) + func columns(type: String, values: [PluginCellValue], flagged: SensitiveValueKind?) throws { + let source = ShareResultSource( + columns: ["c"], columnTypes: [.text(rawType: type)], rows: values.map { [$0] }, totalRowCount: values.count, sql: "" + ) + let detections = try #require(SensitiveDataDetector.detections(in: source, windows: [100])) + #expect(detections[0] == flagged.map(SensitiveDetection.values)) + } + + // MARK: - A result + + @Test("A name beats the values, and a column the rules mask gets nothing") + func resultDetections() throws { + let source = ShareResultSource( + columns: ["phone", "notes", "email", "id"], + columnTypes: [.text(rawType: "text"), .text(rawType: "text"), .text(rawType: "text"), .integer(rawType: "int")], + rows: [[.text("ann@example.com"), .text("4111 1111 1111 1111"), .text("x"), .text("1")]], + totalRowCount: 1, + sql: "", + masks: ColumnMasks(styles: [2: .full]) + ) + let detections = try #require(SensitiveDataDetector.detections(in: source, windows: [10])) + #expect(detections == [0: .name(.phone), 1: .values(.card)]) + } + + @Test("Only the rows that will be shared are read") + func detectionsReadOnlyMaxRows() throws { + let source = ShareResultSource( + columns: ["notes"], columnTypes: [.text(rawType: "text")], rows: [[.text("x")], [.text("4111111111111111")]], + totalRowCount: 2, sql: "" + ) + #expect(try #require(SensitiveDataDetector.detections(in: source, windows: [1])).isEmpty) + #expect(try #require(SensitiveDataDetector.detections(in: source, windows: [2])) == [0: .values(.card)]) + } + + @Test("Each window keeps its own threshold; a column either window flags takes the first kind in table order") + func detectionWindows() throws { + let phones: [PluginCellValue] = [.text("+1 555 0100"), .text("+1 555 0101")] + let emails: [PluginCellValue] = (0..<4).map { .text("user\($0)@example.com") } + let source = ShareResultSource( + columns: ["contact"], columnTypes: [.text(rawType: "text")], rows: (phones + emails).map { [$0] }, + totalRowCount: 6, sql: "" + ) + #expect(try #require(SensitiveDataDetector.detections(in: source, windows: [2])) == [0: .values(.phone)]) + #expect(try #require(SensitiveDataDetector.detections(in: source, windows: [6])) == [0: .values(.email)]) + #expect(try #require(SensitiveDataDetector.detections(in: source, windows: [6, 2])) == [0: .values(.email)]) + + let shortRun = ShareResultSource( + columns: ["contact"], columnTypes: [.text(rawType: "text")], + rows: (phones + Array(repeating: PluginCellValue.text("n/a"), count: 4)).map { [$0] }, + totalRowCount: 6, sql: "" + ) + #expect(try #require(SensitiveDataDetector.detections(in: shortRun, windows: [6])).isEmpty) + #expect(try #require(SensitiveDataDetector.detections(in: shortRun, windows: [6, 2, 0])) == [0: .values(.phone)]) + } + + // MARK: - SQL + + @Test("SQL personal data, fixture table", arguments: SensitiveDataDetectorTests.sqlRows) + func sqlPersonalData(sql: String, hits: [String]) { + #expect(SensitiveDataDetector.personalDataHits(inSQL: sql).map { "\($0.kind.code):\($0.line)" } == hits) + } + + @Test("Literals read '' as a quote, skip double-quoted names and comments, and drop one left open") + func quotedLiterals() { + let literals = SensitiveDataDetector.quotedLiterals(in: "SELECT 'it''s', \"a'b\", 'x' FROM t WHERE c = 'open") + #expect(literals.map(\.text) == ["it's", "x"]) + #expect(SensitiveDataDetector.quotedLiterals(in: "''").map(\.text) == [""]) + #expect(SensitiveDataDetector.quotedLiterals(in: "'abc''").isEmpty) + #expect(SensitiveDataDetector.quotedLiterals(in: "SELECT 1\r\n'a'\r'b'\n'c\nd'").map(\.line) == [2, 3, 4]) + #expect(SensitiveDataDetector.quotedLiterals(in: "-- it's\r\n'a' /* 'b' */ \"c'd\" 'e' /* open 'f'").map(\.text) == ["a", "e"]) + #expect(SensitiveDataDetector.quotedLiterals(in: "'--', '/*', 'x'").map(\.text) == ["--", "/*", "x"]) + // core sql.rs, comments_outside_a_literal_are_skipped. + let commented = SensitiveDataDetector.quotedLiterals(in: "-- don't\nSELECT /* it's */ 'a', '-- b /* c */' -- 'd'\r'e'") + #expect(commented.map(\.text) == ["a", "-- b /* c */", "e"]) + #expect(commented.map(\.line) == [2, 2, 3]) + #expect(SensitiveDataDetector.quotedLiterals(in: "/* 'open").isEmpty) + } + + @Test("The kinds for the Hide SQL notice come in table order, each once") + func personalDataKinds() { + let sql = "WHERE e = 'ann@example.com'\nAND p = '+1 555 0100' AND c = '4111111111111111' AND f = 'bob@example.com'" + #expect(SensitiveDataDetector.personalData(inSQL: sql) == [.card, .email, .phone]) + } +} + +private extension SensitiveValueKind { + var code: String { + switch self { + case .card: "card" + case .iban: "iban" + case .jsonWebToken: "jwt" + case .apiKey: "api_key" + case .email: "email" + case .phone: "phone" + case .ipAddress: "ip" + } + } +} diff --git a/apple/TableProTests/Core/Services/Shares/ShareColumnChoiceTests.swift b/apple/TableProTests/Core/Services/Shares/ShareColumnChoiceTests.swift new file mode 100644 index 0000000000..444d69f479 --- /dev/null +++ b/apple/TableProTests/Core/Services/Shares/ShareColumnChoiceTests.swift @@ -0,0 +1,172 @@ +// +// ShareColumnChoiceTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +struct ShareColumnChoiceTests { + @Test("A rule-masked column starts masked with the rule's style, refuses Keep and offers only stricter styles") + func ruleMaskedColumn() throws { + let choice = ShareColumnChoice(index: 0, name: "phone", ruleStyle: .lastFour, detection: nil) + #expect(choice.action == .mask) + #expect(choice.style == .lastFour) + #expect(!choice.allowsKeep) + #expect(choice.allowedStyles == [.full, .lastFour, .null]) + #expect(choice.choosing(.keep) == nil) + #expect(choice.choosing(style: .email) == nil) + #expect(try #require(choice.choosing(.remove)).sharedColumn == nil) + #expect(ShareColumnChoice(index: 0, name: "x", ruleStyle: .null, detection: nil).allowedStyles == [.null]) + #expect(ShareColumnChoice(index: 0, name: "x", ruleStyle: .full, detection: nil).allowedStyles == [.full, .null]) + } + + @Test("A rule's own style is already on the values, so only a stricter one is applied again") + func ruleStyleIsNotAppliedTwice() throws { + let choice = ShareColumnChoice(index: 3, name: "ip", ruleStyle: .hash, detection: nil) + #expect(choice.sharedColumn == ShareSnapshotBuilder.SharedColumn(source: 3, applying: nil, masked: .hash)) + let stricter = try #require(choice.choosing(style: .full)) + #expect(stricter.sharedColumn == ShareSnapshotBuilder.SharedColumn(source: 3, applying: .full, masked: .full)) + } + + @Test("A detected column starts masked with the suggested style and may be kept") + func detectedColumn() throws { + let choice = ShareColumnChoice(index: 1, name: "contact", ruleStyle: nil, detection: .values(.email)) + #expect(choice.action == .mask) + #expect(choice.style == .email) + #expect(choice.allowedStyles == MaskingStyle.allCases) + #expect(choice.sharedColumn == ShareSnapshotBuilder.SharedColumn(source: 1, applying: .email, masked: .email)) + let kept = try #require(choice.choosing(.keep)) + #expect(kept.sharedColumn == ShareSnapshotBuilder.SharedColumn(source: 1, applying: nil, masked: nil)) + #expect(kept.maskedStyle == nil) + } + + @Test("Any other column starts kept") + func plainColumn() { + let choice = ShareColumnChoice(index: 0, name: "id", ruleStyle: nil, detection: nil) + #expect(choice.action == .keep) + #expect(choice.allowsKeep) + } + + @Test("A column masked only because nothing traced it says so and cannot be kept") + func untracedColumn() throws { + let source = ShareResultSource( + columns: ["id", "total"], + columnTypes: [.integer(rawType: "int8"), .text(rawType: nil)], + rows: [[.text("1"), .text("••••")]], + totalRowCount: 1, + sql: "", + masks: ColumnMasks(styles: [1: .full]), + untracedColumns: [1] + ) + let choices = try #require(ShareColumnChoice.defaults(for: source, windows: [10])) + #expect(choices.map(\.isUntraced) == [false, true]) + #expect(!choices[1].allowsKeep) + #expect(choices[1].allowedStyles == [.full, .null]) + } + + @Test("Choices carry over by name, held to what each column now allows") + func carryOver() throws { + let earlier = [ + try #require(ShareColumnChoice(index: 0, name: "id", ruleStyle: nil, detection: nil).choosing(.remove)), + try #require(ShareColumnChoice(index: 1, name: "phone", ruleStyle: nil, detection: nil).choosing(style: .email)?.choosing(.mask)), + ShareColumnChoice(index: 2, name: "gone", ruleStyle: nil, detection: nil) + ] + let defaults = [ + ShareColumnChoice(index: 0, name: "phone", ruleStyle: .lastFour, detection: nil), + ShareColumnChoice(index: 1, name: "id", ruleStyle: nil, detection: nil), + ShareColumnChoice(index: 2, name: "new", ruleStyle: nil, detection: .values(.email)) + ] + let carried = ShareColumnChoice.carryingOver(earlier, onto: defaults) + #expect(carried.map(\.action) == [.mask, .remove, .mask]) + #expect(carried.map(\.style) == [.lastFour, .full, .email]) + #expect(carried.map(\.index) == [0, 1, 2]) + } + + private static func bodyAndNotes(_ rows: [[PluginCellValue]]) -> ShareResultSource { + ShareResultSource( + columns: ["body", "notes"], + columnTypes: [.text(rawType: "text"), .text(rawType: "text")], + rows: rows, + totalRowCount: rows.count, + sql: "" + ) + } + + private static func snapshotRows(_ outcome: ShareSnapshotOutcome?) -> [[ShareCell]]? { + guard case .snapshot(let snapshot) = outcome else { return nil } + return snapshot.rows + } + + @Test("A card past the rows the body budget sends still flags the column, and the snapshot may go to max_rows") + func detectionReadsPastTheBudget() throws { + let wide = String(repeating: "y", count: 200_000) + var rows: [[PluginCellValue]] = Array(repeating: [.text(wide), .text("x")], count: 40) + rows[39][1] = .text("4111111111111111") + let prepared = try #require(ShareColumnChoice.prepare(Self.bodyAndNotes(rows), maxRows: 1_000, keeping: [])) + let sent = try #require(Self.snapshotRows(prepared.snapshot)) + + #expect(sent.count < 40) + #expect(prepared.rowCap == 1_000) + #expect(prepared.columns.map(\.action) == [.keep, .mask]) + #expect(prepared.columns[1].detection == .values(.card)) + } + + @Test("A 300 KiB cell in the first row refuses the whole snapshot, and the notes' emails are still flagged") + func refusedSnapshotStillDetects() throws { + var rows: [[PluginCellValue]] = (0..<10).map { [.text("short"), .text("user\($0)@example.com")] } + rows[0][0] = .text(String(repeating: "y", count: 300 * 1_024)) + let source = Self.bodyAndNotes(rows) + #expect(ShareSnapshotBuilder.build(source, maxRows: 1_000) == .tooLarge) + + let prepared = try #require(ShareColumnChoice.prepare(source, maxRows: 1_000, keeping: [])) + #expect(prepared.columns.map(\.action) == [.keep, .mask]) + #expect(prepared.columns[1].detection == .values(.email)) + + let notesOnly = try #require(prepared.columns[0].choosing(.remove)) + let shared = [notesOnly, prepared.columns[1]].compactMap(\.sharedColumn) + let sent = try #require(Self.snapshotRows(ShareSnapshotBuilder.build(source, maxRows: prepared.rowCap, columns: shared))) + #expect(sent.count == 10) + #expect(sent.last == [.string("u•••@example.com")]) + } + + @Test("Emails only in the rows that fit once a wide column is removed are flagged, and those rows go masked") + func emailsPastTheBudgetAreFlagged() throws { + let wide = String(repeating: "y", count: 250_000) + let rows: [[PluginCellValue]] = (0..<40).map { index in + [.text(wide), .text(index < 20 ? "no address here" : "user\(index)@example.com")] + } + let source = Self.bodyAndNotes(rows) + let keptWhole = try #require(Self.snapshotRows(ShareSnapshotBuilder.build(source, maxRows: 1_000))) + #expect(keptWhole.count <= 20) + + let prepared = try #require(ShareColumnChoice.prepare(source, maxRows: 1_000, keeping: [])) + #expect(prepared.columns.map(\.action) == [.keep, .mask]) + #expect(prepared.columns[1].detection == .values(.email)) + + let notesOnly = try #require(prepared.columns[0].choosing(.remove)) + let shared = [notesOnly, prepared.columns[1]].compactMap(\.sharedColumn) + let sent = try #require(Self.snapshotRows(ShareSnapshotBuilder.build(source, maxRows: prepared.rowCap, columns: shared))) + #expect(sent.count == 40) + #expect(sent.last == [.string("u•••@example.com")]) + } + + @Test("Defaults come from the source's rule masks and the detectors") + func defaults() throws { + let source = ShareResultSource( + columns: ["id", "email", "password"], + columnTypes: [.integer(rawType: "int8"), .text(rawType: "text"), .text(rawType: "text")], + rows: [[.text("1"), .text("j•••@x.io"), .text("hunter2")]], + totalRowCount: 1, + sql: "", + masks: ColumnMasks(styles: [1: .email]) + ) + let choices = try #require(ShareColumnChoice.defaults(for: source, windows: [10])) + #expect(choices.map(\.action) == [.keep, .mask, .mask]) + #expect(choices.map(\.style) == [.full, .email, .full]) + #expect(choices.map(\.ruleStyle) == [nil, .email, nil]) + #expect(choices.map(\.detection) == [nil, nil, .name(.secret)]) + } +} diff --git a/apple/TableProTests/Core/Services/Shares/ShareSnapshotBuilderTests.swift b/apple/TableProTests/Core/Services/Shares/ShareSnapshotBuilderTests.swift new file mode 100644 index 0000000000..f60c73dee5 --- /dev/null +++ b/apple/TableProTests/Core/Services/Shares/ShareSnapshotBuilderTests.swift @@ -0,0 +1,268 @@ +// +// ShareSnapshotBuilderTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +struct ShareSnapshotBuilderTests { + private func cell(_ value: PluginCellValue, _ type: ColumnType) -> ShareCell { + ShareCellEncoder.encode(value, type: type) + } + + private func source( + columns: [String] = ["n"], + types: [ColumnType] = [.integer(rawType: "int")], + rows: [[PluginCellValue]], + total: Int?? = .none + ) -> ShareResultSource { + ShareResultSource( + columns: columns, + columnTypes: types, + rows: rows, + totalRowCount: total ?? rows.count, + sql: "SELECT n FROM t" + ) + } + + private func snapshot(_ outcome: ShareSnapshotOutcome?) throws -> ShareSnapshot { + try #require(outcome?.built) + } + + @Test("Integers go as number tokens with every digit, at any width") + func integersKeepEveryDigit() { + #expect(cell(.text("42"), .integer(rawType: "int")) == .number("42")) + #expect(cell(.text("42.0"), .integer(rawType: "int")) == .number("42")) + #expect(cell(.text("18446744073709551615"), .integer(rawType: "bigint unsigned")) == .number("18446744073709551615")) + #expect(cell(.text("-9007199254740993"), .integer(rawType: "bigint")) == .number("-9007199254740993")) + } + + @Test("Decimals go as number tokens exactly as the database wrote them", arguments: [ + ("3.10", "3.10"), ("12345678901234567890.12345678901234567890", "12345678901234567890.12345678901234567890"), + ("+5", "5"), (".5", "0.5"), ("1e+20", "1e20") + ]) + func decimalsKeepEveryDigit(text: String, token: String) { + #expect(cell(.text(text), .decimal(rawType: "numeric")) == .number(token)) + } + + @Test("A number JSON cannot hold goes as its name", arguments: ["NaN", "Infinity", "-Infinity"]) + func nonFiniteNumbersAreNames(text: String) { + #expect(cell(.text(text), .decimal(rawType: "float8")) == .string(text)) + } + + @Test("A JSON column goes as its document, key order and digits as written") + func jsonIsADocument() { + #expect(cell(.text(" {\"b\": 1, \"a\": [1, 12345678901234567890]} "), .json(rawType: "jsonb")) + == .document("{\"b\": 1, \"a\": [1, 12345678901234567890]}")) + #expect(cell(.text("not json"), .json(rawType: "json")) == .string("not json")) + } + + @Test("A PostgreSQL array goes as an array, each element by the element type") + func postgresArraysRecurse() { + let ints = ColumnType.array(rawType: "_int8", element: .integer(rawType: "int8")) + #expect(cell(.text("{1,NULL,18446744073709551615}"), ints) == .array([.number("1"), .null, .number("18446744073709551615")])) + let texts = ColumnType.array(rawType: "_text", element: .text(rawType: "text")) + #expect(cell(.text("{\"a b\",c}"), texts) == .array([.string("a b"), .string("c")])) + } + + @Test("An array a driver writes as JSON goes as that document") + func jsonArraysAreDocuments() { + let type = ColumnType.array(rawType: "Array(Int64)", element: .integer(rawType: "Int64")) + #expect(cell(.text("[1, 2, 3]"), type) == .document("[1, 2, 3]")) + } + + @Test("Timestamps are written in ISO 8601 with the offset as +HH:MM", arguments: [ + ("2026-11-13 10:00:00", "2026-11-13T10:00:00"), + ("2026-11-13 10:00:00.123456", "2026-11-13T10:00:00.123456"), + ("2026-11-13 10:00:00+07", "2026-11-13T10:00:00+07:00"), + ("2026-11-13 10:00:00.5 +0530", "2026-11-13T10:00:00.5+05:30"), + ("2026-11-13T10:00:00Z", "2026-11-13T10:00:00+00:00"), + ("not a time", "not a time") + ]) + func timestampsAreISO(text: String, iso: String) { + #expect(cell(.text(text), .timestamp(rawType: "timestamptz")) == .string(iso)) + } + + @Test("Booleans normalize and a TINYINT(1) value outside 0 and 1 stays a number") + func booleans() { + #expect(cell(.text("1"), .boolean(rawType: "tinyint(1)")) == .bool(true)) + #expect(cell(.text("t"), .boolean(rawType: "bool")) == .bool(true)) + #expect(cell(.text("false"), .boolean(rawType: "bool")) == .bool(false)) + #expect(cell(.text("2"), .boolean(rawType: "tinyint(1)")) == .number("2")) + } + + @Test("Null stays null, bytes say how many, dates and text stay text") + func otherCells() { + #expect(cell(.null, .text(rawType: nil)) == .null) + #expect(cell(.bytes(Data(count: 1_024)), .blob(rawType: "blob")) == .string("(binary, 1024 bytes)")) + #expect(cell(.text("hello"), .text(rawType: "text")) == .string("hello")) + #expect(cell(.text("2026-11-13"), .date(rawType: "date")) == .string("2026-11-13")) + } + + @Test("Rows past max_rows are cut and the true total is kept") + func rowsAreCappedToTheLimit() throws { + let rows = (0..<1_500).map { [PluginCellValue.text(String($0))] } + let built = try snapshot(ShareSnapshotBuilder.build(source(rows: rows, total: 48_210), maxRows: 1_000)) + + #expect(built.rows.count == 1_000) + #expect(built.rowCount == 48_210) + #expect(built.isTruncated) + #expect(built.rows.last == [.number("999")]) + } + + @Test("A total nobody counted stays unknown, and the snapshot says it is cut") + func unknownTotal() throws { + let built = try snapshot(ShareSnapshotBuilder.build(source(rows: [[.text("1")]], total: .some(nil)), maxRows: 10)) + #expect(built.rowCount == nil) + #expect(built.isTruncated) + } + + @Test("A result inside the limit is not truncated") + func smallResultIsWhole() throws { + let built = try snapshot(ShareSnapshotBuilder.build(source(rows: [[.text("1")], [.text("2")]]), maxRows: 1_000)) + + #expect(built.rows.count == 2) + #expect(built.rowCount == 2) + #expect(!built.isTruncated) + } + + @Test("Columns carry their raw type, or the type's name when the driver gave none") + func columnTypes() throws { + let built = try snapshot(ShareSnapshotBuilder.build(source( + columns: ["id", "price"], + types: [.integer(rawType: "bigint"), .decimal(rawType: nil)], + rows: [[.text("1"), .text("2.5")]] + ), maxRows: 10)) + + #expect(built.columns == [ + ShareSnapshot.Column(name: "id", type: "bigint"), + ShareSnapshot.Column(name: "price", type: "decimal") + ]) + } + + @Test("More columns than the server takes sends the first ones, never refuses") + func tooManyColumns() throws { + let count = ShareSnapshotBuilder.maxColumns + 1 + let built = try snapshot(ShareSnapshotBuilder.build(source( + columns: (0..= 20) + #expect(built.rowCount == 40) + #expect(built.isTruncated) + } + + @Test("A build whose task was cancelled gives nothing") + func cancelledBuild() async { + let rows = (0..<10_000).map { [PluginCellValue.text(String($0))] } + let task = Task.detached { () -> ShareSnapshotOutcome? in + withUnsafeCurrentTask { $0?.cancel() } + return ShareSnapshotBuilder.build(ShareResultSource( + columns: ["n"], columnTypes: [.integer(rawType: "int")], rows: rows, totalRowCount: 10_000, sql: "" + ), maxRows: 10_000) + } + #expect(await task.value == nil) + } + + @Test("Rule-masked columns are marked, and their values go as text even in a number column") + func ruleMasksAreMarked() throws { + let built = try snapshot(ShareSnapshotBuilder.build(ShareResultSource( + columns: ["id", "email"], + columnTypes: [.integer(rawType: "int8"), .text(rawType: "text")], + rows: [[.text("123456789012"), .text("j•••@example.com")]], + totalRowCount: 1, + sql: "", + masks: ColumnMasks(styles: [0: .hash, 1: .email]) + ), maxRows: 10)) + + #expect(built.columns.map(\.masked) == [.hash, .email]) + #expect(built.columns.map(\.type) == ["int8", "text"]) + #expect(built.rows == [[.string("123456789012"), .string("j•••@example.com")]]) + } + + @Test("Chosen columns are read in order, masked here when asked, and the rest are left out") + func sharedColumnsApplyStyles() throws { + let source = ShareResultSource( + columns: ["id", "phone", "secret", "note"], + columnTypes: [.integer(rawType: "int8"), .text(rawType: "text"), .text(rawType: "text"), .text(rawType: "text")], + rows: [[.text("7"), .text("+1 555 123 4567"), .text("••••"), .null]], + totalRowCount: 1, + sql: "", + masks: ColumnMasks(styles: [2: .full]) + ) + let shared: [ShareSnapshotBuilder.SharedColumn] = [ + .init(source: 0, applying: nil, masked: nil), + .init(source: 1, applying: .lastFour, masked: .lastFour), + .init(source: 2, applying: .null, masked: .null), + .init(source: 3, applying: .full, masked: .full) + ] + let built = try snapshot(ShareSnapshotBuilder.build(source, maxRows: 10, columns: shared)) + + #expect(built.columns.map(\.name) == ["id", "phone", "secret", "note"]) + #expect(built.columns.map(\.masked) == [nil, .lastFour, .null, .full]) + #expect(built.rows == [[.number("7"), .string("••••4567"), .null, .null]]) + + let fewer = try snapshot(ShareSnapshotBuilder.build(source, maxRows: 10, columns: [shared[1]])) + #expect(fewer.columns.map(\.name) == ["phone"]) + #expect(fewer.rows == [[.string("••••4567")]]) + } + + @Test("A share with every column removed has nothing to send, and the cap counts only the kept columns") + func removedColumns() throws { + let count = ShareSnapshotBuilder.maxColumns + 1 + let source = ShareResultSource( + columns: (0.. Void)? + } + + private func makeOpener(_ service: FakeShareService, _ recorder: Recorder) -> SharedLinkOpener { + SharedLinkOpener( + service: { service }, + presentation: SharedLinkOpener.Presentation( + askPassword: { prompt in + recorder.prompts.append(prompt) + return recorder.answers.isEmpty ? nil : recorder.answers.removeFirst() + }, + openQuery: { recorder.opened.append($0); recorder.events.append("open") }, + tell: { recorder.messages.append($0); recorder.events.append("tell") }, + showProgress: { cancel in recorder.cancel = cancel; recorder.events.append("progress") }, + hideProgress: { recorder.events.append("hide") }, + fallBack: { recorder.events.append("welcome") } + ) + ) + } + + @Test("A shared query opens its SQL in a new tab named after the share, after the progress closes") + func opensSQL() async { + let service = FakeShareService() + service.fetchResults = [.success(SharedQuery(kind: .query, title: "Top users", sql: "SELECT 1"))] + let recorder = Recorder() + await makeOpener(service, recorder).open(token: Self.token) + + #expect(recorder.opened == [SharedQueryOpen(sql: "SELECT 1", title: "Top users")]) + #expect(recorder.events == ["progress", "hide", "open"]) + #expect(service.fetchedPasswords == [nil]) + } + + @Test("An untitled share opens under the editor's own tab name") + func untitledShare() async { + let service = FakeShareService() + service.fetchResults = [.success(SharedQuery(kind: .query, title: " ", sql: "SELECT 1"))] + let recorder = Recorder() + await makeOpener(service, recorder).open(token: Self.token) + #expect(recorder.opened == [SharedQueryOpen(sql: "SELECT 1", title: nil)]) + } + + @Test("A password-protected share asks for the password and retries a wrong one") + func passwordFlow() async { + let service = FakeShareService() + service.fetchResults = [ + .failure(.passwordRequired), + .failure(.passwordWrong), + .success(SharedQuery(kind: .result, title: "Report", sql: "SELECT 2")) + ] + let recorder = Recorder() + recorder.answers = ["wrong", "right"] + await makeOpener(service, recorder).open(token: Self.token) + + #expect(recorder.prompts == [.required, .wrong]) + #expect(service.fetchedPasswords == [nil, "wrong", "right"]) + #expect(recorder.opened.map(\.sql) == ["SELECT 2"]) + } + + @Test("Cancelling the password prompt opens nothing, says nothing and falls back to Welcome") + func cancelledPassword() async { + let service = FakeShareService() + service.fetchResults = [.failure(.passwordRequired)] + let recorder = Recorder() + await makeOpener(service, recorder).open(token: Self.token) + + #expect(recorder.opened.isEmpty) + #expect(recorder.messages.isEmpty) + #expect(recorder.events == ["progress", "hide", "welcome"]) + } + + @Test("A result share with hidden or no SQL has nothing to open", arguments: [nil, "", " \n"] as [String?]) + func hiddenSQL(sql: String?) async { + let service = FakeShareService() + service.fetchResults = [.success(SharedQuery(kind: .result, title: "Report", sql: sql))] + let recorder = Recorder() + await makeOpener(service, recorder).open(token: Self.token) + + #expect(recorder.opened.isEmpty) + #expect(recorder.messages == [String(localized: "This shared result hides its SQL, so there is nothing to open.")]) + } + + @Test("A link that no longer resolves says so, then falls back to Welcome") + func gone() async { + let service = FakeShareService() + service.fetchResults = [.failure(.notFound)] + let recorder = Recorder() + await makeOpener(service, recorder).open(token: Self.token) + #expect(recorder.messages == [String(localized: "This shared link is no longer available.")]) + #expect(recorder.events == ["progress", "hide", "tell", "welcome"]) + } + + @Test("Cancel in the progress window stops the read and falls back to Welcome without a message") + func cancelProgress() async throws { + let service = FakeShareService() + let gate = AsyncGate() + service.fetchGate = gate + service.fetchResults = [.success(SharedQuery(kind: .query, title: "T", sql: "SELECT 1"))] + let recorder = Recorder() + let opener = makeOpener(service, recorder) + + let opening = Task { await opener.open(token: Self.token) } + await gate.arrived(1) + let cancel = try #require(recorder.cancel) + cancel() + await gate.open() + await opening.value + + #expect(recorder.opened.isEmpty) + #expect(recorder.messages.isEmpty) + #expect(recorder.events.last == "welcome") + } + + @Test("A malformed token never reaches the server") + func malformedToken() async { + let service = FakeShareService() + let recorder = Recorder() + await makeOpener(service, recorder).open(token: "nope") + #expect(service.fetchedPasswords.isEmpty) + #expect(recorder.events.isEmpty) + } +} diff --git a/apple/TableProTests/Core/Services/SupportLinksTests.swift b/apple/TableProTests/Core/Services/SupportLinksTests.swift index 2106cadd92..82fb98e2e8 100644 --- a/apple/TableProTests/Core/Services/SupportLinksTests.swift +++ b/apple/TableProTests/Core/Services/SupportLinksTests.swift @@ -12,7 +12,7 @@ import Testing struct SupportLinksTests { private static let everyReferrer: [SupportReferrer] = - [.supportWindow, .aboutPanel, .licenseSettings, .ask, .blackFriday, .welcome] + [.supportWindow, .aboutPanel, .licenseSettings, .ask, .blackFriday, .welcome, .shareSheet] + ProFeature.allCases.map { .featureGate($0) } private static func components(_ url: URL) -> URLComponents? { diff --git a/apple/TableProTests/Core/Services/TableQueryBuilderFilterTests.swift b/apple/TableProTests/Core/Services/TableQueryBuilderFilterTests.swift index dd0082f2bc..7b58f4604b 100644 --- a/apple/TableProTests/Core/Services/TableQueryBuilderFilterTests.swift +++ b/apple/TableProTests/Core/Services/TableQueryBuilderFilterTests.swift @@ -10,6 +10,60 @@ import Foundation import TableProPluginKit import Testing +struct TableQueryBuilderViewQueryTests { + private static func dialect(_ style: SQLDialectDescriptor.PaginationStyle) -> SQLDialectDescriptor { + SQLDialectDescriptor( + identifierQuote: "`", keywords: [], functions: [], dataTypes: [], + regexSyntax: .regexp, booleanLiteralStyle: .numeric, + likeEscapeStyle: .implicit, paginationStyle: style + ) + } + + private static func builder(_ style: SQLDialectDescriptor.PaginationStyle) -> TableQueryBuilder { + TableQueryBuilder(databaseType: .mysql, dialect: dialect(style), pagination: .offset, dialectQuote: SQLEscaping.quoteIdentifier) + } + + private static let sort = SortState(columns: [SortColumn(columnIndex: 1, direction: .descending, columnName: "name")]) + + @Test("A view query without its window keeps the filter and the sort and drops LIMIT and OFFSET") + func viewQueryHasNoWindow() throws { + var filter = TableFilter() + filter.columnName = "name" + filter.filterOperator = .equal + filter.value = "Alice" + filter.isEnabled = true + + let query = try #require(Self.builder(.limit).buildFilteredQuery( + tableName: "users", filters: [filter], sortState: Self.sort, columns: ["id", "name"], + limit: 1_000, offset: 3_000, window: false + )) + #expect(query.contains("WHERE")) + #expect(query.contains("ORDER BY")) + #expect(!query.contains("LIMIT")) + #expect(!query.contains("OFFSET")) + } + + @Test("A base view query without its window has no pagination, and no default ORDER BY on OFFSET FETCH engines") + func baseViewQueryHasNoWindow() { + let plain = Self.builder(.offsetFetch).buildBaseQuery(tableName: "users", limit: 1_000, offset: 2_000, window: false) + #expect(!plain.contains("OFFSET")) + #expect(!plain.contains("FETCH")) + #expect(!plain.contains("ORDER BY")) + + let sorted = Self.builder(.limit).buildBaseQuery( + tableName: "users", sortState: Self.sort, columns: ["id", "name"], window: false + ) + #expect(sorted.hasSuffix("DESC")) + #expect(!sorted.contains("LIMIT")) + } + + @Test("The windowed query still carries its page") + func windowedQueryKeepsItsPage() { + let query = Self.builder(.limit).buildBaseQuery(tableName: "users", limit: 100, offset: 200) + #expect(query.hasSuffix("LIMIT 100 OFFSET 200")) + } +} + struct TableQueryBuilderFilteredQueryTests { /// The dialect is what carries the quoting and the operators, so a builder without one emits no /// query at all: that is what `TableQueryBuilderDialectlessTests` asserts. These cases are diff --git a/apple/TableProTests/Helpers/FakeShareService.swift b/apple/TableProTests/Helpers/FakeShareService.swift new file mode 100644 index 0000000000..677df531bc --- /dev/null +++ b/apple/TableProTests/Helpers/FakeShareService.swift @@ -0,0 +1,127 @@ +// +// FakeShareService.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProTestSupport + +@MainActor +final class FakeShareService: ShareService { + var limitsResults: [Result] + var createResult: Result = .success( + CreatedShare(id: "shr_1", url: URL(string: "https://s.tablepro.app/abc")!) + ) + var linksResult: Result<[ShareLink], ShareFailure> = .success([]) + var revokeFailure: ShareFailure? + var fetchResults: [Result] = [] + var createGate: AsyncGate? + var fetchGate: AsyncGate? + + private(set) var limitsCalls = 0 + private(set) var drafts: [ShareDraft] = [] + private(set) var revokedIDs: [String] = [] + private(set) var fetchedPasswords: [String?] = [] + private(set) var linkTeams: [String?] = [] + + init(limits: ShareLimits = .free()) { + limitsResults = [.success(limits)] + } + + // The protocol is nonisolated, so each call hops to the main actor to read and record. + nonisolated func limits() async throws(ShareFailure) -> ShareLimits { + try await nextLimits().get() + } + + nonisolated func create(_ draft: ShareDraft) async throws(ShareFailure) -> CreatedShare { + let gate = await record(draft) + await gate?.wait() + return try await createResultNow().get() + } + + nonisolated func liveLinks(teamID: String?) async throws(ShareFailure) -> [ShareLink] { + try await linksResult(for: teamID).get() + } + + nonisolated func revoke(id: String) async throws(ShareFailure) { + if let failure = await recordRevoke(id) { throw failure } + } + + nonisolated func fetchShared(token: String, password: String?) async throws(ShareFailure) -> SharedQuery { + let gate = await recordFetch(password) + await gate?.wait() + // A cancelled URL load answers as cancelled, whatever the server would have said. + if Task.isCancelled { throw .canceled } + return try await nextFetch().get() + } + + private func nextLimits() -> Result { + limitsCalls += 1 + return limitsResults.count > 1 ? limitsResults.removeFirst() : limitsResults[0] + } + + private func record(_ draft: ShareDraft) -> AsyncGate? { + drafts.append(draft) + return createGate + } + + private func createResultNow() -> Result { + createResult + } + + private func linksResult(for teamID: String?) -> Result<[ShareLink], ShareFailure> { + linkTeams.append(teamID) + return linksResult + } + + private func recordRevoke(_ id: String) -> ShareFailure? { + revokedIDs.append(id) + return revokeFailure + } + + private func recordFetch(_ password: String?) -> AsyncGate? { + fetchedPasswords.append(password) + return fetchGate + } + + private func nextFetch() -> Result { + guard !fetchResults.isEmpty else { return .failure(.notFound) } + return fetchResults.removeFirst() + } +} + +extension ShareLimits { + static func free(live: Int = 3, emailVerified: Bool = true, sharingDisabled: Bool = false) -> ShareLimits { + ShareLimits( + plan: .free, + live: live, + liveLimit: 5, + maxRows: 1_000, + expiries: [.oneDay, .sevenDays, .thirtyDays], + defaultExpiry: .thirtyDays, + allowsPassword: false, + allowsDisablingDownload: false, + allowsTeamLinks: false, + emailVerified: emailVerified, + sharingDisabled: sharingDisabled + ) + } + + static func pro(live: Int = 12, teams: [ShareTeam] = []) -> ShareLimits { + ShareLimits( + plan: .pro, + live: live, + liveLimit: 1_000, + maxRows: 10_000, + expiries: [.oneDay, .sevenDays, .thirtyDays, .never], + defaultExpiry: .never, + allowsPassword: true, + allowsDisablingDownload: true, + allowsTeamLinks: true, + emailVerified: true, + sharingDisabled: false, + teams: teams + ) + } +} diff --git a/apple/TableProTests/Views/Editor/AIEditorContextMenuTests.swift b/apple/TableProTests/Views/Editor/AIEditorContextMenuTests.swift index 0b00c0b2c7..2a69645af1 100644 --- a/apple/TableProTests/Views/Editor/AIEditorContextMenuTests.swift +++ b/apple/TableProTests/Views/Editor/AIEditorContextMenuTests.swift @@ -72,7 +72,8 @@ struct AIEditorContextMenuTests { contextClickWord: nil ), onFormat: @escaping (NSRange) -> Void = { _ in }, - onFavorite: @escaping (String) -> Void = { _ in } + onFavorite: @escaping (String) -> Void = { _ in }, + onShare: @escaping (String) -> Void = { _ in } ) -> AIEditorContextMenu { let menu = AIEditorContextMenu(title: "") menu.fullText = { text } @@ -81,6 +82,7 @@ struct AIEditorContextMenuTests { menu.onAIAction = { _ in } menu.onFormatSQL = onFormat menu.onSaveAsFavorite = onFavorite + menu.onShareQuery = onShare menu.foldStateAtCursor = { foldState } menu.onToggleFold = {} menu.menuNeedsUpdate(menu) @@ -99,10 +101,13 @@ struct AIEditorContextMenuTests { return !zip(separators, separators.dropFirst()).contains { $0 && $1 } } - @Test("With every item available the groups are Edit, Select All, Format and Fold, Favorite, and AI") + @Test("With every item available the groups are Edit, Select All, Format and Fold, Favorite and Share, and AI") func fullMenuLayout() { let titles = editorMenu(ai: available()).items.map { $0.isSeparatorItem ? "-" : $0.title } - let expected = ["Cut", "Copy", "Paste", "-", "Select All", "-", "Format SQL", "Fold", "-", "Save as Favorite…", "-"] + let expected = [ + "Cut", "Copy", "Paste", "-", "Select All", "-", "Format SQL", "Fold", "-", + "Save as Favorite…", "Share Query…", "-" + ] #expect(titles == expected + aiTitles) } @@ -112,6 +117,7 @@ struct AIEditorContextMenuTests { let titles = menu.items.map { $0.title } #expect(!titles.contains("Format SQL")) #expect(!titles.contains("Save as Favorite…")) + #expect(!titles.contains("Share Query…")) #expect(menu.items.allSatisfy { $0.action != nil || $0.isSeparatorItem }) } @@ -196,4 +202,31 @@ struct AIEditorContextMenuTests { #expect(saved == ["SELECT id"]) } + + @Test("Share Query after a right-click on a word shares the whole query, not the word") + func shareIgnoresTheClickedWord() throws { + let word = NSRange(location: 10, length: 4) + var shared: [String] = [] + let menu = editorMenu( + selection: EditorContextSelection(selectedRange: word, contextClickWord: word), + onShare: { shared.append($0) } + ) + + try perform("Share Query…", in: menu) + + #expect(shared == ["SELECT id FROM users"]) + } + + @Test("Share Query shares a selection the user made") + func shareKeepsAUserSelection() throws { + var shared: [String] = [] + let menu = editorMenu( + selection: EditorContextSelection(selectedRange: NSRange(location: 0, length: 9), contextClickWord: nil), + onShare: { shared.append($0) } + ) + + try perform("Share Query…", in: menu) + + #expect(shared == ["SELECT id"]) + } } diff --git a/apple/TableProTests/Views/Main/ShareResultRequestTests.swift b/apple/TableProTests/Views/Main/ShareResultRequestTests.swift new file mode 100644 index 0000000000..c59107f98b --- /dev/null +++ b/apple/TableProTests/Views/Main/ShareResultRequestTests.swift @@ -0,0 +1,481 @@ +// +// ShareResultRequestTests.swift +// TableProTests +// + +import Combine +import Foundation +@testable import TablePro +import TableProPluginKit +import TableProTestSupport +import Testing + +extension GlobalStateSuites { + @MainActor + struct ShareResultRequestTests { + private let fixture: CoordinatorFixture = { + var connection = TestFixtures.makeConnection(database: "shop") + connection.maskingRules = [MaskingRule(pattern: "*.email", style: .email)] + return CoordinatorFixture(connection: connection) + }() + + private static let emails = ["jane@example.com", "john@example.com", "ann@example.com"] + + private static let tracedOrigins = ["id", "email", "note"].map { PluginColumnOrigin(schema: "shop", table: "users", column: $0) } + + private func load( + _ tab: QueryTab, + origins: [PluginColumnOrigin?]? = tracedOrigins, + isTruncated: Bool = false, + into fixture: CoordinatorFixture? = nil + ) throws -> QueryTab { + let fixture = fixture ?? self.fixture + let added = fixture.tabManager.tabs.contains { $0.id == tab.id } ? tab : fixture.addTab(tab) + fixture.coordinator.applyPhase1Result( + tabId: added.id, + columns: ["id", "email", "note"], + columnTypes: [.integer(rawType: "int"), .text(rawType: "varchar"), .text(rawType: "varchar")], + rows: Self.emails.enumerated().map { index, email in + [.text(String(index + 1)), .text(email), .text("note \(index)")] + }, + executionTime: 0, + rowsAffected: 0, + statusMessage: nil, + tableName: tab.tabType == .table ? tab.tableContext.tableName : nil, + isEditable: false, + metadata: nil, + hasSchema: false, + read: TableFreshness.Read(startedAt: .now, includesDefinition: false), + sql: tab.content.query, + connection: fixture.connection, + isTruncated: isTruncated, + columnOrigins: origins + ) + return try #require(fixture.tabManager.tabs.first { $0.id == added.id }) + } + + // MARK: - Reading past the rows held + + private static func answer(origins: [PluginColumnOrigin?]?) -> @Sendable (String) -> PluginQueryResult { + { _ in + var result = PluginQueryResult( + columns: ["id", "email", "note"], + columnTypeNames: ["int8", "text", "text"], + rows: (1...5).map { [.text(String($0)), .text("user\($0)@example.com"), .text("note \($0)")] }, + rowsAffected: 0, + executionTime: 0 + ) + result.columnOrigins = origins + return result + } + } + + // A coordinator whose connection has a live session answering every statement from `driver`. + private static func drivenFixture(_ driver: AnsweringPluginDriver) -> CoordinatorFixture { + var connection = TestFixtures.makeConnection(database: "shop", type: .postgresql) + connection.maskingRules = [MaskingRule(pattern: "*.email", style: .email)] + _ = AnsweringPluginDriver.install(driver, connection: connection) + let fixture = CoordinatorFixture(connection: connection) + fixture.coordinator.executionGate = AlwaysAllowGate() + return fixture + } + + private static func source(of fixture: CoordinatorFixture, maxRows: Int = 1_000) async throws -> ShareResultSource? { + let request = try #require(fixture.coordinator.activeResultShareRequest()) + let load = try #require(request.loadResult) + return await load(maxRows) + } + + @Test("A cut read is read again up to max_rows in its own statement, masked by the rules") + func cutReadIsReadAgainMasked() async throws { + let driver = AnsweringPluginDriver(answer: Self.answer(origins: Self.tracedOrigins)) + let fixture = Self.drivenFixture(driver) + defer { DatabaseManager.shared.removeSession(for: fixture.connection.id) } + _ = try load(QueryTab(title: "Q", query: "SELECT id, email, note FROM users", tabType: .query), isTruncated: true, into: fixture) + + let shared = try #require(try await Self.source(of: fixture)) + + #expect(driver.sent.map(\.query) == ["SELECT id, email, note FROM users"]) + #expect(driver.sent.first?.rowCap == 1_000) + #expect(shared.rows.count == 5) + #expect(shared.rows.map { $0[1] } == Array(repeating: .text("u•••@example.com"), count: 5)) + #expect(shared.rows.first?[2] == .text("note 1")) + #expect(shared.masks == ColumnMasks(styles: [1: .email])) + } + + @Test("A cut read nothing traced is read again with every column masked whole") + func untracedReadIsMaskedWhole() async throws { + let driver = AnsweringPluginDriver(answer: Self.answer(origins: nil)) + let fixture = Self.drivenFixture(driver) + defer { DatabaseManager.shared.removeSession(for: fixture.connection.id) } + _ = try load( + QueryTab(title: "Q", query: "SELECT id, email, note FROM users", tabType: .query), + origins: nil, isTruncated: true, into: fixture + ) + + let shared = try #require(try await Self.source(of: fixture)) + + #expect(driver.sent.count == 1) + #expect(shared.untracedColumns == [0, 1, 2]) + #expect(shared.masks == ColumnMasks(styles: [0: .full, 1: .full, 2: .full])) + #expect(shared.rows.allSatisfy { row in row == Array(repeating: PluginCellValue.text("••••"), count: 3) }) + } + + @Test("A cut write that returned rows never runs again: the rows held go, marked as cut") + func cutWriteIsNotRunAgain() async throws { + let driver = AnsweringPluginDriver(answer: Self.answer(origins: Self.tracedOrigins)) + let fixture = Self.drivenFixture(driver) + defer { DatabaseManager.shared.removeSession(for: fixture.connection.id) } + let sql = "UPDATE users SET seen = true RETURNING id, email, note" + _ = try load(QueryTab(title: "Q", query: sql, tabType: .query), isTruncated: true, into: fixture) + + let shared = try #require(try await Self.source(of: fixture)) + + #expect(driver.sent.isEmpty) + #expect(shared.rows.count == 3) + #expect(shared.totalRowCount == nil) + #expect(shared.sql == sql) + } + + @Test("A cut result read in another database is not read again in the tab's") + func resultReadElsewhereIsNotReadAgain() async throws { + let driver = AnsweringPluginDriver(answer: Self.answer(origins: Self.tracedOrigins)) + let fixture = Self.drivenFixture(driver) + defer { DatabaseManager.shared.removeSession(for: fixture.connection.id) } + let tab = try load( + QueryTab(title: "Q", query: "SELECT id, email, note FROM users", tabType: .query), isTruncated: true, into: fixture + ) + tab.display.activeResultSet?.origin = ResultOrigin(tableName: "users", databaseName: "archive") + + let shared = try #require(try await Self.source(of: fixture)) + + #expect(driver.sent.isEmpty) + #expect(shared.rows.count == 3) + #expect(shared.totalRowCount == nil) + } + + @Test("Once the tab shows another statement's result, the sheet's loader reads nothing and finds no rows") + func replacedResultReadsNothing() async throws { + let driver = AnsweringPluginDriver(answer: Self.answer(origins: Self.tracedOrigins)) + let fixture = Self.drivenFixture(driver) + defer { DatabaseManager.shared.removeSession(for: fixture.connection.id) } + let tab = try load( + QueryTab(title: "Q", query: "SELECT id, email, note FROM users", tabType: .query), isTruncated: true, into: fixture + ) + let request = try #require(fixture.coordinator.activeResultShareRequest()) + let loader = try #require(request.loadResult) + var other = tab + other.content.query = "SELECT id, email, note FROM archived_users" + _ = try load(other, isTruncated: true, into: fixture) + + #expect(await loader(1_000) == nil) + #expect(driver.sent.isEmpty) + } + + @Test("A refresh of the same table view, as Auto Refresh installs, still shares; another database does not") + func refreshedTableViewStillShares() async throws { + fixture.coordinator.queryBuilder = TableQueryBuilder( + databaseType: .mysql, pagination: .offset, dialectQuote: SQLEscaping.quoteIdentifier + ) + let tab = try load( + QueryTab(title: "users", query: "SELECT * FROM users", tabType: .table, tableName: "users"), origins: nil + ) + let request = try #require(fixture.coordinator.activeResultShareRequest()) + let loader = try #require(request.loadResult) + let opened = fixture.tabManager.tabs.first { $0.id == tab.id }?.display.activeResultSet?.id + + _ = try load(tab, origins: nil) + #expect(fixture.tabManager.tabs.first { $0.id == tab.id }?.display.activeResultSet?.id != opened) + #expect(await loader(1_000)?.rows.count == 3) + + fixture.tabManager.mutate(tabId: tab.id) { $0.tableContext.databaseName = "archive" } + #expect(await loader(1_000) == nil) + } + + @Test("A table tab's view past the page is read with the page's limit off, masked by the rules") + func tableViewReadIsMasked() async throws { + let driver = AnsweringPluginDriver(answer: Self.answer(origins: nil)) + let fixture = Self.drivenFixture(driver) + defer { DatabaseManager.shared.removeSession(for: fixture.connection.id) } + fixture.coordinator.queryBuilder = TableQueryBuilder( + databaseType: .postgresql, + dialect: SQLDialectDescriptor( + identifierQuote: "\"", keywords: [], functions: [], dataTypes: [], + regexSyntax: .regexp, booleanLiteralStyle: .numeric, + likeEscapeStyle: .implicit, paginationStyle: .limit + ), + pagination: .offset, + dialectQuote: SQLEscaping.quoteIdentifier + ) + let tab = try load( + QueryTab(title: "users", query: "SELECT * FROM \"users\" LIMIT 3", tabType: .table, tableName: "users"), + origins: nil, into: fixture + ) + fixture.tabManager.mutate(tabId: tab.id) { + $0.pagination.totalRowCount = 5 + $0.pagination.isApproximateRowCount = false + } + + let shared = try #require(try await Self.source(of: fixture)) + + #expect(driver.sent.count == 1) + #expect(driver.sent.first?.query.contains("users") == true) + #expect(driver.sent.first?.rowCap == 1_000) + #expect(shared.rows.count == 5) + #expect(shared.rows.map { $0[1] } == Array(repeating: .text("u•••@example.com"), count: 5)) + #expect(shared.masks == ColumnMasks(styles: [1: .email])) + #expect(shared.totalRowCount == 5) + } + + @Test("A read for a sheet that closed stops and gives nothing") + func cancelledReadGivesNothing() async throws { + _ = try load(QueryTab(title: "Q", query: "SELECT id, email, note FROM users", tabType: .query)) + let request = try #require(fixture.coordinator.activeResultShareRequest()) + let load = try #require(request.loadResult) + + let read = Task { await load(1_000) } + read.cancel() + #expect(await read.value == nil) + } + + @Test("A table view the host cannot write as SQL stops sharing once its filters or sort change") + func unwrittenTableViewFollowsFiltersAndSort() async throws { + fixture.coordinator.queryBuilder = TableQueryBuilder( + databaseType: .mysql, pagination: .offset, dialectQuote: SQLEscaping.quoteIdentifier + ) + let tab = try load( + QueryTab(title: "users", query: "SELECT * FROM users", tabType: .table, tableName: "users"), origins: nil + ) + let loader = try #require(fixture.coordinator.activeResultShareRequest()?.loadResult) + let openedSort = try #require(fixture.tabManager.tabs.first { $0.id == tab.id }).sortState + + fixture.tabManager.mutate(tabId: tab.id) { + $0.sortState = SortState(columns: [SortColumn(columnIndex: 1, direction: .descending, columnName: "email")], source: .user) + } + #expect(await loader(1_000) == nil) + + fixture.tabManager.mutate(tabId: tab.id) { $0.sortState = openedSort } + #expect(await loader(1_000)?.rows.count == 3) + + fixture.tabManager.mutate(tabId: tab.id) { + $0.filterState.filters = [TableFilter(columnName: "email", filterOperator: .equal, value: "jane@example.com")] + $0.filterState.commit = .all + $0.filterState.adoptAppliedFiltersAsRunning() + } + #expect(await loader(1_000) == nil) + } + + @Test("Only a change to what the connection's masking rules do makes the share read again, ids or none") + func onlyRuleChangesSignalTheSheet() async throws { + let events = AppEvents() + let suite = try EphemeralDefaults() + let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent("share-rules-\(UUID().uuidString).json") + defer { try? FileManager.default.removeItem(at: fileURL) } + let storage = ConnectionStorage( + fileURL: fileURL, userDefaults: suite.defaults, keychain: InMemoryKeychain(), appEvents: events + ) + var connection = fixture.connection + // Hand-written or foreign JSON carries no id, so each read decodes a new one. + connection.additionalFields[DatabaseConnection.maskingRulesKey] = #"[{"pattern":"*.email","style":"email"}]"# + _ = storage.addConnection(connection) + let services = AppServices.live.replacing(databaseManager: DatabaseManager(connectionStorage: storage), appEvents: events) + let ruled = CoordinatorFixture(connection: connection, services: services) + _ = try load(QueryTab(title: "Q", query: "SELECT id, email, note FROM users", tabType: .query), into: ruled) + let changes = try #require(ruled.coordinator.activeResultShareRequest()?.sourceChanges) + let signals = Signals() + let delivered = Signals() + let observation = changes.sink { signals.count += 1 } + let probe = events.connectionUpdated.receive(on: RunLoop.main).sink { _ in delivered.count += 1 } + defer { + observation.cancel() + probe.cancel() + } + + connection.name = "Renamed" + storage.updateConnection(connection) + events.connectionUpdated.send(connection.id) + events.connectionUpdated.send(nil) + try await waitUntil { delivered.count == 2 } + #expect(signals.count == 0) + + connection.maskingRules += [MaskingRule(pattern: "*.note", style: .full)] + storage.updateConnection(connection) + events.connectionUpdated.send(connection.id) + try await waitUntil { signals.count == 1 } + #expect(delivered.count == 3) + } + + @MainActor + private final class Signals { + var count = 0 + } + + private func source(maxRows: Int = 1_000) async throws -> ShareResultSource { + let request = try #require(fixture.coordinator.activeResultShareRequest()) + let load = try #require(request.loadResult) + return try #require(await load(maxRows)) + } + + private func setPagination(_ tabId: UUID, _ change: (inout PaginationState) -> Void) { + fixture.tabManager.mutate(tabId: tabId) { change(&$0.pagination) } + } + + @Test("Share Result reads the grid as shown: masked after Reveal, hidden columns out, pending deletes skipped") + func readsTheGridAsShown() async throws { + var tab = QueryTab(title: "Q", query: "SELECT id, email, note FROM users", tabType: .query) + tab.revealsMaskedValues = true + tab.columnLayout.hiddenColumns = ["note"] + let loaded = try load(tab) + let rows = fixture.coordinator.tabSessionRegistry.tableRows(for: loaded.id) + #expect(rows.rows.contains { $0.values.contains(.text("jane@example.com")) }) + + fixture.changeManager.recordRowDeletion(rowID: rows.rows[1].id, originalRow: Array(rows.rows[1].values)) + let shared = try await source() + + #expect(shared.columns == ["id", "email"]) + #expect(shared.rows.map { $0.first } == [.text("1"), .text("3")]) + #expect(!shared.rows.contains { row in row.contains { Self.emails.contains($0.asText ?? "") } }) + #expect(shared.sql == "SELECT id, email, note FROM users") + } + + @Test("The source says which shared columns the rules masked, at their place after hidden columns") + func sourceCarriesRuleMasks() async throws { + var tab = QueryTab(title: "Q", query: "SELECT id, email, note FROM users", tabType: .query) + tab.columnLayout.hiddenColumns = ["id"] + _ = try load(tab) + let shared = try await source() + + #expect(shared.columns == ["email", "note"]) + #expect(shared.masks == ColumnMasks(styles: [0: .email])) + #expect(shared.rows.first?.first == .text("j•••@example.com")) + } + + @Test("A column nothing traced is masked whole and marked untraced, at its place after hidden columns") + func untracedColumnsAreMarked() async throws { + var tab = QueryTab(title: "Q", query: "SELECT id, email, note FROM users", tabType: .query) + tab.columnLayout.hiddenColumns = ["id"] + _ = try load(tab, origins: [Self.tracedOrigins[0], Self.tracedOrigins[1], nil]) + let shared = try await source() + + #expect(shared.columns == ["email", "note"]) + #expect(shared.untracedColumns == [1]) + #expect(shared.masks == ColumnMasks(styles: [0: .email, 1: .full])) + #expect(shared.rows.first?.last == .text("••••")) + } + + @Test("A result cut short sends its exact count") + func exactCountIsTheTotal() async throws { + let tab = try load(QueryTab(title: "Q", query: "SELECT * FROM users", tabType: .query)) + setPagination(tab.id) { + $0.hasMoreRows = true + $0.totalRowCount = 500 + $0.isApproximateRowCount = false + } + #expect(try await source().totalRowCount == 500) + } + + @Test("An estimate above the rows held stands in for the total") + func estimateAboveTheRowsIsTheTotal() async throws { + let tab = try load(QueryTab(title: "Q", query: "SELECT * FROM users", tabType: .query)) + setPagination(tab.id) { + $0.hasMoreRows = true + $0.totalRowCount = 10_000 + $0.isApproximateRowCount = true + } + #expect(try await source().totalRowCount == 10_000) + } + + @Test("More rows than max_rows with no count read only max_rows positions and leave the total unknown") + func cutWithoutACountIsUnknown() async throws { + let tab = try load(QueryTab(title: "Q", query: "SELECT * FROM users", tabType: .query)) + setPagination(tab.id) { + $0.totalRowCount = nil + $0.hasMoreRows = false + } + let shared = try await source(maxRows: 2) + #expect(shared.rows.count == 2) + #expect(shared.totalRowCount == nil) + } + + @Test("A table tab shares its view's SQL without the page's LIMIT and OFFSET") + func tableTabSharesItsViewWithoutWindow() throws { + fixture.coordinator.queryBuilder = TableQueryBuilder( + databaseType: .mysql, + dialect: SQLDialectDescriptor( + identifierQuote: "`", keywords: [], functions: [], dataTypes: [], + regexSyntax: .regexp, booleanLiteralStyle: .numeric, + likeEscapeStyle: .implicit, paginationStyle: .limit + ), + pagination: .offset, + dialectQuote: SQLEscaping.quoteIdentifier + ) + var tab = QueryTab(title: "users", query: "SELECT * FROM `users` LIMIT 1000 OFFSET 3000", tabType: .table, tableName: "users") + tab.pagination.currentOffset = 3_000 + fixture.addTab(tab) + + #expect(fixture.coordinator.shareSQL(of: tab) == "SELECT * FROM \"users\"") + } + + @Test("A table view the host cannot write as SQL shares no SQL") + func dialectlessTableSharesNoSQL() { + fixture.coordinator.queryBuilder = TableQueryBuilder( + databaseType: .mysql, pagination: .offset, dialectQuote: SQLEscaping.quoteIdentifier + ) + let tab = QueryTab(title: "users", query: "", tabType: .table, tableName: "users") + fixture.addTab(tab) + #expect(fixture.coordinator.shareSQL(of: tab).isEmpty) + } + + @Test("A whole result held in the grid is its own total") + func wholeResultCountsItself() async throws { + let tab = try load(QueryTab(title: "Q", query: "SELECT * FROM users", tabType: .query)) + setPagination(tab.id) { + $0.totalRowCount = nil + $0.hasMoreRows = false + } + let shared = try await source() + #expect(shared.rows.count == 3) + #expect(shared.totalRowCount == 3) + } + } +} + +@MainActor +private extension AppServices { + func replacing(databaseManager: DatabaseManager, appEvents: AppEvents) -> AppServices { + AppServices( + appEvents: appEvents, + appSettings: appSettings, + appSettingsStorage: appSettingsStorage, + connectionStorage: connectionStorage, + databaseManager: databaseManager, + pluginManager: pluginManager, + schemaService: schemaService, + schemaRefreshService: schemaRefreshService, + schemaProviderRegistry: schemaProviderRegistry, + catalogChangeService: catalogChangeService, + sqlFavoriteManager: sqlFavoriteManager, + favoriteTablesStorage: favoriteTablesStorage, + favoriteDatabasesStorage: favoriteDatabasesStorage, + tableFolderStorage: tableFolderStorage, + aiChatStorage: aiChatStorage, + aiKeyStorage: aiKeyStorage, + aiAccessApprovals: aiAccessApprovals, + groupStorage: groupStorage, + tagStorage: tagStorage, + sshProfileStorage: sshProfileStorage, + credentialProfileStorage: credentialProfileStorage, + featureAccess: featureAccess, + syncMetadataStorage: syncMetadataStorage, + favoritesExpansionState: favoritesExpansionState, + linkedFolderWatcher: linkedFolderWatcher, + queryHistoryManager: queryHistoryManager, + dateFormattingService: dateFormattingService, + copilotService: copilotService, + mcpServerManager: mcpServerManager, + syncTracker: syncTracker, + welcomeRouter: welcomeRouter, + telemetry: telemetry + ) + } +} diff --git a/apple/TableProTests/Views/Share/ShareSheetModelTests.swift b/apple/TableProTests/Views/Share/ShareSheetModelTests.swift new file mode 100644 index 0000000000..e0a60495cd --- /dev/null +++ b/apple/TableProTests/Views/Share/ShareSheetModelTests.swift @@ -0,0 +1,865 @@ +// +// ShareSheetModelTests.swift +// TableProTests +// + +import Combine +import Foundation +@testable import TablePro +import TableProPluginKit +import TableProTestSupport +import Testing + +@MainActor +struct ShareSheetModelTests { + private final class Box { + var copied: [String] = [] + var signedIn: Bool + let signIns = PassthroughSubject() + + init(signedIn: Bool) { + self.signedIn = signedIn + } + } + + private static func source(rows: Int, total: Int??, sql: String) -> ShareResultSource { + ShareResultSource( + columns: ["id", "api_key"], + columnTypes: [.integer(rawType: "int8"), .text(rawType: "text")], + rows: (0.. ShareRequest { + .result(title: "Users", dialect: "PostgreSQL", source: source(rows: rows, total: total, sql: sql)) + } + + private static func link(_ id: String, at seconds: TimeInterval = 0) -> ShareLink { + ShareLink( + id: id, title: id, kind: .query, createdAt: Date(timeIntervalSince1970: seconds), expiresAt: nil, isSuspended: false + ) + } + + private static let acme = ShareTeam(id: "team_acme", name: "Acme", live: 4, liveLimit: 1_000, allowsPublicLinks: true) + private static let closed = ShareTeam(id: "team_closed", name: "Closed", live: 0, liveLimit: 1_000, allowsPublicLinks: false) + + private func makeModel( + _ request: ShareRequest = .query(title: "Report", sql: "SELECT 1", dialect: "MySQL"), + service: FakeShareService, + box: Box = Box(signedIn: true) + ) -> ShareSheetModel { + ShareSheetModel( + request: request, + service: service, + isSignedIn: { box.signedIn }, + signInChanges: box.signIns.eraseToAnyPublisher(), + copyToClipboard: { box.copied.append($0) } + ) + } + + private func formatted(_ key: String.LocalizationValue, _ arguments: any CVarArg...) -> String { + String(format: String(localized: key), locale: .current, arguments: arguments) + } + + // MARK: - Phases + + @Test("Signed out shows the sign-in prompt and asks the server nothing") + func signedOut() async { + let service = FakeShareService() + let model = makeModel(service: service, box: Box(signedIn: false)) + await model.load() + #expect(model.phase == .signedOut) + #expect(service.limitsCalls == 0) + } + + @Test("Signing in from the prompt loads the limits") + func signingInLoads() async throws { + let service = FakeShareService() + let box = Box(signedIn: false) + let model = makeModel(service: service, box: box) + await model.load() + + box.signedIn = true + box.signIns.send(true) + try await waitUntil { model.phase == .form } + #expect(service.limitsCalls == 1) + } + + @Test("An unverified email stops at Open Account") + func emailUnverified() async { + let model = makeModel(service: FakeShareService(limits: .free(emailVerified: false))) + await model.load() + #expect(model.phase == .emailUnverified) + } + + @Test("Sharing turned off for the account stops at its message") + func sharingDisabled() async { + let model = makeModel(service: FakeShareService(limits: .free(sharingDisabled: true))) + await model.load() + #expect(model.phase == .sharingDisabled) + } + + @Test("Offline shows the offline message with a retry that recovers") + func offlineThenRetry() async { + let service = FakeShareService() + service.limitsResults = [.failure(.offline), .success(.free())] + let model = makeModel(service: service) + + await model.load() + #expect(model.phase == .loadFailed(String(localized: "You appear to be offline. Try again once you're connected."))) + + await model.load() + #expect(model.phase == .form) + } + + @Test("A refused session on load returns to the sign-in prompt") + func refusedSessionSignsOut() async { + let service = FakeShareService() + service.limitsResults = [.failure(.signedOut)] + let model = makeModel(service: service) + await model.load() + #expect(model.phase == .signedOut) + } + + // MARK: - Plan gating + + private func needsPro(_ action: String.LocalizationValue) -> String { + String(localized: "This option needs TablePro Pro.") + " " + String(localized: action) + } + + @Test("Free defaults to 30 days, and Never, a password or downloads turned off hold Create with the reason, never dropped") + func freeGating() async throws { + let model = makeModel(service: FakeShareService(limits: .free())) + await model.load() + + #expect(model.expiry == .thirtyDays) + #expect(!model.isAvailable(.never)) + #expect(model.isAvailable(.oneDay)) + #expect(model.canCreate) + + model.expiry = .never + #expect(model.expiryMessage == needsPro("Choose another expiry to create the link.")) + model.password = "secret" + #expect(model.passwordMessage == needsPro("Clear the password to create the link.")) + model.allowsDownload = false + #expect(model.downloadMessage == needsPro("Turn downloads back on to create the link.")) + #expect(!model.canCreate) + #expect(model.makeDraft() == nil) + + model.expiry = .sevenDays + model.password = "" + model.allowsDownload = true + #expect(model.canCreate) + let draft = try #require(model.makeDraft()) + #expect(draft.expiry == .sevenDays) + #expect(draft.password == nil) + #expect(draft.allowsDownload == nil) + } + + @Test("A reload as Free keeps the typed password and Never, and holds Create until the person changes them") + func downgradeKeepsChoices() async throws { + let service = FakeShareService() + service.limitsResults = [.success(.pro()), .success(.free())] + service.createResult = .failure(.limitReached) + let model = makeModel(service: service) + await model.load() + #expect(model.expiry == .never) + model.password = "hunter2" + + await model.create() + #expect(model.limits?.plan == .free) + #expect(model.phase == .form) + #expect(model.password == "hunter2") + #expect(model.expiry == .never) + #expect(model.passwordMessage == needsPro("Clear the password to create the link.")) + #expect(model.expiryMessage == needsPro("Choose another expiry to create the link.")) + #expect(!model.canCreate) + + model.password = "" + model.expiry = .thirtyDays + #expect(model.canCreate) + } + + @Test("A password goes without leading and trailing spaces and tabs, and one of only those holds Create") + func passwordWhitespace() async throws { + let model = makeModel(service: FakeShareService(limits: .pro())) + await model.load() + + model.password = " \thunter 2\t " + #expect(try #require(model.makeDraft()).password == "hunter 2") + + model.password = " \t " + #expect(model.passwordMessage == String(localized: "A password can't be only spaces or tabs.")) + #expect(!model.canCreate) + #expect(model.makeDraft() == nil) + } + + @Test("SQL is held to 256 KiB of UTF-8, not 262,144 characters") + func sqlLimitCountsBytes() async { + let atLimit = makeModel( + .query(title: "Q", sql: String(repeating: "\u{E9}", count: ShareSheetModel.sqlLimit / 2), dialect: nil), + service: FakeShareService() + ) + await atLimit.load() + #expect(atLimit.sqlTooLongMessage == nil) + #expect(atLimit.canCreate) + + let over = makeModel( + .query(title: "Q", sql: String(repeating: "\u{E9}", count: ShareSheetModel.sqlLimit / 2 + 1), dialect: nil), + service: FakeShareService() + ) + await over.load() + #expect(over.sqlTooLongMessage == String( + format: String(localized: "This query is too long to share. A link holds up to %@ of SQL."), + ByteCountFormatter.string(fromByteCount: Int64(ShareSheetModel.sqlLimit), countStyle: .memory) + )) + #expect(!over.canCreate) + } + + @Test("Pro defaults to Never and sends a password and turned-off downloads") + func proOptions() async throws { + let model = makeModel(service: FakeShareService(limits: .pro())) + await model.load() + + #expect(model.expiry == .never) + #expect(model.isAvailable(.never)) + + model.password = "hunter2" + model.allowsDownload = false + let draft = try #require(model.makeDraft()) + #expect(draft.expiry == .never) + #expect(draft.password == "hunter2") + #expect(draft.allowsDownload == false) + } + + @Test("Downloads left on are not sent, so the server keeps its default") + func downloadsDefault() async throws { + let model = makeModel(service: FakeShareService(limits: .pro())) + await model.load() + #expect(try #require(model.makeDraft()).allowsDownload == nil) + } + + @Test("The footer names the plan and its usage") + func footer() async { + let free = makeModel(service: FakeShareService(limits: .free(live: 3))) + await free.load() + #expect(free.footer == formatted("Free · %1$lld of %2$lld links · first %3$lld rows", Int64(3), Int64(5), Int64(1_000))) + + let pro = makeModel(service: FakeShareService(limits: .pro(live: 12))) + await pro.load() + #expect(pro.footer == formatted("Pro · %lld links", Int64(12))) + } + + @Test("A password over 128 characters and SQL over 262,144 characters block Create with a reason") + func fieldLimitsBlockCreate() async { + let model = makeModel(service: FakeShareService(limits: .pro())) + await model.load() + model.password = String(repeating: "p", count: ShareSheetModel.passwordLimit + 1) + #expect(model.passwordMessage != nil) + #expect(!model.canCreate) + model.password = String(repeating: "p", count: ShareSheetModel.passwordLimit) + #expect(model.canCreate) + + let long = makeModel( + .query(title: "Long", sql: String(repeating: "x", count: ShareSheetModel.sqlLimit + 1), dialect: nil), + service: FakeShareService() + ) + await long.load() + #expect(long.sqlTooLongMessage != nil) + #expect(!long.canCreate) + } + + // MARK: - Teams + + @Test("Share as a team sends its ID and the footer counts the team's links") + func teamTarget() async throws { + let model = makeModel(service: FakeShareService(limits: .pro(teams: [Self.acme, Self.closed]))) + await model.load() + + #expect(model.teams.map(\.id) == ["team_acme", "team_closed"]) + model.target = .team("team_acme") + #expect(try #require(model.makeDraft()).teamID == "team_acme") + #expect(model.footer == formatted("%1$@ · %2$lld of %3$lld links", "Acme", Int64(4), Int64(1_000))) + + model.target = .personal + #expect(try #require(model.makeDraft()).teamID == nil) + } + + @Test("A team at its cap shows that team's links, and switching back shows the form") + func teamAtCap() async throws { + let full = ShareTeam(id: "team_full", name: "Full", live: 1_000, liveLimit: 1_000, allowsPublicLinks: true) + let service = FakeShareService(limits: .pro(teams: [full])) + service.linksResult = .success([Self.link("shr_team")]) + let model = makeModel(service: service) + await model.load() + #expect(model.phase == .form) + + model.target = .team("team_full") + #expect(model.phase == .atCap) + #expect(model.atCapMessage == formatted("This team has %lld live links.", Int64(1_000)) + " " + + formatted("Teams allow %lld. Revoke one to share another.", Int64(1_000))) + try await waitUntil { !model.liveLinks.isEmpty } + #expect(service.linkTeams.last == "team_full") + + model.target = .personal + #expect(model.phase == .form) + } + + // MARK: - Drafts + + @Test("A query share always shows its SQL and carries no snapshot") + func queryDraft() async throws { + let model = makeModel(service: FakeShareService()) + await model.load() + model.title = " Report " + model.note = " " + let draft = try #require(model.makeDraft()) + + #expect(draft.kind == .query) + #expect(draft.sql == "SELECT 1") + #expect(draft.title == "Report") + #expect(draft.note == nil) + #expect(draft.hidesSQL == nil) + #expect(draft.snapshot == nil) + #expect(draft.dialect == "MySQL") + } + + @Test("A result share carries Hide SQL, the loaded statement, and a snapshot cut to the plan's rows") + func resultDraft() async throws { + let model = makeModel( + Self.resultRequest(rows: 1_200, total: 48_210, sql: "SELECT * FROM users LIMIT 1000"), + service: FakeShareService(limits: .free()) + ) + await model.load() + model.hidesSQL = true + let draft = try #require(model.makeDraft()) + let snapshot = try #require(draft.snapshot) + + #expect(draft.kind == .result) + #expect(draft.hidesSQL == true) + #expect(draft.sql == "SELECT * FROM users LIMIT 1000") + #expect(snapshot.rows.count == 1_000) + #expect(snapshot.rowCount == 48_210) + #expect(model.capNote == formatted("Shares the first %1$lld of %2$lld rows.", Int64(1_000), Int64(48_210))) + #expect(model.previewRows.count == ShareSheetModel.previewRowCount) + } + + @MainActor + private final class Asked { + var maxRows: [Int] = [] + } + + @Test("The loader is asked for the plan's rows") + func loaderGetsMaxRows() async throws { + let asked = Asked() + let request = ShareRequest.result(title: "T", sql: "SELECT 1", dialect: nil) { maxRows in + asked.maxRows.append(maxRows) + return Self.source(rows: 2, total: .none, sql: "SELECT 1") + } + let model = makeModel(request, service: FakeShareService(limits: .pro())) + await model.load() + #expect(asked.maxRows == [10_000]) + #expect(model.phase == .form) + } + + @Test("A result with no SQL to share sends its rows without Hide SQL") + func resultWithoutSQL() async throws { + let model = makeModel(Self.resultRequest(rows: 3, sql: ""), service: FakeShareService()) + await model.load() + model.hidesSQL = true + let draft = try #require(model.makeDraft()) + #expect(!model.hasSharedSQL) + #expect(draft.sql.isEmpty) + #expect(draft.hidesSQL == nil) + #expect(draft.snapshot != nil) + } + + @Test("A total nobody counted says the result is larger") + func unknownTotalNote() async { + let model = makeModel(Self.resultRequest(rows: 3, total: .some(nil)), service: FakeShareService()) + await model.load() + #expect(model.capNote == formatted("Shares the first %lld rows of a larger result.", Int64(3))) + } + + @Test("A result inside the limit has no cap note") + func noCapNote() async { + let model = makeModel(Self.resultRequest(rows: 3), service: FakeShareService()) + await model.load() + #expect(model.capNote == nil) + } + + @Test("Long fields are cut to the server's caps") + func fieldCaps() async throws { + let model = makeModel(service: FakeShareService(limits: .pro())) + await model.load() + model.title = String(repeating: "t", count: 300) + model.note = String(repeating: "n", count: 3_000) + let draft = try #require(model.makeDraft()) + #expect(draft.title.count == ShareSheetModel.titleLimit) + #expect(draft.note?.count == ShareSheetModel.noteLimit) + } + + // MARK: - Creating + + @Test("Creating copies the link and shows it") + func createCopiesLink() async { + let service = FakeShareService() + let box = Box(signedIn: true) + let model = makeModel(service: service, box: box) + await model.load() + await model.create() + + let url = URL(string: "https://s.tablepro.app/abc")! + #expect(model.phase == .created(url)) + #expect(box.copied == [url.absoluteString]) + #expect(model.limits?.live == 4) + } + + @Test("A second Create while the first is out sends nothing") + func noDoubleSubmit() async throws { + let service = FakeShareService() + let gate = AsyncGate() + service.createGate = gate + let model = makeModel(service: service) + await model.load() + + let first = Task { await model.create() } + await gate.arrived(1) + #expect(model.isCreating) + #expect(!model.canCreate) + await model.create() + await gate.open() + await first.value + + #expect(service.drafts.count == 1) + } + + @Test("A create that answers after the sheet closed leaves the clipboard alone") + func closedSheetKeepsClipboard() async throws { + let service = FakeShareService() + let gate = AsyncGate() + service.createGate = gate + let box = Box(signedIn: true) + let model = makeModel(service: service, box: box) + await model.load() + + let first = Task { await model.create() } + await gate.arrived(1) + model.close() + await gate.open() + await first.value + + #expect(box.copied.isEmpty) + #expect(model.phase == .form) + } + + @Test("Each refusal is worded for its code", arguments: [ + (ShareFailure.proRequired, "This option needs TablePro Pro."), + (.teamSharingDisabled, "Public links are turned off for this team."), + (.snapshotTooLarge, "This result is too large to share."), + (.rateLimited, "Too many links just now. Try again in a moment."), + (.offline, "You appear to be offline. Try again once you're connected."), + (.server, "The link couldn't be created. Try again.") + ]) + func refusalWording(failure: ShareFailure, english: String) async { + let service = FakeShareService() + service.createResult = .failure(failure) + let model = makeModel(service: service) + await model.load() + await model.create() + + #expect(model.phase == .form) + #expect(model.failureMessage == String(localized: String.LocalizationValue(english))) + } + + @Test("Hitting the cap on create shows the live links") + func createAtCap() async throws { + let service = FakeShareService() + service.limitsResults = [.success(.free(live: 4)), .success(.free(live: 5))] + service.createResult = .failure(.limitReached) + let model = makeModel(service: service) + await model.load() + await model.create() + + #expect(model.phase == .atCap) + } + + @Test("A cell past the server's cap makes the result too large to share") + func tooLargeBlocksCreate() async { + let request = ShareRequest.result( + title: "Huge", + dialect: nil, + source: ShareResultSource( + columns: ["body"], + columnTypes: [.text(rawType: "text")], + rows: [[.text(String(repeating: "x", count: ShareSnapshotBuilder.maxCellBytes))]], + totalRowCount: 1, + sql: "SELECT *" + ) + ) + let model = makeModel(request, service: FakeShareService()) + await model.load() + + #expect(model.isSnapshotTooLarge) + #expect(!model.canCreate) + } + + @Test("More than 100 kept columns share the first 100, say so before and after, and count only those sent") + func columnCap() async throws { + let count = ShareSnapshotBuilder.maxColumns + 2 + let names = (0.. ShareRequest { + .result(title: "People", dialect: "PostgreSQL", source: peopleSource(sql: sql)) + } + + private static func peopleSource(sql: String = "SELECT * FROM people") -> ShareResultSource { + ShareResultSource( + columns: ["id", "email", "ip", "note"], + columnTypes: [.integer(rawType: "int8"), .text(rawType: "text"), .text(rawType: "inet"), .text(rawType: "text")], + rows: [ + [.text("1"), .text("jane@example.com"), .text("j•••@x.io"), .text("hello")], + [.text("2"), .text("john@example.com"), .text("a1b2c3d4e5f6"), .text("world")] + ], + totalRowCount: 2, + sql: sql, + masks: ColumnMasks(styles: [2: .hash]) + ) + } + + @Test("Rows read again for a new row limit keep the column choices, and the snapshot follows them") + func reloadKeepsChoices() async throws { + let service = FakeShareService() + service.limitsResults = [.success(.free()), .success(.pro())] + service.createResult = .failure(.limitReached) + let asked = Asked() + let request = ShareRequest.result(title: "People", sql: "SELECT * FROM people", dialect: nil) { maxRows in + asked.maxRows.append(maxRows) + return Self.peopleSource() + } + let model = makeModel(request, service: service) + await model.load() + model.setAction(.mask, forColumn: 0) + model.setAction(.remove, forColumn: 3) + try await waitUntil { model.canCreate } + + await model.create() + #expect(asked.maxRows == [1_000, 10_000]) + #expect(model.columns.map(\.action) == [.mask, .mask, .mask, .remove]) + try await waitUntil { model.canCreate } + let snapshot = try #require(model.makeDraft()?.snapshot) + #expect(snapshot.columns.map(\.name) == ["id", "email", "ip"]) + #expect(snapshot.columns.map(\.masked) == [.full, .email, .hash]) + } + + @Test("Columns start from the rules and the detectors, and the snapshot sends the values as the preview shows them") + func columnDefaults() async throws { + let model = makeModel(Self.peopleRequest(), service: FakeShareService()) + await model.load() + + #expect(model.columns.map(\.action) == [.keep, .mask, .mask, .keep]) + #expect(model.columns.map(\.style) == [.full, .email, .hash, .full]) + #expect(model.hasDetections) + #expect(model.columnSummary == formatted("%1$lld columns masked, %2$lld removed.", Int64(2), Int64(0))) + let snapshot = try #require(model.makeDraft()?.snapshot) + #expect(snapshot.columns.map(\.masked) == [nil, .email, .hash, nil]) + #expect(snapshot.rows.first == [.number("1"), .string("j•••@example.com"), .string("j•••@x.io"), .string("hello")]) + #expect(model.previewRows.first == snapshot.rows.first) + } + + @Test("A rule-masked column cannot be kept and takes only a stricter style") + func ruleMaskedColumnStaysMasked() async { + let model = makeModel(Self.peopleRequest(), service: FakeShareService()) + await model.load() + + model.setAction(.keep, forColumn: 2) + model.setStyle(.email, forColumn: 2) + #expect(model.columns[2].action == .mask) + #expect(model.columns[2].style == .hash) + #expect(model.canCreate) + } + + @Test("A change to the columns holds Create until the snapshot is rebuilt with it") + func columnChangeRebuilds() async throws { + let model = makeModel(Self.peopleRequest(), service: FakeShareService()) + await model.load() + + model.setAction(.remove, forColumn: 3) + model.setAction(.keep, forColumn: 1) + model.setStyle(.null, forColumn: 2) + #expect(!model.canCreate) + #expect(model.makeDraft() == nil) + + try await waitUntil { model.canCreate } + let snapshot = try #require(model.makeDraft()?.snapshot) + #expect(snapshot.columns.map(\.name) == ["id", "email", "ip"]) + #expect(snapshot.columns.map(\.masked) == [nil, nil, .null]) + #expect(snapshot.rows.first == [.number("1"), .string("jane@example.com"), .null]) + #expect(model.columnSummary == formatted("%1$lld columns masked, %2$lld removed.", Int64(1), Int64(1))) + } + + @Test("Removing every column says so and blocks Create") + func everyColumnRemoved() async throws { + let model = makeModel(Self.peopleRequest(), service: FakeShareService()) + await model.load() + for index in 0..<4 { + model.setAction(.remove, forColumn: index) + } + try await waitUntil { model.isEveryColumnRemoved } + #expect(!model.canCreate) + } + + @Test("Personal data in the SQL suggests Hide SQL until it is on, and never for a query share") + func hideSQLSuggestion() async throws { + let model = makeModel( + Self.peopleRequest(sql: "SELECT * FROM people WHERE email = 'jane@example.com'"), + service: FakeShareService() + ) + await model.load() + try await waitUntil { model.hideSQLSuggestion != nil } + #expect(model.hideSQLSuggestion == String( + format: String(localized: "This query contains what looks like personal data (%@). Turn on Hide SQL to keep the query private."), + ListFormatter.localizedString(byJoining: [SensitiveValueKind.email.displayName]) + )) + model.hidesSQL = true + #expect(model.hideSQLSuggestion == nil) + + let query = makeModel(.query(title: "Q", sql: "SELECT 'jane@example.com'", dialect: nil), service: FakeShareService()) + await query.load() + try await waitUntil { !query.sqlPersonalData.isEmpty } + #expect(query.hideSQLSuggestion == nil) + } + + // MARK: - The rows changing under the sheet + + private static func notesSource(masked: Bool) -> ShareResultSource { + ShareResultSource( + columns: ["id", "notes"], + columnTypes: [.integer(rawType: "int8"), .text(rawType: "text")], + rows: [[.text("1"), .text(masked ? "••••" : "hello")]], + totalRowCount: 1, + sql: "SELECT id, notes FROM people", + masks: masked ? ColumnMasks(styles: [1: .full]) : .none + ) + } + + @Test("A rule saved while the sheet is open reads the rows again, and Create waits for them") + func ruleSavedRereadsTheRows() async throws { + let changes = PassthroughSubject() + let asked = Asked() + let request = ShareRequest.result( + title: "People", sql: "SELECT id, notes FROM people", dialect: nil, sourceChanges: changes.eraseToAnyPublisher() + ) { maxRows in + asked.maxRows.append(maxRows) + return Self.notesSource(masked: asked.maxRows.count > 1) + } + let model = makeModel(request, service: FakeShareService()) + await model.load() + #expect(model.canCreate) + model.setAction(.remove, forColumn: 0) + try await waitUntil { model.canCreate } + + changes.send() + #expect(!model.canCreate) + #expect(model.makeDraft() == nil) + try await waitUntil { model.canCreate } + + #expect(asked.maxRows == [1_000, 1_000]) + #expect(model.columns.map(\.action) == [.remove, .mask]) + #expect(model.columns.map(\.ruleStyle) == [nil, .full]) + let snapshot = try #require(model.makeDraft()?.snapshot) + #expect(snapshot.columns.map(\.masked) == [.full]) + #expect(snapshot.rows == [[.string("••••")]]) + } + + @Test("A rule saved during a reload as Free reads the rows again at the Free limit, not the Pro one") + func ruleSavedDuringAFreeReloadUsesItsLimit() async throws { + let service = FakeShareService() + service.limitsResults = [.success(.pro()), .success(.free())] + service.createResult = .failure(.limitReached) + let changes = PassthroughSubject() + let asked = Asked() + let freeReadHeld = AsyncGate() + let request = ShareRequest.result( + title: "Users", sql: "SELECT id FROM users", dialect: nil, sourceChanges: changes.eraseToAnyPublisher() + ) { maxRows in + asked.maxRows.append(maxRows) + if asked.maxRows.count == 2 { + await freeReadHeld.wait() + } + return Self.source(rows: 1_200, total: 48_210, sql: "SELECT id FROM users") + } + let model = makeModel(request, service: service) + await model.load() + + let create = Task { await model.create() } + await freeReadHeld.arrived(1) + changes.send() + try await waitUntil { asked.maxRows.count == 3 } + await freeReadHeld.open() + await create.value + // Never stays picked after the reload as Free, and holds Create until changed. + model.expiry = .thirtyDays + try await waitUntil { model.canCreate } + + #expect(asked.maxRows == [10_000, 1_000, 1_000]) + #expect(model.makeDraft()?.snapshot?.rows.count == 1_000) + } + + @Test("A result no longer open says why Create is off") + func resultGone() async { + let request = ShareRequest.result(title: "Gone", sql: "SELECT 1", dialect: nil) { _ in nil } + let model = makeModel(request, service: FakeShareService()) + await model.load() + + #expect(model.phase == .form) + #expect(model.resultGoneMessage == String(localized: "This result is no longer open, so there are no rows to share.")) + #expect(!model.canCreate) + } + + @Test("Counts read with the user's digit grouping, as PLAN 6 writes them") + func countsAreGrouped() async { + let free = makeModel(Self.resultRequest(rows: 1_200, total: 48_210), service: FakeShareService(limits: .free())) + await free.load() + #expect(free.footer == formatted("Free · %1$lld of %2$lld links · first %3$lld rows", Int64(3), Int64(5), Int64(1_000))) + #expect(free.footer?.contains(1_000.formatted()) == true) + #expect(free.capNote?.contains(1_000.formatted()) == true) + #expect(free.capNote?.contains(48_210.formatted()) == true) + } +} diff --git a/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift b/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift index 4f8fff68a5..ba18f3a01e 100644 --- a/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift +++ b/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift @@ -376,6 +376,29 @@ struct FavoritesMenuSpecTests { #expect(issued.contains(.showFavoriteHistory(query))) } + @Test("A saved query offers Share… right after Copy Query, whatever the plan") + func savedQueryOffersShare() throws { + let query = favorite() + let issued = commands(FavoritesMenuSpec.sections(for: context(clicked: .query(.favorite(query))))) + let copy = try #require(issued.firstIndex(of: .copyText(query.query))) + #expect(issued.firstIndex(of: .shareFavorite(query)) == copy + 1) + } + + @Test("A linked file offers Share… right after Copy Query") + func linkedFileOffersShare() throws { + let file = linkedFile() + let issued = linkedCommands(file, gitState: nil) + let copy = try #require(issued.firstIndex(of: .copyLinkedFavoriteQuery(file))) + #expect(issued.firstIndex(of: .shareLinkedFavorite(file)) == copy + 1) + } + + @Test("Only a saved query offers Share…") + func onlySavedQueriesOfferShare() { + let folder = SQLFavoriteFolder(name: "Reports") + let issued = commands(FavoritesMenuSpec.sections(for: context(clicked: .query(.folder(folder, children: []))))) + #expect(!issued.contains { if case .shareFavorite = $0 { return true } else { return false } }) + } + private func linkedFile() -> LinkedSQLFavorite { LinkedSQLFavorite( folderId: UUID(), @@ -424,7 +447,7 @@ struct FavoritesMenuSpecTests { sections.nonEmptySections().map { commands($0.items) } } - @Test("A linked file copies its absolute and relative paths between Copy Query and Show in Finder") + @Test("A linked file copies its absolute and relative paths between Copy Query, Share… and Show in Finder") func linkedFileOffersBothPaths() { let file = LinkedSQLFavorite( folderId: UUID(), @@ -438,6 +461,7 @@ struct FavoritesMenuSpecTests { #expect(groups.contains([ .copyLinkedFavoriteQuery(file), + .shareLinkedFavorite(file), .copyPath("/tmp/queries/reports/daily.sql"), .copyRelativePath("reports/daily.sql"), .revealLinkedFavorite(file) diff --git a/apple/TableProTests/Views/Sidebar/FavoritesOutlinePathCommandTests.swift b/apple/TableProTests/Views/Sidebar/FavoritesOutlinePathCommandTests.swift index fbc77c2fd6..b369c79376 100644 --- a/apple/TableProTests/Views/Sidebar/FavoritesOutlinePathCommandTests.swift +++ b/apple/TableProTests/Views/Sidebar/FavoritesOutlinePathCommandTests.swift @@ -12,6 +12,7 @@ import Testing struct FavoritesOutlinePathCommandTests { private final class Handler: FavoritesOutlineKeyHandling { var selectedFilePath: FavoriteFilePath? + var selectedShareCommand: FavoritesMenuCommand? var performed: [FavoritesMenuCommand] = [] func performPrimaryAction() {} @@ -73,4 +74,34 @@ struct FavoritesOutlinePathCommandTests { view.copyPath(nil) #expect(handler.performed.isEmpty) } + + @Test("A selected saved query or linked file answers File > Share Query… with itself") + func savedQueryAnswersShareQuery() { + let favorite = SQLFavorite(name: "Report", query: "SELECT 1") + let linked = LinkedSQLFavorite( + folderId: UUID(), + fileURL: URL(fileURLWithPath: "/tmp/queries/orders.sql"), + relativePath: "orders.sql", + name: "orders", + mtime: Date(), + fileSize: 10 + ) + for command in [FavoritesMenuCommand.shareFavorite(favorite), .shareLinkedFavorite(linked)] { + let (view, handler) = outline(selecting: nil) + handler.selectedShareCommand = command + + #expect(validates(view, #selector(FavoritesNSOutlineView.shareQuery(_:)))) + view.shareQuery(nil) + #expect(handler.performed == [command]) + } + } + + @Test("Share Query… is dimmed with no saved query selected") + func noSavedQueryDimsShareQuery() { + let (view, handler) = outline(selecting: FavoriteFilePath(absolute: "/tmp/queries/a.sql", relative: "a.sql")) + + #expect(!validates(view, #selector(FavoritesNSOutlineView.shareQuery(_:)))) + view.shareQuery(nil) + #expect(handler.performed.isEmpty) + } } diff --git a/apple/changelog.d/4253.added.1.md b/apple/changelog.d/4253.added.1.md new file mode 100644 index 0000000000..a2b7d7d5af --- /dev/null +++ b/apple/changelog.d/4253.added.1.md @@ -0,0 +1 @@ +Open a shared link in TablePro to get its SQL in a new query tab, without running it. diff --git a/apple/changelog.d/4253.added.2.md b/apple/changelog.d/4253.added.2.md new file mode 100644 index 0000000000..02e2dc8633 --- /dev/null +++ b/apple/changelog.d/4253.added.2.md @@ -0,0 +1 @@ +Share Result masks columns that look sensitive before upload, and lets you keep, mask or remove each column. diff --git a/apple/changelog.d/4253.added.md b/apple/changelog.d/4253.added.md new file mode 100644 index 0000000000..3701e7671d --- /dev/null +++ b/apple/changelog.d/4253.added.md @@ -0,0 +1 @@ +Share a query, a saved query or a result as a link anyone can open in a browser. diff --git a/core/ARCHITECTURE.md b/core/ARCHITECTURE.md index c4770bb521..bb2889d361 100644 --- a/core/ARCHITECTURE.md +++ b/core/ARCHITECTURE.md @@ -49,7 +49,7 @@ core/crates/ | `cli` | no workspace crate | | `ai` | `core`, `net` | | `account` | `core`, `storage` | -| `ffi` | `core`, `session`, `ssh`, `storage`, and every driver behind its default `engines` feature | +| `ffi` | `account`, `core`, `session`, `ssh`, `storage`, and every driver behind its default `engines` feature | | An app, such as `linux/crates/app` | every crate above, and its platform crate | Rules, enforced by review: @@ -84,7 +84,7 @@ A value or a trait the app passes in: | `SecretVault` and `SecretItems`, labelled through `SecretLabeler` and `SecretItemLabeler` | `tablepro_linux_platform::SecretStore`, the Secret Service through oo7 | `Core::with_system_secrets`, the platform's store the core reaches itself (below); `HostSecrets`, a callback interface, for a host with a store of its own | | `SshTunnels` | `tablepro_ssh::SshServices`, the system OpenSSH client | `tablepro_ssh::InProcessSsh`, behind `tablepro-session`'s `in-process-ssh` feature ([ADR 0009](docs/decisions/0009-in-process-ssh-on-windows.md)) | | `ProcessHold` | `gio::Application::hold` | none | -| `RefreshTokenVault`, `BrowserLauncher`, `MachineId` and `AppClient` (`tablepro-account`) | the keyring through `SecretStore`, `gtk::UriLauncher`, `MachineId::derive` of what `tablepro_linux_platform::read_machine_id` reads, `AppClient::LINUX` | none yet | +| `RefreshTokenVault`, `BrowserLauncher`, `MachineId` and `AppClient` (`tablepro-account`) | the keyring through `SecretStore`, `gtk::UriLauncher`, `MachineId::derive` of what `tablepro_linux_platform::read_machine_id` reads, `AppClient::LINUX` | the Core's secret store, the `HostBrowser` callback, `MachineId::derive_machine_guid` of the registry's MachineGuid, `AppClient::WINDOWS` ([ADR 0026](docs/decisions/0026-the-windows-app-signs-in-through-the-ffi.md)) | | `Host` (`tablepro-cli`) | `LinuxHost` in the app crate: the port and switch from GSettings, the token read from the keyring, `NameHasOwner` for a running app, each connection's peer checked by `Host::verify_peer` through `tablepro_net::loopback_peer_is_ours` | none yet | | `ForeignAppDirs` and `ForeignHost` (`tablepro-foreign-import`) | `tablepro_linux_platform::foreign_app_dirs`, the host's XDG directories inside a Flatpak, and `PlainHost`: no other app's keychain | none yet | @@ -98,7 +98,8 @@ A `cfg` split inside a crate: | SQLite | the distribution's | bundled | bundled | | DuckDB's file lock while a file is replaced | fcntl | fcntl | LockFileEx | | SQL Server integrated login | MIT Kerberos, behind the `kerberos` feature | the system's GSS framework, behind the `kerberos` feature | SSPI, NTLM only (winauth) | -| `ffi`'s system secret store | none | none | Credential Manager, generic credentials named `TablePro/connection//`; a secret over a credential's 2,560 bytes goes on in `/1`, `/2`, each part carrying a `TablePro_Parts` attribute with its write, part count and length (`credential_parts`) | +| `ffi`'s system secret store | none | none | Credential Manager, generic credentials named `TablePro/connection//`, `TablePro/` and `TablePro/account//refresh-token`; a secret over a credential's 2,560 bytes goes on in `/1`, `/2`, each part carrying a `TablePro_Parts` attribute with its write, part count and length (`credential_parts`) | +| The account's machine ID (`ffi`) | not read | not read | `HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid`, from the 64-bit view | | OpenSSH transport, askpass helper | yes | yes | not built | | The in-process SSH transport's agent | `SSH_AUTH_SOCK` | `SSH_AUTH_SOCK` | `SSH_AUTH_SOCK`, else `\\.\pipe\openssh-ssh-agent`, then Pageant | | A server's own Unix-domain socket (`tablepro_net::LocalSocketTransport`, `NetworkOption::LocalSocket`) | yes | yes | not built: no engine offers one | @@ -112,6 +113,7 @@ Each boundary error has a stable `code()`, such as `driver.timeout` or `ssh.host `ffi` is the library an app outside Rust loads: the Windows app as a DLL, the Apple apps as a static library in an XCFramework, built without the `engines` feature by `apple/scripts/build-core.sh`. Core ADRs 0002, on the bindings, 0003, on result windows, and 0009, on the macOS slices, hold the reasons. - One UniFFI API. `Core` lists the engines with the family each is listed under, opens a file, connects a saved connection or tests one from a form, and parses a connection URL with `tablepro_core::connection_url`, refusing one that needs a setting its record has no field for. Its `ConnectionLibrary` reads and changes the saved connections, groups, favourites and tags in `connections.json` and stores their secrets, and gives the Apple apps the library's CloudKit records and merges a pull into it (`tablepro_storage::cloudkit`). A `DatabaseSession` reads the catalog one level at a time, writes a table's sorted page at an offset and counts the table, writes a query re-run with a sort (`docs/decisions/0007-sorting-a-result.md`), picks the statement at a caret with the session's grammar (`statement_at`), says what Safe Mode lets an editor run do at the session's level and takes a level saved while it is open (`gate_run`, over `SafeModeLevel::gate`, and `set_safe_mode`), reports and waits on the session's health, opens a `QueryEditor`, and opens a `TableEditor`, which plans a table tab's typed edits into a `RowSave` and runs it (`docs/decisions/0019-row-edits-through-the-ffi.md`). `QueryEditor::run` returns a `QueryRun` at once; the app drains its events after a `RunListener` call, which comes only when no earlier one is waiting to be drained, and the last says which transaction the editor is left in. Each result set is a `ResultSet`, whose `sorted` gives the rows it holds in a column's order. +- `Core::open_account` opens the TablePro account as an `AccountService`, whose `AccountListener` only signals that `status()` changed. It also shares links: `create_share` builds a result's snapshot from a `ResultSet` in Rust, and a table page's `view_sql` is the query its view stands for ([ADR 0027](docs/decisions/0027-share-links.md)). `create_share` takes the share sheet's Keep, Mask or Remove for each column, and `ResultSet::share_masking`, `share_preview` and `share_summary` start the sheet's columns from the detectors and show and count what a share sends ([ADR 0028](docs/decisions/0028-data-masking.md)). `scan_sql_for_secrets`, `scan_columns_for_secrets`, `scan_sql_for_personal_data` and `share_token_from_link` are functions of their own. - The grid reads a `ResultSet` through the C ABI in `src/window_abi.rs`: `tablepro_cursor_fetch` packs the display text of one visible range, and `tablepro_cursor_free` ends the cursor. - The library owns one tokio runtime. Each async export runs on it and is aborted when the foreign side drops the call; a `CancelToken` stops it sooner, since UniFFI cannot cancel. - A result set takes rows as the driver reads them. Each column keeps a kind byte, a raw `i64` and the exact text `tablepro_core::export::value_text` writes, or a binary value's bytes, in chunks of 65,536 rows. A window only cuts and copies. diff --git a/core/crates/account/build.rs b/core/crates/account/build.rs index acf27fb15e..b28df3154d 100644 --- a/core/crates/account/build.rs +++ b/core/crates/account/build.rs @@ -10,7 +10,10 @@ fn main() -> Result<(), Box> { let mut settings = progenitor::GenerationSettings::new(); settings .with_inner_type("crate::cloud_api::Bearer".parse()?) - .with_hooks(progenitor::HooksMode::Expected); + .with_hooks(progenitor::HooksMode::Expected) + // A snapshot's rows go out as the core's raw JSON tokens, and a shared link's rows are never read. + .with_replacement("SnapshotBody", "crate::share::SnapshotBody", std::iter::empty()) + .with_replacement("PublicSnapshot", "crate::share::PublicSnapshot", std::iter::empty()); let tokens = progenitor::Generator::new(&settings).generate_tokens(&spec)?; let out = PathBuf::from(std::env::var("OUT_DIR")?).join("v2.rs"); std::fs::write(out, tokens.to_string())?; diff --git a/core/crates/account/openapi/v2.openapi-3.0.json b/core/crates/account/openapi/v2.openapi-3.0.json index e400b16478..63e3113f71 100644 --- a/core/crates/account/openapi/v2.openapi-3.0.json +++ b/core/crates/account/openapi/v2.openapi-3.0.json @@ -106,6 +106,83 @@ ], "type": "object" }, + "CreateShareBody": { + "additionalProperties": false, + "properties": { + "allow_download": { + "description": "Defaults to true; false needs Pro", + "type": "boolean" + }, + "dialect": { + "description": "The SQL dialect, for display", + "maxLength": 40, + "type": "string" + }, + "expiry": { + "$ref": "#/components/schemas/ShareExpiry", + "description": "Omit for the plan's default_expiry" + }, + "hide_sql": { + "description": "Only with kind result", + "type": "boolean" + }, + "kind": { + "$ref": "#/components/schemas/ShareKind" + }, + "note": { + "maxLength": 2000, + "type": "string" + }, + "password": { + "description": "Needs Pro", + "maxLength": 128, + "type": "string" + }, + "snapshot": { + "$ref": "#/components/schemas/SnapshotBody", + "description": "Required with kind result, refused with kind query" + }, + "sql": { + "description": "Always stored; the viewer hides it with hide_sql. May be empty for a result share, which then shares its data alone", + "maxLength": 262144, + "type": "string" + }, + "team_id": { + "description": "Team TypeID for a team link; needs Pro, a seat, and a team that allows public links", + "type": "string" + }, + "title": { + "maxLength": 200, + "type": "string" + } + }, + "required": [ + "kind", + "sql" + ], + "type": "object" + }, + "CreatedShare": { + "properties": { + "share": { + "$ref": "#/components/schemas/ShareView" + }, + "token": { + "description": "The raw link token, 43 base62 characters", + "type": "string" + }, + "url": { + "description": "SHARE_BASE_URL/token", + "type": "string" + } + }, + "required": [ + "share", + "token", + "url" + ], + "type": "object" + }, "Cycle": { "enum": [ "monthly", @@ -158,12 +235,13 @@ "type": "string" }, "platform": { - "description": "Extensible enum: macos, linux", + "description": "Extensible enum: macos, linux, windows", "example": "macos", "type": "string", "x-extensible-enum": [ "macos", - "linux" + "linux", + "windows" ] } }, @@ -697,14 +775,16 @@ "type": "string" }, "source": { - "description": "Extensible enum: subscription, order, manual, legacy", + "description": "Extensible enum: subscription, order, manual, legacy, redeem_code, education", "example": "subscription", "type": "string", "x-extensible-enum": [ "subscription", "order", "manual", - "legacy" + "legacy", + "redeem_code", + "education" ] }, "status": { @@ -773,12 +853,13 @@ "type": "string" }, "platform": { - "description": "Extensible enum: macos, linux", + "description": "Extensible enum: macos, linux, windows", "example": "macos", "type": "string", "x-extensible-enum": [ "macos", - "linux" + "linux", + "windows" ] } }, @@ -1076,7 +1157,8 @@ "Platform": { "enum": [ "macos", - "linux" + "linux", + "windows" ], "type": "string" }, @@ -1087,6 +1169,9 @@ "example": "VN", "type": "string" }, + "education": { + "$ref": "#/components/schemas/PricingEducation" + }, "plans": { "items": { "$ref": "#/components/schemas/PlanPrice" @@ -1096,7 +1181,20 @@ }, "required": [ "country", - "plans" + "plans", + "education" + ], + "type": "object" + }, + "PricingEducation": { + "properties": { + "open": { + "description": "Whether students and teachers can claim Pro free with a school address now", + "type": "boolean" + } + }, + "required": [ + "open" ], "type": "object" }, @@ -1126,6 +1224,11 @@ "nullable": true, "type": "array" }, + "live_limit": { + "description": "With share_limit_reached: the most live links the plan allows", + "format": "int64", + "type": "integer" + }, "status": { "description": "HTTP status code", "format": "int64", @@ -1149,6 +1252,151 @@ ], "type": "object" }, + "PublicColumn": { + "properties": { + "masked": { + "description": "Extensible enum: full, lastFour, email, hash, null. How the app masked the column's values before sharing; absent for an unmasked column", + "example": "full", + "type": "string", + "x-extensible-enum": [ + "full", + "lastFour", + "email", + "hash", + "null" + ] + }, + "name": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "name", + "type" + ], + "type": "object" + }, + "PublicShare": { + "properties": { + "allow_download": { + "type": "boolean" + }, + "created_at": { + "format": "date-time", + "type": "string" + }, + "dialect": { + "type": "string" + }, + "expires_at": { + "format": "date-time", + "type": "string" + }, + "kind": { + "description": "Extensible enum: query, result", + "example": "query", + "type": "string", + "x-extensible-enum": [ + "query", + "result" + ] + }, + "made_with": { + "description": "Attribution the viewer page shows", + "type": "string" + }, + "note": { + "type": "string" + }, + "snapshot": { + "$ref": "#/components/schemas/PublicSnapshot" + }, + "sql": { + "description": "Absent when the owner hid it", + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "kind", + "title", + "note", + "dialect", + "created_at", + "allow_download", + "made_with" + ], + "type": "object" + }, + "PublicSnapshot": { + "properties": { + "columns": { + "items": { + "$ref": "#/components/schemas/PublicColumn" + }, + "type": "array" + }, + "row_count": { + "description": "The rows the query returned, which may be more than those shown; null when the app cut the result without knowing its total", + "format": "int64", + "nullable": true, + "type": "integer" + }, + "rows": { + "description": "An integer outside plus or minus 2^53-1 arrives as a string of its digits", + "items": { + "items": {}, + "nullable": true, + "type": "array" + }, + "type": "array" + }, + "truncated": { + "type": "boolean" + } + }, + "required": [ + "columns", + "rows", + "row_count", + "truncated" + ], + "type": "object" + }, + "ReportAccepted": { + "type": "object" + }, + "ReportShareBody": { + "additionalProperties": false, + "properties": { + "contact_email": { + "description": "Where staff may answer; optional", + "maxLength": 254, + "type": "string" + }, + "details": { + "maxLength": 2000, + "type": "string" + }, + "reason": { + "$ref": "#/components/schemas/ShareReportReason" + }, + "turnstile_token": { + "description": "The token of the viewer's Turnstile widget, rendered with the action share_report; a missing or rejected one answers human_check_failed", + "maxLength": 2048, + "type": "string" + } + }, + "required": [ + "reason" + ], + "type": "object" + }, "Seats": { "properties": { "available": { @@ -1183,81 +1431,124 @@ ], "type": "object" }, - "Team": { + "ShareExpiry": { + "enum": [ + "1d", + "7d", + "30d", + "never" + ], + "type": "string" + }, + "ShareKind": { + "enum": [ + "query", + "result" + ], + "type": "string" + }, + "ShareLimits": { "properties": { - "has_seat": { - "description": "Whether the caller holds one of the team's seats", - "type": "boolean" - }, - "id": { - "description": "Team TypeID", - "example": "team_01jbvh7pn9e3sv4bzq4rqk4kzh", - "type": "string" - }, - "name": { - "example": "Acme", - "type": "string" - }, - "role": { - "description": "Extensible enum: owner, admin, member. The caller's role", - "example": "owner", + "default_expiry": { + "description": "Extensible enum: 1d, 7d, 30d, never. The expiry a create without one gets", + "example": "1d", "type": "string", "x-extensible-enum": [ - "owner", - "admin", - "member" + "1d", + "7d", + "30d", + "never" ] - } - }, - "required": [ - "id", - "name", - "role", - "has_seat" - ], - "type": "object" - }, - "TeamDetail": { - "properties": { - "has_seat": { - "description": "Whether the caller holds a seat; absent for a team API token", + }, + "disable_download": { + "description": "The plan allows turning viewer downloads off", "type": "boolean" }, - "id": { - "description": "Team TypeID", - "example": "team_01jbvh7pn9e3sv4bzq4rqk4kzh", - "type": "string" + "email_verified": { + "description": "false: every create answers email_unverified", + "type": "boolean" }, - "name": { - "example": "Acme", - "type": "string" + "expiries": { + "description": "The expiries the plan allows", + "items": { + "description": "Extensible enum: 1d, 7d, 30d, never", + "example": "1d", + "type": "string", + "x-extensible-enum": [ + "1d", + "7d", + "30d", + "never" + ] + }, + "type": "array" }, - "role": { - "description": "Extensible enum: owner, admin, member. The caller's role; absent for a team API token", - "example": "owner", + "live": { + "description": "The account's live personal links", + "format": "int64", + "type": "integer" + }, + "live_limit": { + "description": "The most live personal links the plan allows", + "format": "int64", + "type": "integer" + }, + "max_rows": { + "description": "The most snapshot rows the plan keeps; the server cuts the rest", + "format": "int64", + "type": "integer" + }, + "password": { + "description": "The plan allows a link password", + "type": "boolean" + }, + "plan": { + "description": "Extensible enum: free, pro", + "example": "free", "type": "string", "x-extensible-enum": [ - "owner", - "admin", - "member" + "free", + "pro" ] }, - "seats": { - "$ref": "#/components/schemas/Seats" + "sharing_disabled": { + "description": "true: every create answers sharing_disabled", + "type": "boolean" + }, + "team": { + "description": "The plan allows team links", + "type": "boolean" + }, + "teams": { + "description": "The teams the caller holds a seat in, for a team link; empty on Free", + "items": { + "$ref": "#/components/schemas/ShareTeam" + }, + "type": "array" } }, "required": [ - "id", - "name", - "seats" + "plan", + "live", + "live_limit", + "max_rows", + "expiries", + "default_expiry", + "password", + "disable_download", + "team", + "email_verified", + "sharing_disabled", + "teams" ], "type": "object" }, - "TeamList": { + "ShareList": { "properties": { "data": { + "description": "Newest first", "items": { - "$ref": "#/components/schemas/Team" + "$ref": "#/components/schemas/ShareView" }, "type": "array" }, @@ -1271,15 +1562,369 @@ ], "type": "object" }, - "TeamRef": { + "ShareListState": { + "enum": [ + "live", + "all" + ], + "type": "string" + }, + "ShareMaskStyle": { + "enum": [ + "full", + "lastFour", + "email", + "hash", + "null" + ], + "type": "string" + }, + "ShareReportReason": { + "enum": [ + "illegal", + "malware_phishing", + "personal_data", + "spam", + "copyright", + "other" + ], + "type": "string" + }, + "ShareTeam": { "properties": { "id": { - "description": "Team TypeID", - "example": "team_01jbvh7pn9e3sv4bzq4rqk4kzh", + "description": "Team TypeID, the create's team_id", "type": "string" }, - "name": { - "example": "Acme", + "live": { + "description": "The team's live links", + "format": "int64", + "type": "integer" + }, + "live_limit": { + "description": "The most live links a team may hold", + "format": "int64", + "type": "integer" + }, + "name": { + "type": "string" + }, + "public_links": { + "description": "false: the team turned public links off, and a team link answers team_sharing_disabled", + "type": "boolean" + } + }, + "required": [ + "id", + "name", + "live", + "live_limit", + "public_links" + ], + "type": "object" + }, + "ShareView": { + "properties": { + "allow_download": { + "description": "The viewer offers CSV and JSON downloads", + "type": "boolean" + }, + "created_at": { + "format": "date-time", + "type": "string" + }, + "dialect": { + "description": "The SQL dialect, for display", + "type": "string" + }, + "expires_at": { + "description": "Absent for a link that never expires", + "format": "date-time", + "type": "string" + }, + "has_password": { + "type": "boolean" + }, + "has_snapshot": { + "description": "true for a result share", + "type": "boolean" + }, + "hide_sql": { + "description": "The viewer shows the result without its SQL", + "type": "boolean" + }, + "id": { + "description": "Share TypeID", + "example": "shr_01jbvh7pn9e3sv4bzq4rqk4kzh", + "type": "string" + }, + "kind": { + "description": "Extensible enum: query, result", + "example": "query", + "type": "string", + "x-extensible-enum": [ + "query", + "result" + ] + }, + "note": { + "type": "string" + }, + "removed_at": { + "format": "date-time", + "type": "string" + }, + "removed_reason": { + "description": "With state removed: why TablePro removed the link", + "type": "string" + }, + "revoked_at": { + "format": "date-time", + "type": "string" + }, + "row_count": { + "description": "With a snapshot: the rows the query returned, which may be more than those shared; null when the app cut the result without knowing its total", + "format": "int64", + "nullable": true, + "type": "integer" + }, + "scope": { + "description": "Extensible enum: account, team. account: a personal link; team: a team link", + "example": "account", + "type": "string", + "x-extensible-enum": [ + "account", + "team" + ] + }, + "sql": { + "description": "Only in the answer for one share, never in a list", + "type": "string" + }, + "state": { + "description": "Extensible enum: live, expired, revoked, removed. live, or why the link no longer resolves", + "example": "live", + "type": "string", + "x-extensible-enum": [ + "live", + "expired", + "revoked", + "removed" + ] + }, + "suspended": { + "description": "true while the team turned public links off or staff turned the creator's sharing off: the link does not resolve and has no url, and comes back when the switch is on again", + "type": "boolean" + }, + "suspended_by": { + "description": "Extensible enum: account, team, team_deleted. With suspended: account (staff turned the creator's sharing off), team (the team turned public links off) or team_deleted (its owner deleted the team); team_deleted wins, then account", + "example": "account", + "type": "string", + "x-extensible-enum": [ + "account", + "team", + "team_deleted" + ] + }, + "team_id": { + "description": "Team TypeID, for a team link", + "type": "string" + }, + "title": { + "type": "string" + }, + "truncated": { + "description": "With a snapshot: true when the server kept fewer rows than row_count", + "type": "boolean" + }, + "updated_at": { + "format": "date-time", + "type": "string" + }, + "url": { + "description": "The link; present only for a caller who manages the share, and only while the server can rebuild it", + "type": "string" + }, + "view_count": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "id", + "kind", + "scope", + "title", + "note", + "dialect", + "has_snapshot", + "hide_sql", + "allow_download", + "has_password", + "state", + "suspended", + "view_count", + "created_at", + "updated_at" + ], + "type": "object" + }, + "SnapshotBody": { + "additionalProperties": false, + "properties": { + "columns": { + "items": { + "$ref": "#/components/schemas/SnapshotColumnBody" + }, + "maxItems": 100, + "minItems": 1, + "type": "array" + }, + "more_rows": { + "description": "The app holds rows past those sent; with no row_count above them, the total is stored as unknown", + "type": "boolean" + }, + "row_count": { + "description": "The rows the query returned, when more than those sent", + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "rows": { + "description": "One array per row, one value per column. The server keeps the plan's max_rows and cuts the rest", + "items": { + "items": {}, + "nullable": true, + "type": "array" + }, + "type": "array" + } + }, + "required": [ + "columns", + "rows" + ], + "type": "object" + }, + "SnapshotColumnBody": { + "additionalProperties": false, + "properties": { + "masked": { + "$ref": "#/components/schemas/ShareMaskStyle", + "description": "How the app masked the column's values before sharing; omit for an unmasked column" + }, + "name": { + "maxLength": 256, + "type": "string" + }, + "type": { + "description": "The column's database type, for display and alignment", + "maxLength": 256, + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "Team": { + "properties": { + "has_seat": { + "description": "Whether the caller holds one of the team's seats", + "type": "boolean" + }, + "id": { + "description": "Team TypeID", + "example": "team_01jbvh7pn9e3sv4bzq4rqk4kzh", + "type": "string" + }, + "name": { + "example": "Acme", + "type": "string" + }, + "role": { + "description": "Extensible enum: owner, admin, member. The caller's role", + "example": "owner", + "type": "string", + "x-extensible-enum": [ + "owner", + "admin", + "member" + ] + } + }, + "required": [ + "id", + "name", + "role", + "has_seat" + ], + "type": "object" + }, + "TeamDetail": { + "properties": { + "has_seat": { + "description": "Whether the caller holds a seat; absent for a team API token", + "type": "boolean" + }, + "id": { + "description": "Team TypeID", + "example": "team_01jbvh7pn9e3sv4bzq4rqk4kzh", + "type": "string" + }, + "name": { + "example": "Acme", + "type": "string" + }, + "role": { + "description": "Extensible enum: owner, admin, member. The caller's role; absent for a team API token", + "example": "owner", + "type": "string", + "x-extensible-enum": [ + "owner", + "admin", + "member" + ] + }, + "seats": { + "$ref": "#/components/schemas/Seats" + } + }, + "required": [ + "id", + "name", + "seats" + ], + "type": "object" + }, + "TeamList": { + "properties": { + "data": { + "items": { + "$ref": "#/components/schemas/Team" + }, + "type": "array" + }, + "next_cursor": { + "description": "Pass as cursor for the next page; absent on the last page", + "type": "string" + } + }, + "required": [ + "data" + ], + "type": "object" + }, + "TeamRef": { + "properties": { + "id": { + "description": "Team TypeID", + "example": "team_01jbvh7pn9e3sv4bzq4rqk4kzh", + "type": "string" + }, + "name": { + "example": "Acme", "type": "string" } }, @@ -1288,61 +1933,1583 @@ "name" ], "type": "object" - } - }, - "securitySchemes": { - "oauth": { - "description": "An access token from the TablePro app's sign-in.", - "flows": { - "authorizationCode": { - "authorizationUrl": "https://account.tablepro.app/oauth/authorize", - "refreshUrl": "https://account.tablepro.app/oauth/token", - "scopes": { - "app": "Use the API as the TablePro app" + }, + "UpdateShareBody": { + "additionalProperties": false, + "properties": { + "allow_download": { + "description": "false needs Pro", + "type": "boolean" + }, + "clear_password": { + "description": "Remove the password", + "type": "boolean" + }, + "expiry": { + "$ref": "#/components/schemas/ShareExpiry", + "description": "A new expiry from now. On an expired link it revives the link when a live slot is free" + }, + "hide_sql": { + "description": "Only on a result share", + "type": "boolean" + }, + "note": { + "maxLength": 2000, + "type": "string" + }, + "password": { + "description": "A new password; needs Pro", + "maxLength": 128, + "minLength": 1, + "type": "string" + }, + "title": { + "maxLength": 200, + "type": "string" + } + }, + "type": "object" + } + }, + "securitySchemes": { + "oauth": { + "description": "An access token from the TablePro app's sign-in.", + "flows": { + "authorizationCode": { + "authorizationUrl": "https://account.tablepro.app/oauth/authorize", + "refreshUrl": "https://account.tablepro.app/oauth/token", + "scopes": { + "app": "Use the API as the TablePro app" + }, + "tokenUrl": "https://account.tablepro.app/oauth/token" + } + }, + "type": "oauth2" + }, + "team_token": { + "bearerFormat": "tpt_...", + "description": "A team API token, created by the team's owner or admins in the portal.", + "scheme": "bearer", + "type": "http" + } + } + }, + "info": { + "title": "TablePro API", + "version": "2" + }, + "openapi": "3.0.3", + "paths": { + "/checkouts": { + "post": { + "description": "Creates Polar's checkout for a guest. The price is the catalog's, less the discount code's discount or, without a code, the regional discount GET /pricing shows; tax and currency follow the caller's IP address.", + "operationId": "create-checkout", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CheckoutRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Checkout" + } + } + }, + "description": "Created", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "summary": "Start a checkout", + "tags": [ + "Checkout" + ] + } + }, + "/devices": { + "get": { + "description": "Every device that was not removed, oldest first.", + "operationId": "list-devices", + "parameters": [ + { + "description": "Devices per page", + "explode": false, + "in": "query", + "name": "limit", + "schema": { + "default": 50, + "description": "Devices per page", + "format": "int64", + "maximum": 200, + "minimum": 1, + "type": "integer" + } + }, + { + "description": "next_cursor of the previous page; absent for the first page", + "explode": false, + "in": "query", + "name": "cursor", + "schema": { + "description": "next_cursor of the previous page; absent for the first page", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeviceList" + } + } + }, + "description": "OK", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "code": "unauthorized", + "detail": "The token is invalid or has expired.", + "status": 401, + "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/unauthorized" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "The token lacks the app scope.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "422": { + "content": { + "application/json": { + "examples": { + "validation_failed": { + "summary": "Validation failed", + "value": { + "code": "validation_failed", + "detail": "validation failed", + "errors": [ + { + "location": "query.cursor", + "message": "expected the next_cursor of a previous page", + "value": "abc" + } + ], + "status": 422, + "title": "Validation failed", + "type": "https://api.tablepro.app/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "code": "rate_limited", + "detail": "Too many requests. Try again later.", + "status": 429, + "title": "Rate limited", + "type": "https://api.tablepro.app/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "The account's devices", + "tags": [ + "Devices" + ] + }, + "post": { + "description": "Registers the machine the app runs on, or updates the account's device for it, and binds the refresh token family of the caller's sign-in to the device: access tokens refreshed afterwards carry dev, which the entitlement needs. Answers 201 for a new device and 200 when the machine was registered already. A sign-in already bound to another device is refused. 10 an hour per account.", + "operationId": "register-device", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeviceRegistration" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Device" + } + } + }, + "description": "The machine was registered already; its name, platform and versions are updated", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Device" + } + } + }, + "description": "Created", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "code": "unauthorized", + "detail": "The token is invalid or has expired.", + "status": 401, + "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/unauthorized" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "The token lacks the app scope.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + }, + "forbidden_2": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "This sign-in belongs to another device. Sign in again on this one.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "422": { + "content": { + "application/json": { + "examples": { + "validation_failed": { + "summary": "Validation failed", + "value": { + "code": "validation_failed", + "detail": "validation failed", + "errors": [ + { + "location": "body.machine_id", + "message": "expected string to match pattern ^[0-9a-f]{64}$", + "value": "MAC-1" + } + ], + "status": 422, + "title": "Validation failed", + "type": "https://api.tablepro.app/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "code": "rate_limited", + "detail": "Too many requests. Try again later.", + "status": 429, + "title": "Rate limited", + "type": "https://api.tablepro.app/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "Register this device", + "tags": [ + "Devices" + ] + } + }, + "/devices/{device_id}": { + "delete": { + "description": "Frees its license slot and revokes its refresh tokens, so the app on it signs out at its next refresh. Its entitlement stays valid until it expires. A device with an offline file that has not expired (offline_until) keeps its slot until its last valid file expires and is refused with offline_file_active.", + "operationId": "delete-device", + "parameters": [ + { + "description": "Device TypeID", + "in": "path", + "name": "device_id", + "required": true, + "schema": { + "description": "Device TypeID", + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "No Content", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "code": "unauthorized", + "detail": "The token is invalid or has expired.", + "status": 401, + "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/unauthorized" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "The token lacks the app scope.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "examples": { + "not_found": { + "summary": "Not found", + "value": { + "code": "not_found", + "detail": "This account has no such device.", + "status": 404, + "title": "Not found", + "type": "https://api.tablepro.app/problems/not-found" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "409": { + "content": { + "application/json": { + "examples": { + "offline_file_active": { + "summary": "Offline file active", + "value": { + "code": "offline_file_active", + "detail": "This device's offline file has not expired, so it keeps its license slot until offline_until.", + "status": 409, + "title": "Offline file active", + "type": "https://api.tablepro.app/problems/offline-file-active" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Conflict" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "code": "rate_limited", + "detail": "Too many requests. Try again later.", + "status": 429, + "title": "Rate limited", + "type": "https://api.tablepro.app/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "Remove a device", + "tags": [ + "Devices" + ] + }, + "patch": { + "operationId": "update-device", + "parameters": [ + { + "description": "Device TypeID", + "in": "path", + "name": "device_id", + "required": true, + "schema": { + "description": "Device TypeID", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DeviceUpdate" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Device" + } + } + }, + "description": "OK", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "code": "unauthorized", + "detail": "The token is invalid or has expired.", + "status": 401, + "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/unauthorized" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "The token lacks the app scope.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "examples": { + "not_found": { + "summary": "Not found", + "value": { + "code": "not_found", + "detail": "This account has no such device.", + "status": 404, + "title": "Not found", + "type": "https://api.tablepro.app/problems/not-found" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "422": { + "content": { + "application/json": { + "examples": { + "validation_failed": { + "summary": "Validation failed", + "value": { + "code": "validation_failed", + "detail": "validation failed", + "errors": [ + { + "location": "body.name", + "message": "expected a name of 1 to 100 characters", + "value": "\t" + } + ], + "status": 422, + "title": "Validation failed", + "type": "https://api.tablepro.app/problems/validation-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "code": "rate_limited", + "detail": "Too many requests. Try again later.", + "status": 429, + "title": "Rate limited", + "type": "https://api.tablepro.app/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "Rename a device", + "tags": [ + "Devices" + ] + } + }, + "/devices/{device_id}/entitlement": { + "post": { + "description": "Answers only for the device the caller's token is bound to: register the device, refresh the token, then ask. When the account has a license and the device holds none of its 3 slots, the device takes one, or the answer is device_limit_reached with the devices that hold them. An account without licenses gets a token with no features.", + "operationId": "issue-entitlement", + "parameters": [ + { + "description": "Device TypeID; must be the device the caller's token is bound to (its dev claim)", + "in": "path", + "name": "device_id", + "required": true, + "schema": { + "description": "Device TypeID; must be the device the caller's token is bound to (its dev claim)", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EntitlementRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Entitlement" + } + } + }, + "description": "OK", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "code": "unauthorized", + "detail": "The token is invalid or has expired.", + "status": 401, + "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/unauthorized" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "examples": { + "account_locked": { + "summary": "Account locked", + "value": { + "code": "account_locked", + "detail": "This account is locked.", + "status": 403, + "title": "Account locked", + "type": "https://api.tablepro.app/problems/account-locked" + } + }, + "device_revoked": { + "summary": "Device revoked", + "value": { + "code": "device_revoked", + "detail": "This device was removed from the account. Sign in again to use it.", + "status": 403, + "title": "Device revoked", + "type": "https://api.tablepro.app/problems/device-revoked" + } + }, + "forbidden": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "The token lacks the app scope.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + }, + "forbidden_2": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "This token is not bound to that device. Register this device, refresh the token, and ask again.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "409": { + "content": { + "application/json": { + "examples": { + "device_limit_reached": { + "summary": "Device limit reached", + "value": { + "code": "device_limit_reached", + "detail": "The license is already used on 3 devices.", + "devices": [ + { + "app_version": "2.0.0", + "created_at": "2026-10-01T09:00:00Z", + "id": "dev_01k8djrfaefw08m00000000001", + "last_seen_at": "2026-10-21T09:00:00Z", + "licensed_at": "2026-10-01T09:00:00Z", + "machine_id": "0000000000000000000000000000000000000000000000000000000000000001", + "name": "Ada's MacBook Pro", + "os_version": "26.0", + "platform": "macos" + }, + { + "app_version": "2.0.0", + "created_at": "2026-10-02T09:00:00Z", + "id": "dev_01k8djrfaefw08m00000000002", + "last_seen_at": "2026-10-22T09:00:00Z", + "licensed_at": "2026-10-02T09:00:00Z", + "machine_id": "0000000000000000000000000000000000000000000000000000000000000002", + "name": "Studio", + "offline_until": "2027-10-02T09:00:00Z", + "os_version": "26.0", + "platform": "macos" + }, + { + "app_version": "2.0.0", + "created_at": "2026-10-03T09:00:00Z", + "id": "dev_01k8djrfaefw08m00000000003", + "last_seen_at": "2026-10-23T09:00:00Z", + "licensed_at": "2026-10-03T09:00:00Z", + "machine_id": "0000000000000000000000000000000000000000000000000000000000000003", + "name": "Workstation", + "os_version": "Fedora 43", + "platform": "linux" + } + ], + "status": 409, + "title": "Device limit reached", + "type": "https://api.tablepro.app/problems/device-limit-reached" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Conflict" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "code": "rate_limited", + "detail": "Too many requests. Try again later.", + "status": 429, + "title": "Rate limited", + "type": "https://api.tablepro.app/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "An entitlement for this device", + "tags": [ + "Devices" + ] + } + }, + "/discounts/preview": { + "post": { + "description": "Answers whether checkout would apply the code, and how much it takes off. An unknown code is not an error.", + "operationId": "preview-discount", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiscountPreviewRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiscountPreview" + } + } + }, + "description": "OK", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "summary": "Check a discount code", + "tags": [ + "Checkout" + ] + } + }, + "/me": { + "get": { + "description": "The account, the teams it belongs to with its role and seat in each, and the licenses whose features it can use.", + "operationId": "get-me", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Me" + } + } + }, + "description": "OK", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "code": "unauthorized", + "detail": "The token is invalid or has expired.", + "status": 401, + "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/unauthorized" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "The token lacks the app scope.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "429": { + "content": { + "application/json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "code": "rate_limited", + "detail": "Too many requests. Try again later.", + "status": 429, + "title": "Rate limited", + "type": "https://api.tablepro.app/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "The signed-in account", + "tags": [ + "Account" + ] + } + }, + "/newsletter/stats": { + "get": { + "operationId": "get-newsletter-stats", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewsletterStats" + } + } + }, + "description": "OK" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Service Unavailable" + } + }, + "summary": "Count the newsletter's subscribers", + "tags": [ + "Newsletter" + ] + } + }, + "/newsletter/subscriptions": { + "post": { + "description": "Emails a confirmation link. Answers 202 whether or not the address is subscribed and whether or not the Turnstile check passed, so it reveals nothing.", + "operationId": "create-newsletter-subscription", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NewsletterSubscriptionRequest" + } + } + }, + "required": true + }, + "responses": { + "202": { + "description": "Accepted", + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } }, - "tokenUrl": "https://account.tablepro.app/oauth/token" + "description": "Internal Server Error" } }, - "type": "oauth2" - }, - "team_token": { - "bearerFormat": "tpt_...", - "description": "A team API token, created by the team's owner or admins in the portal.", - "scheme": "bearer", - "type": "http" + "summary": "Sign up for the newsletter", + "tags": [ + "Newsletter" + ] } - } - }, - "info": { - "title": "TablePro API", - "version": "2" - }, - "openapi": "3.0.3", - "paths": { - "/checkouts": { - "post": { - "description": "Creates Polar's checkout for a guest. The price is the catalog's, less the discount code's discount or, without a code, the regional discount GET /pricing shows; tax and currency follow the caller's IP address.", - "operationId": "create-checkout", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CheckoutRequest" + }, + "/pricing": { + "get": { + "description": "What checkout charges the caller without a discount code, regional discount included. Answered for the caller's country, so it is never cached.", + "operationId": "get-pricing", + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pricing" + } + } + }, + "description": "OK", + "headers": { + "Cache-Control": { + "schema": { + "type": "string" + } } } }, - "required": true + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unprocessable Entity" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } }, + "summary": "Prices in the caller's country", + "tags": [ + "Checkout" + ] + } + }, + "/share-limits": { + "get": { + "description": "What the share sheet offers: the plan, its live link count and limit, row cap, expiries and options, and whether the account may create at all.", + "operationId": "get-share-limits", "responses": { - "201": { + "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Checkout" + "$ref": "#/components/schemas/ShareLimits" } } }, - "description": "Created", + "description": "OK", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -1355,19 +3522,65 @@ } } }, - "422": { + "401": { + "content": { + "application/json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "code": "unauthorized", + "detail": "The token is invalid or has expired.", + "status": 401, + "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/unauthorized" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "403": { "content": { "application/json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "The token lacks the app scope.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Unprocessable Entity" + "description": "Forbidden" }, "429": { "content": { "application/json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "code": "rate_limited", + "detail": "Too many requests. Try again later.", + "status": 429, + "title": "Rate limited", + "type": "https://api.tablepro.app/problems/rate-limited" + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } @@ -1400,38 +3613,40 @@ "description": "Internal Server Error" } }, - "summary": "Start a checkout", + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "The caller's plan limits for shared links", "tags": [ - "Checkout" + "Shares" ] } }, - "/devices": { + "/shared/{token}": { "get": { - "description": "Every device that was not removed, oldest first.", - "operationId": "list-devices", + "description": "No authentication. An unknown, revoked, removed, expired or suspended link, a malformed token and a deleted team's link all answer 404 alike. Password guesses are limited per link and client, and per link.", + "operationId": "get-shared", "parameters": [ { - "description": "Devices per page", - "explode": false, - "in": "query", - "name": "limit", + "description": "The link token", + "in": "path", + "name": "token", + "required": true, "schema": { - "default": 50, - "description": "Devices per page", - "format": "int64", - "maximum": 200, - "minimum": 1, - "type": "integer" + "description": "The link token", + "type": "string" } }, { - "description": "next_cursor of the previous page; absent for the first page", - "explode": false, - "in": "query", - "name": "cursor", + "description": "The link password, for a password-protected link", + "in": "header", + "name": "X-Share-Password", "schema": { - "description": "next_cursor of the previous page; absent for the first page", + "description": "The link password, for a password-protected link", "type": "string" } } @@ -1441,11 +3656,11 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeviceList" + "$ref": "#/components/schemas/PublicShare" } } }, - "description": "OK", + "description": "The shared link", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -1462,14 +3677,24 @@ "content": { "application/json": { "examples": { - "unauthorized": { - "summary": "Unauthorized", + "share_password_required": { + "summary": "Share password required", "value": { - "code": "unauthorized", - "detail": "The token is invalid or has expired.", + "code": "share_password_required", + "detail": "This link is password protected.", "status": 401, - "title": "Unauthorized", - "type": "https://api.tablepro.app/problems/unauthorized" + "title": "Share password required", + "type": "https://api.tablepro.app/problems/share-password-required" + } + }, + "share_password_wrong": { + "summary": "Share password wrong", + "value": { + "code": "share_password_wrong", + "detail": "That password is not correct.", + "status": 401, + "title": "Share password wrong", + "type": "https://api.tablepro.app/problems/share-password-wrong" } } }, @@ -1480,18 +3705,18 @@ }, "description": "Unauthorized" }, - "403": { + "404": { "content": { "application/json": { "examples": { - "forbidden": { - "summary": "Forbidden", + "not_found": { + "summary": "Not found", "value": { - "code": "forbidden", - "detail": "The token lacks the app scope.", - "status": 403, - "title": "Forbidden", - "type": "https://api.tablepro.app/problems/forbidden" + "code": "not_found", + "detail": "No such share.", + "status": 404, + "title": "Not found", + "type": "https://api.tablepro.app/problems/not-found" } } }, @@ -1500,30 +3725,11 @@ } } }, - "description": "Forbidden" + "description": "Not Found" }, "422": { "content": { "application/json": { - "examples": { - "validation_failed": { - "summary": "Validation failed", - "value": { - "code": "validation_failed", - "detail": "validation failed", - "errors": [ - { - "location": "query.cursor", - "message": "expected the next_cursor of a previous page", - "value": "abc" - } - ], - "status": 422, - "title": "Validation failed", - "type": "https://api.tablepro.app/problems/validation-failed" - } - } - }, "schema": { "$ref": "#/components/schemas/Problem" } @@ -1576,64 +3782,72 @@ } }, "description": "Internal Server Error" + }, + "503": { + "content": { + "application/json": { + "examples": { + "service_unavailable": { + "summary": "Service unavailable", + "value": { + "code": "service_unavailable", + "detail": "This shared result is busy. Try again in a moment.", + "status": 503, + "title": "Service unavailable", + "type": "https://api.tablepro.app/problems/service-unavailable" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Service Unavailable" } }, - "security": [ - { - "oauth": [ - "app" - ] - } - ], - "summary": "The account's devices", + "summary": "Read a shared link", "tags": [ - "Devices" + "Shares" ] - }, + } + }, + "/shared/{token}/report": { "post": { - "description": "Registers the machine the app runs on, or updates the account's device for it, and binds the refresh token family of the caller's sign-in to the device: access tokens refreshed afterwards carry dev, which the entitlement needs. Answers 201 for a new device and 200 when the machine was registered already. A sign-in already bound to another device is refused. 10 an hour per account.", - "operationId": "register-device", + "description": "No authentication; a Turnstile token instead. Answers 202 for any token, so a report never tells whether a link exists. 10 an hour per client.", + "operationId": "report-shared", + "parameters": [ + { + "description": "The link token", + "in": "path", + "name": "token", + "required": true, + "schema": { + "description": "The link token", + "type": "string" + } + } + ], "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeviceRegistration" + "$ref": "#/components/schemas/ReportShareBody" } } }, "required": true }, "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Device" - } - } - }, - "description": "The machine was registered already; its name, platform and versions are updated", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - } - }, - "201": { + "202": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Device" + "$ref": "#/components/schemas/ReportAccepted" } } }, - "description": "Created", + "description": "Accepted", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -1646,50 +3860,18 @@ } } }, - "401": { - "content": { - "application/json": { - "examples": { - "unauthorized": { - "summary": "Unauthorized", - "value": { - "code": "unauthorized", - "detail": "The token is invalid or has expired.", - "status": 401, - "title": "Unauthorized", - "type": "https://api.tablepro.app/problems/unauthorized" - } - } - }, - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Unauthorized" - }, "403": { "content": { "application/json": { "examples": { - "forbidden": { - "summary": "Forbidden", - "value": { - "code": "forbidden", - "detail": "The token lacks the app scope.", - "status": 403, - "title": "Forbidden", - "type": "https://api.tablepro.app/problems/forbidden" - } - }, - "forbidden_2": { - "summary": "Forbidden", + "human_check_failed": { + "summary": "Human check failed", "value": { - "code": "forbidden", - "detail": "This sign-in belongs to another device. Sign in again on this one.", + "code": "human_check_failed", + "detail": "The check that a person is reporting did not pass. Complete it again, then send the report.", "status": 403, - "title": "Forbidden", - "type": "https://api.tablepro.app/problems/forbidden" + "title": "Human check failed", + "type": "https://api.tablepro.app/problems/human-check-failed" } } }, @@ -1703,25 +3885,6 @@ "422": { "content": { "application/json": { - "examples": { - "validation_failed": { - "summary": "Validation failed", - "value": { - "code": "validation_failed", - "detail": "validation failed", - "errors": [ - { - "location": "body.machine_id", - "message": "expected string to match pattern ^[0-9a-f]{64}$", - "value": "MAC-1" - } - ], - "status": 422, - "title": "Validation failed", - "type": "https://api.tablepro.app/problems/validation-failed" - } - } - }, "schema": { "$ref": "#/components/schemas/Problem" } @@ -1776,38 +3939,73 @@ "description": "Internal Server Error" } }, - "security": [ - { - "oauth": [ - "app" - ] - } - ], - "summary": "Register this device", + "summary": "Report a shared link", "tags": [ - "Devices" + "Shares" ] } }, - "/devices/{device_id}": { - "delete": { - "description": "Frees its license slot and revokes its refresh tokens, so the app on it signs out at its next refresh. Its entitlement stays valid until it expires. A device with an offline file that has not expired (offline_until) keeps its slot until its last valid file expires and is refused with offline_file_active.", - "operationId": "delete-device", + "/shares": { + "get": { + "description": "The caller's personal links, or with team a team's links: every one for its owner and admins, its own for a seated member, seat_required for a member without a seat. Newest first, without sql.", + "operationId": "list-shares", "parameters": [ { - "description": "Device TypeID", - "in": "path", - "name": "device_id", - "required": true, + "description": "Team TypeID: that team's links, every one for its owner and admins, a seated member's own for a member; omit for the caller's personal links", + "explode": false, + "in": "query", + "name": "team", "schema": { - "description": "Device TypeID", + "description": "Team TypeID: that team's links, every one for its owner and admins, a seated member's own for a member; omit for the caller's personal links", + "maxLength": 64, + "type": "string" + } + }, + { + "description": "live: only live links; all: every state", + "explode": false, + "in": "query", + "name": "state", + "schema": { + "$ref": "#/components/schemas/ShareListState", + "default": "all", + "description": "live: only live links; all: every state" + } + }, + { + "description": "next_cursor of the previous page; absent for the first page", + "explode": false, + "in": "query", + "name": "cursor", + "schema": { + "description": "next_cursor of the previous page; absent for the first page", + "maxLength": 64, "type": "string" } + }, + { + "explode": false, + "in": "query", + "name": "limit", + "schema": { + "default": 50, + "format": "int64", + "maximum": 200, + "minimum": 1, + "type": "integer" + } } ], "responses": { - "204": { - "description": "No Content", + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareList" + } + } + }, + "description": "OK", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -1855,6 +4053,16 @@ "title": "Forbidden", "type": "https://api.tablepro.app/problems/forbidden" } + }, + "seat_required": { + "summary": "Seat required", + "value": { + "code": "seat_required", + "detail": "A team link needs a seat in the team.", + "status": 403, + "title": "Seat required", + "type": "https://api.tablepro.app/problems/seat-required" + } } }, "schema": { @@ -1872,7 +4080,7 @@ "summary": "Not found", "value": { "code": "not_found", - "detail": "This account has no such device.", + "detail": "No such share.", "status": 404, "title": "Not found", "type": "https://api.tablepro.app/problems/not-found" @@ -1886,18 +4094,24 @@ }, "description": "Not Found" }, - "409": { + "422": { "content": { "application/json": { "examples": { - "offline_file_active": { - "summary": "Offline file active", + "validation_failed": { + "summary": "Validation failed", "value": { - "code": "offline_file_active", - "detail": "This device's offline file has not expired, so it keeps its license slot until offline_until.", - "status": 409, - "title": "Offline file active", - "type": "https://api.tablepro.app/problems/offline-file-active" + "code": "validation_failed", + "detail": "validation failed", + "errors": [ + { + "location": "query.cursor", + "message": "expected the next_cursor of the previous page" + } + ], + "status": 422, + "title": "Validation failed", + "type": "https://api.tablepro.app/problems/validation-failed" } } }, @@ -1906,16 +4120,6 @@ } } }, - "description": "Conflict" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, "description": "Unprocessable Entity" }, "429": { @@ -1972,45 +4176,34 @@ ] } ], - "summary": "Remove a device", + "summary": "List shared links", "tags": [ - "Devices" + "Shares" ] }, - "patch": { - "operationId": "update-device", - "parameters": [ - { - "description": "Device TypeID", - "in": "path", - "name": "device_id", - "required": true, - "schema": { - "description": "Device TypeID", - "type": "string" - } - } - ], + "post": { + "description": "Needs a verified email. Free allows 5 live personal links, expiry 1d, 7d or 30d and no password, no team and no download switch; Pro allows 1,000 and every option. Rows past the plan's max_rows are cut and truncated is set. 60 an hour and 300 a day per account.", + "operationId": "create-share", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DeviceUpdate" + "$ref": "#/components/schemas/CreateShareBody" } } }, "required": true }, "responses": { - "200": { + "201": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Device" + "$ref": "#/components/schemas/CreatedShare" } } }, - "description": "OK", + "description": "Created", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -2049,6 +4242,16 @@ "content": { "application/json": { "examples": { + "email_unverified": { + "summary": "Email unverified", + "value": { + "code": "email_unverified", + "detail": "Verify your email address to share links.", + "status": 403, + "title": "Email unverified", + "type": "https://api.tablepro.app/problems/email-unverified" + } + }, "forbidden": { "summary": "Forbidden", "value": { @@ -2058,6 +4261,46 @@ "title": "Forbidden", "type": "https://api.tablepro.app/problems/forbidden" } + }, + "pro_required": { + "summary": "Pro required", + "value": { + "code": "pro_required", + "detail": "This option needs TablePro Pro.", + "status": 403, + "title": "Pro required", + "type": "https://api.tablepro.app/problems/pro-required" + } + }, + "seat_required": { + "summary": "Seat required", + "value": { + "code": "seat_required", + "detail": "A team link needs a seat in the team.", + "status": 403, + "title": "Seat required", + "type": "https://api.tablepro.app/problems/seat-required" + } + }, + "sharing_disabled": { + "summary": "Sharing disabled", + "value": { + "code": "sharing_disabled", + "detail": "Sharing is turned off for this account.", + "status": 403, + "title": "Sharing disabled", + "type": "https://api.tablepro.app/problems/sharing-disabled" + } + }, + "team_sharing_disabled": { + "summary": "Team sharing disabled", + "value": { + "code": "team_sharing_disabled", + "detail": "Public links are turned off for this team.", + "status": 403, + "title": "Team sharing disabled", + "type": "https://api.tablepro.app/problems/team-sharing-disabled" + } } }, "schema": { @@ -2075,7 +4318,7 @@ "summary": "Not found", "value": { "code": "not_found", - "detail": "This account has no such device.", + "detail": "No such share.", "status": 404, "title": "Not found", "type": "https://api.tablepro.app/problems/not-found" @@ -2089,25 +4332,41 @@ }, "description": "Not Found" }, + "409": { + "content": { + "application/json": { + "examples": { + "share_limit_reached": { + "summary": "Share limit reached", + "value": { + "code": "share_limit_reached", + "detail": "You have reached your plan's live link limit.", + "live_limit": 5, + "status": 409, + "title": "Share limit reached", + "type": "https://api.tablepro.app/problems/share-limit-reached" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Conflict" + }, "422": { "content": { "application/json": { "examples": { - "validation_failed": { - "summary": "Validation failed", + "snapshot_too_large": { + "summary": "Snapshot too large", "value": { - "code": "validation_failed", - "detail": "validation failed", - "errors": [ - { - "location": "body.name", - "message": "expected a name of 1 to 100 characters", - "value": "\t" - } - ], - "status": 422, - "title": "Validation failed", - "type": "https://api.tablepro.app/problems/validation-failed" + "code": "snapshot_too_large", + "detail": "This result is too large to share.", + "status": 422, + "title": "Snapshot too large", + "type": "https://api.tablepro.app/problems/snapshot-too-large" } } }, @@ -2131,6 +4390,16 @@ "title": "Rate limited", "type": "https://api.tablepro.app/problems/rate-limited" } + }, + "rate_limited_2": { + "summary": "Rate limited", + "value": { + "code": "rate_limited", + "detail": "Too many requests. Try again later.", + "status": 429, + "title": "Rate limited", + "type": "https://api.tablepro.app/problems/rate-limited" + } } }, "schema": { @@ -2172,48 +4441,32 @@ ] } ], - "summary": "Rename a device", + "summary": "Create a shared link", "tags": [ - "Devices" + "Shares" ] } }, - "/devices/{device_id}/entitlement": { - "post": { - "description": "Answers only for the device the caller's token is bound to: register the device, refresh the token, then ask. When the account has a license and the device holds none of its 3 slots, the device takes one, or the answer is device_limit_reached with the devices that hold them. An account without licenses gets a token with no features.", - "operationId": "issue-entitlement", + "/shares/{share_id}": { + "delete": { + "description": "The link stops working at once. Revoking a revoked link changes nothing.", + "operationId": "delete-share", "parameters": [ { - "description": "Device TypeID; must be the device the caller's token is bound to (its dev claim)", + "description": "Share TypeID", "in": "path", - "name": "device_id", + "name": "share_id", "required": true, "schema": { - "description": "Device TypeID; must be the device the caller's token is bound to (its dev claim)", + "description": "Share TypeID", + "maxLength": 64, "type": "string" } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EntitlementRequest" - } - } - }, - "required": true - }, "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Entitlement" - } - } - }, - "description": "OK", + "204": { + "description": "No Content", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -2252,26 +4505,6 @@ "content": { "application/json": { "examples": { - "account_locked": { - "summary": "Account locked", - "value": { - "code": "account_locked", - "detail": "This account is locked.", - "status": 403, - "title": "Account locked", - "type": "https://api.tablepro.app/problems/account-locked" - } - }, - "device_revoked": { - "summary": "Device revoked", - "value": { - "code": "device_revoked", - "detail": "This device was removed from the account. Sign in again to use it.", - "status": 403, - "title": "Device revoked", - "type": "https://api.tablepro.app/problems/device-revoked" - } - }, "forbidden": { "summary": "Forbidden", "value": { @@ -2281,16 +4514,6 @@ "title": "Forbidden", "type": "https://api.tablepro.app/problems/forbidden" } - }, - "forbidden_2": { - "summary": "Forbidden", - "value": { - "code": "forbidden", - "detail": "This token is not bound to that device. Register this device, refresh the token, and ask again.", - "status": 403, - "title": "Forbidden", - "type": "https://api.tablepro.app/problems/forbidden" - } } }, "schema": { @@ -2300,54 +4523,18 @@ }, "description": "Forbidden" }, - "409": { + "404": { "content": { "application/json": { "examples": { - "device_limit_reached": { - "summary": "Device limit reached", + "not_found": { + "summary": "Not found", "value": { - "code": "device_limit_reached", - "detail": "The license is already used on 3 devices.", - "devices": [ - { - "app_version": "2.0.0", - "created_at": "2026-10-01T09:00:00Z", - "id": "dev_01k8djrfaefw08m00000000001", - "last_seen_at": "2026-10-21T09:00:00Z", - "licensed_at": "2026-10-01T09:00:00Z", - "machine_id": "0000000000000000000000000000000000000000000000000000000000000001", - "name": "Ada's MacBook Pro", - "os_version": "26.0", - "platform": "macos" - }, - { - "app_version": "2.0.0", - "created_at": "2026-10-02T09:00:00Z", - "id": "dev_01k8djrfaefw08m00000000002", - "last_seen_at": "2026-10-22T09:00:00Z", - "licensed_at": "2026-10-02T09:00:00Z", - "machine_id": "0000000000000000000000000000000000000000000000000000000000000002", - "name": "Studio", - "offline_until": "2027-10-02T09:00:00Z", - "os_version": "26.0", - "platform": "macos" - }, - { - "app_version": "2.0.0", - "created_at": "2026-10-03T09:00:00Z", - "id": "dev_01k8djrfaefw08m00000000003", - "last_seen_at": "2026-10-23T09:00:00Z", - "licensed_at": "2026-10-03T09:00:00Z", - "machine_id": "0000000000000000000000000000000000000000000000000000000000000003", - "name": "Workstation", - "os_version": "Fedora 43", - "platform": "linux" - } - ], - "status": 409, - "title": "Device limit reached", - "type": "https://api.tablepro.app/problems/device-limit-reached" + "code": "not_found", + "detail": "No such share.", + "status": 404, + "title": "Not found", + "type": "https://api.tablepro.app/problems/not-found" } } }, @@ -2356,7 +4543,7 @@ } } }, - "description": "Conflict" + "description": "Not Found" }, "422": { "content": { @@ -2422,32 +4609,32 @@ ] } ], - "summary": "An entitlement for this device", + "summary": "Revoke a shared link", "tags": [ - "Devices" + "Shares" ] - } - }, - "/discounts/preview": { - "post": { - "description": "Answers whether checkout would apply the code, and how much it takes off. An unknown code is not an error.", - "operationId": "preview-discount", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/DiscountPreviewRequest" - } + }, + "get": { + "operationId": "get-share", + "parameters": [ + { + "description": "Share TypeID", + "in": "path", + "name": "share_id", + "required": true, + "schema": { + "description": "Share TypeID", + "maxLength": 64, + "type": "string" } - }, - "required": true - }, + } + ], "responses": { "200": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/DiscountPreview" + "$ref": "#/components/schemas/ShareView" } } }, @@ -2464,95 +4651,62 @@ } } }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Unprocessable Entity" - }, - "429": { + "401": { "content": { "application/json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "code": "unauthorized", + "detail": "The token is invalid or has expired.", + "status": 401, + "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/unauthorized" + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Too Many Requests", - "headers": { - "Retry-After": { - "$ref": "#/components/headers/Retry-After" - }, - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - } + "description": "Unauthorized" }, - "500": { + "403": { "content": { "application/json": { + "examples": { + "forbidden": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "The token lacks the app scope.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Internal Server Error" - } - }, - "summary": "Check a discount code", - "tags": [ - "Checkout" - ] - } - }, - "/me": { - "get": { - "description": "The account, the teams it belongs to with its role and seat in each, and the licenses whose features it can use.", - "operationId": "get-me", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Me" - } - } - }, - "description": "OK", - "headers": { - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - } + "description": "Forbidden" }, - "401": { + "404": { "content": { "application/json": { "examples": { - "unauthorized": { - "summary": "Unauthorized", + "not_found": { + "summary": "Not found", "value": { - "code": "unauthorized", - "detail": "The token is invalid or has expired.", - "status": 401, - "title": "Unauthorized", - "type": "https://api.tablepro.app/problems/unauthorized" + "code": "not_found", + "detail": "No such share.", + "status": 404, + "title": "Not found", + "type": "https://api.tablepro.app/problems/not-found" } } }, @@ -2561,29 +4715,17 @@ } } }, - "description": "Unauthorized" + "description": "Not Found" }, - "403": { + "422": { "content": { "application/json": { - "examples": { - "forbidden": { - "summary": "Forbidden", - "value": { - "code": "forbidden", - "detail": "The token lacks the app scope.", - "status": 403, - "title": "Forbidden", - "type": "https://api.tablepro.app/problems/forbidden" - } - } - }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Forbidden" + "description": "Unprocessable Entity" }, "429": { "content": { @@ -2639,70 +4781,47 @@ ] } ], - "summary": "The signed-in account", + "summary": "Get one shared link, with its SQL", "tags": [ - "Account" + "Shares" ] - } - }, - "/newsletter/stats": { - "get": { - "operationId": "get-newsletter-stats", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/NewsletterStats" - } - } - }, - "description": "OK" - }, - "500": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Internal Server Error" - }, - "503": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Service Unavailable" + }, + "patch": { + "description": "Title, note, expiry, password, downloads and hide_sql, under the same plan rules as create. Works on an expired link without reviving it; a new expiry revives it when a live slot is free.", + "operationId": "update-share", + "parameters": [ + { + "description": "Share TypeID", + "in": "path", + "name": "share_id", + "required": true, + "schema": { + "description": "Share TypeID", + "maxLength": 64, + "type": "string" + } } - }, - "summary": "Count the newsletter's subscribers", - "tags": [ - "Newsletter" - ] - } - }, - "/newsletter/subscriptions": { - "post": { - "description": "Emails a confirmation link. Answers 202 whether or not the address is subscribed and whether or not the Turnstile check passed, so it reveals nothing.", - "operationId": "create-newsletter-subscription", + ], "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NewsletterSubscriptionRequest" + "$ref": "#/components/schemas/UpdateShareBody" } } }, "required": true }, "responses": { - "202": { - "description": "Accepted", + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareView" + } + } + }, + "description": "OK", "headers": { "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" @@ -2715,88 +4834,210 @@ } } }, - "422": { + "401": { "content": { "application/json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "code": "unauthorized", + "detail": "The token is invalid or has expired.", + "status": 401, + "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/unauthorized" + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Unprocessable Entity" + "description": "Unauthorized" }, - "429": { + "403": { "content": { "application/json": { + "examples": { + "email_unverified": { + "summary": "Email unverified", + "value": { + "code": "email_unverified", + "detail": "Verify your email address to share links.", + "status": 403, + "title": "Email unverified", + "type": "https://api.tablepro.app/problems/email-unverified" + } + }, + "forbidden": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "The token lacks the app scope.", + "status": 403, + "title": "Forbidden", + "type": "https://api.tablepro.app/problems/forbidden" + } + }, + "pro_required": { + "summary": "Pro required", + "value": { + "code": "pro_required", + "detail": "This option needs TablePro Pro.", + "status": 403, + "title": "Pro required", + "type": "https://api.tablepro.app/problems/pro-required" + } + }, + "seat_required": { + "summary": "Seat required", + "value": { + "code": "seat_required", + "detail": "A team link needs a seat in the team.", + "status": 403, + "title": "Seat required", + "type": "https://api.tablepro.app/problems/seat-required" + } + }, + "sharing_disabled": { + "summary": "Sharing disabled", + "value": { + "code": "sharing_disabled", + "detail": "Sharing is turned off for this account.", + "status": 403, + "title": "Sharing disabled", + "type": "https://api.tablepro.app/problems/sharing-disabled" + } + }, + "team_sharing_disabled": { + "summary": "Team sharing disabled", + "value": { + "code": "team_sharing_disabled", + "detail": "Public links are turned off for this team.", + "status": 403, + "title": "Team sharing disabled", + "type": "https://api.tablepro.app/problems/team-sharing-disabled" + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Too Many Requests", - "headers": { - "Retry-After": { - "$ref": "#/components/headers/Retry-After" - }, - "X-RateLimit-Limit": { - "$ref": "#/components/headers/X-RateLimit-Limit" - }, - "X-RateLimit-Remaining": { - "$ref": "#/components/headers/X-RateLimit-Remaining" - }, - "X-RateLimit-Reset": { - "$ref": "#/components/headers/X-RateLimit-Reset" - } - } + "description": "Forbidden" }, - "500": { + "404": { "content": { "application/json": { + "examples": { + "not_found": { + "summary": "Not found", + "value": { + "code": "not_found", + "detail": "No such share.", + "status": 404, + "title": "Not found", + "type": "https://api.tablepro.app/problems/not-found" + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Internal Server Error" - } - }, - "summary": "Sign up for the newsletter", - "tags": [ - "Newsletter" - ] - } - }, - "/pricing": { - "get": { - "description": "What checkout charges the caller without a discount code, regional discount included. Answered for the caller's country, so it is never cached.", - "operationId": "get-pricing", - "responses": { - "200": { + "description": "Not Found" + }, + "409": { "content": { "application/json": { + "examples": { + "share_limit_reached": { + "summary": "Share limit reached", + "value": { + "code": "share_limit_reached", + "detail": "You have reached your plan's live link limit.", + "live_limit": 5, + "status": 409, + "title": "Share limit reached", + "type": "https://api.tablepro.app/problems/share-limit-reached" + } + }, + "share_removed": { + "summary": "Share removed", + "value": { + "code": "share_removed", + "detail": "TablePro removed this link.", + "status": 409, + "title": "Share removed", + "type": "https://api.tablepro.app/problems/share-removed" + } + }, + "share_revoked": { + "summary": "Share revoked", + "value": { + "code": "share_revoked", + "detail": "This link was revoked.", + "status": 409, + "title": "Share revoked", + "type": "https://api.tablepro.app/problems/share-revoked" + } + } + }, "schema": { - "$ref": "#/components/schemas/Pricing" + "$ref": "#/components/schemas/Problem" } } }, - "description": "OK", - "headers": { - "Cache-Control": { + "description": "Conflict" + }, + "422": { + "content": { + "application/json": { "schema": { - "type": "string" + "$ref": "#/components/schemas/Problem" } } - } + }, + "description": "Unprocessable Entity" }, - "422": { + "429": { "content": { "application/json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "code": "rate_limited", + "detail": "Too many requests. Try again later.", + "status": 429, + "title": "Rate limited", + "type": "https://api.tablepro.app/problems/rate-limited" + } + } + }, "schema": { "$ref": "#/components/schemas/Problem" } } }, - "description": "Unprocessable Entity" + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } }, "500": { "content": { @@ -2809,9 +5050,16 @@ "description": "Internal Server Error" } }, - "summary": "Prices in the caller's country", + "security": [ + { + "oauth": [ + "app" + ] + } + ], + "summary": "Change a shared link", "tags": [ - "Checkout" + "Shares" ] } }, diff --git a/core/crates/account/src/account.rs b/core/crates/account/src/account/mod.rs similarity index 99% rename from core/crates/account/src/account.rs rename to core/crates/account/src/account/mod.rs index 7aa0005d7c..f682142929 100644 --- a/core/crates/account/src/account.rs +++ b/core/crates/account/src/account/mod.rs @@ -9,7 +9,7 @@ use secrecy::{ExposeSecret as _, SecretString}; use tokio::sync::{Mutex, watch}; use tokio::time::Instant; -use crate::account_error::AccountError; +use crate::account_error::{AccountError, http_text}; use crate::account_file::{self, AccountFile}; use crate::account_settings::AccountSettings; use crate::account_status::{AccountStatus, EntitlementProblem, SignedIn}; @@ -22,6 +22,8 @@ use crate::oauth::{OAuth, Tokens}; use crate::profile::{Device, Profile}; use crate::token_vault::RefreshTokenVault; +mod share_calls; + // The server forgets an unanswered sign-in after 10 minutes. const SIGN_IN_TIMEOUT: Duration = Duration::from_secs(10 * 60); const ACCESS_TOKEN_MARGIN: TimeDelta = TimeDelta::seconds(60); @@ -77,6 +79,9 @@ enum Call { Profile, Devices, RemoveDevice, + Share, + // Rate limited apart from the other share calls on the server, so its 429 holds only further creates. + ShareCreate, } impl Session { @@ -128,7 +133,7 @@ impl Account { .connect_timeout(CONNECT_TIMEOUT) .timeout(REQUEST_TIMEOUT) .build() - .map_err(|error| AccountError::Protocol(error.to_string()))?; + .map_err(|error| AccountError::Protocol(http_text(error)))?; let oauth = OAuth::new(settings.client, &settings.endpoints, http.clone())?; Ok(Self { inner: Arc::new(Inner { @@ -517,7 +522,7 @@ impl Account { && let Some((access, until)) = &session.access && *until > Utc::now() + ACCESS_TOKEN_MARGIN { - return Ok(Bearer(access.clone())); + return Ok(Bearer::token(access.clone())); } let refresh = session.refresh.clone().ok_or(AccountError::SignedOut)?; session.waited(Call::Token)?; @@ -525,7 +530,7 @@ impl Account { let tokens = session.answered(Call::Token, tokens)?; let access = tokens.access.clone(); self.adopt(session, tokens).await; - Ok(Bearer(access)) + Ok(Bearer::token(access)) } async fn adopt(&self, session: &mut Session, tokens: Tokens) { diff --git a/core/crates/account/src/account/share_calls.rs b/core/crates/account/src/account/share_calls.rs new file mode 100644 index 0000000000..975b459767 --- /dev/null +++ b/core/crates/account/src/account/share_calls.rs @@ -0,0 +1,920 @@ +use std::num::NonZeroU64; +use std::sync::atomic::Ordering; +use std::time::Duration; + +use progenitor_client::{Error, ResponseValue}; +use secrecy::{ExposeSecret as _, SecretString}; + +use super::{Account, Call, Session}; +use crate::account_error::AccountError; +use crate::cloud_api::{Bearer, answer_error, v2}; +use crate::share::{ + CreatedShare, MAX_SHARE_COLUMNS, MAX_SHARE_SQL_BYTES, Share, ShareExpiry, ShareLimits, SharePage, ShareRequest, + SharedLink, SnapshotBody, sent_share_password, +}; +use crate::share_link::is_share_token; + +const SHARE_PAGE: NonZeroU64 = NonZeroU64::MIN.saturating_add(99); +// A body of up to 8 MiB on a slow link outlasts the client's 30 seconds. +const UPLOAD_TIMEOUT: Duration = Duration::from_secs(5 * 60); +// The document's maxLength for each, in characters; a longer title, note or dialect is cut rather than refused. +const TITLE_CHARACTERS: usize = 200; +const NOTE_CHARACTERS: usize = 2_000; +const DIALECT_CHARACTERS: usize = 40; + +impl Account { + // What the plan allows and how many live links the account holds, for the share sheet. + pub async fn share_limits(&self) -> Result { + self.share_call(Call::Share, async |api| { + answer(api.get_share_limits().await).await.map(ShareLimits::from) + }) + .await + } + + // The URL is the link to copy. A result's snapshot must already be cut to the plan's `max_rows`. The session is + // held for the token only, so no other call waits out the upload. + pub async fn create_share(&self, request: ShareRequest) -> Result { + let columns_truncated = request + .snapshot + .as_ref() + .is_some_and(|snapshot| snapshot.columns.len() > MAX_SHARE_COLUMNS); + let body = create_body(request)?; + let (bearer, attempt) = { + let mut session = self.inner.session.lock().await; + let taken = match session.waited(Call::ShareCreate) { + Ok(()) => self.bearer(&mut session, false).await, + Err(error) => Err(error), + }; + let bearer = self.ended_by(&mut session, taken).await?; + (bearer, self.inner.attempts.load(Ordering::SeqCst)) + }; + let api = self.api(bearer.lasting(UPLOAD_TIMEOUT)); + let sent = answer(api.create_share(&body).await).await; + let mut session = self.inner.session.lock().await; + // A sign-in or sign-out since the token was taken owns the session now. + let answered = match self.inner.attempts.load(Ordering::SeqCst) == attempt { + true => { + let answered = session.answered(Call::ShareCreate, sent); + self.ended_by(&mut session, answered).await + } + false => sent, + }; + drop(session); + let created = CreatedShare { + columns_truncated, + ..answered?.into() + }; + tracing::info!(kind = %created.share.kind, "created a shared link"); + Ok(created) + } + + // The account's own links, or a team's, newest first, without their SQL: every one of the team's for its owner + // and admins, a member's own otherwise. `live_only` leaves out expired, revoked and removed links. + pub async fn list_shares( + &self, + live_only: bool, + team_id: Option<&str>, + cursor: Option<&str>, + ) -> Result { + let state = list_state(live_only)?; + let team: Option = team_id.map(known).transpose()?; + let cursor: Option = cursor + .map(|cursor| limited(cursor.to_owned(), "not a cursor the server gave")) + .transpose()?; + self.share_call(Call::Share, async |api| { + let sent = api + .list_shares(cursor.as_ref(), Some(SHARE_PAGE), Some(state), team.as_ref()) + .await; + answer(sent).await.map(SharePage::from) + }) + .await + } + + // The link stops working at once; revoking it again changes nothing. + pub async fn revoke_share(&self, share_id: &str) -> Result<(), AccountError> { + let share_id: v2::types::DeleteShareShareId = known(share_id)?; + self.share_call(Call::Share, async |api| answer(api.delete_share(&share_id).await).await) + .await?; + tracing::info!("revoked a shared link"); + Ok(()) + } + + // A new expiry counted from now, which also revives an expired link while a live slot is free. + pub async fn extend_share(&self, share_id: &str, expiry: ShareExpiry) -> Result { + let share_id: v2::types::UpdateShareShareId = known(share_id)?; + let body = v2::types::UpdateShareBody { + expiry: Some(wire(expiry.code())?), + ..Default::default() + }; + self.share_call(Call::Share, async |api| { + answer(api.update_share(&share_id, &body).await).await.map(Share::from) + }) + .await + } + + // Public: no session and no token, so anyone with a link reads it, signed in or not. + pub async fn fetch_shared(&self, token: &str, password: Option<&SecretString>) -> Result { + if !is_share_token(token) { + return Err(not_found("not a share token")); + } + let api = self.api(Bearer::public()); + let password = password + .map(|password| sent_share_password(password.expose_secret())) + .filter(|password| !password.is_empty()); + answer(api.get_shared(token, password).await) + .await + .map(SharedLink::from) + } + + // Each call holds the session, waits out its 429, takes the bearer and ends the session on a refused sign-in. + async fn share_call( + &self, + call: Call, + request: impl AsyncFnOnce(v2::Client) -> Result, + ) -> Result { + let mut session = self.inner.session.lock().await; + let answered = self.share_answer(&mut session, call, request).await; + self.ended_by(&mut session, answered).await + } + + async fn share_answer( + &self, + session: &mut Session, + call: Call, + request: impl AsyncFnOnce(v2::Client) -> Result, + ) -> Result { + session.waited(call)?; + let api = self.api(self.bearer(session, false).await?); + let answer = request(api).await; + session.answered(call, answer) + } +} + +async fn answer(sent: Result, Error>) -> Result { + match sent { + Ok(answer) => Ok(answer.into_inner()), + Err(error) => Err(answer_error(error).await), + } +} + +fn create_body(request: ShareRequest) -> Result { + if request.sql.len() > MAX_SHARE_SQL_BYTES { + return Err(invalid("the SQL is longer than the server takes")); + } + Ok(v2::types::CreateShareBody { + kind: wire(request.kind.code())?, + sql: limited(request.sql, "the SQL is longer than the server takes")?, + title: cut(request.title, TITLE_CHARACTERS)?, + note: cut(request.note, NOTE_CHARACTERS)?, + dialect: cut(request.dialect, DIALECT_CHARACTERS)?, + expiry: request.expiry.map(|expiry| wire(expiry.code())).transpose()?, + hide_sql: request.hide_sql.then_some(true), + allow_download: request.allow_download, + password: request + .password + .as_ref() + .map(|password| match sent_share_password(password.expose_secret()) { + "" => Err(invalid("the password is only spaces")), + kept => limited(kept.to_owned(), "the password is too long"), + }) + .transpose()?, + team_id: request.team_id.map(|team| limited(team, "not a team ID")).transpose()?, + snapshot: request.snapshot.map(SnapshotBody::from), + }) +} + +fn list_state(live_only: bool) -> Result { + wire(if live_only { "live" } else { "all" }) +} + +// A value of one of the document's string enums, by its wire spelling. +fn wire(code: &str) -> Result { + code.parse() + .map_err(|_| AccountError::Protocol(format!("{code:?} is not in the /v2 document"))) +} + +// The document's own check, such as a maxLength, answered as the server would answer it. +fn limited>(text: String, detail: &str) -> Result { + T::try_from(text).map_err(|_| invalid(detail)) +} + +fn cut>(text: Option, characters: usize) -> Result, AccountError> { + let Some(text) = text.map(|text| text.trim().chars().take(characters).collect::()) else { + return Ok(None); + }; + if text.is_empty() { + return Ok(None); + } + limited(text, "a field is longer than the server takes").map(Some) +} + +// An ID longer than the document allows names no share or team the server holds. +fn known>(id: &str) -> Result { + T::try_from(id.to_owned()).map_err(|_| not_found("not an ID the server gave")) +} + +fn not_found(detail: &str) -> AccountError { + AccountError::Refused { + status: 404, + code: "not_found".to_owned(), + detail: detail.to_owned(), + } +} + +fn invalid(detail: &str) -> AccountError { + AccountError::Refused { + status: 422, + code: "validation_failed".to_owned(), + detail: detail.to_owned(), + } +} + +#[cfg(test)] +mod tests { + use std::io::{BufRead as _, Read as _, Write as _}; + use std::path::Path; + use std::sync::{Arc, Mutex}; + + use async_trait::async_trait; + use chrono::Utc; + use tablepro_core::credentials::SecretError; + use tokio::sync::watch; + + use super::*; + use crate::account_file::{self, AccountFile}; + use crate::account_settings::{AccountSettings, AppClient, CallbackPage, DeviceDescription, Endpoints}; + use crate::account_status::AccountStatus; + use crate::browser::BrowserLauncher; + use crate::entitlement::test_tokens::keys; + use crate::machine_id::MachineId; + use crate::share::ShareKind; + use crate::token_vault::RefreshTokenVault; + + const TOKEN: &str = "Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK"; + const TOKENS: &str = + r#"{"access_token":"stub-access","token_type":"Bearer","expires_in":900,"refresh_token":"stub-refresh"}"#; + const VIEW: &str = r#"{"id":"shr_01","kind":"query","scope":"account","title":"Orders","note":"","dialect":"postgres", + "has_snapshot":false,"hide_sql":false,"allow_download":true,"has_password":false,"state":"live","suspended":false,"view_count":3, + "created_at":"2026-11-13T00:00:00Z","updated_at":"2026-11-13T00:00:00Z","expires_at":"2026-12-13T00:00:00Z", + "url":"https://s.tablepro.app/Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK"}"#; + + // What the stub was sent: the method and path, the header lines in lower case, and the body. + #[derive(Debug, Clone)] + struct Sent { + request: String, + headers: String, + body: String, + } + + type Log = Arc>>; + type Answer = dyn Fn(&Sent) -> (u16, &'static str, String) + Send + Sync; + + // Each connection on a thread of its own, so one slow answer holds back no other. + fn cloud(answer: impl Fn(&Sent) -> (u16, &'static str, String) + Send + Sync + 'static) -> (Endpoints, Log) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a free port"); + let base = format!("http://{}", listener.local_addr().expect("its address")); + let log = Log::default(); + let kept = log.clone(); + let answer: Arc = Arc::new(answer); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let (answer, kept) = (answer.clone(), kept.clone()); + std::thread::spawn(move || serve(stream, &*answer, &kept)); + } + }); + let endpoints = Endpoints::new(&base, &format!("{base}/v2")).expect("the endpoints"); + (endpoints, log) + } + + fn serve(stream: std::net::TcpStream, answer: &Answer, log: &Log) { + let mut reader = std::io::BufReader::new(stream.try_clone().expect("a second handle")); + let mut line = String::new(); + reader.read_line(&mut line).expect("the request line"); + let mut words = line.split_whitespace(); + let request = format!( + "{} {}", + words.next().unwrap_or_default(), + words.next().unwrap_or_default() + ); + let (mut headers, mut length) = (String::new(), 0); + loop { + let mut header = String::new(); + reader.read_line(&mut header).expect("a header"); + if header.trim().is_empty() { + break; + } + let header = header.to_ascii_lowercase(); + if let Some(value) = header.strip_prefix("content-length:") { + length = value.trim().parse().expect("a length"); + } + headers.push_str(&header); + } + let mut body = vec![0; length]; + reader.read_exact(&mut body).expect("the body"); + let sent = Sent { + request, + headers, + body: String::from_utf8_lossy(&body).into_owned(), + }; + let (status, extra, answer) = answer(&sent); + log.lock().expect("the log").push(sent); + let mut stream = stream; + write!( + stream, + "HTTP/1.1 {status} Stub\r\ncontent-type: application/json\r\n{extra}content-length: {}\r\nconnection: close\r\n\r\n{answer}", + answer.len() + ) + .expect("the answer"); + } + + struct Vault; + + #[async_trait] + impl RefreshTokenVault for Vault { + async fn load_refresh_token(&self) -> Result, SecretError> { + Ok(Some(SecretString::from("refresh"))) + } + + async fn store_refresh_token(&self, _: &SecretString) -> Result<(), SecretError> { + Ok(()) + } + + async fn delete_refresh_token(&self) -> Result<(), SecretError> { + Ok(()) + } + } + + struct NoBrowser; + + #[async_trait] + impl BrowserLauncher for NoBrowser { + async fn open(&self, _: &url::Url) -> Result<(), String> { + Err("a unit test opens no browser".to_owned()) + } + } + + // Signed in from a kept sign-in, as at a launch, so the first call refreshes the token. + async fn signed_in(dir: &Path, endpoints: Endpoints) -> Account { + let file = AccountFile { + device_id: Some("dev_01".to_owned()), + ..AccountFile::default() + }; + account_file::write(&dir.join("account.json"), &file) + .await + .expect("the account file"); + let settings = AccountSettings { + client: AppClient::WINDOWS, + endpoints, + device: DeviceDescription { + name: "Lab".to_owned(), + app_version: "1.0.0".to_owned(), + os_version: "Windows 11".to_owned(), + }, + machine_id: MachineId::derive_machine_guid("d3b07384-d113-4ec6-a2f1-6a3f0c2e9b7a").expect("a machine"), + keys: keys(), + account_file: dir.join("account.json"), + callback_page: CallbackPage { + finished: String::new(), + unknown: String::new(), + }, + }; + let account = Account::new( + settings, + Arc::new(Vault), + Arc::new(NoBrowser), + watch::Sender::new(AccountStatus::SignedOut), + ) + .expect("an account"); + account.restore().await; + account + } + + fn problem(status: u16, code: &str) -> String { + format!(r#"{{"type":"about:blank","title":"Refused","status":{status},"code":"{code}"}}"#) + } + + fn query(title: &str) -> ShareRequest { + ShareRequest { + kind: ShareKind::Query, + sql: "SELECT * FROM orders".to_owned(), + title: Some(title.to_owned()), + note: None, + dialect: Some("postgres".to_owned()), + expiry: None, + hide_sql: false, + allow_download: None, + password: None, + team_id: None, + snapshot: None, + } + } + + fn sent(log: &Log, request: &str) -> Vec { + log.lock() + .expect("the log") + .iter() + .filter(|sent| sent.request.starts_with(request)) + .cloned() + .collect() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_limits_say_what_the_plan_allows() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let (endpoints, log) = cloud(|sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "GET /v2/share-limits" => ( + 200, + "", + r#"{"plan":"free","live":5,"live_limit":5,"max_rows":1000,"expiries":["1d","7d","30d","2w"], + "default_expiry":"30d","password":false,"disable_download":false,"team":false, + "email_verified":true,"sharing_disabled":false,"teams":[]}"# + .to_owned(), + ), + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + + let limits = account.share_limits().await.expect("the limits"); + + assert_eq!(limits.plan, "free"); + assert_eq!( + limits.expiries, + [ShareExpiry::OneDay, ShareExpiry::SevenDays, ShareExpiry::ThirtyDays] + ); + assert_eq!(limits.default_expiry, Some(ShareExpiry::ThirtyDays)); + assert_eq!(limits.max_rows, 1_000); + assert!(limits.at_limit()); + assert!( + sent(&log, "GET /v2/share-limits")[0] + .headers + .contains("authorization: bearer stub-access") + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_create_sends_only_what_was_set_and_gives_the_url() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let (endpoints, log) = cloud(|sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "POST /v2/shares" => ( + 201, + "", + format!(r#"{{"share":{VIEW},"token":"{TOKEN}","url":"https://s.tablepro.app/{TOKEN}"}}"#), + ), + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + let request = ShareRequest { + expiry: Some(ShareExpiry::SevenDays), + note: Some(" ".to_owned()), + ..query(&format!(" {} ", "t".repeat(250))) + }; + + let created = account.create_share(request).await.expect("created"); + + assert_eq!(created.url, format!("https://s.tablepro.app/{TOKEN}")); + assert_eq!(created.share.id, "shr_01"); + assert!(created.share.is_live()); + let body: serde_json::Value = + serde_json::from_str(&sent(&log, "POST /v2/shares")[0].body).expect("a JSON body"); + assert_eq!(body["kind"], "query"); + assert_eq!(body["expiry"], "7d"); + assert_eq!(body["title"].as_str().map(|title| title.chars().count()), Some(200)); + for absent in ["note", "hide_sql", "password", "team_id", "snapshot", "allow_download"] { + assert!( + body.get(absent).is_none_or(serde_json::Value::is_null), + "{absent}: {body}" + ); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_result_s_rows_go_out_as_the_core_wrote_them() { + use tablepro_core::column::{ColumnType, ResultColumn}; + use tablepro_core::export::{ResultExtent, build_snapshot}; + use tablepro_core::value::Value; + + let dir = tempfile::tempdir().expect("a temporary directory"); + let (endpoints, log) = cloud(|sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "POST /v2/shares" => ( + 201, + "", + format!(r#"{{"share":{VIEW},"token":"{TOKEN}","url":"https://s.tablepro.app/{TOKEN}"}}"#), + ), + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + let columns = [ResultColumn::new("big", ColumnType::untyped_text("numeric"))]; + let rows = [ + vec![Value::Decimal( + "123456789012345678901234567890.5".parse().expect("a decimal"), + )], + vec![Value::Null], + ]; + let request = ShareRequest { + kind: ShareKind::Result, + hide_sql: true, + snapshot: Some( + build_snapshot( + &columns, + &rows, + ResultExtent::finished(2, Some(48_210), tablepro_core::Truncation::ReadPastLimit), + 1, + ) + .expect("a snapshot"), + ), + ..query("Orders") + }; + + account.create_share(request).await.expect("created"); + + let body = sent(&log, "POST /v2/shares")[0].body.clone(); + assert!( + body.contains(r#""rows":[[123456789012345678901234567890.5]]"#), + "{body}" + ); + assert!(body.contains(r#""row_count":48210"#), "{body}"); + assert!( + body.contains(r#""columns":[{"name":"big","type":"numeric"}]"#), + "{body}" + ); + assert!(body.contains(r#""hide_sql":true"#), "{body}"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn each_refusal_reads_as_the_code_the_app_words() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let answers = Arc::new(Mutex::new(vec![ + (403, problem(403, "email_unverified")), + (403, problem(403, "pro_required")), + (409, problem(409, "share_limit_reached")), + (413, "Request Entity Too Large".to_owned()), + (422, problem(422, "snapshot_too_large")), + ])); + let (endpoints, _) = cloud(move |sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "POST /v2/shares" => { + let (status, body) = answers.lock().expect("the answers").remove(0); + (status, "", body) + } + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + + let mut codes = Vec::new(); + for _ in 0..5 { + codes.push(account.create_share(query("Orders")).await.expect_err("refused").code()); + } + + assert_eq!( + codes, + [ + "account.email_unverified", + "account.pro_required", + "account.share_limit_reached", + "account.snapshot_too_large", + "account.snapshot_too_large", + ] + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_429_on_create_holds_further_creates_and_nothing_else() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let (endpoints, log) = cloud(|sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "POST /v2/shares" => (429, "retry-after: 60\r\n", problem(429, "rate_limited")), + request if request.starts_with("GET /v2/shares") => (200, "", format!(r#"{{"data":[{VIEW}]}}"#)), + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + + let limited = account.create_share(query("Orders")).await; + let held = account.create_share(query("Orders")).await; + let listed = account.list_shares(true, None, None).await.expect("the list"); + + assert!( + matches!(limited, Err(AccountError::RateLimited { retry_after: Some(wait) }) if wait.as_secs() == 60), + "{limited:?}" + ); + assert!(matches!(held, Err(AccountError::RateLimited { .. })), "{held:?}"); + assert_eq!(sent(&log, "POST /v2/shares").len(), 1); + assert_eq!(listed.shares.len(), 1); + assert_eq!(listed.next_cursor, None); + let list = &sent(&log, "GET /v2/shares")[0].request; + assert!(list.contains("state=live") && list.contains("limit=100"), "{list}"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn an_extend_sends_the_expiry_and_a_revoke_deletes() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let (endpoints, log) = cloud(|sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "PATCH /v2/shares/shr_01" => (200, "", VIEW.to_owned()), + "DELETE /v2/shares/shr_01" => (204, "", String::new()), + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + + let extended = account + .extend_share("shr_01", ShareExpiry::ThirtyDays) + .await + .expect("extended"); + account.revoke_share("shr_01").await.expect("revoked"); + + assert_eq!( + extended.expires_at.map(|at| at.to_rfc3339()).as_deref(), + Some("2026-12-13T00:00:00+00:00") + ); + assert_eq!(sent(&log, "PATCH /v2/shares/shr_01")[0].body, r#"{"expiry":"30d"}"#); + assert_eq!(sent(&log, "DELETE /v2/shares/shr_01").len(), 1); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_shared_link_is_read_without_a_token_and_with_its_password() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let path = format!("GET /v2/shared/{TOKEN}"); + let (endpoints, log) = cloud(move |sent| match sent.request.as_str() { + request if request == path && sent.headers.contains("x-share-password: hunter2") => ( + 200, + "", + r#"{"kind":"result","title":"Orders","note":"","dialect":"postgres","sql":"SELECT 1", + "created_at":"2026-11-13T00:00:00Z","allow_download":true,"made_with":"TablePro", + "snapshot":{"columns":[{"name":"n","type":"int"}],"rows":[["9007199254740993"],[1]], + "row_count":48210,"truncated":true}}"# + .to_owned(), + ), + request if request == path && sent.headers.contains("x-share-password:") => { + (401, "", problem(401, "share_password_wrong")) + } + request if request == path => (401, "", problem(401, "share_password_required")), + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + + let required = account.fetch_shared(TOKEN, None).await; + let wrong = account.fetch_shared(TOKEN, Some(&SecretString::from("nope"))).await; + let opened = account + .fetch_shared(TOKEN, Some(&SecretString::from("hunter2"))) + .await + .expect("the link"); + let malformed = account.fetch_shared("short", None).await; + + assert_eq!(required.expect_err("refused").code(), "account.share_password_required"); + assert_eq!(wrong.expect_err("refused").code(), "account.share_password_wrong"); + assert_eq!(opened.sql.as_deref(), Some("SELECT 1")); + assert_eq!((opened.row_count, opened.truncated), (Some(48_210), Some(true))); + assert_eq!(opened.expires_at, None); + assert_eq!(malformed.expect_err("refused").code(), "account.not_found"); + let log = log.lock().expect("the log"); + assert_eq!(log.len(), 3, "{log:?}"); + assert!( + log.iter().all(|sent| !sent.headers.contains("authorization")), + "{log:?}" + ); + assert!(opened.created_at <= Utc::now()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn an_upload_holds_the_session_only_for_its_token() { + use std::sync::atomic::{AtomicBool, Ordering}; + + let dir = tempfile::tempdir().expect("a temporary directory"); + let limits_answered = Arc::new(AtomicBool::new(false)); + let upload_started = Arc::new(AtomicBool::new(false)); + let (answered, started) = (limits_answered.clone(), upload_started.clone()); + let (endpoints, log) = cloud(move |sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "GET /v2/share-limits" => { + answered.store(true, Ordering::SeqCst); + ( + 200, + "", + r#"{"plan":"pro","live":1,"live_limit":1000,"max_rows":10000,"expiries":["never"], + "default_expiry":"never","password":true,"disable_download":true,"team":true, + "email_verified":true,"sharing_disabled":false,"teams":[]}"# + .to_owned(), + ) + } + "POST /v2/shares" => { + started.store(true, Ordering::SeqCst); + // The upload answers only once the limits are read, which a held session would never let happen. + for _ in 0..500 { + if answered.load(Ordering::SeqCst) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + ( + 201, + "", + format!(r#"{{"share":{VIEW},"token":"{TOKEN}","url":"https://s.tablepro.app/{TOKEN}"}}"#), + ) + } + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + account.share_limits().await.expect("a token first"); + limits_answered.store(false, Ordering::SeqCst); + + let read_meanwhile = async { + while !upload_started.load(Ordering::SeqCst) { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + account.share_limits().await + }; + let (created, limits) = tokio::join!(account.create_share(query("Orders")), read_meanwhile); + + created.expect("created"); + assert_eq!(limits.expect("the limits").plan, "pro"); + let order: Vec = log + .lock() + .expect("the log") + .iter() + .map(|sent| sent.request.clone()) + .collect(); + let limits_at = order.iter().rposition(|request| request == "GET /v2/share-limits"); + let created_at = order.iter().position(|request| request == "POST /v2/shares"); + assert!( + matches!((limits_at, created_at), (Some(limits), Some(created)) if limits < created), + "{order:?}" + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_result_past_100_columns_shares_the_first_ones_and_says_so() { + use tablepro_core::column::{ColumnType, ResultColumn}; + use tablepro_core::export::{ResultExtent, build_snapshot}; + use tablepro_core::value::Value; + + let dir = tempfile::tempdir().expect("a temporary directory"); + let (endpoints, log) = cloud(|sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "POST /v2/shares" => ( + 201, + "", + format!(r#"{{"share":{VIEW},"token":"{TOKEN}","url":"https://s.tablepro.app/{TOKEN}"}}"#), + ), + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + let columns: Vec = (0..120) + .map(|index| ResultColumn::new(format!("c{index}"), ColumnType::untyped_text("int"))) + .collect(); + let row: Vec = (0..120).map(Value::Int).collect(); + let request = ShareRequest { + kind: ShareKind::Result, + snapshot: Some(build_snapshot(&columns, [row], ResultExtent::complete(1), 10).expect("a snapshot")), + ..query("Wide") + }; + + let created = account.create_share(request).await.expect("created"); + + assert!(created.columns_truncated); + let body = sent(&log, "POST /v2/shares")[0].body.clone(); + assert!(body.contains(r#"{"name":"c99","type":"int"}]"#), "{body}"); + assert!(!body.contains(r#""c100""#), "{body}"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_team_link_goes_to_its_team_and_its_refusals_read_as_their_codes() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let (endpoints, log) = cloud(|sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "GET /v2/share-limits" => ( + 200, + "", + r#"{"plan":"pro","live":2,"live_limit":1000,"max_rows":10000,"expiries":["1d","never"], + "default_expiry":"never","password":true,"disable_download":true,"team":true, + "email_verified":true,"sharing_disabled":false,"teams":[ + {"id":"team_01","name":"Acme","live":1000,"live_limit":1000,"public_links":true}, + {"id":"team_02","name":"Lab","live":0,"live_limit":1000,"public_links":false}]}"# + .to_owned(), + ), + "POST /v2/shares" if sent.body.contains(r#""team_id":"team_02""#) => { + (403, "", problem(403, "team_sharing_disabled")) + } + "POST /v2/shares" if sent.body.contains(r#""team_id":"team_03""#) => { + (403, "", problem(403, "seat_required")) + } + "POST /v2/shares" => ( + 201, + "", + format!(r#"{{"share":{VIEW},"token":"{TOKEN}","url":"https://s.tablepro.app/{TOKEN}"}}"#), + ), + request if request.starts_with("GET /v2/shares") => (200, "", format!(r#"{{"data":[{VIEW}]}}"#)), + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + let team = |id: &str| ShareRequest { + team_id: Some(id.to_owned()), + ..query("Orders") + }; + + let limits = account.share_limits().await.expect("the limits"); + account.create_share(team("team_01")).await.expect("a team link"); + let off = account.create_share(team("team_02")).await; + let seatless = account.create_share(team("team_03")).await; + account + .list_shares(true, Some("team_01"), None) + .await + .expect("the team's links"); + + assert_eq!( + limits.teams.iter().map(|team| team.name.as_str()).collect::>(), + ["Acme", "Lab"] + ); + assert!(limits.teams[0].at_limit() && limits.teams[0].public_links); + assert!(!limits.teams[1].public_links); + assert_eq!(off.expect_err("refused").code(), "account.team_sharing_disabled"); + assert_eq!(seatless.expect_err("refused").code(), "account.seat_required"); + assert!(sent(&log, "POST /v2/shares")[0].body.contains(r#""team_id":"team_01""#)); + let list = &sent(&log, "GET /v2/shares")[0].request; + assert!(list.contains("team=team_01") && list.contains("state=live"), "{list}"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_password_goes_without_its_outer_spaces_and_one_of_only_spaces_is_refused() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let path = format!("GET /v2/shared/{TOKEN}"); + let (endpoints, log) = cloud(move |sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "POST /v2/shares" => ( + 201, + "", + format!(r#"{{"share":{VIEW},"token":"{TOKEN}","url":"https://s.tablepro.app/{TOKEN}"}}"#), + ), + request if request == path && sent.headers.contains("x-share-password: hunter2\r\n") => ( + 200, + "", + r#"{"kind":"query","title":"Orders","note":"","dialect":"postgres","sql":"SELECT 1", + "created_at":"2026-11-13T00:00:00Z","allow_download":true,"made_with":"TablePro"}"# + .to_owned(), + ), + request if request == path => (401, "", problem(401, "share_password_wrong")), + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + let with = |password: &str| ShareRequest { + password: Some(SecretString::from(password.to_owned())), + ..query("Orders") + }; + + account.create_share(with(" \thunter2\t ")).await.expect("created"); + let blank = account.create_share(with(" \t ")).await; + let opened = account + .fetch_shared(TOKEN, Some(&SecretString::from(" hunter2\t"))) + .await; + + let posts = sent(&log, "POST /v2/shares"); + assert_eq!(posts.len(), 1, "a password of only spaces was sent"); + let body: serde_json::Value = serde_json::from_str(&posts[0].body).expect("a JSON body"); + assert_eq!(body["password"], "hunter2"); + assert_eq!(blank.expect_err("refused").code(), "account.validation_failed"); + assert_eq!(opened.expect("the link").sql.as_deref(), Some("SELECT 1")); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn sql_is_measured_in_bytes_as_the_server_measures_it() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let (endpoints, log) = cloud(|sent| match sent.request.as_str() { + "POST /oauth/token" => (200, "", TOKENS.to_owned()), + "POST /v2/shares" => ( + 201, + "", + format!(r#"{{"share":{VIEW},"token":"{TOKEN}","url":"https://s.tablepro.app/{TOKEN}"}}"#), + ), + _ => (404, "", String::new()), + }); + let account = signed_in(dir.path(), endpoints).await; + let with = |sql: String| ShareRequest { sql, ..query("Orders") }; + + // Two bytes a character: half the server's 262,144 characters already fill its 256 KiB. + let over = account.create_share(with("é".repeat(131_073))).await; + account + .create_share(with("é".repeat(131_072))) + .await + .expect("256 KiB goes"); + + assert_eq!(over.expect_err("refused").code(), "account.validation_failed"); + assert_eq!(sent(&log, "POST /v2/shares").len(), 1); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_network_failure_never_words_the_share_token() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a free port"); + let base = format!("http://{}", listener.local_addr().expect("its address")); + drop(listener); + let endpoints = Endpoints::new(&base, &format!("{base}/v2")).expect("the endpoints"); + let account = signed_in(dir.path(), endpoints).await; + + let failed = account.fetch_shared(TOKEN, None).await.expect_err("nothing listens"); + + assert_eq!(failed.code(), "account.unreachable"); + assert!(!failed.to_string().contains(TOKEN), "{failed}"); + assert!(!format!("{failed:?}").contains(TOKEN), "{failed:?}"); + } +} diff --git a/core/crates/account/src/account_error.rs b/core/crates/account/src/account_error.rs index 32f79dbc56..0c8db458a1 100644 --- a/core/crates/account/src/account_error.rs +++ b/core/crates/account/src/account_error.rs @@ -35,6 +35,24 @@ pub enum AccountError { Protocol(String), } +// Problem codes an app words on its own (PLAN, tablepro-cloud api.md). They stay `Refused`, so a match on the +// variants keeps compiling; any other refused code is account.refused. +const WORDED_REFUSALS: [(&str, &str); 13] = [ + ("email_unverified", "account.email_unverified"), + ("pro_required", "account.pro_required"), + ("sharing_disabled", "account.sharing_disabled"), + ("team_sharing_disabled", "account.team_sharing_disabled"), + ("seat_required", "account.seat_required"), + ("not_found", "account.not_found"), + ("share_limit_reached", "account.share_limit_reached"), + ("share_revoked", "account.share_revoked"), + ("share_removed", "account.share_removed"), + ("validation_failed", "account.validation_failed"), + ("snapshot_too_large", "account.snapshot_too_large"), + ("share_password_required", "account.share_password_required"), + ("share_password_wrong", "account.share_password_wrong"), +]; + impl AccountError { // A stable code an app outside Rust words the error from. pub fn code(&self) -> &'static str { @@ -48,7 +66,10 @@ impl AccountError { Self::DeviceRevoked => "account.device_revoked", Self::DeviceLimitReached { .. } => "account.device_limit_reached", Self::OtherAccount => "account.other_account", - Self::Refused { .. } => "account.refused", + Self::Refused { code, .. } => WORDED_REFUSALS + .iter() + .find(|(problem, _)| problem == code) + .map_or("account.refused", |(_, worded)| worded), Self::RateLimited { .. } => "account.rate_limited", Self::Entitlement(_) => "account.entitlement", Self::Storage { .. } => "account.storage", @@ -56,15 +77,55 @@ impl AccountError { } } - // reqwest keeps the cause, such as a refused connection, a level down. - pub(crate) fn unreachable(error: &dyn std::error::Error) -> Self { - let mut detail = error.to_string(); - let mut source = error.source(); - while let Some(cause) = source { - detail.push_str(": "); - detail.push_str(&cause.to_string()); - source = cause.source(); + pub(crate) fn unreachable(error: reqwest::Error) -> Self { + Self::Unreachable(http_text(error)) + } +} + +// Without the URL, whose path can hold a share token. reqwest keeps the cause, such as a refused connection, below. +pub(crate) fn http_text(error: reqwest::Error) -> String { + let error = error.without_url(); + let mut detail = error.to_string(); + let mut source = std::error::Error::source(&error); + while let Some(cause) = source { + detail.push_str(": "); + detail.push_str(&cause.to_string()); + source = cause.source(); + } + detail +} + +#[cfg(test)] +mod tests { + use super::*; + + fn refused(code: &str) -> AccountError { + AccountError::Refused { + status: 403, + code: code.to_owned(), + detail: String::new(), } - Self::Unreachable(detail) + } + + #[test] + fn a_problem_an_app_words_has_its_own_code_and_any_other_is_refused() { + assert_eq!(refused("pro_required").code(), "account.pro_required"); + assert_eq!(refused("share_limit_reached").code(), "account.share_limit_reached"); + assert_eq!(refused("share_password_wrong").code(), "account.share_password_wrong"); + assert_eq!(refused("account_locked").code(), "account.refused"); + } + + #[test] + fn every_worded_problem_has_a_code_of_its_own() { + let mut codes: Vec<&str> = WORDED_REFUSALS.iter().map(|(_, code)| *code).collect(); + codes.sort_unstable(); + codes.dedup(); + + assert_eq!(codes.len(), WORDED_REFUSALS.len()); + assert!( + WORDED_REFUSALS + .iter() + .all(|(problem, code)| code.strip_prefix("account.") == Some(*problem)) + ); } } diff --git a/core/crates/account/src/account_settings.rs b/core/crates/account/src/account_settings.rs index daba15b66d..650f2eda3a 100644 --- a/core/crates/account/src/account_settings.rs +++ b/core/crates/account/src/account_settings.rs @@ -1,13 +1,15 @@ +use std::fmt::Write as _; use std::path::PathBuf; +use aws_lc_rs::digest; use url::Url; use crate::cloud_api::v2::types::Platform; use crate::entitlement_keys::EntitlementKeys; use crate::machine_id::MachineId; -// tablepro-cloud registers one public OAuth client per app, each with its own redirect: the loopback one -// this crate listens on is the Linux client's (api.md, OAuth). Another app adds its own once the server does. +// tablepro-cloud registers one public OAuth client per app, each with its own redirect: Linux's and Windows's take +// the loopback one this crate listens on, on any port (api.md, OAuth). The Mac's is a custom scheme. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct AppClient { pub client_id: &'static str, @@ -22,6 +24,12 @@ impl AppClient { platform: Platform::Linux, system: "Linux", }; + + pub const WINDOWS: Self = Self { + client_id: "tablepro-windows", + platform: Platform::Windows, + system: "Windows", + }; } #[derive(Debug, Clone, PartialEq, Eq)] @@ -80,6 +88,27 @@ pub struct AccountSettings { pub callback_page: CallbackPage, } +impl AccountSettings { + // Names this sign-in among the others a user's secret store can hold: another server, or another build's + // state folder, keeps a refresh token of its own. 16 hex characters of SHA-256 over the API and the file. + pub fn sign_in_key(&self) -> String { + let named = format!("{}\n{}", self.endpoints.api, self.account_file.display()); + let hash = digest::digest(&digest::SHA256, named.as_bytes()); + hash.as_ref() + .iter() + .take(8) + .fold(String::with_capacity(16), |mut text, byte| { + let _ = write!(text, "{byte:02x}"); + text + }) + } + + // tablepro.app's own service, which a sign-in kept before the key existed was always for. + pub fn is_production(&self) -> bool { + self.endpoints == Endpoints::production() + } +} + #[cfg(test)] mod tests { use super::*; @@ -95,6 +124,53 @@ mod tests { assert_eq!(endpoints.api, "http://api.localhost:5284/v2"); } + #[test] + fn each_desktop_app_signs_in_as_its_own_client_and_platform() { + assert_eq!( + (AppClient::LINUX.client_id, AppClient::LINUX.platform.to_string()), + ("tablepro-linux", "linux".to_owned()) + ); + assert_eq!( + (AppClient::WINDOWS.client_id, AppClient::WINDOWS.platform.to_string()), + ("tablepro-windows", "windows".to_owned()) + ); + } + + fn settings(api: &str, file: &str) -> AccountSettings { + AccountSettings { + client: AppClient::WINDOWS, + endpoints: Endpoints::new("https://account.tablepro.app", api).expect("the endpoints"), + device: DeviceDescription { + name: "Lab".to_owned(), + app_version: "1.0.0".to_owned(), + os_version: "Windows 11".to_owned(), + }, + machine_id: MachineId::derive("4c4f5e2a0b6d4f3c9e8a7b6c5d4e3f20\n").expect("a machine"), + keys: crate::entitlement::test_tokens::keys(), + account_file: PathBuf::from(file), + callback_page: CallbackPage { + finished: String::new(), + unknown: String::new(), + }, + } + } + + #[test] + fn each_server_and_state_folder_signs_in_under_a_key_of_its_own() { + let production = settings("https://api.tablepro.app/v2", "C:/Users/a/LocalState/account.json"); + let local = settings("http://api.localhost:5284/v2", "C:/Users/a/LocalState/account.json"); + let other_build = settings("https://api.tablepro.app/v2", "C:/Users/a/Dev/LocalState/account.json"); + // python3 -c 'import hashlib;print(hashlib.sha256(b"https://api.tablepro.app/v2\nC:/Users/a/LocalState/account.json").hexdigest()[:16])' + let expected = "e6989de2b8e8cbc0"; + + assert_eq!(production.sign_in_key(), expected); + assert_eq!(production.sign_in_key(), production.clone().sign_in_key()); + assert_ne!(production.sign_in_key(), local.sign_in_key()); + assert_ne!(production.sign_in_key(), other_build.sign_in_key()); + assert!(production.is_production()); + assert!(!local.is_production()); + } + #[test] fn production_is_tablepro_app_over_https() { let endpoints = Endpoints::production(); diff --git a/core/crates/account/src/cloud_api.rs b/core/crates/account/src/cloud_api.rs index b39c8de332..d249e1ee8b 100644 --- a/core/crates/account/src/cloud_api.rs +++ b/core/crates/account/src/cloud_api.rs @@ -5,7 +5,7 @@ use reqwest::StatusCode; use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue, RETRY_AFTER}; use secrecy::{ExposeSecret, SecretString}; -use crate::account_error::AccountError; +use crate::account_error::{AccountError, http_text}; #[expect( clippy::unwrap_used, @@ -15,13 +15,47 @@ pub mod v2 { include!(concat!(env!("OUT_DIR"), "/v2.rs")); } +// What each request of a client carries: the access token, none for a public call such as reading a shared link, +// and a timeout of its own for a call that takes longer than the client's, such as an upload. #[derive(Clone, Debug)] -pub struct Bearer(pub(crate) SecretString); +pub struct Bearer { + token: Option, + timeout: Option, +} + +impl Bearer { + pub(crate) fn token(token: SecretString) -> Self { + Self { + token: Some(token), + timeout: None, + } + } + + pub(crate) fn public() -> Self { + Self { + token: None, + timeout: None, + } + } + + pub(crate) fn lasting(self, timeout: Duration) -> Self { + Self { + timeout: Some(timeout), + ..self + } + } +} impl ClientHooks for v2::Client { async fn pre(&self, request: &mut reqwest::Request, _: &OperationInfo) -> Result<(), Error> { use progenitor_client::ClientInfo as _; - let mut value = HeaderValue::from_str(&format!("Bearer {}", self.inner().0.expose_secret())) + if let Some(timeout) = self.inner().timeout { + *request.timeout_mut() = Some(timeout); + } + let Some(token) = &self.inner().token else { + return Ok(()); + }; + let mut value = HeaderValue::from_str(&format!("Bearer {}", token.expose_secret())) .map_err(|_| Error::InvalidRequest("the access token is not a header value".to_owned()))?; value.set_sensitive(true); request.headers_mut().insert(AUTHORIZATION, value); @@ -37,26 +71,40 @@ pub(crate) async fn answer_error(error: Error) -> AccountErr Error::UnexpectedResponse(response) if response.status() == StatusCode::TOO_MANY_REQUESTS => { rate_limited(response.headers()) } + // The framework's or the proxy's, with no problem code of ours: only a share's snapshot gets that large. + Error::ErrorResponse(answer) if answer.status().as_u16() == TOO_LARGE => too_large(), + Error::UnexpectedResponse(response) if response.status().as_u16() == TOO_LARGE => too_large(), Error::ErrorResponse(answer) => problem_error(answer.status().as_u16(), answer.into_inner()), // A status the document does not list, such as a proxy's. Error::UnexpectedResponse(response) => { let status = response.status().as_u16(); let body = match response.bytes().await { Ok(body) => body, - Err(error) => return AccountError::unreachable(&error), + Err(error) => return AccountError::unreachable(error), }; match serde_json::from_slice::(&body) { Ok(problem) => problem_error(status, problem), Err(_) => AccountError::Protocol(format!("HTTP {status} without a problem")), } } - Error::CommunicationError(error) => AccountError::unreachable(&error), + Error::CommunicationError(error) | Error::ResponseBodyError(error) => AccountError::unreachable(error), + Error::InvalidUpgrade(error) => AccountError::Protocol(http_text(error)), // Its text carries the whole answer, an entitlement or the account's details among them. Error::InvalidResponsePayload(_, error) => AccountError::Protocol(schema_mismatch(&error)), other => AccountError::Protocol(other.to_string()), } } +const TOO_LARGE: u16 = 413; + +fn too_large() -> AccountError { + AccountError::Refused { + status: TOO_LARGE, + code: "snapshot_too_large".to_owned(), + detail: "the request is larger than the server takes".to_owned(), + } +} + // Where the answer stopped matching, without any of its values. pub(crate) fn schema_mismatch(error: &serde_json::Error) -> String { format!( @@ -165,6 +213,35 @@ mod tests { ); } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_request_s_own_timeout_overrides_the_client_s() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a free port"); + let base = format!("http://{}/v2", listener.local_addr().expect("its address")); + // Takes the request and never answers it. + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + std::thread::sleep(Duration::from_secs(3)); + drop(stream); + } + }); + let http = reqwest::Client::builder() + .timeout(Duration::from_secs(30)) + .build() + .expect("a client"); + let api = v2::Client::new_with_client(&base, http, Bearer::public().lasting(Duration::from_millis(200))); + let started = std::time::Instant::now(); + + let sent = api + .get_shared("Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK", None) + .await; + + assert!( + matches!(&sent, Err(Error::CommunicationError(error)) if error.is_timeout()), + "{sent:?}" + ); + assert!(started.elapsed() < Duration::from_secs(2), "{:?}", started.elapsed()); + } + #[test] fn a_429_keeps_its_retry_after_in_seconds() { let answer = |value: &str| { diff --git a/core/crates/account/src/lib.rs b/core/crates/account/src/lib.rs index 3dc8dd24c1..5be8ab2dd4 100644 --- a/core/crates/account/src/lib.rs +++ b/core/crates/account/src/lib.rs @@ -16,6 +16,8 @@ mod machine_id; mod oauth; mod offline_file; mod profile; +mod share; +mod share_link; mod token_vault; pub use account::{Account, REFRESH_INTERVAL, RETRY_INTERVAL}; @@ -32,5 +34,10 @@ pub use entitlement_keys::{EntitlementKeys, KeyError}; pub use machine_id::MachineId; pub use offline_file::{OfflineFileError, read_offline_file_blocking}; pub use profile::{Device, Membership, Profile}; +pub use share::{ + CreatedShare, MAX_SHARE_COLUMNS, MAX_SHARE_SQL_BYTES, Share, ShareExpiry, ShareKind, ShareLimits, SharePage, + ShareRequest, ShareTeam, SharedLink, SnapshotBody, SnapshotColumnBody, sent_share_password, +}; +pub use share_link::{is_share_token, share_token_from_link}; pub use token_vault::RefreshTokenVault; pub use url::Url; diff --git a/core/crates/account/src/machine_id.rs b/core/crates/account/src/machine_id.rs index 2ac9ae0f7e..3a958a4427 100644 --- a/core/crates/account/src/machine_id.rs +++ b/core/crates/account/src/machine_id.rs @@ -2,20 +2,34 @@ use std::fmt::Write as _; use aws_lc_rs::hmac; -// Changing it makes every Linux machine a new device. Both build profiles share it. +// Changing it makes every machine a new device. Both build profiles share it. const KEY: &str = "app.tablepro.TablePro"; -// Linux's: an HMAC of the machine ID the app reads from /etc/machine-id, which machine-id(5) says never to send -// as it is. The machine ID itself never leaves the machine. +// An HMAC of the platform's machine ID, which machine-id(5) says never to send as it is. The machine ID itself +// never leaves the machine. #[derive(Debug, Clone, PartialEq, Eq)] pub struct MachineId(String); impl MachineId { - // machine-id(5): 32 hex characters and a newline, never all zero. + // Linux's /etc/machine-id, per machine-id(5): 32 hex characters and a newline, never all zero. pub fn derive(machine_id: &str) -> Option { - let raw = decode_machine_id(machine_id.trim_end_matches('\n'))?; - let tag = hmac::sign(&hmac::Key::new(hmac::HMAC_SHA256, KEY.as_bytes()), &raw); - Some(Self(hex(tag.as_ref()))) + decode_machine_id(machine_id.trim_end_matches('\n')).map(|raw| Self::keyed(&raw)) + } + + // Windows's HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid, 8-4-4-4-12 hex digits: the same HMAC over the + // 16 bytes they write, in the order they are written. + pub fn derive_machine_guid(machine_guid: &str) -> Option { + let groups: Vec<&str> = machine_guid.split('-').collect(); + let lengths: Vec = groups.iter().map(|group| group.len()).collect(); + if lengths != [8, 4, 4, 4, 12] { + return None; + } + decode_machine_id(&groups.concat()).map(|raw| Self::keyed(&raw)) + } + + fn keyed(raw: &[u8; 16]) -> Self { + let tag = hmac::sign(&hmac::Key::new(hmac::HMAC_SHA256, KEY.as_bytes()), raw); + Self(hex(tag.as_ref())) } pub fn as_str(&self) -> &str { @@ -24,7 +38,8 @@ impl MachineId { } fn decode_machine_id(text: &str) -> Option<[u8; 16]> { - if text.len() != 32 { + // from_str_radix would also take a pair such as "+f". + if text.len() != 32 || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) { return None; } let mut raw = [0u8; 16]; @@ -100,10 +115,49 @@ mod tests { "4c4f5e2a0b6d4f3c9e8a7b6c5d4e3f200\n", "4c4f5e2a-0b6d-4f3c-9e8a-7b6c5d4e3f20\n", "zc4f5e2a0b6d4f3c9e8a7b6c5d4e3f20\n", + "+c4f5e2a0b6d4f3c9e8a7b6c5d4e3f20\n", " 4c4f5e2a0b6d4f3c9e8a7b6c5d4e3f20\n", "00000000000000000000000000000000\n", ] { assert_eq!(MachineId::derive(text), None, "{text:?}"); } } + + #[test] + fn a_machine_guid_is_keyed_as_linux_keys_its_machine_id() { + let windows = MachineId::derive_machine_guid("4c4f5e2a-0b6d-4f3c-9e8a-7b6c5d4e3f20").expect("a machine ID"); + + assert_eq!(windows.as_str(), EXPECTED); + assert_eq!(Some(windows), MachineId::derive(ETC_MACHINE_ID)); + } + + #[test] + fn a_machine_guid_gives_its_own_id_in_either_case() { + // python3 -c 'import hmac,hashlib;print(hmac.new(b"app.tablepro.TablePro", + // bytes.fromhex("d3b07384d1134ec6a2f16a3f0c2e9b7a"),hashlib.sha256).hexdigest())' + let expected = "304a889059f4befc83a542069ca52d990fd963e22766f6db230543bfddf7e336"; + + let lower = MachineId::derive_machine_guid("d3b07384-d113-4ec6-a2f1-6a3f0c2e9b7a").expect("a machine ID"); + let upper = MachineId::derive_machine_guid("D3B07384-D113-4EC6-A2F1-6A3F0C2E9B7A").expect("a machine ID"); + + assert_eq!(lower.as_str(), expected); + assert_eq!(lower, upper); + } + + #[test] + fn what_is_not_a_machine_guid_is_refused() { + for text in [ + "", + "4c4f5e2a0b6d4f3c9e8a7b6c5d4e3f20", + "{4c4f5e2a-0b6d-4f3c-9e8a-7b6c5d4e3f20}", + " 4c4f5e2a-0b6d-4f3c-9e8a-7b6c5d4e3f20", + "4c4f5e2a-0b6d-4f3c-9e8a-7b6c5d4e3f2", + "4c4f5e2a-0b6d4-f3c-9e8a-7b6c5d4e3f20", + "zc4f5e2a-0b6d-4f3c-9e8a-7b6c5d4e3f20", + "+c4f5e2a-0b6d-4f3c-9e8a-7b6c5d4e3f20", + "00000000-0000-0000-0000-000000000000", + ] { + assert_eq!(MachineId::derive_machine_guid(text), None, "{text:?}"); + } + } } diff --git a/core/crates/account/src/oauth.rs b/core/crates/account/src/oauth.rs index a31c11846f..f17cc57e4c 100644 --- a/core/crates/account/src/oauth.rs +++ b/core/crates/account/src/oauth.rs @@ -118,7 +118,7 @@ impl OAuth { .form(&form) .send() .await - .map_err(|error| AccountError::unreachable(&error))?; + .map_err(AccountError::unreachable)?; match response.status().is_success() { true => Ok(()), false => Err(AccountError::Refused { @@ -182,7 +182,7 @@ fn grant_error( code: answer.error().to_string(), detail: answer.error_description().cloned().unwrap_or_default(), }, - RequestTokenError::Request(HttpClientError::Reqwest(error)) => AccountError::unreachable(&*error), + RequestTokenError::Request(HttpClientError::Reqwest(error)) => AccountError::unreachable(*error), other => AccountError::Protocol(other.to_string()), } } diff --git a/core/crates/account/src/share.rs b/core/crates/account/src/share.rs new file mode 100644 index 0000000000..7a775d7510 --- /dev/null +++ b/core/crates/account/src/share.rs @@ -0,0 +1,504 @@ +use chrono::{DateTime, Utc}; +use secrecy::SecretString; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use tablepro_core::export::Snapshot; + +use crate::cloud_api::v2::types; + +// The server's caps on a snapshot's columns: more columns or a longer name is refused, so the rest are left out. +pub const MAX_SHARE_COLUMNS: usize = 100; +const COLUMN_NAME_CHARACTERS: usize = 256; +// The server counts a share's SQL in UTF-8 bytes, which the document's maxLength in characters does not. +pub const MAX_SHARE_SQL_BYTES: usize = 256 * 1_024; + +// The password as a link keeps it: a reader sends it in X-Share-Password, whose value HTTP strips of outer spaces and +// tabs. One that strips to nothing is refused. +pub fn sent_share_password(password: &str) -> &str { + password.trim_matches([' ', '\t']) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ShareKind { + Query, + Result, +} + +// The server computes the expiry from its own clock. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ShareExpiry { + OneDay, + SevenDays, + ThirtyDays, + Never, +} + +impl ShareKind { + pub fn code(self) -> &'static str { + match self { + Self::Query => "query", + Self::Result => "result", + } + } +} + +impl ShareExpiry { + pub const ALL: [Self; 4] = [Self::OneDay, Self::SevenDays, Self::ThirtyDays, Self::Never]; + + pub fn code(self) -> &'static str { + match self { + Self::OneDay => "1d", + Self::SevenDays => "7d", + Self::ThirtyDays => "30d", + Self::Never => "never", + } + } + + pub fn from_code(code: &str) -> Option { + Self::ALL.into_iter().find(|expiry| expiry.code() == code) + } +} + +// What the account's plan allows, and where it stands. Plan and codes stay strings, as the profile's do. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ShareLimits { + pub plan: String, + pub live: u64, + pub live_limit: u64, + pub max_rows: u64, + // The same on every plan; a result with more shares the first ones. + pub max_columns: u64, + // An expiry this build does not know is left out. + pub expiries: Vec, + pub default_expiry: Option, + pub password: bool, + pub disable_download: bool, + pub team: bool, + pub email_verified: bool, + pub sharing_disabled: bool, + // The teams the account holds a seat in, for a team link; empty on Free. + pub teams: Vec, +} + +// A team link counts against the team's own limit, never the account's. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ShareTeam { + pub id: String, + pub name: String, + pub live: u64, + pub live_limit: u64, + // False: the team turned public links off, and a team link answers team_sharing_disabled. + pub public_links: bool, +} + +impl ShareLimits { + pub fn at_limit(&self) -> bool { + self.live >= self.live_limit + } +} + +impl ShareTeam { + pub fn at_limit(&self) -> bool { + self.live >= self.live_limit + } +} + +#[derive(Debug, Clone)] +pub struct ShareRequest { + pub kind: ShareKind, + pub sql: String, + pub title: Option, + pub note: Option, + pub dialect: Option, + // None takes the plan's default. + pub expiry: Option, + // Only for a result. + pub hide_sql: bool, + // None leaves downloads on. + pub allow_download: Option, + pub password: Option, + pub team_id: Option, + // A result's rows, already cut to the plan's `max_rows`. + pub snapshot: Option, +} + +// A link its owner manages. State, kind and scope stay strings. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Share { + pub id: String, + pub kind: String, + pub scope: String, + pub team_id: Option, + pub title: String, + pub note: String, + pub dialect: String, + // Only when one link is read on its own. + pub sql: Option, + pub has_snapshot: bool, + pub row_count: Option, + pub truncated: Option, + pub hide_sql: bool, + pub allow_download: bool, + pub has_password: bool, + pub state: String, + pub removed_reason: Option, + // A team turned public links off, staff turned the creator's sharing off, or the team was deleted: the link + // does not resolve until the switch is on again. `suspended_by` is account, team or team_deleted. + pub suspended: bool, + pub suspended_by: Option, + pub view_count: u64, + pub created_at: DateTime, + pub updated_at: DateTime, + pub expires_at: Option>, + pub revoked_at: Option>, + pub removed_at: Option>, + pub url: Option, +} + +impl Share { + pub fn is_live(&self) -> bool { + self.state == "live" + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CreatedShare { + pub share: Share, + pub url: String, + // The result had more than `MAX_SHARE_COLUMNS` columns, and only the first ones were shared. + pub columns_truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SharePage { + pub shares: Vec, + pub next_cursor: Option, +} + +// A link as anyone with it reads it. The app opens its SQL and never its rows, so they are not kept. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SharedLink { + pub kind: String, + pub title: String, + pub note: String, + pub dialect: String, + // None when the owner hid it, or a result was shared with no SQL. + pub sql: Option, + pub created_at: DateTime, + pub expires_at: Option>, + pub allow_download: bool, + pub row_count: Option, + pub truncated: Option, +} + +// The document's SnapshotBody, which build.rs puts in place of the generated one: its rows go out as the raw JSON +// tokens the core wrote, where the generated `serde_json::Value` would round a big number. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SnapshotBody { + pub columns: Vec, + pub rows: Vec>>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub row_count: Option, + // Rows exist beyond those sent and nobody counted them; the viewer then says so rather than read the rows as + // the whole result. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub more_rows: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SnapshotColumnBody { + pub name: String, + #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] + pub type_name: Option, + // The document's ShareMaskStyle: how the app masked the column's values before they left it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub masked: Option, +} + +// The document's maxLength for a column's type. +const COLUMN_TYPE_CHARACTERS: usize = 256; + +// Only the first `MAX_SHARE_COLUMNS` columns, and each row's cells for them. +impl From for SnapshotBody { + fn from(snapshot: Snapshot) -> Self { + Self { + columns: snapshot + .columns + .into_iter() + .take(MAX_SHARE_COLUMNS) + .map(|column| SnapshotColumnBody { + name: column.name.chars().take(COLUMN_NAME_CHARACTERS).collect(), + type_name: Some(column.type_name.chars().take(COLUMN_TYPE_CHARACTERS).collect()) + .filter(|type_name: &String| !type_name.is_empty()), + masked: column.masked.map(|style| style.code().to_owned()), + }) + .collect(), + rows: snapshot + .rows + .into_iter() + .map(|mut row| { + row.truncate(MAX_SHARE_COLUMNS); + row + }) + .collect(), + row_count: snapshot.row_count.map(|count| i64::try_from(count).unwrap_or(i64::MAX)), + more_rows: snapshot.more_rows.then_some(true), + } + } +} + +// The document's PublicSnapshot, which build.rs puts in place of the generated one. Only the counts are read: the +// app opens a link's SQL, so its rows are skipped rather than parsed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct PublicSnapshot { + // None for a result cut with no count. + #[serde(default)] + pub row_count: Option, + pub truncated: bool, +} + +impl From for ShareLimits { + fn from(limits: types::ShareLimits) -> Self { + Self { + plan: limits.plan.to_string(), + live: count(limits.live), + live_limit: count(limits.live_limit), + max_rows: count(limits.max_rows), + max_columns: MAX_SHARE_COLUMNS as u64, + expiries: limits + .expiries + .iter() + .filter_map(|expiry| ShareExpiry::from_code(&expiry.to_string())) + .collect(), + default_expiry: ShareExpiry::from_code(&limits.default_expiry.to_string()), + password: limits.password, + disable_download: limits.disable_download, + team: limits.team, + email_verified: limits.email_verified, + sharing_disabled: limits.sharing_disabled, + teams: limits + .teams + .into_iter() + .map(|team| ShareTeam { + id: team.id, + name: team.name, + live: count(team.live), + live_limit: count(team.live_limit), + public_links: team.public_links, + }) + .collect(), + } + } +} + +impl From for Share { + fn from(view: types::ShareView) -> Self { + Self { + id: view.id, + kind: view.kind.to_string(), + scope: view.scope.to_string(), + team_id: view.team_id.filter(|team| !team.is_empty()), + title: view.title, + note: view.note, + dialect: view.dialect, + sql: view.sql, + has_snapshot: view.has_snapshot, + row_count: view.row_count.map(count), + truncated: view.truncated, + hide_sql: view.hide_sql, + allow_download: view.allow_download, + has_password: view.has_password, + state: view.state.to_string(), + removed_reason: view.removed_reason.filter(|reason| !reason.is_empty()), + suspended: view.suspended, + suspended_by: view.suspended_by.filter(|by| view.suspended && !by.is_empty()), + view_count: count(view.view_count), + created_at: view.created_at, + updated_at: view.updated_at, + expires_at: view.expires_at, + revoked_at: view.revoked_at, + removed_at: view.removed_at, + url: view.url.filter(|url| !url.is_empty()), + } + } +} + +impl From for CreatedShare { + fn from(created: types::CreatedShare) -> Self { + Self { + share: created.share.into(), + url: created.url, + columns_truncated: false, + } + } +} + +impl From for SharePage { + fn from(list: types::ShareList) -> Self { + Self { + shares: list.data.into_iter().map(Share::from).collect(), + next_cursor: list.next_cursor.filter(|cursor| !cursor.is_empty()), + } + } +} + +impl From for SharedLink { + fn from(shared: types::PublicShare) -> Self { + Self { + kind: shared.kind.to_string(), + title: shared.title, + note: shared.note, + dialect: shared.dialect, + sql: shared.sql.filter(|sql| !sql.trim().is_empty()), + created_at: shared.created_at, + expires_at: shared.expires_at, + allow_download: shared.allow_download, + row_count: shared.snapshot.and_then(|snapshot| snapshot.row_count).map(count), + truncated: shared.snapshot.map(|snapshot| snapshot.truncated), + } + } +} + +// A count the server sends as a signed integer, never below zero. +fn count(number: i64) -> u64 { + u64::try_from(number).unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use tablepro_core::column::{ColumnType, ResultColumn}; + use tablepro_core::export::{ResultExtent, build_snapshot}; + use tablepro_core::value::Value; + + use super::*; + + #[test] + fn a_snapshot_shares_its_first_100_columns_with_names_cut_to_the_server_s_length() { + let mut columns: Vec = (0..=MAX_SHARE_COLUMNS) + .map(|index| ResultColumn::new(format!("c{index}"), ColumnType::untyped_text("text"))) + .collect(); + columns[0].name = "n".repeat(300); + let row: Vec = (0..=MAX_SHARE_COLUMNS).map(|index| Value::Int(index as i64)).collect(); + + let body = + SnapshotBody::from(build_snapshot(&columns, [row], ResultExtent::complete(1), 10).expect("a snapshot")); + + assert_eq!(body.columns.len(), MAX_SHARE_COLUMNS); + assert_eq!(body.columns[0].name.chars().count(), 256); + assert_eq!(body.columns[99].name, "c99"); + assert_eq!(body.rows[0].len(), MAX_SHARE_COLUMNS); + assert_eq!(body.rows[0][99].get(), "99"); + } + + fn view(suspended: bool, by: &str) -> Share { + let json = format!( + r#"{{"id":"shr_01","kind":"query","scope":"team","team_id":"team_01","title":"","note":"","dialect":"", + "has_snapshot":false,"hide_sql":false,"allow_download":true,"has_password":false,"state":"live", + "suspended":{suspended},"suspended_by":"{by}","view_count":0, + "created_at":"2026-11-13T00:00:00Z","updated_at":"2026-11-13T00:00:00Z"}}"# + ); + serde_json::from_str::(&json).expect("a share").into() + } + + #[test] + fn a_masked_column_names_its_style_and_an_unmasked_one_sends_none() { + use tablepro_core::masking::MaskingStyle; + + let columns = [ + ResultColumn::new("email", ColumnType::untyped_text("text")), + ResultColumn::new("id", ColumnType::untyped_text("int")), + ]; + let mut snapshot = build_snapshot( + &columns, + [vec![Value::Text("a•••@x.io".to_owned()), Value::Int(1)]], + ResultExtent::complete(1), + 10, + ) + .expect("a snapshot"); + snapshot.columns[0].masked = Some(MaskingStyle::LastFour); + + let json = serde_json::to_string(&SnapshotBody::from(snapshot)).expect("JSON"); + + assert!( + json.contains(r#"{"name":"email","type":"text","masked":"lastFour"}"#), + "{json}" + ); + assert!(json.contains(r#"{"name":"id","type":"int"}"#), "{json}"); + } + + #[test] + fn every_style_is_one_the_document_takes() { + use tablepro_core::masking::MaskingStyle; + + for style in MaskingStyle::ALL { + let parsed: types::ShareMaskStyle = + serde_json::from_value(serde_json::json!(style.code())).expect("a ShareMaskStyle"); + assert_eq!(parsed.to_string(), style.code()); + } + } + + #[test] + fn a_suspended_link_says_who_suspended_it() { + let deleted = view(true, "team_deleted"); + let live = view(false, "team"); + + assert!(deleted.suspended); + assert_eq!(deleted.suspended_by.as_deref(), Some("team_deleted")); + assert!(!live.suspended); + assert_eq!(live.suspended_by, None); + } + + #[test] + fn a_cut_result_nobody_counted_sends_more_rows_and_no_count() { + let columns = [ResultColumn::new("n", ColumnType::untyped_text("int"))]; + let rows = [vec![Value::Int(1)]]; + let uncounted = ResultExtent::finished(1, None, tablepro_core::Truncation::ReadPastLimit); + + let cut = serde_json::to_string(&SnapshotBody::from( + build_snapshot(&columns, rows.clone(), uncounted, 10).expect("a snapshot"), + )) + .expect("JSON"); + let whole = serde_json::to_string(&SnapshotBody::from( + build_snapshot(&columns, rows, ResultExtent::complete(1), 10).expect("a snapshot"), + )) + .expect("JSON"); + + assert!( + cut.contains(r#""more_rows":true"#) && !cut.contains("row_count"), + "{cut}" + ); + assert!( + whole.contains(r#""row_count":1"#) && !whole.contains("more_rows"), + "{whole}" + ); + } + + #[test] + fn a_shared_result_with_no_count_reads_as_cut_without_one() { + let json = r#"{"kind":"result","title":"","note":"","dialect":"","created_at":"2026-11-13T00:00:00Z", + "allow_download":true,"made_with":"TablePro", + "snapshot":{"columns":[{"name":"n","type":"int"}],"rows":[[1]],"row_count":null,"truncated":true}}"#; + + let shared: SharedLink = serde_json::from_str::(json) + .expect("a shared link") + .into(); + + assert_eq!((shared.row_count, shared.truncated), (None, Some(true))); + } + + #[test] + fn a_result_shared_with_blank_sql_has_none_to_open() { + let read = |sql: Option<&str>| { + let sql = sql.map(|sql| format!(r#""sql":{},"#, serde_json::to_string(sql).expect("JSON"))); + let json = format!( + r#"{{"kind":"result","title":"Orders","note":"","dialect":"postgres",{} + "created_at":"2026-11-13T00:00:00Z","allow_download":true,"made_with":"TablePro"}}"#, + sql.unwrap_or_default() + ); + SharedLink::from(serde_json::from_str::(&json).expect("a shared link")).sql + }; + + assert_eq!([read(Some("")), read(Some(" \r\n\t")), read(None)], [None, None, None]); + assert_eq!(read(Some("SELECT 1")).as_deref(), Some("SELECT 1")); + } +} diff --git a/core/crates/account/src/share_link.rs b/core/crates/account/src/share_link.rs new file mode 100644 index 0000000000..45b909dcc7 --- /dev/null +++ b/core/crates/account/src/share_link.rs @@ -0,0 +1,70 @@ +use url::Url; + +// tablepro-cloud mints 32 random bytes as 43 base62 characters, and its validation takes exactly that. +const TOKEN_LENGTH: usize = 43; + +pub fn is_share_token(token: &str) -> bool { + token.len() == TOKEN_LENGTH && token.bytes().all(|byte| byte.is_ascii_alphanumeric()) +} + +// The token of `tablepro://share?token=`, the deep link a viewer page opens the app with. +pub fn share_token_from_link(link: &str) -> Option { + let url = Url::parse(link.trim()).ok()?; + if url.scheme() != "tablepro" || url.host_str() != Some("share") || !matches!(url.path(), "" | "/") { + return None; + } + let mut tokens = url.query_pairs().filter(|(name, _)| name == "token"); + let token = tokens.next()?.1.into_owned(); + (tokens.next().is_none() && is_share_token(&token)).then_some(token) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TOKEN: &str = "Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK"; + + #[test] + fn a_token_is_43_base62_characters() { + assert_eq!(TOKEN.len(), 43); + assert!(is_share_token(TOKEN)); + for token in [ + "", + &TOKEN[..42], + &format!("{TOKEN}a"), + &format!("{}-", &TOKEN[..42]), + &format!("{}_", &TOKEN[..42]), + &format!("{}é", &TOKEN[..41]), + ] { + assert!(!is_share_token(token), "{token:?}"); + } + } + + #[test] + fn the_deep_link_gives_its_token() { + assert_eq!( + share_token_from_link(&format!("tablepro://share?token={TOKEN}")).as_deref(), + Some(TOKEN) + ); + assert_eq!( + share_token_from_link(&format!(" tablepro://share/?token={TOKEN}&from=viewer\n")).as_deref(), + Some(TOKEN) + ); + } + + #[test] + fn any_other_link_gives_none() { + for link in [ + format!("https://share?token={TOKEN}"), + format!("tablepro://connect?token={TOKEN}"), + format!("tablepro://share/open?token={TOKEN}"), + "tablepro://share".to_owned(), + "tablepro://share?token=short".to_owned(), + format!("tablepro://share?token={TOKEN}&token={TOKEN}"), + format!("https://s.tablepro.app/{TOKEN}"), + TOKEN.to_owned(), + ] { + assert_eq!(share_token_from_link(&link), None, "{link}"); + } + } +} diff --git a/core/crates/account/tests/browser/portal.cjs b/core/crates/account/tests/browser/portal.cjs index 0965a4cfa2..dd31a6e8de 100644 --- a/core/crates/account/tests/browser/portal.cjs +++ b/core/crates/account/tests/browser/portal.cjs @@ -27,12 +27,12 @@ const seedDevices = Number(process.env.TABLEPRO_CLOUD_SEED_DEVICES ?? '0'); // Where the redirect to the app goes instead of to the app, for an app the browser cannot reach. const callbackFile = process.env.TABLEPRO_CLOUD_CALLBACK_FILE ?? ''; const [step, authorizeURL] = process.argv.slice(2); -const signInSubject = /^Sign in to TablePro$/; +const signInSubject = /^Your TablePro sign-in code$/; async function signInEmails() { const response = await fetch(`${mailURL}/_e2e/emails?to=${encodeURIComponent(email)}`); if (!response.ok) { - throw new Error(`the fake Resend answered ${response.status}`); + throw new Error(`the fake SES answered ${response.status}`); } return (await response.json()).filter((sent) => signInSubject.test(sent.subject)); } diff --git a/core/crates/account/tests/browser/seed.cjs b/core/crates/account/tests/browser/seed.cjs new file mode 100644 index 0000000000..b02b555380 --- /dev/null +++ b/core/crates/account/tests/browser/seed.cjs @@ -0,0 +1,85 @@ +'use strict'; + +// The database steps of tests/cloud_stack.rs that need no browser, written as tablepro-cloud's web/e2e/src/seed.ts +// writes them. Same NODE_PATH as portal.cjs. + +const { Client } = require('pg'); + +function env(name) { + const value = process.env[name]; + if (!value) { + throw new Error(`${name} is not set`); + } + return value; +} + +const databaseURL = env('TABLEPRO_CLOUD_DATABASE_URL'); +const email = env('TABLEPRO_CLOUD_EMAIL'); +const [step] = process.argv.slice(2); + +async function accountID(client, address) { + const { rows } = await client.query('select id from accounts where email = $1', [address]); + if (rows.length === 0) { + throw new Error(`no account for ${address}`); + } + return rows[0].id; +} + +async function unverify(client) { + await client.query('update accounts set email_verified_at = null where id = $1', [await accountID(client, email)]); +} + +// The account owns the team and TABLEPRO_CLOUD_MEMBER_EMAIL holds a seat, on a Team license of 5 seats. +async function team(client) { + const owner = await accountID(client, email); + const member = await accountID(client, env('TABLEPRO_CLOUD_MEMBER_EMAIL')); + const product = await client.query( + "select id from products where plan = 'team' and not archived order by cycle = 'lifetime' desc, polar_created_at desc limit 1", + ); + if (product.rows.length === 0) { + throw new Error('no Team product'); + } + await client.query('begin'); + try { + const { rows } = await client.query('insert into teams (name) values ($1) returning id', [`Stack ${email}`]); + const teamID = rows[0].id; + await client.query("insert into team_members (team_id, account_id, role, has_seat) values ($1, $2, 'owner', true)", [teamID, owner]); + await client.query("insert into team_members (team_id, account_id, role, has_seat) values ($1, $2, 'member', true)", [teamID, member]); + await client.query( + "insert into licenses (team_id, product_id, source, seats, starts_at, note) values ($1, $2, 'manual', 5, now(), 'tablepro-account stack test')", + [teamID, product.rows[0].id], + ); + await client.query('commit'); + } catch (error) { + await client.query('rollback'); + throw error; + } +} + +// What PUT /api/teams/{team_id}/sharing writes, for the team the account owns. +async function teamLinksOff(client) { + await client.query( + "update teams set public_links_disabled = true where id in (select team_id from team_members where account_id = $1 and role = 'owner')", + [await accountID(client, email)], + ); +} + +async function main() { + const steps = { unverify, team, 'team-links-off': teamLinksOff }; + const run = steps[step]; + if (run === undefined) { + throw new Error(`no step ${step}: ${Object.keys(steps).join(', ')}`); + } + const client = new Client({ connectionString: databaseURL }); + await client.connect(); + try { + await run(client); + } finally { + await client.end(); + } +} + +main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/core/crates/account/tests/cloud_stack.rs b/core/crates/account/tests/cloud_stack.rs index 0502603f04..2be5552464 100644 --- a/core/crates/account/tests/cloud_stack.rs +++ b/core/crates/account/tests/cloud_stack.rs @@ -13,10 +13,14 @@ use async_trait::async_trait; use chrono::Utc; use secrecy::{ExposeSecret, SecretString}; use tablepro_account::{ - Account, AccountError, AccountSettings, AccountStatus, BrowserLauncher, CallbackPage, DeviceDescription, - EntitlementKeys, EntitlementProblem, FeatureAccess, MachineId, RefreshTokenVault, SignedIn, + Account, AccountError, AccountSettings, AccountStatus, BrowserLauncher, CallbackPage, CreatedShare, + DeviceDescription, EntitlementKeys, EntitlementProblem, FeatureAccess, MachineId, RefreshTokenVault, Share, + ShareExpiry, ShareKind, ShareRequest, SignedIn, }; +use tablepro_core::column::{ColumnType, ResultColumn}; use tablepro_core::credentials::SecretError; +use tablepro_core::export::{ResultExtent, build_snapshot}; +use tablepro_core::value::Value; use tokio::process::{Child, Command}; use url::Url; @@ -299,8 +303,21 @@ fn signed_in(account: &Account) -> SignedIn { } } -// Fails when the browser step does, not 10 minutes later when the sign-in times out. +// The stack takes 30 token requests a minute per client, which the whole suite passes; a sign-in it refuses for that +// waits out the Retry-After and starts again. async fn sign_in(account: &Account, browser: &Browser) -> Result<(), AccountError> { + loop { + match sign_in_once(account, browser).await { + Err(AccountError::RateLimited { retry_after }) => { + tokio::time::sleep(retry_after.unwrap_or(std::time::Duration::from_secs(60))).await; + } + answered => return answered, + } + } +} + +// Fails when the browser step does, not 10 minutes later when the sign-in times out. +async fn sign_in_once(account: &Account, browser: &Browser) -> Result<(), AccountError> { let signing_in = account.sign_in(std::future::pending()); tokio::pin!(signing_in); loop { @@ -605,3 +622,453 @@ async fn over_the_device_limit_a_removal_moves_the_license_here_and_an_offline_d let after = account.devices().await.expect("the devices"); assert!(after.iter().all(|device| device.id != other.id)); } + +const SHARED_SQL: &str = "SELECT id, label FROM orders"; +const PASSWORD: &str = "correct horse"; +// Well formed, and no link or team of the stack's. +const UNKNOWN_TOKEN: &str = "Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK"; +const UNKNOWN_TEAM: &str = "team_01h2xcejqtf2nbrexx3vqjhp41"; + +async fn signed_in_as(stack: &Stack, label: &str, licensed: bool) -> (Arc, Machine, Account) { + let user = User::new(stack, label); + let machine = Machine::new("Linux"); + let browser = Browser::new(&user, &machine, licensed); + let account = machine.account(stack, Arc::new(MemoryKeyring::default()), browser.clone()); + sign_in(&account, &browser).await.expect("signed in"); + (user, machine, account) +} + +async fn seed(user: &User, step: &str, member: Option<&User>) { + let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/browser/seed.cjs"); + let mut command = Command::new("node"); + command + .arg(script) + .arg(step) + .env("TABLEPRO_CLOUD_EMAIL", &user.email) + .kill_on_drop(true); + if let Some(member) = member { + command.env("TABLEPRO_CLOUD_MEMBER_EMAIL", &member.email); + } + let status = command.status().await.expect("node ran"); + assert!(status.success(), "the {step} seed failed: {status}"); +} + +fn refusal(answer: Result) -> (u16, String) { + match answer { + Err(AccountError::Refused { status, code, .. }) => (status, code), + other => panic!("not refused: {other:?}"), + } +} + +fn refused(status: u16, code: &str) -> (u16, String) { + (status, code.to_owned()) +} + +fn token_of(created: &CreatedShare) -> String { + let token = created.url.rsplit('/').next().unwrap_or_default().to_owned(); + assert!(tablepro_account::is_share_token(&token), "{}", created.url); + token +} + +fn query_share(title: &str) -> ShareRequest { + ShareRequest { + kind: ShareKind::Query, + sql: SHARED_SQL.to_owned(), + title: Some(title.to_owned()), + note: None, + dialect: Some("postgres".to_owned()), + expiry: None, + hide_sql: false, + allow_download: None, + password: None, + team_id: None, + snapshot: None, + } +} + +// `rows` numbered rows of a result of `row_count`, of which the client keeps `kept`. +fn result_share(title: &str, rows: usize, row_count: u64, kept: usize) -> ShareRequest { + let columns = [ + ResultColumn::new("id", ColumnType::untyped_text("bigint")), + ResultColumn::new("label", ColumnType::untyped_text("text")), + ]; + let rows: Vec> = (0..rows) + .map(|row| { + vec![ + Value::Int(i64::try_from(row).expect("a small row number")), + Value::Text(format!("row {row}")), + ] + }) + .collect(); + ShareRequest { + kind: ShareKind::Result, + snapshot: Some(build_snapshot(&columns, &rows, ResultExtent::complete(row_count), kept).expect("a snapshot")), + ..query_share(title) + } +} + +fn assert_expires_in(share: &Share, days: i64) { + let expires_at = share.expires_at.expect("an expiry"); + let wanted = Utc::now() + chrono::TimeDelta::days(days); + assert!( + (expires_at - wanted).num_seconds().abs() < 300, + "{expires_at} is not {days} days from now" + ); +} + +// The public read as the viewer page makes it, for what the account does not keep: the rows and the headers. +async fn public_read( + stack: &Stack, + token: &str, + password: Option<&str>, +) -> (u16, reqwest::header::HeaderMap, serde_json::Value) { + let mut request = reqwest::Client::new().get(format!("{}/shared/{token}", stack.api_url)); + if let Some(password) = password { + request = request.header("X-Share-Password", password); + } + let answer = request.send().await.expect("an answer"); + let status = answer.status().as_u16(); + let headers = answer.headers().clone(); + let body = answer.text().await.expect("the body"); + (status, headers, serde_json::from_str(&body).expect("a JSON body")) +} + +fn rows(body: &serde_json::Value) -> &[serde_json::Value] { + body["snapshot"]["rows"] + .as_array() + .map(Vec::as_slice) + .unwrap_or_default() +} + +fn assert_public_headers(headers: &reqwest::header::HeaderMap) { + for (name, value) in [ + ("x-robots-tag", "noindex, nofollow, noarchive"), + ("cache-control", "no-store"), + ("referrer-policy", "no-referrer"), + ] { + assert_eq!(headers.get(name).and_then(|it| it.to_str().ok()), Some(value), "{name}"); + } +} + +// A Turnstile token the stack's siteverify passes for the share_report action. +fn report_token() -> String { + std::env::var("TABLEPRO_CLOUD_REPORT_TOKEN").expect("TABLEPRO_CLOUD_REPORT_TOKEN is not set") +} + +async fn report(stack: &Stack, token: &str, turnstile_token: Option<&str>) -> (u16, String) { + let body = match turnstile_token { + Some(turnstile_token) => format!( + r#"{{"reason":"spam","turnstile_token":{}}}"#, + serde_json::to_string(turnstile_token).expect("a JSON string") + ), + None => r#"{"reason":"spam"}"#.to_owned(), + }; + let answer = reqwest::Client::new() + .post(format!("{}/shared/{token}/report", stack.api_url)) + .header("Content-Type", "application/json") + .body(body) + .send() + .await + .expect("an answer"); + let status = answer.status().as_u16(); + (status, answer.text().await.expect("the body").trim_end().to_owned()) +} + +fn pro_only_requests() -> [(&'static str, ShareRequest); 4] { + [ + ( + "password", + ShareRequest { + password: Some(SecretString::from(PASSWORD)), + ..query_share("Locked") + }, + ), + ( + "never", + ShareRequest { + expiry: Some(ShareExpiry::Never), + ..query_share("Forever") + }, + ), + ( + "no download", + ShareRequest { + allow_download: Some(false), + ..result_share("Kept", 1, 1, 1) + }, + ), + ( + "team", + ShareRequest { + team_id: Some(UNKNOWN_TEAM.to_owned()), + ..query_share("Team") + }, + ), + ] +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires a tablepro-cloud stack"] +async fn a_free_account_holds_five_links_and_is_refused_a_sixth_and_every_pro_option() { + let stack = Stack::from_env(); + let (_user, _machine, account) = signed_in_as(&stack, "share-free", false).await; + + let limits = account.share_limits().await.expect("the limits"); + assert_eq!(limits.plan, "free"); + assert_eq!((limits.live, limits.live_limit, limits.max_rows), (0, 5, 1_000)); + assert_eq!( + limits.expiries, + [ShareExpiry::OneDay, ShareExpiry::SevenDays, ShareExpiry::ThirtyDays] + ); + assert_eq!(limits.default_expiry, Some(ShareExpiry::ThirtyDays)); + assert!(!limits.password && !limits.disable_download && !limits.team); + assert!(limits.email_verified && !limits.sharing_disabled); + for (option, request) in pro_only_requests() { + let answer = account.create_share(request).await; + assert_eq!(refusal(answer), refused(403, "pro_required"), "{option}"); + } + + let mut created = Vec::new(); + for (expiry, days) in [ + (None, 30), + (Some(ShareExpiry::OneDay), 1), + (Some(ShareExpiry::SevenDays), 7), + (Some(ShareExpiry::ThirtyDays), 30), + ] { + let share = account + .create_share(ShareRequest { + expiry, + ..query_share("Orders") + }) + .await + .expect("created"); + assert_expires_in(&share.share, days); + assert_eq!( + (share.share.scope.as_str(), share.share.state.as_str()), + ("account", "live") + ); + created.push(share); + } + // A client that kept too many rows: the server keeps the plan's 1,000 and the true count. + let cut = account + .create_share(result_share("Big", 1_001, 48_210, 1_001)) + .await + .expect("created"); + assert_eq!((cut.share.row_count, cut.share.truncated), (Some(48_210), Some(true))); + let opened = account.fetch_shared(&token_of(&cut), None).await.expect("the link"); + assert_eq!((opened.row_count, opened.truncated), (Some(48_210), Some(true))); + let (status, _, body) = public_read(&stack, &token_of(&cut), None).await; + assert_eq!((status, rows(&body).len()), (200, 1_000)); + + let sixth = account.create_share(query_share("Sixth")).await; + assert_eq!(refusal(sixth), refused(409, "share_limit_reached")); + let listed = account.list_shares(true, None, None).await.expect("the list"); + assert_eq!(listed.shares.len(), 5); + assert!( + listed + .shares + .iter() + .all(|share| share.url.is_some() && share.sql.is_none()), + "{listed:?}" + ); + extend_revoke_and_share_again(&stack, &account, &created).await; +} + +// The 1-day link is extended to 30 days; the 7-day one is revoked, which frees a slot for a result without its SQL. +async fn extend_revoke_and_share_again(stack: &Stack, account: &Account, created: &[CreatedShare]) { + let extended = account + .extend_share(&created[1].share.id, ShareExpiry::ThirtyDays) + .await + .expect("extended"); + assert_expires_in(&extended, 30); + assert!(extended.is_live()); + + let revoked = &created[2]; + account.revoke_share(&revoked.share.id).await.expect("revoked"); + let gone = account.fetch_shared(&token_of(revoked), None).await; + assert_eq!(refusal(gone), refused(404, "not_found")); + let again = account.extend_share(&revoked.share.id, ShareExpiry::ThirtyDays).await; + assert_eq!(refusal(again), refused(409, "share_revoked")); + assert_eq!(account.share_limits().await.expect("the limits").live, 4); + + let hidden = account + .create_share(ShareRequest { + hide_sql: true, + ..result_share("Hidden", 3, 3, 1_000) + }) + .await + .expect("created in the freed slot"); + assert!(hidden.share.hide_sql); + let opened = account.fetch_shared(&token_of(&hidden), None).await.expect("the link"); + assert_eq!(opened.sql, None); + assert_eq!((opened.row_count, opened.truncated), (Some(3), Some(false))); + let (status, _, body) = public_read(stack, &token_of(&hidden), None).await; + assert_eq!(status, 200); + assert!(body.get("sql").is_none(), "{body}"); + assert_eq!(rows(&body).len(), 3); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires a tablepro-cloud stack"] +async fn an_account_whose_email_is_not_verified_is_told_so_and_shares_nothing() { + let stack = Stack::from_env(); + let (user, _machine, account) = signed_in_as(&stack, "share-unverified", false).await; + seed(&user, "unverify", None).await; + + let limits = account.share_limits().await.expect("the limits"); + let refusal = refusal(account.create_share(query_share("Orders")).await); + + assert!(!limits.email_verified); + assert_eq!(refusal, refused(403, "email_unverified")); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires a tablepro-cloud stack"] +async fn a_pro_link_behind_a_password_opens_with_it_keeps_every_digit_and_takes_a_report() { + let stack = Stack::from_env(); + let (_user, _machine, account) = signed_in_as(&stack, "share-pro", true).await; + let limits = account.share_limits().await.expect("the limits"); + assert_eq!(limits.plan, "pro"); + assert_eq!((limits.live_limit, limits.max_rows), (1_000, 10_000)); + assert_eq!(limits.expiries, ShareExpiry::ALL); + assert_eq!(limits.default_expiry, Some(ShareExpiry::Never)); + assert!(limits.password && limits.disable_download && limits.team); + + let columns = [ + ResultColumn::new("id", ColumnType::untyped_text("bigint")), + ResultColumn::new("label", ColumnType::untyped_text("text")), + ]; + let rows_shared = [ + vec![Value::Int(9_007_199_254_740_993), Value::Text("past 2^53".to_owned())], + vec![Value::Int(42), Value::Text("small".to_owned())], + ]; + let max_rows = usize::try_from(limits.max_rows).expect("a row count"); + let created = account + .create_share(ShareRequest { + kind: ShareKind::Result, + password: Some(SecretString::from(PASSWORD)), + allow_download: Some(false), + snapshot: Some( + build_snapshot(&columns, &rows_shared, ResultExtent::complete(2), max_rows).expect("a snapshot"), + ), + ..query_share("Ledger") + }) + .await + .expect("created"); + assert!(created.share.has_password && !created.share.allow_download); + assert_eq!(created.share.expires_at, None); + assert_eq!( + (created.share.row_count, created.share.truncated), + (Some(2), Some(false)) + ); + let token = token_of(&created); + assert_password_gate(&stack, &account, &token).await; + + let (status, headers, body) = public_read(&stack, &token, Some(PASSWORD)).await; + assert_eq!(status, 200); + assert_public_headers(&headers); + assert_eq!(rows(&body)[0][0], serde_json::json!("9007199254740993")); + assert_eq!(rows(&body)[1][0], serde_json::json!(42)); + assert_eq!(body["made_with"], "TablePro"); + + assert_eq!( + report(&stack, &token, Some(&report_token())).await, + (202, "{}".to_owned()) + ); + assert_eq!( + report(&stack, UNKNOWN_TOKEN, Some(&report_token())).await, + (202, "{}".to_owned()) + ); + let (status, problem) = report(&stack, &token, None).await; + assert!( + status == 403 && problem.contains("human_check_failed"), + "{status} {problem}" + ); + assert_password_guesses_run_out(&account, &token).await; + + account.revoke_share(&created.share.id).await.expect("revoked"); + let gone = account.fetch_shared(&token, None).await; + assert_eq!(refusal(gone), refused(404, "not_found")); + let (status, headers, _) = public_read(&stack, &token, None).await; + assert_eq!(status, 404); + assert_public_headers(&headers); +} + +async fn assert_password_gate(stack: &Stack, account: &Account, token: &str) { + let required = account.fetch_shared(token, None).await; + let wrong = account + .fetch_shared(token, Some(&SecretString::from("battery staple"))) + .await; + let opened = account + .fetch_shared(token, Some(&SecretString::from(PASSWORD))) + .await + .expect("opened with its password"); + assert_eq!(refusal(required), refused(401, "share_password_required")); + assert_eq!(refusal(wrong), refused(401, "share_password_wrong")); + assert_eq!(opened.sql.as_deref(), Some(SHARED_SQL)); + assert!(!opened.allow_download); + assert_eq!( + (opened.row_count, opened.truncated, opened.expires_at), + (Some(2), Some(false), None) + ); + let (status, headers, problem) = public_read(stack, token, None).await; + assert_eq!( + (status, problem["code"].as_str()), + (401, Some("share_password_required")) + ); + assert_public_headers(&headers); +} + +// 10 guesses per link and client in 15 minutes; the ones before count too. +async fn assert_password_guesses_run_out(account: &Account, token: &str) { + let guess = SecretString::from("battery staple"); + for _ in 0..10 { + match account.fetch_shared(token, Some(&guess)).await { + Err(AccountError::RateLimited { retry_after }) => { + assert!(retry_after.is_some_and(|wait| wait.as_secs() > 0), "{retry_after:?}"); + return; + } + other => assert_eq!(refusal(other), refused(401, "share_password_wrong")), + } + } + panic!("10 more wrong guesses were never limited"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires a tablepro-cloud stack"] +async fn a_seated_member_shares_a_team_link_outside_its_own_limit_until_the_team_turns_public_links_off() { + let stack = Stack::from_env(); + let (owner, _owner_machine, _owner_account) = signed_in_as(&stack, "share-owner", false).await; + let (member, _member_machine, account) = signed_in_as(&stack, "share-member", false).await; + seed(&owner, "team", Some(&member)).await; + + let limits = account.share_limits().await.expect("the limits"); + assert_eq!((limits.plan.as_str(), limits.team), ("pro", true)); + let profile = account.profile().await.expect("the profile"); + let team = profile.teams.first().expect("the team").team.id.clone(); + let created = account + .create_share(ShareRequest { + team_id: Some(team.clone()), + ..query_share("Team orders") + }) + .await + .expect("created"); + assert_eq!(created.share.scope, "team"); + assert_eq!(created.share.team_id.as_deref(), Some(team.as_str())); + let personal = account.list_shares(false, None, None).await.expect("the list"); + assert!(personal.shares.is_empty(), "{personal:?}"); + assert_eq!(account.share_limits().await.expect("the limits").live, 0); + let token = token_of(&created); + account.fetch_shared(&token, None).await.expect("the team link"); + + seed(&owner, "team-links-off", None).await; + let another = account + .create_share(ShareRequest { + team_id: Some(team), + ..query_share("Another") + }) + .await; + assert_eq!(refusal(another), refused(403, "team_sharing_disabled")); + let suspended = account.fetch_shared(&token, None).await; + assert_eq!(refusal(suspended), refused(404, "not_found")); +} diff --git a/core/crates/core/Cargo.toml b/core/crates/core/Cargo.toml index f85d042be6..2ed7507434 100644 --- a/core/crates/core/Cargo.toml +++ b/core/crates/core/Cargo.toml @@ -12,17 +12,23 @@ comfy-table.workspace = true csv.workspace = true flate2.workspace = true futures.workspace = true +# The per-process key of a masked value's Stable Hash. +getrandom = "0.3" +hmac.workspace = true num-bigint.workspace = true percent-encoding.workspace = true +regex.workspace = true rust_xlsxwriter.workspace = true rustls-pki-types.workspace = true secrecy.workspace = true serde.workspace = true serde_json.workspace = true +sha2.workspace = true sqlparser.workspace = true thiserror.workspace = true tokio = { workspace = true, features = ["io-util", "rt"] } tokio-util.workspace = true +unicode-segmentation.workspace = true unicode-width.workspace = true uuid.workspace = true diff --git a/core/crates/core/src/browse/build_export.rs b/core/crates/core/src/browse/build_export.rs index bd8ad73240..59846263ff 100644 --- a/core/crates/core/src/browse/build_export.rs +++ b/core/crates/core/src/browse/build_export.rs @@ -19,8 +19,23 @@ use super::{BrowseSqlError, ExportRequest}; /// could be written. A table's rows hold only its columns, so SQL reads /// the listed columns for either `ExportFields`. pub fn build_export(dialect: &dyn SqlDialect, request: &ExportRequest<'_>) -> Result { + export_with(dialect, request, StatementBuilder::new()) +} + +// The export's statement, every page at once and with no row window, its filter's values written as literals: the +// query a table view stands for, for a person to read or a share link to carry. +pub fn build_view_sql(dialect: &dyn SqlDialect, request: &ExportRequest<'_>) -> Result { + let (sql, _) = export_with(dialect, request, StatementBuilder::inlining())?.into_parts(); + Ok(sql) +} + +fn export_with( + dialect: &dyn SqlDialect, + request: &ExportRequest<'_>, + mut builder: StatementBuilder, +) -> Result { if crate::document::speaks_shell(dialect) { - return crate::document::export(request); + return crate::document::export(request, &builder); } let projection = projection_list(dialect, request.columns)?; let components = identity_components(request.identity, request.columns)?; @@ -35,7 +50,6 @@ pub fn build_export(dialect: &dyn SqlDialect, request: &ExportRequest<'_>) -> Re (TablePaging::InStatement, false) => with_tiebreak(user, &identity_order(dialect, request.table, &components)?), }; - let mut builder = StatementBuilder::new(); let mut conditions = Vec::new(); if build_filter(&mut builder, dialect, request.columns, request.filter)? { conditions.push(builder.take_fragment()); diff --git a/core/crates/core/src/browse/mod.rs b/core/crates/core/src/browse/mod.rs index fc31bf97dc..053c99d78c 100644 --- a/core/crates/core/src/browse/mod.rs +++ b/core/crates/core/src/browse/mod.rs @@ -25,7 +25,7 @@ mod tests; pub use browse_page::BrowsePage; pub use browse_sql_error::BrowseSqlError; pub use build_count::build_count; -pub use build_export::build_export; +pub use build_export::{build_export, build_view_sql}; pub use build_page::build_page; pub use declared_precision::DeclaredPrecisionSink; pub use export_request::{ExportFields, ExportRequest}; diff --git a/core/crates/core/src/browse/tests.rs b/core/crates/core/src/browse/tests.rs index e8d458bf7c..f772fde083 100644 --- a/core/crates/core/src/browse/tests.rs +++ b/core/crates/core/src/browse/tests.rs @@ -618,3 +618,47 @@ fn a_page_splits_into_keys_the_dml_can_bind_back() { assert_eq!(delete.sql(), r#"DELETE FROM "public"."users" WHERE rowid = $1"#); assert_eq!(delete.params()[0].value(), &Value::Int(77)); } + +#[test] +fn a_view_s_sql_reads_every_page_with_its_filter_values_written_in() { + let dialect = TestDialect::exact(); + let columns = columns(); + let table = table(); + let filter = FilterSet { + combinator: Combinator::And, + rules: vec![ + FilterRule { + column: "id".to_owned(), + op: FilterOp::Gt, + value: Some(FilterValue::Single("18".to_owned())), + }, + FilterRule { + column: "name".to_owned(), + op: FilterOp::Contains, + value: Some(FilterValue::Single("O'Brien".to_owned())), + }, + ], + extra_sql: None, + }; + let sort = [SortKey { + column: 1, + ascending: false, + }]; + let request = ExportRequest { + table: &table, + columns: &columns, + filter: &filter, + sort: &sort, + identity: &by_id(), + fields: ExportFields::Listed, + }; + + let sql = build_view_sql(&dialect, &request).expect("the view's SQL"); + let export = build_export(&dialect, &request).expect("the export"); + + assert_eq!( + sql, + r#"SELECT "id", "name" FROM "public"."users" WHERE "id" > 18 AND "name" LIKE '%O''Brien%' ESCAPE '!' ORDER BY "users"."name" DESC, "users"."id" ASC"# + ); + assert_eq!(export.params().len(), 2, "the export still binds its values"); +} diff --git a/core/crates/core/src/document/document_read.rs b/core/crates/core/src/document/document_read.rs index 807ad7d896..1907ed9573 100644 --- a/core/crates/core/src/document/document_read.rs +++ b/core/crates/core/src/document/document_read.rs @@ -7,7 +7,7 @@ use crate::dml::BuildSqlError; use crate::filter::FilterSet; use crate::meta::{PageCost, PagePosition, PageStability, RowIdentity, TableRef}; use crate::sql_syntax::mongo::{CallRoot, ShellCall, ShellMethod, ShellValue, is_addressable_field}; -use crate::statement::Statement; +use crate::statement::{Statement, StatementBuilder}; use crate::value::Value; use super::document_filter::{field, filter_document}; @@ -102,9 +102,9 @@ pub(crate) fn count(table: &TableRef, columns: &[ColumnInfo], filter: &FilterSet /// Every document the filter matches, in the page's order, for an export. /// `ExportFields::Every` writes no `$project`, so the server sends each /// whole document and the driver finds the columns in them. -pub(crate) fn export(request: &ExportRequest<'_>) -> Result { +pub(crate) fn export(request: &ExportRequest<'_>, builder: &StatementBuilder) -> Result { let key = key_column(request.identity, request.columns)?; - let mut params = ShellParams::new(); + let mut params = ShellParams::like(builder); let mut stages = Vec::new(); if let Some(filter) = filter_document(request.columns, request.filter, &mut params)? { stages.push(field("$match", filter)); diff --git a/core/crates/core/src/document/shell_params.rs b/core/crates/core/src/document/shell_params.rs index 2065f82639..1a8fec7a4d 100644 --- a/core/crates/core/src/document/shell_params.rs +++ b/core/crates/core/src/document/shell_params.rs @@ -1,8 +1,8 @@ use std::cmp::Ordering; -use crate::column::{ColumnInfo, SqlTypeExpr}; -use crate::dialect::BindError; -use crate::sql_syntax::mongo::{ShellCall, ShellValue}; +use crate::column::{ColumnInfo, ColumnType, SqlTypeExpr}; +use crate::dialect::{BindError, LiteralError}; +use crate::sql_syntax::mongo::{ShellCall, ShellValue, parse_value}; use crate::statement::{BoundParam, ParamType, Statement, StatementBuilder}; use crate::value::Value; use crate::value::order::decimal_of; @@ -19,9 +19,22 @@ impl ShellParams { Self::default() } + // As `StatementBuilder::inlining`: each value is written as its shell literal and none is bound. + pub(crate) fn like(builder: &StatementBuilder) -> Self { + match builder.is_inlining() { + true => Self { + builder: StatementBuilder::inlining(), + }, + false => Self::new(), + } + } + /// Bind `value` as the next parameter, typed by `column` where there /// is one, and return the marker that stands for it. pub(crate) fn bind(&mut self, value: Value, column: Option<&ColumnInfo>) -> Result { + if self.builder.is_inlining() { + return inline_literal(&value, column); + } let param = bind_param(value, column, None)?; Ok(ShellValue::Param(self.builder.push_bound(param))) } @@ -53,6 +66,22 @@ impl ShellParams { } } +fn inline_literal(value: &Value, column: Option<&ColumnInfo>) -> Result { + let unknown = ColumnType::unknown(); + let column_type = column.map_or(&unknown, |column| &column.column_type); + let text = super::shell_literal(value, column_type).map_err(|error| match error { + LiteralError::Undecodable { reason } => BindError::Undecodable { reason }, + LiteralError::Unrepresentable { found } => BindError::Unrepresentable { + expected: "a shell literal", + found, + }, + })?; + parse_value(&text).map_err(|_| BindError::Unrepresentable { + expected: "a shell literal", + found: value.variant_name(), + }) +} + fn renumbered(value: &ShellValue, by: usize) -> ShellValue { match value { ShellValue::Param(index) => ShellValue::Param(index + by), diff --git a/core/crates/core/src/document/tests.rs b/core/crates/core/src/document/tests.rs index afbbd6907f..8e233bd4b1 100644 --- a/core/crates/core/src/document/tests.rs +++ b/core/crates/core/src/document/tests.rs @@ -1,5 +1,6 @@ use crate::browse::{ ExportFields, ExportRequest, PageRequest, RowKeyLayout, SortKey, build_count, build_export, build_page, + build_view_sql, }; use crate::column::{ ColumnDefault, ColumnInfo, ColumnKind, ColumnType, FloatWidth, IntegerKind, IntegerWidth, ReadForm, TextLength, @@ -483,6 +484,35 @@ fn an_export_reads_every_document_in_page_order() { ); } +#[test] +fn a_view_s_shell_command_writes_its_filter_values_in() { + let columns = columns(); + let filter = FilterSet { + combinator: Combinator::And, + rules: vec![FilterRule { + column: "qty".to_owned(), + op: FilterOp::Gt, + value: Some(FilterValue::Single("5".to_owned())), + }], + extra_sql: None, + }; + let request = ExportRequest { + table: &TableRef::unqualified("users"), + columns: &columns, + filter: &filter, + sort: &[], + identity: &by_id(), + fields: ExportFields::Every, + }; + + let text = build_view_sql(&shell(), &request).expect("the view's command"); + + assert_eq!( + text, + r#"db.getCollection("users").aggregate([{"$match": {"qty": {"$gt": 5}}}, {"$sort": {"_id": 1}}], {"allowDiskUse": true})"# + ); +} + #[test] fn an_export_of_every_field_reads_whole_documents_in_page_order() { let statement = export(ExportFields::Every); diff --git a/core/crates/core/src/export/mod.rs b/core/crates/core/src/export/mod.rs index d4f28a061a..474faf06e9 100644 --- a/core/crates/core/src/export/mod.rs +++ b/core/crates/core/src/export/mod.rs @@ -7,6 +7,7 @@ mod json; mod json_field_names; mod markdown; mod render_insert_error; +mod snapshot; mod sql; mod text_table; mod tsv; @@ -32,6 +33,10 @@ pub use json::{render_json, row_to_json}; pub use json_field_names::json_field_names; pub use markdown::render_markdown; pub use render_insert_error::RenderInsertError; +pub use snapshot::{ + MAX_SNAPSHOT_BODY_BYTES, MAX_SNAPSHOT_CELL_BYTES, ResultExtent, Snapshot, SnapshotColumn, SnapshotFit, + SnapshotRefusal, build_snapshot, snapshot_row_count, +}; pub use sql::{literal, render_inserts, render_sql_insert}; pub use text_table::{TextTableError, render_text_table}; pub use tsv::{TSV_NULL, render_tsv, tsv_writer_builder}; diff --git a/core/crates/core/src/export/snapshot.rs b/core/crates/core/src/export/snapshot.rs new file mode 100644 index 0000000000..fa533ee5a6 --- /dev/null +++ b/core/crates/core/src/export/snapshot.rs @@ -0,0 +1,625 @@ +use serde::ser::{Serialize, SerializeSeq, Serializer}; +use serde_json::value::RawValue; +use thiserror::Error; + +use crate::Truncation; +use crate::column::{ColumnKind, ResultColumn}; +use crate::masking::MaskingStyle; +use crate::value::Value; + +use super::json::JsonCell; +use super::value_text::element_kind; + +// A result as a share link carries it. Cells are raw JSON tokens, so a big number keeps every digit and a JSON +// column keeps its key order, which serde_json::Value would lose. +#[derive(Debug, Clone)] +pub struct Snapshot { + pub columns: Vec, + pub rows: Vec>>, + // Every row of the result, the ones left out included; None when it was cut and nobody counted it. + pub row_count: Option, + // Rows exist beyond those here, how many unknown. + pub more_rows: bool, +} + +// What a result knows of its rows. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ResultExtent { + // The rows the result holds. + pub held: u64, + // Every row of the result when something counted them: the server, or a count of a table view. + pub total: Option, + // Rows may follow those held: a row or byte limit, one page of a table, or a run that ended first. + pub cut: bool, +} + +impl ResultExtent { + pub fn complete(held: u64) -> Self { + Self { + held, + total: None, + cut: false, + } + } + + // As the result's `ResultEvent::ResultSetFinished` reports it. + pub fn finished(held: u64, total_rows: Option, truncation: Truncation) -> Self { + Self { + held, + total: total_rows, + cut: truncation != Truncation::Complete, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SnapshotColumn { + pub name: String, + pub type_name: String, + // How the app masked the column's values before they left it; the viewer marks the column. + pub masked: Option, +} + +impl Snapshot { + pub fn truncated(&self) -> bool { + self.more_rows || self.row_count.is_some_and(|count| count > self.rows.len() as u64) + } +} + +// What a snapshot body may weigh, as the macOS app counts it (ShareSnapshotBuilder): under the server's 5 MiB, so a +// size it counts differently never refuses a share the app offered. +pub const MAX_SNAPSHOT_BODY_BYTES: usize = 4_500_000; +pub const MAX_SNAPSHOT_CELL_BYTES: usize = 256 * 1_024; + +// A share that cannot go out even cut: the server refuses a cell this big, a body with no row and a body with no +// column. +#[derive(Debug, Clone, PartialEq, Eq, Error)] +pub enum SnapshotRefusal { + #[error("a value in column {column} is over 256 KiB")] + Cell { column: String }, + #[error("the first row alone is over the share's 4.5 MB")] + FirstRow, + #[error("every column was removed")] + NoColumns, +} + +impl SnapshotRefusal { + pub fn code(&self) -> &'static str { + match self { + Self::Cell { .. } | Self::FirstRow => "export.snapshot_too_large", + Self::NoColumns => "export.snapshot_no_columns", + } + } +} + +// Takes at most `max_rows` rows, and stops before the row that would take the body past `MAX_SNAPSHOT_BODY_BYTES`; the +// row count stays the result's, so the server marks the share cut. A result cut with no count says only that more rows +// exist, so a viewer never reads the rows held as the whole result. +pub fn build_snapshot>( + columns: &[ResultColumn], + rows: impl IntoIterator, + extent: ResultExtent, + max_rows: usize, +) -> Result { + if columns.is_empty() { + return Err(SnapshotRefusal::NoColumns); + } + let mut budget = Budget::new(columns); + let mut kept: Vec>> = Vec::new(); + for row in rows.into_iter().take(max_rows) { + let (cells, bytes) = sized_row(columns, row.as_ref())?; + if !budget.take(bytes, kept.is_empty())? { + break; + } + kept.push(cells); + } + let at_least = extent.held.max(kept.len() as u64); + let (row_count, more_rows) = match (extent.total, extent.cut) { + (Some(total), _) => (Some(total.max(at_least)), false), + (None, false) => (Some(at_least), false), + (None, true) => (None, true), + }; + Ok(Snapshot { + columns: columns + .iter() + .map(|column| SnapshotColumn { + name: column.name.clone(), + type_name: column.column_type.name.clone(), + masked: None, + }) + .collect(), + row_count, + more_rows, + rows: kept, + }) +} + +// How many of `rows` a snapshot of `max_rows` keeps, by the same budget, for a preview or a summary that must read +// exactly the rows sent. +pub fn snapshot_row_count>( + columns: &[ResultColumn], + rows: impl IntoIterator, + max_rows: usize, +) -> Result { + let mut fit = SnapshotFit::new(columns)?; + let mut kept = 0; + for row in rows.into_iter().take(max_rows) { + if !fit.take(row.as_ref())? { + break; + } + kept += 1; + } + Ok(kept) +} + +// The snapshot's cut a row at a time, for a reader that holds no rows: true while a row fits the body, false for the +// first that does not, and the refusal `build_snapshot` would give. +pub struct SnapshotFit<'c> { + columns: &'c [ResultColumn], + budget: Budget, + kept: usize, +} + +impl<'c> SnapshotFit<'c> { + pub fn new(columns: &'c [ResultColumn]) -> Result { + if columns.is_empty() { + return Err(SnapshotRefusal::NoColumns); + } + Ok(Self { + columns, + budget: Budget::new(columns), + kept: 0, + }) + } + + pub fn take(&mut self, row: &[Value]) -> Result { + let (_, bytes) = sized_row(self.columns, row)?; + let fits = self.budget.take(bytes, self.kept == 0)?; + self.kept += usize::from(fits); + Ok(fits) + } +} + +// The body as the macOS app weighs it: braces and each column's quoted name plus 24, then each row's brackets, commas +// and closing comma. +struct Budget { + spent: usize, +} + +impl Budget { + fn new(columns: &[ResultColumn]) -> Self { + Self { + spent: 2 + columns + .iter() + .map(|column| quoted_bytes(&column.name) + 24) + .sum::(), + } + } + + // False once the row would cross the budget; the first row not fitting refuses the share. + fn take(&mut self, row: usize, first: bool) -> Result { + if self.spent + row > MAX_SNAPSHOT_BODY_BYTES { + return match first { + true => Err(SnapshotRefusal::FirstRow), + false => Ok(false), + }; + } + self.spent += row; + Ok(true) + } +} + +fn sized_row(columns: &[ResultColumn], row: &[Value]) -> Result<(Vec>, usize), SnapshotRefusal> { + let mut bytes = 2 + columns.len().saturating_sub(1) + 1; + let mut cells = Vec::with_capacity(columns.len()); + for (index, column) in columns.iter().enumerate() { + let value = row.get(index).unwrap_or(&Value::Null); + let value = crate::document::json_number(value, &column.column_type); + let cell = SnapshotCell { + value: &value, + kind: &column.column_type.kind, + }; + let token = serde_json::value::to_raw_value(&cell).unwrap_or_else(|_| RawValue::NULL.to_owned()); + let size = cell_bytes(&value, &column.column_type.kind, &token); + if size > MAX_SNAPSHOT_CELL_BYTES { + return Err(SnapshotRefusal::Cell { + column: column.name.clone(), + }); + } + bytes += size; + cells.push(token); + } + Ok((cells, bytes)) +} + +// A cell's JSON bytes as the macOS app counts them: a document and a number as written, a string with `<`, `>` and `&` +// escaped as six bytes each, an array element by element. +fn cell_bytes(value: &Value, kind: &ColumnKind, token: &RawValue) -> usize { + match value { + Value::Array(values) => { + let element = element_kind(kind); + 2 + values.len().saturating_sub(1) + + values + .iter() + .map(|value| { + let cell = SnapshotCell { value, kind: element }; + serde_json::value::to_raw_value(&cell).map_or(4, |token| cell_bytes(value, element, &token)) + }) + .sum::() + } + Value::Json(_) => token.get().len(), + _ => match token.get().starts_with('"') { + true => serde_json::from_str::(token.get()).map_or(token.get().len(), |text| quoted_bytes(&text)), + false => token.get().len(), + }, + } +} + +fn quoted_bytes(text: &str) -> usize { + 2 + text + .bytes() + .map(|byte| match byte { + b'"' | b'\\' | 0x08 | 0x0c | b'\n' | b'\r' | b'\t' => 2, + 0x00..=0x1f | b'<' | b'>' | b'&' => 6, + _ => 1, + }) + .sum::() +} + +// The export's JSON cell, except that bytes name their size: a viewer has no use for hex it cannot show. +struct SnapshotCell<'a> { + value: &'a Value, + kind: &'a ColumnKind, +} + +impl Serialize for SnapshotCell<'_> { + fn serialize(&self, serializer: S) -> Result { + match self.value { + Value::Bytes(bytes) => serializer.serialize_str(&format!("(binary, {} bytes)", bytes.len())), + Value::Array(values) => { + let element = element_kind(self.kind); + let mut seq = serializer.serialize_seq(Some(values.len()))?; + for value in values { + seq.serialize_element(&SnapshotCell { value, kind: element })?; + } + seq.end() + } + value => JsonCell { value, kind: self.kind }.serialize(serializer), + } + } +} + +#[cfg(test)] +mod tests { + use crate::column::{ColumnKind, IntegerKind, IntegerWidth, TemporalZone, TextLength}; + use crate::value::{JsonText, Temporal, UndecodableReason, UndecodedValue}; + + use super::super::test_columns::{cols, typed}; + use super::*; + + fn snap>( + columns: &[ResultColumn], + rows: impl IntoIterator, + extent: ResultExtent, + max_rows: usize, + ) -> Snapshot { + build_snapshot(columns, rows, extent, max_rows).expect("a snapshot") + } + + fn texts(snapshot: &Snapshot) -> Vec> { + snapshot + .rows + .iter() + .map(|row| row.iter().map(|cell| cell.get()).collect()) + .collect() + } + + #[test] + fn rows_past_the_cap_are_left_out_and_counted() { + let columns = cols(&["n"]); + let rows: Vec> = (0..5).map(|row| vec![Value::Int(row)]).collect(); + + let snapshot = snap(&columns, &rows, ResultExtent::complete(rows.len() as u64), 3); + + assert_eq!(texts(&snapshot), [["0"], ["1"], ["2"]]); + assert_eq!(snapshot.row_count, Some(5)); + assert!(snapshot.truncated()); + } + + #[test] + fn a_result_within_the_cap_is_whole() { + let columns = cols(&["n"]); + let rows = vec![vec![Value::Int(1)], vec![Value::Int(2)]]; + + let snapshot = snap(&columns, &rows, ResultExtent::complete(2), 1_000); + + assert_eq!(snapshot.rows.len(), 2); + assert_eq!(snapshot.row_count, Some(2)); + assert!(!snapshot.truncated()); + } + + #[test] + fn a_count_below_the_rows_taken_is_raised_to_them() { + let columns = cols(&["n"]); + let rows = vec![vec![Value::Int(1)], vec![Value::Int(2)]]; + + let snapshot = snap(&columns, &rows, ResultExtent::complete(0), 10); + + assert_eq!(snapshot.row_count, Some(2)); + } + + #[test] + fn a_cut_result_nobody_counted_says_only_that_more_rows_exist() { + let columns = cols(&["n"]); + let rows = vec![vec![Value::Int(1)], vec![Value::Int(2)]]; + let cut = |total, truncation| ResultExtent::finished(2, total, truncation); + + let uncounted = snap(&columns, &rows, cut(None, Truncation::ReadPastLimit), 10); + let byte_limit = snap(&columns, &rows, cut(None, Truncation::ByteLimit), 10); + let counted = snap(&columns, &rows, cut(Some(48_210), Truncation::ReadPastLimit), 10); + + assert_eq!((uncounted.row_count, uncounted.more_rows), (None, true)); + assert!(uncounted.truncated()); + assert_eq!((byte_limit.row_count, byte_limit.more_rows), (None, true)); + assert_eq!((counted.row_count, counted.more_rows), (Some(48_210), false)); + assert!(counted.truncated()); + } + + #[test] + fn columns_carry_their_name_and_type() { + let columns = vec![ + typed( + "id", + "bigint", + ColumnKind::Integer(IntegerKind { + width: IntegerWidth::W64, + signed: true, + }), + ), + typed("body", "text", ColumnKind::Other), + ]; + + let snapshot = snap( + &columns, + std::iter::empty::>(), + ResultExtent::complete(0), + 10, + ); + + assert_eq!( + snapshot.columns, + [ + SnapshotColumn { + name: "id".to_owned(), + type_name: "bigint".to_owned(), + masked: None, + }, + SnapshotColumn { + name: "body".to_owned(), + type_name: "text".to_owned(), + masked: None, + } + ] + ); + } + + #[test] + fn big_numbers_and_decimals_keep_every_digit() { + let columns = vec![ + typed( + "u", + "bigint unsigned", + ColumnKind::Integer(IntegerKind { + width: IntegerWidth::W64, + signed: false, + }), + ), + typed( + "amount", + "numeric(40,20)", + ColumnKind::Decimal { + precision: Some(40), + scale: Some(20), + }, + ), + ]; + let rows = vec![vec![ + Value::UInt(u64::MAX), + Value::Decimal("12345678901234567890.12345678901234567890".parse().expect("a decimal")), + ]]; + + let snapshot = snap(&columns, &rows, ResultExtent::complete(1), 10); + + assert_eq!( + texts(&snapshot), + [["18446744073709551615", "12345678901234567890.12345678901234567890"]] + ); + } + + #[test] + fn a_json_column_goes_in_as_its_document_with_its_key_order() { + let columns = vec![typed("payload", "jsonb", ColumnKind::Json { binary: true })]; + let rows = vec![vec![Value::Json( + JsonText::parse(r#"{"b": 1, "a": [1, 2]}"#.to_owned()).expect("JSON"), + )]]; + + let snapshot = snap(&columns, &rows, ResultExtent::complete(1), 10); + + assert_eq!(texts(&snapshot), [[r#"{"b": 1, "a": [1, 2]}"#]]); + } + + #[test] + fn bytes_name_their_size_inside_arrays_too() { + let columns = vec![ + typed( + "blob", + "bytea", + ColumnKind::Bytes { + length: TextLength::Unbounded, + }, + ), + typed( + "blobs", + "bytea[]", + ColumnKind::Array { + element: Box::new(ColumnKind::Bytes { + length: TextLength::Unbounded, + }), + }, + ), + ]; + let rows = vec![vec![ + Value::Bytes(vec![0xca, 0xfe, 0x00]), + Value::Array(vec![Value::Bytes(vec![1]), Value::Null]), + ]]; + + let snapshot = snap(&columns, &rows, ResultExtent::complete(1), 10); + + assert_eq!( + texts(&snapshot), + [[r#""(binary, 3 bytes)""#, r#"["(binary, 1 bytes)",null]"#]] + ); + } + + #[test] + fn timestamps_are_iso_and_an_unreadable_value_is_null() { + let columns = vec![ + typed( + "at", + "timestamp(3)", + ColumnKind::Timestamp { + fractional_digits: Some(3), + zone: TemporalZone::Naive, + }, + ), + typed("odd", "geometry", ColumnKind::Other), + ]; + let stamp = chrono::NaiveDate::from_ymd_opt(2024, 6, 15) + .expect("a date") + .and_hms_milli_opt(12, 0, 0, 500) + .expect("a time"); + let rows = vec![vec![ + Value::Timestamp(Temporal::Finite(stamp)), + Value::Undecodable(Box::new(UndecodedValue { + type_name: "geometry".to_owned(), + reason: UndecodableReason::UnsupportedType, + })), + ]]; + + let snapshot = snap(&columns, &rows, ResultExtent::complete(1), 10); + + assert_eq!(texts(&snapshot), [[r#""2024-06-15T12:00:00.500""#, "null"]]); + } + + #[test] + fn a_short_row_fills_with_null_and_a_long_one_is_cut_to_the_columns() { + let columns = cols(&["a", "b"]); + let rows = vec![vec![Value::Int(1)], vec![Value::Int(1), Value::Int(2), Value::Int(3)]]; + + let snapshot = snap(&columns, &rows, ResultExtent::complete(2), 10); + + assert_eq!(texts(&snapshot), [["1", "null"], ["1", "2"]]); + } + + #[test] + fn a_number_field_s_json_goes_in_as_the_number() { + let (columns, rows) = super::super::test_columns::mixed_json(); + + let snapshot = snap(&columns, &rows, ResultExtent::complete(1), 10); + + let row = &texts(&snapshot)[0]; + assert_eq!(row[0], "3000000000"); + assert_eq!(row[1], "19.90"); + } + + #[test] + fn every_cell_is_json_a_reader_parses() { + let columns = cols(&["s", "f"]); + let rows = vec![vec![ + Value::Text("a \"quoted\"\nline".to_owned()), + Value::Float64(f64::NAN), + ]]; + + let snapshot = snap(&columns, &rows, ResultExtent::complete(1), 10); + + let parsed: Vec = snapshot.rows[0] + .iter() + .map(|cell| serde_json::from_str(cell.get()).expect("JSON")) + .collect(); + assert_eq!( + parsed, + [serde_json::json!("a \"quoted\"\nline"), serde_json::json!("NaN")] + ); + } + + fn wide_rows(rows: usize, columns: usize, chars: usize) -> Vec> { + (0..rows) + .map(|_| (0..columns).map(|_| Value::Text("x".repeat(chars))).collect()) + .collect() + } + + #[test] + fn a_string_weighs_as_the_macos_app_counts_it() { + assert_eq!(quoted_bytes("abc"), 5); + assert_eq!(quoted_bytes("a&"), 2 + 2 + 18); + assert_eq!(quoted_bytes("\"\\\n\r\t"), 2 + 10); + assert_eq!(quoted_bytes("\u{1}\u{7f}"), 2 + 6 + 1); + assert_eq!(quoted_bytes("é•"), 2 + 5); + } + + #[test] + fn rows_stop_before_the_one_that_would_cross_the_budget() { + let columns = cols(&["c"]); + // 29 bytes of header, then 200,005 a row: 22 rows fit in 4,500,000. + let rows = wide_rows(30, 1, 200_000); + + let snapshot = snap(&columns, &rows, ResultExtent::complete(30), 1_000); + + assert_eq!(snapshot.rows.len(), 22); + assert_eq!(snapshot.row_count, Some(30)); + assert!(snapshot.truncated()); + assert_eq!(snapshot_row_count(&columns, &rows, 1_000), Ok(22)); + assert_eq!(snapshot_row_count(&columns, &rows, 5), Ok(5)); + } + + #[test] + fn a_first_row_over_the_budget_refuses_the_share() { + let columns = cols(&[ + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", + "v", "w", + ]); + let rows = wide_rows(1, columns.len(), 200_000); + + assert_eq!( + build_snapshot(&columns, &rows, ResultExtent::complete(1), 10).err(), + Some(SnapshotRefusal::FirstRow) + ); + assert_eq!(snapshot_row_count(&columns, &rows, 10), Err(SnapshotRefusal::FirstRow)); + } + + #[test] + fn a_snapshot_with_no_column_is_refused() { + let rows = vec![vec![Value::Int(1)]]; + + let refused = build_snapshot(&[], &rows, ResultExtent::complete(1), 10).err(); + + assert_eq!(refused, Some(SnapshotRefusal::NoColumns)); + assert_eq!(snapshot_row_count(&[], &rows, 10), Err(SnapshotRefusal::NoColumns)); + assert_eq!(SnapshotRefusal::NoColumns.code(), "export.snapshot_no_columns"); + } + + #[test] + fn a_cell_over_256_kib_refuses_the_share_and_one_at_it_goes() { + let columns = cols(&["note"]); + let at_limit = wide_rows(1, 1, MAX_SNAPSHOT_CELL_BYTES - 2); + let over = wide_rows(1, 1, MAX_SNAPSHOT_CELL_BYTES - 1); + + assert_eq!(snap(&columns, &at_limit, ResultExtent::complete(1), 10).rows.len(), 1); + assert_eq!( + build_snapshot(&columns, &over, ResultExtent::complete(1), 10).err(), + Some(SnapshotRefusal::Cell { + column: "note".to_owned() + }) + ); + } +} diff --git a/core/crates/core/src/filter/build_filter.rs b/core/crates/core/src/filter/build_filter.rs index f14361072d..58de16ea1f 100644 --- a/core/crates/core/src/filter/build_filter.rs +++ b/core/crates/core/src/filter/build_filter.rs @@ -27,7 +27,7 @@ pub fn build_filter( return Err(BuildFilterError::CombinatorNotAllowed(filter.combinator)); } if crate::document::speaks_shell(dialect) { - let mut params = crate::document::ShellParams::new(); + let mut params = crate::document::ShellParams::like(builder); let Some(document) = crate::document::filter_document(columns, filter, &mut params)? else { return Ok(false); }; diff --git a/core/crates/core/src/lib.rs b/core/crates/core/src/lib.rs index cb750b59df..c36800dbc4 100644 --- a/core/crates/core/src/lib.rs +++ b/core/crates/core/src/lib.rs @@ -49,6 +49,7 @@ mod liveness_policy; mod local_socket; mod local_socket_problem; mod loss_phase; +pub mod masking; pub mod meta; mod network_endpoint; mod network_options; @@ -66,6 +67,7 @@ mod row_limit; mod run_options; mod safe_mode_level; pub mod save; +pub mod secret_scan; mod server_diagnostics; mod server_info; mod server_name_override; diff --git a/core/crates/core/src/masking/detect/fixtures.rs b/core/crates/core/src/masking/detect/fixtures.rs new file mode 100644 index 0000000000..544107d0d4 --- /dev/null +++ b/core/crates/core/src/masking/detect/fixtures.rs @@ -0,0 +1,460 @@ +// The detectors' shared fixtures: the macOS app mirrors these tables in its own tests, and +// `print_fixtures_markdown` writes them out for it (DETECTOR-FIXTURES.md). + +use std::fmt::Write as _; + +use super::SensitiveKind::{self, ApiKey, Card, Email, Iban, Ip, Jwt, Phone}; +use super::{column_name_hit, column_value_kind, scan_sql_personal_data}; +use crate::column::ColumnType; +use crate::masking::MaskingStyle::{self, Email as EmailStyle, Full, Hash, LastFour}; +use crate::secret_scan::SecretHitKind::{ + self, AssignedSecret, AwsAccessKey, GitHubToken, GoogleApiKey, JsonWebToken, PrivateKey, SlackToken, StripeKey, + UrlCredentials, +}; +use crate::secret_scan::{scan_columns, scan_sql}; +use crate::value::Value; + +const JWT_TEXT: &str = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abc-DEF_123"; + +// A column name and the term and style it hits. +const NAMES: &[(&str, Option<(&str, MaskingStyle)>)] = &[ + ("email", Some(("email", EmailStyle))), + ("E-Mail", Some(("email", EmailStyle))), + ("e_mail", Some(("email", EmailStyle))), + ("mail", Some(("mail", EmailStyle))), + ("work_mail", Some(("mail", EmailStyle))), + ("ma_il", None), + ("email_address", Some(("email", EmailStyle))), + ("phone", Some(("phone", LastFour))), + ("mobilePhone", Some(("phone", LastFour))), + ("mobile", Some(("mobile", LastFour))), + ("tel_no", Some(("tel", LastFour))), + ("hotel", None), + ("fax", Some(("fax", LastFour))), + ("msisdn", Some(("msisdn", LastFour))), + ("password_hash", Some(("password", Full))), + ("passwords", None), + ("stripe_api_key", Some(("apikey", Full))), + ("apiKey", Some(("apikey", Full))), + ("API-KEY", Some(("apikey", Full))), + ("aws_access_key", Some(("accesskey", Full))), + ("PrivateKey", Some(("privatekey", Full))), + ("credential", Some(("credential", Full))), + ("credentials", None), + ("refresh_token", Some(("token", Full))), + ("ssn", Some(("ssn", LastFour))), + ("customerSSN", Some(("ssn", LastFour))), + ("ssn4", Some(("ssn", LastFour))), + ("classname", None), + ("class_name", None), + ("social_security_number", Some(("socialsecurity", LastFour))), + ("national_id", Some(("nationalid", LastFour))), + ("tax_id", Some(("taxid", LastFour))), + ("tin", Some(("tin", LastFour))), + ("credit_card_number", Some(("creditcard", LastFour))), + ("CardNumber", Some(("cardnumber", LastFour))), + ("pan", Some(("pan", LastFour))), + ("company", None), + ("iban", Some(("iban", LastFour))), + ("routing_number", Some(("routingnumber", LastFour))), + ("street_address", Some(("address", Full))), + ("street", Some(("street", Full))), + ("Address2Line", Some(("address", Full))), + ("zip", Some(("zip", Full))), + ("zipcode", Some(("zipcode", Full))), + ("zip_code", Some(("zipcode", Full))), + ("postal_code", Some(("postal", Full))), + ("dob", Some(("dob", Full))), + ("date_of_birth", Some(("dateofbirth", Full))), + ("birthday", Some(("birthday", Full))), + ("ip", Some(("ip", Hash))), + ("ip_address", Some(("ipaddress", Hash))), + ("IPAddress", Some(("ipaddress", Hash))), + ("ipv4", Some(("ipv4", Hash))), + ("client_ipv6", Some(("ipv6", Hash))), + ("ipv", None), + ("user_first_name", Some(("firstname", Full))), + ("lastName", Some(("lastname", Full))), + ("surname", Some(("surname", Full))), + ("given_name", Some(("givenname", Full))), + ("home_phone_address", Some(("phone", LastFour))), + ("id", None), + ("", None), +]; + +// A value and every kind it matches, in table order. +const VALUES: &[(&str, &[SensitiveKind])] = &[ + ("4111 1111 1111 1111", &[Card]), + ("4111-1111-1111-1111", &[Card]), + ("4111111111111111", &[Card]), + ("4222222222222", &[Card]), + ("4222 2222 22222", &[Card, Phone]), + ("4111111111111112", &[]), + ("411111111111", &[]), + ("4111.1111.1111.1111", &[]), + (" 4111111111111111", &[Card]), + ("GB82 WEST 1234 5698 7654 32", &[Iban]), + ("GB82WEST12345698765432", &[Iban]), + ("DE89 3704 0044 0532 0130 00", &[Iban]), + ("GB82 WEST 1234 5698 7654 33", &[]), + ("gb82west12345698765432", &[]), + ("GB82\tWEST12345698765432", &[]), + (JWT_TEXT, &[Jwt]), + (" eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abc", &[]), + ("AKIAIOSFODNN7EXAMPLE", &[ApiKey]), + ("key=AKIAIOSFODNN7EXAMPLE;", &[ApiKey]), + ("ghp_0123456789abcdefghijABCDEFGHIJ012345", &[ApiKey]), + ("xoxb-123", &[ApiKey]), + ("sk_live_abc", &[ApiKey]), + ("AIzaSyA1234567890abcdefghijklmnopqrstuv", &[ApiKey]), + ("sk_test_abc", &[]), + ("ann@example.com", &[Email]), + ("émile@exämple.fr", &[Email]), + ("a@b@c.com", &[]), + ("ann@localhost", &[]), + ("ann @example.com", &[]), + ("ann@example.com ", &[]), + ("ann\u{a0}x@example.com", &[]), + ("+1 555 0100", &[Phone]), + ("(555) 010-0100", &[Phone]), + ("555.010.0100", &[Phone]), + ("+15550100", &[Phone]), + ("1.234.567", &[Phone]), + ("5550100", &[]), + ("+123456", &[]), + ("+1234567890123456", &[]), + ("555-0100 ext 2", &[]), + ("2024-01-02", &[]), + ("2024-01-0212345", &[]), + ("1234567.89", &[]), + ("-1234567.89", &[]), + ("12:30:45", &[]), + ("192.168.100.200", &[Ip]), + ("192.168.1.1", &[Ip]), + ("0.0.0.0", &[Ip]), + ("192.168.01.1", &[Phone]), + ("256.1.1.1", &[]), + ("256.10.10.10", &[Phone]), + ("1.2.3", &[]), + ("1.1.1.1 ", &[]), + ("::1", &[Ip]), + ("2001:db8::1", &[Ip]), + ("1:2:3:4:5:6:7:8", &[Ip]), + ("::ffff:192.168.1.1", &[Ip]), + ("fe80::1%eth0", &[]), + ("[::1]", &[]), + ("2001:db8::1::2", &[]), + ("12345::1", &[]), + ("", &[]), +]; + +enum Cell { + Text(&'static str), + Null, + Bytes, +} + +// A column's type, its values and the kind it is flagged as. +const COLUMNS: &[(&str, &[Cell], Option)] = &[ + ( + "text", + &[ + Cell::Text("ann@example.com"), + Cell::Text("bob@example.com"), + Cell::Text("n/a"), + Cell::Text("x"), + ], + Some(Email), + ), + ( + "text", + &[Cell::Text("ann@example.com"), Cell::Text("x"), Cell::Text("y")], + None, + ), + ( + "text", + &[Cell::Text("ann@example.com"), Cell::Null, Cell::Null], + Some(Email), + ), + ( + "text", + &[Cell::Text("ann@example.com"), Cell::Text(""), Cell::Text("")], + None, + ), + ("text", &[Cell::Text("ann@example.com"), Cell::Bytes, Cell::Bytes], None), + ( + "text", + &[Cell::Text("x"), Cell::Text("y"), Cell::Text("4111 1111 1111 1111")], + Some(Card), + ), + ( + "text", + &[Cell::Text("ann@example.com"), Cell::Text(JWT_TEXT)], + Some(Jwt), + ), + ("text", &[Cell::Text("192.168.1.1"), Cell::Text("10.0.0.1")], Some(Ip)), + ( + "varchar(64)", + &[Cell::Text("+1 555 0100"), Cell::Text("x")], + Some(Phone), + ), + ("", &[Cell::Text("ann@example.com")], Some(Email)), + ("Nullable(String)", &[Cell::Text("ann@example.com")], Some(Email)), + ("bigint", &[Cell::Text("4111111111111111")], None), + ("uuid", &[Cell::Text("ann@example.com")], None), + ("Nullable(UInt64)", &[Cell::Text("4111111111111111")], None), + ( + "timestamp with time zone", + &[Cell::Text("2024-01-02 10:00:00+00")], + None, + ), + ("text", &[Cell::Null, Cell::Null], None), + ("text", &[], None), +]; + +// A query and the personal data its single-quoted literals hold, each kind once per line. +const SQL: &[(&str, &[(SensitiveKind, u32)])] = &[ + ("SELECT * FROM users WHERE email = 'ann@example.com'", &[(Email, 1)]), + (r#"SELECT "ann@example.com" FROM t"#, &[]), + ("WHERE note = 'call +1 555 0100'", &[]), + ("WHERE card = '4111-1111-1111-1111'", &[(Card, 1)]), + ("WHERE iban = 'GB82 WEST 1234 5698 7654 32'", &[(Iban, 1)]), + ( + "SET token = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abc-DEF_123'", + &[(Jwt, 1)], + ), + ("WHERE k = 'id AKIAIOSFODNN7EXAMPLE'", &[(ApiKey, 1)]), + ("SELECT 'o''brien@example.com'", &[(Email, 1)]), + ("WHERE ip = '192.168.1.1'", &[]), + ("WHERE e = 'ann@example.com", &[]), + ("-- don't\nWHERE e = 'ann@example.com'", &[(Email, 2)]), + ("SELECT /* it's */ 'ann@example.com'", &[(Email, 1)]), + ("SELECT 1 -- 'ann@example.com'", &[]), + ("SELECT 1 /* 'ann@example.com' */", &[]), + ("/* 'ann@example.com'", &[]), + ("-- it's\r'ann@example.com'", &[(Email, 2)]), + ("SELECT 'a--b@example.com'", &[(Email, 1)]), + (r#"SELECT "x--y", 'ann@example.com'"#, &[(Email, 1)]), + ("SELECT 1 - -1, 'ann@example.com'", &[(Email, 1)]), + ( + "WHERE e = 'a@b.co' AND f = 'c@d.co'\nOR p = '(555) 010-0100'", + &[(Email, 1), (Phone, 2)], + ), + ("SELECT 1;\r\n\r\nSELECT '+1 555 0100'", &[(Phone, 3)]), + ("SELECT 1", &[]), +]; + +// A query and what the secret scan finds, each kind once per line. +const SECRET_SQL: &[(&str, &[(SecretHitKind, u32)])] = &[ + ("-- AKIAIOSFODNN7EXAMPLE", &[(AwsAccessKey, 1)]), + ("-----BEGIN RSA PRIVATE KEY-----", &[(PrivateKey, 1)]), + ("-----BEGIN PRIVATE KEY-----", &[(PrivateKey, 1)]), + ("-----BEGIN OPENSSH PRIVATE KEY-----", &[(PrivateKey, 1)]), + ("-----BEGIN EC2 PRIVATE KEY-----", &[(PrivateKey, 1)]), + ("-----BEGIN ENCRYPTED PRIVATE KEY-----", &[]), + ("-----BEGIN rsa PRIVATE KEY-----", &[]), + ("-----BEGIN PUBLIC KEY-----", &[]), + ( + "-- eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abc-DEF_123", + &[(JsonWebToken, 1)], + ), + ("-- ghp_0123456789abcdefghijABCDEFGHIJ012345", &[(GitHubToken, 1)]), + ("-- xoxb-123", &[(SlackToken, 1)]), + ("-- sk_live_abc", &[(StripeKey, 1)]), + ("-- AIzaSyA1234567890abcdefghijklmnopqrstuv", &[(GoogleApiKey, 1)]), + ("-- postgres://app:hunter2@db.internal/shop", &[(UrlCredentials, 1)]), + ("-- https://a@b:c@d", &[]), + ("https://tablepro.app/docs", &[]), + ("WHERE u.password = 'hunter2'", &[(AssignedSecret, 1)]), + (r#"SELECT '{"token": "abc"}'::jsonb"#, &[(AssignedSecret, 1)]), + (r#"WHERE "password" = 'x'"#, &[(AssignedSecret, 1)]), + (r#"WHERE 'password' = "x""#, &[(AssignedSecret, 1)]), + ("SET `password` := 'x'", &[(AssignedSecret, 1)]), + ("VALUES ([db_passwd] => 'x')", &[(AssignedSecret, 1)]), + ("WHERE Api_Key: 'x'", &[(AssignedSecret, 1)]), + ("WHERE password = ''", &[]), + (r#"WHERE password = """#, &[]), + (r#"WHERE password = 'abc" AND 1 = 1"#, &[]), + ("WHERE password = 'a\nb'", &[(AssignedSecret, 1)]), + ("SELECT password FROM users", &[]), + ("WHERE token = :token", &[]), + ("SELECT 'password' AS label", &[]), + ( + "SELECT 'AKIAIOSFODNN7EXAMPLE', 'AKIAIOSFODNN7EXAMPLF';\nSELECT 'sk_live_a'", + &[(AwsAccessKey, 1), (StripeKey, 2)], + ), + ("\r\rsk_live_x", &[(StripeKey, 3)]), + ("\r\n\r\nsk_live_x", &[(StripeKey, 3)]), + ("\n\rsk_live_x", &[(StripeKey, 3)]), +]; + +// Column names and the ones the secret scan names, in order, each once. +const SECRET_COLUMNS: &[(&[&str], &[&str])] = &[ + ( + &[ + "id", + "user_password", + "PasswordHash", + "access_token", + "apiKey", + "API-KEY", + "client_secret", + "ssn", + "customerSSN", + "ssn_last4", + "credit_card", + "CardNumber", + "class_name", + "lesson", + "id", + "user_password", + ], + &[ + "user_password", + "PasswordHash", + "access_token", + "apiKey", + "API-KEY", + "client_secret", + "ssn", + "customerSSN", + "ssn_last4", + "credit_card", + "CardNumber", + ], + ), + ( + &["passwords", "tokens", "passwd", "secrets", "api_key_id"], + &["passwd", "api_key_id"], + ), +]; + +fn cell(cell: &Cell) -> Value { + match cell { + Cell::Text(text) => Value::Text((*text).to_owned()), + Cell::Null => Value::Null, + Cell::Bytes => Value::Bytes(vec![0x40, 0x41]), + } +} + +#[test] +fn column_names() { + for (name, expected) in NAMES { + let found = column_name_hit(name).map(|hit| (hit.term, hit.style)); + assert_eq!(found, *expected, "{name:?}"); + } +} + +#[test] +fn values() { + for (text, expected) in VALUES { + let found: Vec = SensitiveKind::ALL + .into_iter() + .filter(|kind| kind.matches(text)) + .collect(); + assert_eq!(found, *expected, "{text:?}"); + } +} + +#[test] +fn columns() { + for (type_name, cells, expected) in COLUMNS { + let values: Vec = cells.iter().map(cell).collect(); + assert_eq!( + column_value_kind(&ColumnType::untyped_text(*type_name), &values), + *expected, + "{type_name}" + ); + } +} + +#[test] +fn sql_personal_data() { + for (sql, expected) in SQL { + let found: Vec<(SensitiveKind, u32)> = scan_sql_personal_data(sql) + .into_iter() + .map(|hit| (hit.kind, hit.line)) + .collect(); + assert_eq!(found, *expected, "{sql:?}"); + } +} + +#[test] +fn secret_sql() { + for (sql, expected) in SECRET_SQL { + let found: Vec<(SecretHitKind, u32)> = scan_sql(sql).into_iter().map(|hit| (hit.kind, hit.line)).collect(); + assert_eq!(found, *expected, "{sql:?}"); + } +} + +#[test] +fn secret_columns() { + for (names, expected) in SECRET_COLUMNS { + assert_eq!(scan_columns(names), *expected); + } +} + +#[test] +#[ignore = "prints the fixtures as Markdown for the macOS app's tests: cargo test -p tablepro-core --lib print_fixtures_markdown -- --ignored --nocapture"] +fn print_fixtures_markdown() { + println!("{}", fixtures_markdown()); +} + +fn shown(text: &str) -> String { + format!("`{}`", text.escape_debug()).replace('|', "\\|") +} + +fn fixtures_markdown() -> String { + let mut out = String::from("## Column names\n\n| Name | Term | Style |\n|---|---|---|\n"); + for (name, hit) in NAMES { + let (term, style) = hit.map_or(("none", "none"), |(term, style)| (term, style.code())); + let _ = writeln!(out, "| {} | {term} | {style} |", shown(name)); + } + out.push_str("\n## Values (each kind tested alone, table order)\n\n| Value | Kinds |\n|---|---|\n"); + for (text, kinds) in VALUES { + let _ = writeln!( + out, + "| {} | {} |", + shown(text), + codes(kinds.iter().map(|kind| kind.code())) + ); + } + out.push_str("\n## Columns (thresholds, text-like types)\n\n| Type | Values | Flagged |\n|---|---|---|\n"); + for (type_name, cells, kind) in COLUMNS { + let values: Vec = cells + .iter() + .map(|cell| match cell { + Cell::Text(text) => shown(text), + Cell::Null => "NULL".to_owned(), + Cell::Bytes => "bytes".to_owned(), + }) + .collect(); + let flagged = kind.map_or("none", SensitiveKind::code); + let _ = writeln!(out, "| {} | {} | {flagged} |", shown(type_name), values.join(", ")); + } + out.push_str("\n## SQL personal data\n\n| SQL | Hits (kind:line) |\n|---|---|\n"); + for (sql, hits) in SQL { + let hits = hits.iter().map(|(kind, line)| format!("{}:{line}", kind.code())); + let _ = writeln!(out, "| {} | {} |", shown(sql), codes(hits)); + } + out.push_str("\n## Secret scan, SQL\n\n| SQL | Hits (kind:line) |\n|---|---|\n"); + for (sql, hits) in SECRET_SQL { + let hits = hits.iter().map(|(kind, line)| format!("{}:{line}", kind.code())); + let _ = writeln!(out, "| {} | {} |", shown(sql), codes(hits)); + } + out.push_str("\n## Secret scan, columns\n\n| Names | Found |\n|---|---|\n"); + for (names, found) in SECRET_COLUMNS { + let names: Vec = names.iter().map(|name| shown(name)).collect(); + let found: Vec = found.iter().map(|name| shown(name)).collect(); + let _ = writeln!(out, "| {} | {} |", names.join(", "), found.join(", ")); + } + out +} + +fn codes>(codes: impl Iterator) -> String { + let joined: Vec = codes.map(|code| code.as_ref().to_owned()).collect(); + match joined.is_empty() { + true => "none".to_owned(), + false => joined.join(", "), + } +} diff --git a/core/crates/core/src/masking/detect/mod.rs b/core/crates/core/src/masking/detect/mod.rs new file mode 100644 index 0000000000..451a301218 --- /dev/null +++ b/core/crates/core/src/masking/detect/mod.rs @@ -0,0 +1,149 @@ +// What a share masks before the user asks: columns named or holding personal data, and such data in the SQL. The +// lists, thresholds and rules are PLAN-MASKING 8.3 and 8.3.1, which the macOS app follows too; the shared fixtures +// in `fixtures.rs` pin them. + +mod names; +mod sql; +mod values; + +#[cfg(test)] +mod fixtures; + +pub use names::{NameHit, column_name_hit, name_words}; +pub(crate) use names::{Term, longest_term}; +pub use sql::{PersonalDataHit, scan_sql_personal_data}; +pub use values::{Seen, SensitiveKind, ValueTally, column_value_kind, is_text_like}; + +use super::MaskingStyle; +use crate::column::ResultColumn; +use crate::value::Value; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MaskSuggestion { + pub style: MaskingStyle, + pub reason: SuggestionReason, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SuggestionReason { + // The term as its words join, such as "apikey". + ColumnName { term: &'static str }, + Values { kind: SensitiveKind }, +} + +// One per column, from the rows to be shared. A name beats what the values show. +pub fn suggest_masks>(columns: &[ResultColumn], rows: &[R]) -> Vec> { + let tallies: Vec = columns + .iter() + .enumerate() + .map(|(index, column)| { + let mut tally = ValueTally::default(); + if is_text_like(&column.column_type) { + for value in rows.iter().filter_map(|row| row.as_ref().get(index)) { + tally.record(Seen::of(&column.column_type, value)); + } + } + tally + }) + .collect(); + suggest_from_tallies(columns, &[tallies]) +} + +// From a tally per column for each window of rows: a column any window flags is flagged, each window by its own +// thresholds, and the first kind in table order wins. +pub fn suggest_from_tallies>( + columns: &[ResultColumn], + windows: &[T], +) -> Vec> { + columns + .iter() + .enumerate() + .map(|(index, column)| { + if let Some(hit) = column_name_hit(&column.name) { + return Some(MaskSuggestion { + style: hit.style, + reason: SuggestionReason::ColumnName { term: hit.term }, + }); + } + windows + .iter() + .filter_map(|tallies| tallies.as_ref().get(index)?.kind()) + .min() + .map(|kind| MaskSuggestion { + style: kind.style(), + reason: SuggestionReason::Values { kind }, + }) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::column::ColumnType; + + fn text(value: &str) -> Value { + Value::Text(value.to_owned()) + } + + #[test] + fn a_name_beats_the_values() { + let columns = [ + ResultColumn::new("phone", ColumnType::untyped_text("text")), + ResultColumn::new("notes", ColumnType::untyped_text("text")), + ResultColumn::new("id", ColumnType::untyped_text("int")), + ]; + let rows = vec![vec![ + text("ann@example.com"), + text("4111 1111 1111 1111"), + Value::Int(1), + ]]; + + let suggested = suggest_masks(&columns, &rows); + + assert_eq!( + suggested, + [ + Some(MaskSuggestion { + style: MaskingStyle::LastFour, + reason: SuggestionReason::ColumnName { term: "phone" }, + }), + Some(MaskSuggestion { + style: MaskingStyle::LastFour, + reason: SuggestionReason::Values { + kind: SensitiveKind::Card + }, + }), + None, + ] + ); + } + + #[test] + fn a_column_two_windows_flag_differently_takes_the_first_kind_in_table_order() { + let columns = [ResultColumn::new("contact", ColumnType::untyped_text("text"))]; + let emails = vec![vec![text("ann@example.com")]]; + let cards = vec![ + vec![text("4111 1111 1111 1111")], + vec![text("ann@example.com")], + vec![text("x")], + ]; + + let tally = |rows: &[Vec]| { + let mut tally = ValueTally::default(); + for row in rows { + tally.record(Seen::of(&columns[0].column_type, &row[0])); + } + vec![tally] + }; + + let suggested = suggest_from_tallies(&columns, &[tally(&emails), tally(&cards)]); + + assert_eq!( + suggested[0].map(|found| found.reason), + Some(SuggestionReason::Values { + kind: SensitiveKind::Card + }) + ); + } +} diff --git a/core/crates/core/src/masking/detect/names.rs b/core/crates/core/src/masking/detect/names.rs new file mode 100644 index 0000000000..49eb6df340 --- /dev/null +++ b/core/crates/core/src/masking/detect/names.rs @@ -0,0 +1,203 @@ +use crate::masking::MaskingStyle; + +// A term as the words of a name spell it once joined. `single_word` terms match only one whole word. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Term { + pub compact: &'static str, + pub single_word: bool, + pub style: MaskingStyle, +} + +const fn term(compact: &'static str, style: MaskingStyle) -> Term { + Term { + compact, + single_word: false, + style, + } +} + +// PLAN-MASKING 8.3, in table order: a tie between two terms covering as many words goes to the earlier one. The +// table's "e-mail" and "api key" split into the words of "email" and "apikey". +const NAME_TERMS: [Term; 49] = { + use MaskingStyle::{Email, Full, Hash, LastFour}; + [ + term("email", Email), + Term { + compact: "mail", + single_word: true, + style: Email, + }, + term("phone", LastFour), + term("mobile", LastFour), + term("tel", LastFour), + term("telephone", LastFour), + term("fax", LastFour), + term("msisdn", LastFour), + term("password", Full), + term("passwd", Full), + term("pwd", Full), + term("secret", Full), + term("token", Full), + term("apikey", Full), + term("accesskey", Full), + term("privatekey", Full), + term("credential", Full), + term("ssn", LastFour), + term("socialsecurity", LastFour), + term("nationalid", LastFour), + term("passport", LastFour), + term("taxid", LastFour), + term("tin", LastFour), + term("creditcard", LastFour), + term("cardnumber", LastFour), + term("ccnumber", LastFour), + term("pan", LastFour), + term("iban", LastFour), + term("accountnumber", LastFour), + term("routingnumber", LastFour), + term("address", Full), + term("street", Full), + term("zip", Full), + term("zipcode", Full), + term("postcode", Full), + term("postal", Full), + term("dob", Full), + term("birthdate", Full), + term("dateofbirth", Full), + term("birthday", Full), + term("ip", Hash), + term("ipaddress", Hash), + term("ipv4", Hash), + term("ipv6", Hash), + term("firstname", Full), + term("lastname", Full), + term("fullname", Full), + term("surname", Full), + term("givenname", Full), + ] +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NameHit { + // The term as its words join, such as "apikey" for `stripe_api_key`. + pub term: &'static str, + pub style: MaskingStyle, +} + +// The term a column's name holds, as whole words: the one covering the most words, a tie going to table order. +pub fn column_name_hit(name: &str) -> Option { + longest_term(&name_words(name), &NAME_TERMS).map(|term| NameHit { + term: term.compact, + style: term.style, + }) +} + +// Split at `_`, `-`, `.` and a space, where a lower-case letter meets an upper-case one, and where a letter meets an +// ASCII digit either way; each word lower-cased. +pub fn name_words(name: &str) -> Vec { + let mut words = Vec::new(); + let mut word = String::new(); + let mut previous: Option = None; + for character in name.chars() { + if matches!(character, '_' | '-' | '.' | ' ') { + push_word(&mut words, &mut word); + previous = None; + continue; + } + if let Some(previous) = previous { + let case_break = previous.is_lowercase() && character.is_uppercase(); + let digit_break = (previous.is_alphabetic() && character.is_ascii_digit()) + || (previous.is_ascii_digit() && character.is_alphabetic()); + if case_break || digit_break { + push_word(&mut words, &mut word); + } + } + word.push(character); + previous = Some(character); + } + push_word(&mut words, &mut word); + words +} + +fn push_word(words: &mut Vec, word: &mut String) { + if !word.is_empty() { + words.push(std::mem::take(word).to_lowercase()); + } +} + +// A term equals one word or several consecutive words joined; never part of a word. +pub(crate) fn longest_term<'t>(words: &[String], terms: &'t [Term]) -> Option<&'t Term> { + let longest = terms.iter().map(|term| term.compact.len()).max().unwrap_or(0); + let mut best: Option<(usize, usize)> = None; + for start in 0..words.len() { + let mut joined = String::new(); + for (span, word) in words[start..].iter().enumerate() { + joined.push_str(word); + if joined.len() > longest { + break; + } + let covered = span + 1; + let found = terms + .iter() + .position(|term| term.compact == joined && (!term.single_word || covered == 1)); + if let Some(order) = found + && best.is_none_or(|(most, first)| covered > most || (covered == most && order < first)) + { + best = Some((covered, order)); + } + } + } + best.and_then(|(_, order)| terms.get(order)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hit(name: &str) -> Option<(&'static str, MaskingStyle)> { + column_name_hit(name).map(|hit| (hit.term, hit.style)) + } + + #[test] + fn names_split_at_separators_case_changes_and_digits() { + assert_eq!(name_words("stripe_api_key"), ["stripe", "api", "key"]); + assert_eq!(name_words("userFirstName"), ["user", "first", "name"]); + assert_eq!(name_words("ipv4"), ["ipv", "4"]); + assert_eq!(name_words("Address2Line"), ["address", "2", "line"]); + assert_eq!(name_words("API-KEY"), ["api", "key"]); + assert_eq!(name_words("IPAddress"), ["ipaddress"]); + assert_eq!(name_words("e.mail x"), ["e", "mail", "x"]); + assert_eq!(name_words("e#mail"), ["e#mail"]); + assert!(name_words("__").is_empty()); + } + + #[test] + fn a_term_matches_whole_words_only() { + assert_eq!(hit("stripe_api_key"), Some(("apikey", MaskingStyle::Full))); + assert_eq!(hit("user_first_name"), Some(("firstname", MaskingStyle::Full))); + assert_eq!(hit("ipv4"), Some(("ipv4", MaskingStyle::Hash))); + assert_eq!(hit("zipcode"), Some(("zipcode", MaskingStyle::Full))); + assert_eq!(hit("classname"), None); + assert_eq!(hit("company"), None); + assert_eq!(hit("hotel"), None); + assert_eq!(hit("passwords"), None); + } + + #[test] + fn mail_matches_only_as_one_word() { + assert_eq!(hit("mail"), Some(("mail", MaskingStyle::Email))); + assert_eq!(hit("work_mail"), Some(("mail", MaskingStyle::Email))); + assert_eq!(hit("ma_il"), None); + assert_eq!(hit("e_mail"), Some(("email", MaskingStyle::Email))); + assert_eq!(hit("E-Mail"), Some(("email", MaskingStyle::Email))); + } + + #[test] + fn the_term_covering_the_most_words_wins_and_a_tie_goes_to_table_order() { + assert_eq!(hit("ip_address"), Some(("ipaddress", MaskingStyle::Hash))); + assert_eq!(hit("email_address"), Some(("email", MaskingStyle::Email))); + assert_eq!(hit("home_phone_address"), Some(("phone", MaskingStyle::LastFour))); + assert_eq!(hit("date_of_birth"), Some(("dateofbirth", MaskingStyle::Full))); + assert_eq!(hit("customerSSN"), Some(("ssn", MaskingStyle::LastFour))); + } +} diff --git a/core/crates/core/src/masking/detect/sql.rs b/core/crates/core/src/masking/detect/sql.rs new file mode 100644 index 0000000000..53eaf455d4 --- /dev/null +++ b/core/crates/core/src/masking/detect/sql.rs @@ -0,0 +1,127 @@ +use super::SensitiveKind; +use crate::secret_scan::line_starts; + +// What a single-quoted literal of a shared query looks like. Never an IP address: a query names hosts for its own +// reasons. +const SQL_KINDS: [SensitiveKind; 6] = [ + SensitiveKind::Card, + SensitiveKind::Iban, + SensitiveKind::Jwt, + SensitiveKind::ApiKey, + SensitiveKind::Email, + SensitiveKind::Phone, +]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PersonalDataHit { + pub kind: SensitiveKind, + // Where the literal starts, from 1; CR, LF and CRLF each end a line. + pub line: u32, +} + +// Each kind once per line, by line. Only single-quoted literals, `''` being a quote inside one; double-quoted text +// is a name, `--` to the end of the line and `/* */` are comments, and a literal left open is not read. +pub fn scan_sql_personal_data(sql: &str) -> Vec { + let starts = line_starts(sql); + let line_of = |offset: usize| u32::try_from(starts.partition_point(|start| *start <= offset)).unwrap_or(u32::MAX); + let mut hits: Vec = single_quoted_literals(sql) + .into_iter() + .filter_map(|(offset, literal)| { + let kind = SQL_KINDS.into_iter().find(|kind| kind.matches(&literal))?; + Some(PersonalDataHit { + kind, + line: line_of(offset), + }) + }) + .collect(); + hits.sort_by_key(|hit| (hit.line, hit.kind)); + hits.dedup(); + hits +} + +// Each closed literal's byte offset and its text with `''` read as one quote. +fn single_quoted_literals(sql: &str) -> Vec<(usize, String)> { + let mut literals = Vec::new(); + let mut characters = sql.char_indices().peekable(); + while let Some((offset, character)) = characters.next() { + match character { + '"' => { + for (_, inside) in characters.by_ref() { + if inside == '"' { + break; + } + } + } + '-' if characters.next_if(|(_, next)| *next == '-').is_some() => { + while characters.next_if(|(_, next)| !matches!(next, '\n' | '\r')).is_some() {} + } + '/' if characters.next_if(|(_, next)| *next == '*').is_some() => { + while let Some((_, inside)) = characters.next() { + if inside == '*' && characters.next_if(|(_, next)| *next == '/').is_some() { + break; + } + } + } + '\'' => { + let mut literal = String::new(); + let mut closed = false; + while let Some((_, inside)) = characters.next() { + if inside != '\'' { + literal.push(inside); + } else if characters.next_if(|(_, next)| *next == '\'').is_some() { + literal.push('\''); + } else { + closed = true; + break; + } + } + if closed { + literals.push((offset, literal)); + } + } + _ => {} + } + } + literals +} + +#[cfg(test)] +mod tests { + use super::*; + + fn found(sql: &str) -> Vec<(SensitiveKind, u32)> { + scan_sql_personal_data(sql) + .into_iter() + .map(|hit| (hit.kind, hit.line)) + .collect() + } + + #[test] + fn comments_outside_a_literal_are_skipped() { + assert_eq!( + single_quoted_literals("-- don't\nSELECT /* it's */ 'a', '-- b /* c */' -- 'd'\r'e'"), + [ + (27, "a".to_owned()), + (32, "-- b /* c */".to_owned()), + (54, "e".to_owned()) + ] + ); + assert!(single_quoted_literals("/* 'open").is_empty()); + } + + #[test] + fn literals_read_with_doubled_quotes_and_names_are_skipped() { + assert_eq!( + single_quoted_literals(r#"SELECT 'it''s', "a'b", 'x' FROM t WHERE c = 'open"#), + [(7, "it's".to_owned()), (23, "x".to_owned())] + ); + } + + #[test] + fn a_kind_counts_once_per_line_on_the_literal_s_first_line() { + let sql = + "SELECT *\r\nFROM users WHERE email IN ('ann@example.com', 'bob@example.com')\rAND phone = '+1 555 0100'"; + + assert_eq!(found(sql), [(SensitiveKind::Email, 2), (SensitiveKind::Phone, 3)]); + } +} diff --git a/core/crates/core/src/masking/detect/values.rs b/core/crates/core/src/masking/detect/values.rs new file mode 100644 index 0000000000..accb2e0453 --- /dev/null +++ b/core/crates/core/src/masking/detect/values.rs @@ -0,0 +1,326 @@ +use std::net::{IpAddr, Ipv4Addr}; +use std::sync::LazyLock; + +use regex::Regex; + +use crate::column::ColumnType; +use crate::export::value_text; +use crate::masking::MaskingStyle; +use crate::secret_scan::SecretHitKind; +use crate::value::Value; + +// What the values of a column look like, in table order: a column several kinds flag takes the first. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum SensitiveKind { + Card, + Iban, + Jwt, + ApiKey, + Email, + Phone, + Ip, +} + +impl SensitiveKind { + pub const ALL: [Self; 7] = [ + Self::Card, + Self::Iban, + Self::Jwt, + Self::ApiKey, + Self::Email, + Self::Phone, + Self::Ip, + ]; + + pub fn code(self) -> &'static str { + match self { + Self::Card => "card", + Self::Iban => "iban", + Self::Jwt => "jwt", + Self::ApiKey => "api_key", + Self::Email => "email", + Self::Phone => "phone", + Self::Ip => "ip", + } + } + + pub fn style(self) -> MaskingStyle { + match self { + Self::Card | Self::Iban | Self::Phone => MaskingStyle::LastFour, + Self::Jwt | Self::ApiKey => MaskingStyle::Full, + Self::Email => MaskingStyle::Email, + Self::Ip => MaskingStyle::Hash, + } + } + + // One such value flags its column; the rest need at least half the non-null values. + fn flags_on_any(self) -> bool { + matches!(self, Self::Card | Self::Iban | Self::Jwt | Self::ApiKey) + } + + pub fn matches(self, text: &str) -> bool { + match self { + Self::Card => is_card(text), + Self::Iban => is_iban(text), + Self::Jwt => JWT.is_match(text), + Self::ApiKey => API_KEYS.iter().any(|key| key.is_match(text)), + Self::Email => EMAIL.is_match(text), + Self::Phone => is_phone(text), + Self::Ip => text.parse::().is_ok(), + } + } +} + +// A fixed pattern, which `every_pattern_compiles` proves; one that did not would match nothing. +struct Pattern(Option); + +impl Pattern { + fn new(source: &str) -> Self { + Self(Regex::new(source).ok()) + } + + fn is_match(&self, text: &str) -> bool { + self.0.as_ref().is_some_and(|regex| regex.is_match(text)) + } +} + +static NOT_TEXT: LazyLock = LazyLock::new(|| { + Pattern::new( + r"\A(u?int[0-9]*|tinyint|smallint|mediumint|bigint|integer|serial|smallserial|bigserial|numeric|decimal[0-9]*|number|real|float[0-9]*|double|money|smallmoney|bool|boolean|bit|date[0-9]*|datetime[0-9]*|smalldatetime|datetimeoffset|time|timetz|timestamp|timestamptz|interval|year|uuid|uniqueidentifier)( .*)?\z", + ) +}); +static IBAN: LazyLock = LazyLock::new(|| Pattern::new(r"\A[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}\z")); +static JWT: LazyLock = + LazyLock::new(|| Pattern::new(r"\AeyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\z")); +static EMAIL: LazyLock = LazyLock::new(|| Pattern::new(r"\A[^\s@]+@[^\s@]+\.[^\s@]+\z")); +static PHONE: LazyLock = LazyLock::new(|| Pattern::new(r"\A\+?[0-9() .-]+\z")); +static ISO_DATE: LazyLock = LazyLock::new(|| Pattern::new(r"\A[0-9]{4}-[0-9]{2}-[0-9]{2}")); +static DECIMAL: LazyLock = LazyLock::new(|| Pattern::new(r"\A[+-]?[0-9]+\.[0-9]+\z")); +// The secret scan's key patterns, found anywhere in the value. +static API_KEYS: LazyLock> = LazyLock::new(|| { + [ + SecretHitKind::AwsAccessKey, + SecretHitKind::GitHubToken, + SecretHitKind::SlackToken, + SecretHitKind::StripeKey, + SecretHitKind::GoogleApiKey, + ] + .into_iter() + .map(|kind| Pattern::new(kind.pattern())) + .collect() +}); + +// A result names `TINYINT(1)` or `Nullable(String)` where the list says `tinyint` or `string`: ClickHouse wrappers are +// unwrapped and the width dropped, as the macOS app reads a type. +fn base_type_name(type_name: &str) -> String { + const WRAPPERS: [&str; 2] = ["NULLABLE(", "LOWCARDINALITY("]; + let mut name = trim_blanks(type_name); + while name.ends_with(')') { + let Some(wrapper) = WRAPPERS.iter().find(|wrapper| { + name.get(..wrapper.len()) + .is_some_and(|head| head.eq_ignore_ascii_case(wrapper)) + }) else { + break; + }; + name = trim_blanks(&name[wrapper.len()..name.len() - 1]); + } + trim_blanks(name.split('(').next().unwrap_or_default()).to_owned() +} + +// Foundation's `.whitespaces`: tab and the space separators, never a line break. +fn trim_blanks(text: &str) -> &str { + text.trim_matches(|character: char| { + matches!( + character, + '\t' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'..='\u{200a}' | '\u{202f}' | '\u{205f}' | '\u{3000}' + ) + }) +} + +// A number, date, time, boolean or UUID column holds no text a person typed; an unknown or empty type might. +pub fn is_text_like(column: &ColumnType) -> bool { + !NOT_TEXT.is_match(&base_type_name(&column.name).to_lowercase()) +} + +// The first kind in table order the column's non-null values show. Bytes and empty strings count and never match. +pub fn column_value_kind<'v>( + column: &ColumnType, + values: impl IntoIterator, +) -> Option { + if !is_text_like(column) { + return None; + } + let mut tally = ValueTally::default(); + for value in values { + tally.record(Seen::of(column, value)); + } + tally.kind() +} + +// What one value of a text-like column adds to a tally, worked out once for every window it falls in. +#[derive(Debug, Clone, Copy, Default)] +pub struct Seen { + counted: bool, + matched: [bool; SensitiveKind::ALL.len()], +} + +impl Seen { + pub fn of(column: &ColumnType, value: &Value) -> Self { + let mut seen = Self::default(); + match value { + Value::Null => {} + Value::Bytes(_) => seen.counted = true, + value => { + seen.counted = true; + if let Some(text) = value_text(value, column).filter(|text| !text.is_empty()) { + for (matched, kind) in seen.matched.iter_mut().zip(SensitiveKind::ALL) { + *matched = kind.matches(&text); + } + } + } + } + seen + } +} + +// A column's values counted a value at a time, so no window of rows is held to judge them. +#[derive(Debug, Clone, Default)] +pub struct ValueTally { + counted: usize, + matched: [usize; SensitiveKind::ALL.len()], +} + +impl ValueTally { + pub fn record(&mut self, seen: Seen) { + self.counted += usize::from(seen.counted); + for (count, matched) in self.matched.iter_mut().zip(seen.matched) { + *count += usize::from(matched); + } + } + + pub fn kind(&self) -> Option { + SensitiveKind::ALL + .into_iter() + .zip(self.matched) + .find(|(kind, count)| *count > 0 && (kind.flags_on_any() || count * 2 >= self.counted)) + .map(|(kind, _)| kind) + } +} + +// Only digits, spaces and dashes; 13 to 19 digits; Luhn. +fn is_card(text: &str) -> bool { + if !text.chars().all(|character| matches!(character, '0'..='9' | ' ' | '-')) { + return false; + } + let digits: Vec = text.chars().filter_map(|character| character.to_digit(10)).collect(); + if !(13..=19).contains(&digits.len()) { + return false; + } + let sum: u32 = digits + .iter() + .rev() + .enumerate() + .map(|(place, digit)| match place % 2 { + 1 if digit * 2 > 9 => digit * 2 - 9, + 1 => digit * 2, + _ => *digit, + }) + .sum(); + sum.is_multiple_of(10) +} + +// Spaces (U+0020 only) removed, the upper-case form, and mod-97 of the rearranged digits is 1. +fn is_iban(text: &str) -> bool { + let compact: String = text.chars().filter(|character| *character != ' ').collect(); + if !IBAN.is_match(&compact) { + return false; + } + let (head, tail) = compact.split_at(4); + let mut remainder = 0_u32; + for character in tail.chars().chain(head.chars()) { + let Some(value) = character.to_digit(36) else { + return false; + }; + remainder = match value { + 0..=9 => (remainder * 10 + value) % 97, + _ => (remainder * 100 + value) % 97, + }; + } + remainder == 1 +} + +// 7 to 15 digits with at least one of `+ ( ) - .` or a space, and neither an IPv4 address, an ISO date nor a decimal. +fn is_phone(text: &str) -> bool { + if !PHONE.is_match(text) { + return false; + } + let digits = text.chars().filter(char::is_ascii_digit).count(); + (7..=15).contains(&digits) + && text.contains(['+', '(', ')', '-', '.', ' ']) + && text.parse::().is_err() + && !ISO_DATE.is_match(text) + && !DECIMAL.is_match(text) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::column::ColumnType; + + fn texts(values: &[&str]) -> Vec { + values.iter().map(|value| Value::Text((*value).to_owned())).collect() + } + + fn kind_of(type_name: &str, values: &[Value]) -> Option { + column_value_kind(&ColumnType::untyped_text(type_name), values) + } + + #[test] + fn every_pattern_compiles() { + for pattern in [&*NOT_TEXT, &*IBAN, &*JWT, &*EMAIL, &*PHONE, &*ISO_DATE, &*DECIMAL] { + assert!(pattern.0.is_some()); + } + assert!(API_KEYS.iter().all(|key| key.0.is_some())); + assert_eq!(API_KEYS.len(), 5); + } + + #[test] + fn a_column_of_numbers_dates_or_uuids_is_not_read_for_values() { + for type_name in [ + "int", + "bigint unsigned", + "UInt64", + "Nullable(Int32)", + "double precision", + "timestamp with time zone", + "Date32", + "DateTime64(3)", + "numeric(10,2)", + "uniqueidentifier", + "BOOLEAN", + ] { + assert!(!is_text_like(&ColumnType::untyped_text(type_name)), "{type_name}"); + } + for type_name in [ + "", + "text", + "varchar(255)", + "jsonb", + "String", + "interval_text", + "geometry", + ] { + assert!(is_text_like(&ColumnType::untyped_text(type_name)), "{type_name}"); + } + assert_eq!(kind_of("bigint", &texts(&["4111111111111111"])), None); + } + + #[test] + fn base_type_names_unwrap_clickhouse_wrappers_and_drop_the_width() { + assert_eq!(base_type_name("TINYINT(1)"), "TINYINT"); + assert_eq!(base_type_name(" Nullable( String ) "), "String"); + assert_eq!(base_type_name("lowcardinality(nullable(String))"), "String"); + assert_eq!(base_type_name("numeric (10, 2)"), "numeric"); + assert_eq!(base_type_name(""), ""); + } +} diff --git a/core/crates/core/src/masking/mask_value.rs b/core/crates/core/src/masking/mask_value.rs new file mode 100644 index 0000000000..3cb87cb6ee --- /dev/null +++ b/core/crates/core/src/masking/mask_value.rs @@ -0,0 +1,216 @@ +use std::hash::{BuildHasher, RandomState}; +use std::sync::LazyLock; + +use hmac::{Hmac, KeyInit, Mac}; +use sha2::Sha256; +use unicode_segmentation::UnicodeSegmentation; + +use super::MaskingStyle; +use crate::column::ColumnType; +use crate::export::value_text; +use crate::value::Value; + +pub const BULLETS: &str = "••••"; + +// Drawn once per process and never stored, so equal values hash alike within a run but a hash cannot be looked up +// across runs or apps. +static HASH_KEY: LazyLock<[u8; 32]> = LazyLock::new(|| { + let mut key = [0_u8; 32]; + if getrandom::fill(&mut key).is_err() { + // The standard library's own per-process keys, from the same system source by another path. + for (index, chunk) in key.chunks_mut(8).enumerate() { + chunk.copy_from_slice(&RandomState::new().hash_one(index).to_ne_bytes()); + } + } + key +}); + +// The cell masked by its text form, which `value_text` writes at the column's declared precision. NULL stays NULL; +// bytes hash as they are and otherwise show bullets. +pub fn mask_value(value: &Value, column: &ColumnType, style: MaskingStyle) -> Value { + match (style, value) { + (MaskingStyle::Null, _) | (_, Value::Null) => Value::Null, + (MaskingStyle::Hash, Value::Bytes(bytes)) => Value::Text(stable_hash(bytes)), + (_, Value::Bytes(_) | Value::Undecodable(_)) => Value::Text(BULLETS.to_owned()), + (style, value) => match value_text(value, column) { + Some(text) => mask_text(&text, style).map_or(Value::Null, Value::Text), + None => Value::Text(BULLETS.to_owned()), + }, + } +} + +// None for the NULL style. +pub fn mask_text(text: &str, style: MaskingStyle) -> Option { + Some(match style { + MaskingStyle::Null => return None, + MaskingStyle::Full => BULLETS.to_owned(), + MaskingStyle::LastFour => last_four(text), + MaskingStyle::Email => email(text), + MaskingStyle::Hash => stable_hash(text.as_bytes()), + }) +} + +// HMAC-SHA256 under the process's key, its first 6 bytes as 12 lower-case hex digits. +pub fn stable_hash(bytes: &[u8]) -> String { + let Ok(mut mac) = Hmac::::new_from_slice(&*HASH_KEY) else { + return BULLETS.to_owned(); + }; + mac.update(bytes); + crate::hex::encode_lower(&mac.finalize().into_bytes()[..6]) +} + +fn last_four(text: &str) -> String { + let clusters: Vec<&str> = text.graphemes(true).collect(); + match clusters.len() { + 0..=4 => BULLETS.to_owned(), + count => format!("{BULLETS}{}", clusters[count - 4..].concat()), + } +} + +// The domain after the last `@`, which must not be the first character and must be followed by something. +fn email(text: &str) -> String { + let clusters: Vec<&str> = text.graphemes(true).collect(); + match clusters.iter().rposition(|cluster| *cluster == "@") { + Some(at) if at > 0 && at + 1 < clusters.len() => { + format!("{}•••@{}", clusters[0], clusters[at + 1..].concat()) + } + _ => BULLETS.to_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::column::{ColumnKind, ReadForm, TextLength}; + use crate::value::{SqlDecimal, UndecodableReason, UndecodedValue}; + + fn masked(text: &str, style: MaskingStyle) -> Option { + mask_text(text, style) + } + + fn text_column() -> ColumnType { + ColumnType { + name: "text".to_owned(), + kind: ColumnKind::Text { + length: TextLength::Unbounded, + }, + catalog: None, + dynamic_storage: false, + read_form: ReadForm::Native, + } + } + + // MASKING-RESEARCH.md section 1, each example as the macOS app masks it. + #[test] + fn last_four_keeps_the_last_four_grapheme_clusters_past_four() { + let cases = [ + ("", "••••"), + ("abcd", "••••"), + ("abcde", "••••bcde"), + ("-12.50", "••••2.50"), + ("e\u{301}e\u{301}e\u{301}e\u{301}", "••••"), + ("👨‍👩‍👧abcd", "••••abcd"), + ("0123456789", "••••6789"), + ]; + for (text, expected) in cases { + assert_eq!( + masked(text, MaskingStyle::LastFour).as_deref(), + Some(expected), + "{text:?}" + ); + } + } + + #[test] + fn email_keeps_the_first_character_and_the_domain_after_the_last_at() { + let cases = [ + ("ann@example.com", "a•••@example.com"), + ("a@b@c.com", "a•••@c.com"), + ("ann@x", "a•••@x"), + ("@b.com", "••••"), + ("a@", "••••"), + ("a@\u{301}b", "••••"), + ("no-at-sign", "••••"), + ("", "••••"), + ("é\u{301}x@d.io", "é\u{301}•••@d.io"), + ]; + for (text, expected) in cases { + assert_eq!(masked(text, MaskingStyle::Email).as_deref(), Some(expected), "{text:?}"); + } + } + + #[test] + fn full_shows_four_bullets_and_null_shows_nothing() { + assert_eq!(masked("secret", MaskingStyle::Full).as_deref(), Some("••••")); + assert_eq!(masked("", MaskingStyle::Full).as_deref(), Some("••••")); + assert_eq!(masked("secret", MaskingStyle::Null), None); + assert_eq!(BULLETS.chars().collect::>(), ['\u{2022}'; 4]); + } + + #[test] + fn a_stable_hash_is_twelve_hex_digits_equal_for_equal_values_in_one_process() { + let first = stable_hash(b"ann@example.com"); + + assert_eq!(first.len(), 12); + assert!( + first + .chars() + .all(|digit| digit.is_ascii_hexdigit() && !digit.is_ascii_uppercase()) + ); + assert_eq!(stable_hash(b"ann@example.com"), first); + assert_ne!(stable_hash(b"bob@example.com"), first); + assert_eq!(masked("ann@example.com", MaskingStyle::Hash), Some(first)); + } + + #[test] + fn the_hash_is_hmac_sha256_cut_to_six_bytes() { + let mut mac = Hmac::::new_from_slice(&*HASH_KEY).expect("a key"); + mac.update(b"x"); + let full = crate::hex::encode_lower(&mac.finalize().into_bytes()); + + assert_eq!(stable_hash(b"x"), full[..12]); + } + + #[test] + fn values_mask_by_their_text_and_null_stays_null() { + let column = text_column(); + let decimal = Value::Decimal("-12.50".parse::().expect("a decimal")); + + assert_eq!(mask_value(&Value::Null, &column, MaskingStyle::Full), Value::Null); + assert_eq!( + mask_value(&Value::Text("x".to_owned()), &column, MaskingStyle::Null), + Value::Null + ); + assert_eq!( + mask_value(&decimal, &column, MaskingStyle::LastFour), + Value::Text("••••2.50".to_owned()) + ); + assert_eq!( + mask_value(&Value::Int(1_234_567), &column, MaskingStyle::LastFour), + Value::Text("••••4567".to_owned()) + ); + } + + #[test] + fn bytes_hash_raw_and_otherwise_show_bullets() { + let column = text_column(); + let bytes = Value::Bytes(vec![0xca, 0xfe]); + let undecodable = Value::Undecodable(Box::new(UndecodedValue { + type_name: "geometry".to_owned(), + reason: UndecodableReason::UnsupportedType, + })); + + assert_eq!( + mask_value(&bytes, &column, MaskingStyle::Hash), + Value::Text(stable_hash(&[0xca, 0xfe])) + ); + for style in [MaskingStyle::Full, MaskingStyle::LastFour, MaskingStyle::Email] { + assert_eq!(mask_value(&bytes, &column, style), Value::Text(BULLETS.to_owned())); + assert_eq!( + mask_value(&undecodable, &column, style), + Value::Text(BULLETS.to_owned()) + ); + } + assert_eq!(mask_value(&bytes, &column, MaskingStyle::Null), Value::Null); + } +} diff --git a/core/crates/core/src/masking/mod.rs b/core/crates/core/src/masking/mod.rs new file mode 100644 index 0000000000..5aadd34007 --- /dev/null +++ b/core/crates/core/src/masking/mod.rs @@ -0,0 +1,11 @@ +// Masking a shared result's columns before they leave the machine: the macOS styles, byte for byte, the detectors that +// suggest which columns to mask, and the plan a share sends by. The decision: core/docs/decisions/0028-data-masking.md. + +pub mod detect; +mod mask_value; +mod share; +mod style; + +pub use mask_value::{BULLETS, mask_text, mask_value, stable_hash}; +pub use share::{ShareChoice, SharePlan, ShareSummary, share_suggestions}; +pub use style::MaskingStyle; diff --git a/core/crates/core/src/masking/share.rs b/core/crates/core/src/masking/share.rs new file mode 100644 index 0000000000..22c158c2b1 --- /dev/null +++ b/core/crates/core/src/masking/share.rs @@ -0,0 +1,393 @@ +use super::detect::{MaskSuggestion, Seen, ValueTally, is_text_like, suggest_from_tallies}; +use super::{MaskingStyle, mask_value}; +use crate::column::ResultColumn; +use crate::export::{SnapshotFit, SnapshotRefusal, snapshot_row_count}; +use crate::value::Value; + +// What the share sheet does with one column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ShareChoice { + Keep, + Mask(MaskingStyle), + Remove, +} + +impl ShareChoice { + pub fn style(self) -> Option { + match self { + Self::Mask(style) => Some(style), + Self::Keep | Self::Remove => None, + } + } +} + +// How a share sends a result's visible columns: which it keeps and how it masks each. The snapshot, the sheet's preview +// and its summary all go through it, so the sheet shows what is sent. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SharePlan { + kept: Vec, + styles: Vec>, + columns_cut: bool, +} + +// What a share with a plan sends, for the sheet's note: the rows the snapshot keeps under the plan's row limit and its +// body budget, or why it cannot go at all. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ShareSummary { + pub rows_sent: usize, + pub columns_sent: usize, + pub columns_cut: bool, + pub refused: Option, +} + +impl SharePlan { + // `choices` is the sheet's for each visible column, Keep past its end. At most `max_columns` columns are kept. + pub fn new(visible: usize, choices: &[ShareChoice], max_columns: usize) -> Self { + let choice = |index: usize| choices.get(index).copied().unwrap_or(ShareChoice::Keep); + let mut kept: Vec = (0..visible) + .filter(|index| choice(*index) != ShareChoice::Remove) + .collect(); + let columns_cut = kept.len() > max_columns; + kept.truncate(max_columns); + Self { + styles: (0..visible).map(|index| choice(index).style()).collect(), + kept, + columns_cut, + } + } + + // Positions among the visible columns, in order. + pub fn kept(&self) -> &[usize] { + &self.kept + } + + // More columns were chosen than `max_columns`, and the rest were left out. + pub fn columns_cut(&self) -> bool { + self.columns_cut + } + + pub fn columns(&self, visible: &[ResultColumn]) -> Vec { + self.kept + .iter() + .filter_map(|index| visible.get(*index).cloned()) + .collect() + } + + // The style each kept column names, in the order of `kept`. + pub fn masked(&self) -> Vec> { + self.kept + .iter() + .map(|index| self.styles.get(*index).copied().flatten()) + .collect() + } + + // One row as sent. `read` gives the value held at a visible position and is asked only for kept columns. + pub fn row(&self, visible: &[ResultColumn], mut read: impl FnMut(usize) -> Value) -> Vec { + self.kept + .iter() + .map(|index| { + let value = read(*index); + match (self.styles.get(*index).copied().flatten(), visible.get(*index)) { + (Some(style), Some(column)) => mask_value(&value, &column.column_type, style), + _ => value, + } + }) + .collect() + } + + // `rows` held rows of the visible columns, read one value at a time by `read(row, column)`; at most `max_rows`. + pub fn summary( + &self, + visible: &[ResultColumn], + rows: usize, + mut read: impl FnMut(usize, usize) -> Value, + max_rows: usize, + ) -> ShareSummary { + let sent = snapshot_row_count( + &self.columns(visible), + (0..rows).map(|row| self.row(visible, |column| read(row, column))), + max_rows, + ); + let (rows_sent, refused) = match sent { + Ok(rows) => (rows, None), + Err(refused) => (0, Some(refused)), + }; + ShareSummary { + rows_sent, + columns_sent: self.kept.len(), + columns_cut: self.columns_cut, + refused, + } + } +} + +// The first `max_rows` held rows whatever they weigh, and the rows a share keeping every column sends (core ADR 0028), +// read a row at a time so no rows are held twice. +pub fn share_suggestions>( + visible: &[ResultColumn], + held: impl IntoIterator, + max_rows: usize, + max_columns: usize, +) -> Vec> { + // Keeping every column, a share sends the first `max_columns` as held. + let kept = &visible[..visible.len().min(max_columns)]; + let text_like: Vec = visible.iter().map(|column| is_text_like(&column.column_type)).collect(); + let mut first = vec![ValueTally::default(); visible.len()]; + let mut sent = vec![ValueTally::default(); visible.len()]; + // None from the first row that does not fit; `refused` when the share cannot go at all. + let mut fit = SnapshotFit::new(kept).ok(); + let mut refused = fit.is_none(); + for row in held.into_iter().take(max_rows) { + let row = row.as_ref(); + let goes = match fit.as_mut().map(|fit| fit.take(&row[..kept.len().min(row.len())])) { + Some(Ok(true)) => true, + Some(Ok(false)) => { + fit = None; + false + } + Some(Err(_)) => { + fit = None; + refused = true; + false + } + None => false, + }; + for (index, column) in visible.iter().enumerate() { + if !text_like[index] { + continue; + } + let seen = Seen::of(&column.column_type, row.get(index).unwrap_or(&Value::Null)); + first[index].record(seen); + if goes { + sent[index].record(seen); + } + } + } + match refused { + true => suggest_from_tallies(visible, &[first]), + false => suggest_from_tallies(visible, &[first, sent]), + } +} + +#[cfg(test)] +mod tests { + use super::MaskingStyle::{Email, Full, LastFour}; + use super::*; + use crate::column::ColumnType; + + fn columns() -> Vec { + ["id", "email", "phone", "notes"] + .iter() + .map(|name| ResultColumn::new(*name, ColumnType::untyped_text("text"))) + .collect() + } + + fn text(value: &str) -> Value { + Value::Text(value.to_owned()) + } + + fn held() -> Vec { + ["1", "ann@example.com", "+1 555 0100", "vip"] + .iter() + .map(|value| text(value)) + .collect() + } + + #[test] + fn removed_columns_go_and_the_rest_take_their_choice() { + let choices = [ + ShareChoice::Remove, + ShareChoice::Mask(Email), + ShareChoice::Mask(LastFour), + ]; + + let plan = SharePlan::new(4, &choices, 100); + let row = held(); + let mut asked = Vec::new(); + let sent = plan.row(&columns(), |index| { + asked.push(index); + row[index].clone() + }); + + assert_eq!(plan.kept(), [1, 2, 3]); + assert_eq!(asked, [1, 2, 3], "a removed column was read"); + assert_eq!(sent, [text("a•••@example.com"), text("••••0100"), text("vip")]); + assert_eq!(plan.masked(), [Some(Email), Some(LastFour), None]); + let names: Vec = plan.columns(&columns()).into_iter().map(|column| column.name).collect(); + assert_eq!(names, ["email", "phone", "notes"]); + } + + #[test] + fn a_null_stays_null_under_every_style() { + for style in MaskingStyle::ALL { + let plan = SharePlan::new(1, &[ShareChoice::Mask(style)], 100); + + assert_eq!(plan.row(&columns(), |_| Value::Null), [Value::Null], "{style:?}"); + } + } + + #[test] + fn columns_past_the_cap_are_left_out_after_removals() { + let plan = SharePlan::new(4, &[ShareChoice::Remove], 2); + + assert_eq!(plan.kept(), [1, 2]); + assert!(plan.columns_cut()); + assert!(!SharePlan::new(3, &[ShareChoice::Remove], 2).columns_cut()); + } + + #[test] + fn a_summary_counts_the_rows_the_budget_keeps_or_says_why_none_go() { + let visible = [ResultColumn::new("note", ColumnType::untyped_text("text"))]; + let plan = SharePlan::new(1, &[], 100); + let long = |chars: usize| Value::Text("x".repeat(chars)); + + let cut = plan.summary(&visible, 30, |_, _| long(200_000), 1_000); + let refused = plan.summary(&visible, 3, |_, _| long(300_000), 1_000); + let masked = + SharePlan::new(1, &[ShareChoice::Mask(Full)], 100).summary(&visible, 30, |_, _| long(200_000), 1_000); + + assert_eq!( + cut, + ShareSummary { + rows_sent: 22, + columns_sent: 1, + columns_cut: false, + refused: None, + } + ); + assert_eq!(refused.rows_sent, 0); + assert_eq!( + refused.refused, + Some(SnapshotRefusal::Cell { + column: "note".to_owned() + }) + ); + assert_eq!(masked.rows_sent, 30, "masked text was not what was weighed"); + } + + #[test] + fn removing_every_column_refuses_the_share() { + let removed = [ + ShareChoice::Remove, + ShareChoice::Remove, + ShareChoice::Remove, + ShareChoice::Remove, + ]; + + let summary = + SharePlan::new(4, &removed, 100).summary(&columns(), 2, |_, column| held()[column].clone(), 1_000); + + assert_eq!( + summary, + ShareSummary { + rows_sent: 0, + columns_sent: 0, + columns_cut: false, + refused: Some(SnapshotRefusal::NoColumns), + } + ); + } + + fn style_of(suggestion: Option) -> Option { + suggestion.map(|suggestion| suggestion.style) + } + + #[test] + fn a_first_row_too_large_to_send_still_has_its_values_read() { + let visible = [ + ResultColumn::new("blob", ColumnType::untyped_text("text")), + ResultColumn::new("notes", ColumnType::untyped_text("text")), + ]; + let rows = vec![ + vec![Value::Text("x".repeat(300 * 1_024)), text("ann@example.com")], + vec![text("small"), text("bob@example.com")], + ]; + + let suggested = share_suggestions(&visible, &rows, 1_000, 100); + + assert_eq!( + suggested.iter().map(|found| style_of(*found)).collect::>(), + [None, Some(Email)] + ); + } + + #[test] + fn values_in_rows_that_go_only_once_a_wide_column_is_removed_are_read() { + let visible = [ + ResultColumn::new("blob", ColumnType::untyped_text("text")), + ResultColumn::new("notes", ColumnType::untyped_text("text")), + ]; + // 22 rows fit the budget with the blob kept; the e-mails are in the 8 after them. + let rows: Vec> = (0..30) + .map(|row| { + let notes = match row < 22 { + true => Value::Null, + false => text(&format!("person{row}@example.com")), + }; + vec![Value::Text("x".repeat(200_000)), notes] + }) + .collect(); + + let suggested = share_suggestions(&visible, &rows, 1_000, 100); + + assert_eq!(style_of(suggested[1]), Some(Email)); + } + + #[test] + fn detection_reads_one_held_row_at_a_time() { + use std::cell::Cell; + use std::rc::Rc; + + // A row that counts the rows alive at once, and the most there were. + struct Counted(Vec, Rc>); + impl AsRef<[Value]> for Counted { + fn as_ref(&self) -> &[Value] { + &self.0 + } + } + impl Drop for Counted { + fn drop(&mut self) { + let (alive, most) = self.1.get(); + self.1.set((alive - 1, most)); + } + } + let visible = [ResultColumn::new("contact", ColumnType::untyped_text("text"))]; + let alive = Rc::new(Cell::new((0, 0))); + let rows = (0..50).map(|row| { + let (now, most) = alive.get(); + alive.set((now + 1, most.max(now + 1))); + Counted(vec![text(&format!("p{row}@example.com"))], alive.clone()) + }); + + let suggested = share_suggestions(&visible, rows, 1_000, 100); + + assert_eq!(style_of(suggested[0]), Some(Email)); + assert_eq!(alive.get(), (0, 1), "rows were held for detection"); + } + + #[test] + fn each_window_keeps_its_own_threshold() { + let visible = [ + ResultColumn::new("blob", ColumnType::untyped_text("text")), + ResultColumn::new("contact", ColumnType::untyped_text("text")), + ]; + // With the wide blob, the budget sends the 22 rows of e-mails; over all 60 they are fewer than half. + let rows = |blob: &str| -> Vec> { + (0..60) + .map(|row| { + let contact = match row < 22 { + true => format!("p{row}@example.com"), + false => "word".to_owned(), + }; + vec![text(blob), Value::Text(contact)] + }) + .collect() + }; + + let wide = share_suggestions(&visible, rows(&"x".repeat(200_000)), 1_000, 100); + let narrow = share_suggestions(&visible, rows("x"), 1_000, 100); + + assert_eq!(style_of(wide[1]), Some(Email)); + assert_eq!(style_of(narrow[1]), None); + } +} diff --git a/core/crates/core/src/masking/style.rs b/core/crates/core/src/masking/style.rs new file mode 100644 index 0000000000..5a1c0044f7 --- /dev/null +++ b/core/crates/core/src/masking/style.rs @@ -0,0 +1,43 @@ +// How a masked value is shown. The codes are the macOS app's stored names and the share link's `masked` values. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum MaskingStyle { + Full, + LastFour, + Email, + Hash, + Null, +} + +impl MaskingStyle { + pub const ALL: [Self; 5] = [Self::Full, Self::LastFour, Self::Email, Self::Hash, Self::Null]; + + pub fn code(self) -> &'static str { + match self { + Self::Full => "full", + Self::LastFour => "lastFour", + Self::Email => "email", + Self::Hash => "hash", + Self::Null => "null", + } + } + + pub fn from_code(code: &str) -> Option { + Self::ALL.into_iter().find(|style| style.code() == code) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_the_macos_names_and_read_back() { + let codes: Vec<&str> = MaskingStyle::ALL.iter().map(|style| style.code()).collect(); + + assert_eq!(codes, ["full", "lastFour", "email", "hash", "null"]); + for style in MaskingStyle::ALL { + assert_eq!(MaskingStyle::from_code(style.code()), Some(style)); + } + assert_eq!(MaskingStyle::from_code("Full"), None); + } +} diff --git a/core/crates/core/src/secret_scan.rs b/core/crates/core/src/secret_scan.rs new file mode 100644 index 0000000000..f807fdde84 --- /dev/null +++ b/core/crates/core/src/secret_scan.rs @@ -0,0 +1,309 @@ +use std::sync::LazyLock; + +use regex::Regex; + +use crate::masking::MaskingStyle; +use crate::masking::detect::{Term, longest_term, name_words}; + +// What a shared query or result may give away. Each app words the kind; a hit warns and never blocks. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum SecretHitKind { + AwsAccessKey, + PrivateKey, + JsonWebToken, + GitHubToken, + SlackToken, + StripeKey, + GoogleApiKey, + UrlCredentials, + AssignedSecret, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SecretHit { + pub kind: SecretHitKind, + // From 1. + pub line: u32, +} + +impl SecretHitKind { + pub const ALL: [Self; 9] = [ + Self::AwsAccessKey, + Self::PrivateKey, + Self::JsonWebToken, + Self::GitHubToken, + Self::SlackToken, + Self::StripeKey, + Self::GoogleApiKey, + Self::UrlCredentials, + Self::AssignedSecret, + ]; + + pub fn code(self) -> &'static str { + match self { + Self::AwsAccessKey => "aws_access_key", + Self::PrivateKey => "private_key", + Self::JsonWebToken => "json_web_token", + Self::GitHubToken => "github_token", + Self::SlackToken => "slack_token", + Self::StripeKey => "stripe_key", + Self::GoogleApiKey => "google_api_key", + Self::UrlCredentials => "url_credentials", + Self::AssignedSecret => "assigned_secret", + } + } + + // PLAN-MASKING 8.3: only what Rust's and Swift's engines both read, no lookaround and no possessive runs. + pub(crate) fn pattern(self) -> &'static str { + match self { + Self::AwsAccessKey => r"AKIA[0-9A-Z]{16}", + Self::PrivateKey => r"-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----", + Self::JsonWebToken => r"eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", + Self::GitHubToken => r"gh[pousr]_[A-Za-z0-9]{36,}", + Self::SlackToken => r"xox[abprs]-", + Self::StripeKey => r"sk_live_", + Self::GoogleApiKey => r"AIza[0-9A-Za-z_-]{35}", + Self::UrlCredentials => r"\w+://[^\s:/@]+:[^\s@]+@", + // A name may be quoted or bracketed, as in JSON or T-SQL; the value closes with the quote it opened with. + Self::AssignedSecret => { + r#"(?i)\w*(?:password|passwd|pwd|secret|token|api_key)\w*["'`\]]?\s*(?:=>|:=|=|:)\s*(?:'[^']+'|"[^"]+")"# + } + } + } +} + +static PATTERNS: LazyLock> = LazyLock::new(|| { + SecretHitKind::ALL + .into_iter() + .filter_map(|kind| Regex::new(kind.pattern()).ok().map(|regex| (kind, regex))) + .collect() +}); + +// Each kind once per line, by line. CR, LF and CRLF each end a line. +pub fn scan_sql(sql: &str) -> Vec { + let line_starts = line_starts(sql); + let line_of = + |offset: usize| u32::try_from(line_starts.partition_point(|start| *start <= offset)).unwrap_or(u32::MAX); + let mut hits: Vec = PATTERNS + .iter() + .flat_map(|(kind, regex)| { + regex.find_iter(sql).map(move |found| SecretHit { + kind: *kind, + line: line_of(found.start()), + }) + }) + .collect(); + hits.sort_by_key(|hit| (hit.line, hit.kind)); + hits.dedup(); + hits +} + +// Byte offsets where each line starts; a CRLF pair is one break. +pub(crate) fn line_starts(text: &str) -> Vec { + let bytes = text.as_bytes(); + let mut starts = vec![0]; + let mut at = 0; + while at < bytes.len() { + match bytes[at] { + b'\r' if bytes.get(at + 1) == Some(&b'\n') => { + at += 2; + starts.push(at); + } + b'\r' | b'\n' => { + at += 1; + starts.push(at); + } + _ => at += 1, + } + } + starts +} + +// The names of the columns that may hold a secret, in their order, each once. +pub fn scan_columns>(names: &[S]) -> Vec { + let mut found: Vec = Vec::new(); + for name in names.iter().map(AsRef::as_ref) { + if column_may_hold_secret(name) && !found.iter().any(|kept| kept == name) { + found.push(name.to_owned()); + } + } + found +} + +const SECRET_TERMS: [Term; 8] = [ + secret_term("password"), + secret_term("passwd"), + secret_term("secret"), + secret_term("token"), + secret_term("apikey"), + secret_term("ssn"), + secret_term("creditcard"), + secret_term("cardnumber"), +]; + +const fn secret_term(compact: &'static str) -> Term { + Term { + compact, + single_word: false, + style: MaskingStyle::Full, + } +} + +// Whole words as the masking detectors split a name, so api_key, apiKey and API-KEY read alike and class_name holds +// no "ssn". +fn column_may_hold_secret(name: &str) -> bool { + longest_term(&name_words(name), &SECRET_TERMS).is_some() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kinds(sql: &str) -> Vec<(SecretHitKind, u32)> { + scan_sql(sql).into_iter().map(|hit| (hit.kind, hit.line)).collect() + } + + #[test] + fn every_pattern_compiles() { + assert_eq!(PATTERNS.len(), SecretHitKind::ALL.len()); + } + + #[test] + fn each_kind_is_found_on_its_line() { + let sql = [ + "SELECT 1;", + "-- AKIAIOSFODNN7EXAMPLE", + "-----BEGIN RSA PRIVATE KEY-----", + "-- eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abc-DEF_123", + "-- ghp_0123456789abcdefghijABCDEFGHIJ012345", + "-- xoxb-123", + "-- sk_live_abc", + "-- AIzaSyA1234567890abcdefghijklmnopqrstuv", + "-- postgres://app:hunter2@db.internal/shop", + "UPDATE users SET api_key = 'abc123' WHERE id = 1;", + ] + .join("\n"); + + assert_eq!( + kinds(&sql), + [ + (SecretHitKind::AwsAccessKey, 2), + (SecretHitKind::PrivateKey, 3), + (SecretHitKind::JsonWebToken, 4), + (SecretHitKind::GitHubToken, 5), + (SecretHitKind::SlackToken, 6), + (SecretHitKind::StripeKey, 7), + (SecretHitKind::GoogleApiKey, 8), + (SecretHitKind::UrlCredentials, 9), + (SecretHitKind::AssignedSecret, 10), + ] + ); + } + + #[test] + fn an_assigned_literal_is_found_in_sql_json_and_brackets() { + for sql in [ + "WHERE u.password = 'hunter2'", + r#"SELECT '{"token": "abc"}'::jsonb"#, + "SET [db_passwd] = 'x'", + "INSERT ... VALUES (secret => 'x')", + "SET @pwd := 'x'", + "WHERE `Api_Key`='x'", + ] { + assert_eq!(kinds(sql), [(SecretHitKind::AssignedSecret, 1)], "{sql}"); + } + } + + #[test] + fn a_name_without_a_quoted_literal_is_no_secret() { + for sql in [ + "SELECT password FROM users", + "WHERE password = ''", + "WHERE password = $1", + "WHERE token = :token", + "WHERE password_hash IS NULL", + "SELECT 'password' AS label", + ] { + assert!(kinds(sql).is_empty(), "{sql}: {:?}", kinds(sql)); + } + } + + #[test] + fn a_kind_counts_once_per_line_and_lines_are_ordered() { + let sql = "SELECT 'AKIAIOSFODNN7EXAMPLE', 'AKIAIOSFODNN7EXAMPLF';\nSELECT 'sk_live_a'"; + + assert_eq!( + kinds(sql), + [(SecretHitKind::AwsAccessKey, 1), (SecretHitKind::StripeKey, 2)] + ); + } + + #[test] + fn near_misses_are_not_secrets() { + for sql in [ + "AKIA123", + "-----BEGIN PUBLIC KEY-----", + "eyJhbGciOiJIUzI1NiJ9", + "ghp_short", + "sk_test_abc", + "AIzaShort", + "https://tablepro.app/docs", + ] { + assert!(kinds(sql).is_empty(), "{sql}: {:?}", kinds(sql)); + } + } + + #[test] + fn a_line_is_counted_from_1_whatever_the_line_endings() { + assert_eq!(kinds("\r\n\r\nsk_live_x"), [(SecretHitKind::StripeKey, 3)]); + assert_eq!(kinds("sk_live_x"), [(SecretHitKind::StripeKey, 1)]); + } + + #[test] + fn secret_columns_are_named_in_their_order_once() { + let names = [ + "id", + "user_password", + "PasswordHash", + "access_token", + "apiKey", + "API-KEY", + "client_secret", + "ssn", + "customerSSN", + "ssn_last4", + "credit_card", + "CardNumber", + "class_name", + "lesson", + "id", + "user_password", + ]; + + assert_eq!( + scan_columns(&names), + [ + "user_password", + "PasswordHash", + "access_token", + "apiKey", + "API-KEY", + "client_secret", + "ssn", + "customerSSN", + "ssn_last4", + "credit_card", + "CardNumber", + ] + ); + } + + #[test] + fn every_kind_has_its_own_code() { + let mut codes: Vec<&str> = SecretHitKind::ALL.iter().map(|kind| kind.code()).collect(); + codes.sort_unstable(); + codes.dedup(); + + assert_eq!(codes.len(), SecretHitKind::ALL.len()); + } +} diff --git a/core/crates/core/src/statement/statement_builder.rs b/core/crates/core/src/statement/statement_builder.rs index 33f7808289..ad03d96ce4 100644 --- a/core/crates/core/src/statement/statement_builder.rs +++ b/core/crates/core/src/statement/statement_builder.rs @@ -1,4 +1,7 @@ -use crate::dialect::{BindError, BindTarget, SqlDialect}; +use std::borrow::Cow; + +use crate::column::ColumnType; +use crate::dialect::{BindError, BindTarget, LiteralError, SqlDialect}; use crate::value::Value; use super::{BoundParam, Statement}; @@ -13,6 +16,7 @@ use super::{BoundParam, Statement}; pub struct StatementBuilder { sql: String, params: Vec, + inline: bool, } impl StatementBuilder { @@ -20,6 +24,19 @@ impl StatementBuilder { Self::default() } + // Writes each value as the dialect's literal and binds none, for SQL a person reads or a share link carries. + // Never for a statement the app runs with values from outside. + pub fn inlining() -> Self { + Self { + inline: true, + ..Self::default() + } + } + + pub fn is_inlining(&self) -> bool { + self.inline + } + /// Append SQL the app itself wrote. Nothing from the user reaches /// this: values go through `push_value`, and identifiers through /// the dialect's quoting. @@ -49,6 +66,9 @@ impl StatementBuilder { value: Value, target: BindTarget<'_>, ) -> Result { + if self.inline { + return inline_literal(dialect, &value, target); + } let placeholder = dialect.placeholder(self.params.len(), value, target)?; if let Some(param) = placeholder.param { self.params.push(param); @@ -78,6 +98,27 @@ impl StatementBuilder { } } +// A LIKE pattern is text whatever its column holds. +fn inline_literal(dialect: &dyn SqlDialect, value: &Value, target: BindTarget<'_>) -> Result { + let column_type = match target { + BindTarget::Column(column) => Cow::Borrowed(&column.column_type), + BindTarget::Pattern => Cow::Owned(ColumnType::untyped_text("")), + BindTarget::EngineRowId(_) => { + return Err(BindError::Unrepresentable { + expected: "a literal", + found: "an engine row address", + }); + } + }; + dialect.literal(value, &column_type).map_err(|error| match error { + LiteralError::Undecodable { reason } => BindError::Undecodable { reason }, + LiteralError::Unrepresentable { found } => BindError::Unrepresentable { + expected: "a literal", + found, + }, + }) +} + #[cfg(test)] mod tests { use crate::column::{ diff --git a/core/crates/ffi/Cargo.toml b/core/crates/ffi/Cargo.toml index 86cfc395d6..7963653d29 100644 --- a/core/crates/ffi/Cargo.toml +++ b/core/crates/ffi/Cargo.toml @@ -26,6 +26,7 @@ engines = [ ] [dependencies] +tablepro-account.workspace = true tablepro-core.workspace = true tablepro-driver-cassandra = { workspace = true, optional = true } tablepro-driver-clickhouse = { workspace = true, optional = true } @@ -43,6 +44,7 @@ async-trait.workspace = true chrono.workspace = true futures.workspace = true secrecy.workspace = true +serde_json.workspace = true thiserror.workspace = true tokio = { workspace = true, features = ["rt-multi-thread"] } tokio-util.workspace = true @@ -54,6 +56,7 @@ uuid.workspace = true windows-sys.workspace = true [dev-dependencies] +tablepro-account = { workspace = true, features = ["fakes"] } csbindgen.workspace = true russh.workspace = true tempfile.workspace = true diff --git a/core/crates/ffi/src/account/account_info.rs b/core/crates/ffi/src/account/account_info.rs new file mode 100644 index 0000000000..55b379f2c1 --- /dev/null +++ b/core/crates/ffi/src/account/account_info.rs @@ -0,0 +1,304 @@ +use chrono::{DateTime, Utc}; +use tablepro_account::{ + AccountStatus, Device, EntitlementProblem, FeatureAccess, LicenseClaim, Membership, Profile, TeamClaim, +}; + +// Codes stay strings, as the account crate keeps them: a plan, status or role this build does not know still shows. +// Times are seconds from the Unix epoch. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct AccountStatusInfo { + pub state: AccountStateTag, + // From the entitlement, kept while a refresh fails. + pub account_id: Option, + pub email: Option, + pub name: Option, + pub features: Vec, + pub licenses: Vec, + pub entitlement_expires_at_secs: Option, + pub problem: Option, + // False when no secret store took the sign-in: the next launch starts signed out. + pub remembered: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum AccountStateTag { + SignedOut, + SignedIn, + // An imported offline file on a machine that is not signed in. + Offline, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum EntitlementProblemTag { + Expired, + // The code of the error the last refresh met. + RefreshFailed { code: String }, + DeviceLimitReached { devices: Vec }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum FeatureAccessTag { + Available, + SignedOut, + NotIncluded, + Expired, + RefreshFailed, + DeviceLimitReached, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct LicenseInfo { + pub id: String, + pub plan: String, + pub cycle: String, + pub source: String, + pub status: String, + pub renews_at_secs: Option, + pub ends_at_secs: Option, + pub team: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct TeamInfo { + pub id: String, + pub name: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct MembershipInfo { + pub team: TeamInfo, + pub role: String, + pub has_seat: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ProfileInfo { + pub id: String, + pub email: String, + pub name: Option, + pub licenses: Vec, + pub teams: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct DeviceInfo { + pub id: String, + pub platform: String, + pub name: String, + pub app_version: String, + pub os_version: String, + pub last_seen_at_secs: i64, + pub licensed_at_secs: Option, + // Until then, removing it is refused with offline_file_active. + pub offline_until_secs: Option, + pub is_this_machine: bool, +} + +impl AccountStatusInfo { + pub(crate) fn of(status: &AccountStatus, machine_id: &str) -> Self { + let (state, signed_in) = match status { + AccountStatus::SignedOut => (AccountStateTag::SignedOut, None), + AccountStatus::SignedIn(signed_in) => (AccountStateTag::SignedIn, Some(signed_in)), + AccountStatus::Offline(_) => (AccountStateTag::Offline, None), + }; + let claims = status.entitlement().map(tablepro_account::Entitlement::claims); + Self { + state, + account_id: claims.map(|claims| claims.sub.clone()), + email: claims.map(|claims| claims.account.email.clone()), + name: claims + .map(|claims| claims.account.name.clone()) + .filter(|name| !name.trim().is_empty()), + features: claims.map(|claims| claims.features.clone()).unwrap_or_default(), + licenses: claims + .map(|claims| claims.licenses.iter().map(LicenseInfo::from).collect()) + .unwrap_or_default(), + entitlement_expires_at_secs: status.entitlement().map(|it| it.expires_at().timestamp()), + problem: signed_in + .and_then(|signed_in| signed_in.problem.as_ref()) + .map(|problem| EntitlementProblemTag::of(problem, machine_id)), + remembered: signed_in.is_some_and(|signed_in| signed_in.remembered), + } + } +} + +impl EntitlementProblemTag { + fn of(problem: &EntitlementProblem, machine_id: &str) -> Self { + match problem { + EntitlementProblem::Expired => Self::Expired, + EntitlementProblem::RefreshFailed(error) => Self::RefreshFailed { + code: error.code().to_owned(), + }, + EntitlementProblem::DeviceLimitReached(devices) => Self::DeviceLimitReached { + devices: devices + .iter() + .map(|device| DeviceInfo::of(device, machine_id)) + .collect(), + }, + } + } +} + +impl From for FeatureAccessTag { + fn from(access: FeatureAccess) -> Self { + match access { + FeatureAccess::Available => Self::Available, + FeatureAccess::SignedOut => Self::SignedOut, + FeatureAccess::NotIncluded => Self::NotIncluded, + FeatureAccess::Expired => Self::Expired, + FeatureAccess::RefreshFailed => Self::RefreshFailed, + FeatureAccess::DeviceLimitReached => Self::DeviceLimitReached, + } + } +} + +impl From<&LicenseClaim> for LicenseInfo { + fn from(license: &LicenseClaim) -> Self { + Self { + id: license.id.clone(), + plan: license.plan.clone(), + cycle: license.cycle.clone(), + source: license.source.clone(), + status: license.status.clone(), + renews_at_secs: license.renews_at.map(seconds), + ends_at_secs: license.ends_at.map(seconds), + team: license.team.as_ref().map(TeamInfo::from), + } + } +} + +impl From<&TeamClaim> for TeamInfo { + fn from(team: &TeamClaim) -> Self { + Self { + id: team.id.clone(), + name: team.name.clone(), + } + } +} + +impl From for ProfileInfo { + fn from(profile: Profile) -> Self { + Self { + id: profile.id, + email: profile.email, + name: profile.name, + licenses: profile.licenses.iter().map(LicenseInfo::from).collect(), + teams: profile.teams.iter().map(MembershipInfo::from).collect(), + } + } +} + +impl From<&Membership> for MembershipInfo { + fn from(membership: &Membership) -> Self { + Self { + team: TeamInfo::from(&membership.team), + role: membership.role.clone(), + has_seat: membership.has_seat, + } + } +} + +impl DeviceInfo { + pub(crate) fn of(device: &Device, machine_id: &str) -> Self { + Self { + id: device.id.clone(), + platform: device.platform.clone(), + name: device.name.clone(), + app_version: device.app_version.clone(), + os_version: device.os_version.clone(), + last_seen_at_secs: seconds(device.last_seen_at), + licensed_at_secs: device.licensed_at.map(seconds), + offline_until_secs: device.offline_until.map(seconds), + is_this_machine: device.machine_id == machine_id, + } + } +} + +fn seconds(at: DateTime) -> i64 { + at.timestamp() +} + +#[cfg(test)] +mod tests { + use chrono::TimeDelta; + use tablepro_account::{AccountError, SignedIn, fakes}; + + use super::*; + + fn device(machine_id: &str) -> Device { + Device { + id: "dev_01".to_owned(), + machine_id: machine_id.to_owned(), + platform: "windows".to_owned(), + name: "Lab".to_owned(), + app_version: "1.0.0".to_owned(), + os_version: "Windows 11".to_owned(), + last_seen_at: DateTime::from_timestamp(1_800_000_000, 0).unwrap(), + licensed_at: None, + offline_until: None, + } + } + + #[test] + fn signed_out_says_nothing_about_an_account() { + let info = AccountStatusInfo::of(&AccountStatus::SignedOut, fakes::MACHINE); + + assert_eq!(info.state, AccountStateTag::SignedOut); + assert_eq!((info.email, info.problem), (None, None)); + assert!(info.features.is_empty()); + assert!(!info.remembered); + } + + #[test] + fn a_signed_in_status_names_the_account_and_its_features() { + let issued = Utc::now(); + let claims = fakes::claims(issued, TimeDelta::days(14), &["shared_links"]); + let entitlement = fakes::entitlement(&claims).unwrap(); + let status = AccountStatus::SignedIn(Box::new(SignedIn { + entitlement: Some(entitlement), + problem: Some(EntitlementProblem::RefreshFailed(AccountError::Unreachable( + "offline".to_owned(), + ))), + remembered: true, + })); + + let info = AccountStatusInfo::of(&status, fakes::MACHINE); + + assert_eq!(info.state, AccountStateTag::SignedIn); + assert_eq!(info.account_id.as_deref(), Some(claims.sub.as_str())); + assert_eq!(info.email.as_deref(), Some(claims.account.email.as_str())); + assert_eq!(info.features, ["shared_links"]); + assert_eq!(info.entitlement_expires_at_secs, Some(claims.exp)); + assert_eq!( + info.problem, + Some(EntitlementProblemTag::RefreshFailed { + code: "account.unreachable".to_owned() + }) + ); + assert!(info.remembered); + } + + #[test] + fn the_device_limit_lists_the_devices_and_marks_this_one() { + let status = AccountStatus::SignedIn(Box::new(SignedIn { + entitlement: None, + problem: Some(EntitlementProblem::DeviceLimitReached(vec![ + device(fakes::MACHINE), + device("another machine"), + ])), + remembered: false, + })); + + let info = AccountStatusInfo::of(&status, fakes::MACHINE); + + let Some(EntitlementProblemTag::DeviceLimitReached { devices }) = info.problem else { + panic!("not the device limit: {:?}", info.problem); + }; + assert_eq!( + devices.iter().map(|device| device.is_this_machine).collect::>(), + [true, false] + ); + assert_eq!(devices[0].last_seen_at_secs, 1_800_000_000); + assert_eq!(info.account_id, None); + } +} diff --git a/core/crates/ffi/src/account/account_service.rs b/core/crates/ffi/src/account/account_service.rs new file mode 100644 index 0000000000..5a64aa6aac --- /dev/null +++ b/core/crates/ffi/src/account/account_service.rs @@ -0,0 +1,326 @@ +use std::path::PathBuf; +use std::sync::Arc; + +use chrono::Utc; +use tablepro_account::{ + Account, AccountSettings, AccountStatus, AppClient, CallbackPage, DeviceDescription, Endpoints, EntitlementKeys, + MachineId, +}; +use tablepro_session::runtime::Tasks; +use tokio::sync::watch; +use tokio_util::task::AbortOnDropHandle; + +use super::account_info::{AccountStatusInfo, DeviceInfo, FeatureAccessTag, ProfileInfo}; +use super::host_browser::{HostBrowser, HostBrowserBridge}; +use crate::cancel_token::{CancelToken, token}; +use crate::core_handle::Core; +use crate::error::CoreError; +use crate::runtime::on_runtime; + +// What the app says about itself and where the account lives. Core ADR 0016 has the flow. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct AccountConfig { + // Both None for tablepro.app; a development build names its local stack's two. + pub account_url: Option, + pub api_url: Option, + // The x of each Ed25519 key a development stack signs with; empty for the release keys. + pub entitlement_keys: Vec, + pub device_name: String, + pub app_version: String, + pub os_version: String, + // The device and entitlement are kept here between launches. + pub account_file: String, + // The browser's page once the sign-in comes back, in the app's language. + pub callback_finished: String, + pub callback_unknown: String, + // None reads MachineGuid from the registry, the only source on Windows; elsewhere the host gives one. + pub machine_guid: Option, +} + +// Told the account's status changed, on a runtime thread. It only schedules a read of `status` on the app's own +// thread: no work, and nothing that blocks. +#[uniffi::export(callback_interface)] +pub trait AccountListener: Send + Sync { + fn status_changed(&self); +} + +// One per app. Dropping it stops the refresh schedule. +#[derive(uniffi::Object)] +pub struct AccountService { + pub(crate) account: Account, + status: watch::Receiver, + pub(crate) tasks: Tasks, + _running: AbortOnDropHandle<()>, +} + +#[uniffi::export] +impl Core { + // Restores the last sign-in and keeps the entitlement fresh while the service lives. + pub async fn open_account( + &self, + config: AccountConfig, + browser: Box, + listener: Box, + ) -> Result, CoreError> { + let refresh_tokens = self.refresh_tokens(); + let tasks = self.tasks.clone(); + let browser = Arc::new(HostBrowserBridge::new(browser, tasks.clone())); + let listener: Arc = Arc::from(listener); + on_runtime(&self.tasks, async move { + // Reading the registry and the system's certificates can block. + let account = tasks + .spawn_blocking_task(move || { + let settings = settings(config)?; + let vault = refresh_tokens(&settings); + let status = watch::Sender::new(AccountStatus::SignedOut); + Account::new(settings, vault, browser, status).map_err(CoreError::from) + }) + .await + .map_err(|failure| CoreError::failed("ffi.panicked", failure.to_string()))??; + Ok(Arc::new(AccountService::start(account, listener, tasks))) + }) + .await + } +} + +impl AccountService { + fn start(account: Account, listener: Arc, tasks: Tasks) -> Self { + let status = account.status(); + let mut changes = account.status(); + let running = { + let account = account.clone(); + tasks.spawn_owned(async move { + let signal = async move { + while changes.changed().await.is_ok() { + listener.status_changed(); + } + }; + tokio::join!(account.run(), signal); + }) + }; + Self { + account, + status, + tasks, + _running: running, + } + } + + fn machine_id(&self) -> String { + self.account.machine_id().as_str().to_owned() + } +} + +#[uniffi::export] +impl AccountService { + pub fn status(&self) -> AccountStatusInfo { + AccountStatusInfo::of(&self.status.borrow(), self.account.machine_id().as_str()) + } + + // From the entitlement's feature codes only: the app knows no plan or tier. + pub fn feature_access(&self, feature: String) -> FeatureAccessTag { + self.status.borrow().feature_access(&feature, Utc::now()).into() + } + + // The cancel ends only the wait for the browser: once it has come back, the sign-in is kept. + pub async fn sign_in(&self, cancel: Option>) -> Result<(), CoreError> { + let account = self.account.clone(); + let cancel = token(cancel); + on_runtime(&self.tasks, async move { + account + .sign_in(async move { cancel.cancelled().await }) + .await + .map_err(CoreError::from) + }) + .await + } + + // Signs out here even when the server could not be told, which the error then says. + pub async fn sign_out(&self) -> Result<(), CoreError> { + let account = self.account.clone(); + on_runtime( + &self.tasks, + async move { account.sign_out().await.map_err(CoreError::from) }, + ) + .await + } + + // Refresh or Try Again, and after any change to the account. + pub async fn refresh(&self) -> Result<(), CoreError> { + let account = self.account.clone(); + on_runtime(&self.tasks, async move { + account.refresh_entitlement().await.map_err(CoreError::from) + }) + .await + } + + // When the app comes back while past the device limit, since a slot may have been freed elsewhere. False when + // it was not past the limit, so nothing was asked. + pub async fn refresh_past_device_limit(&self) -> Result { + let account = self.account.clone(); + on_runtime(&self.tasks, async move { + match account.refresh_past_device_limit().await { + None => Ok(false), + Some(refreshed) => refreshed.map(|()| true).map_err(CoreError::from), + } + }) + .await + } + + pub async fn profile(&self) -> Result { + let account = self.account.clone(); + on_runtime(&self.tasks, async move { + account.profile().await.map(ProfileInfo::from).map_err(CoreError::from) + }) + .await + } + + pub async fn devices(&self) -> Result, CoreError> { + let account = self.account.clone(); + let machine_id = self.machine_id(); + on_runtime(&self.tasks, async move { + let devices = account.devices().await?; + Ok(devices + .iter() + .map(|device| DeviceInfo::of(device, &machine_id)) + .collect()) + }) + .await + } + + pub async fn remove_device(&self, device_id: String) -> Result<(), CoreError> { + let account = self.account.clone(); + on_runtime(&self.tasks, async move { + account.remove_device(&device_id).await.map_err(CoreError::from) + }) + .await + } +} + +impl std::fmt::Debug for AccountService { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("AccountService").finish_non_exhaustive() + } +} + +fn settings(config: AccountConfig) -> Result { + let endpoints = match (config.account_url.as_deref(), config.api_url.as_deref()) { + (None, None) => Endpoints::production(), + (Some(account), Some(api)) => Endpoints::new(account, api) + .map_err(|error| CoreError::failed("ffi.account_config", format!("{account} or {api}: {error}")))?, + _ => { + return Err(CoreError::failed( + "ffi.account_config", + "account_url and api_url go together", + )); + } + }; + let keys = match config.entitlement_keys.is_empty() { + true => EntitlementKeys::release(), + false => EntitlementKeys::from_public_keys(config.entitlement_keys.iter().map(String::as_str)) + .map_err(|error| CoreError::failed("ffi.account_config", error.to_string()))?, + }; + let guid = match config.machine_guid { + Some(guid) => guid, + None => system_machine_guid()?, + }; + let machine_id = MachineId::derive_machine_guid(&guid) + .ok_or_else(|| CoreError::failed("account.no_machine_id", "MachineGuid is not a GUID"))?; + Ok(AccountSettings { + client: AppClient::WINDOWS, + endpoints, + device: DeviceDescription { + name: config.device_name, + app_version: config.app_version, + os_version: config.os_version, + }, + machine_id, + keys, + account_file: PathBuf::from(config.account_file), + callback_page: CallbackPage { + finished: config.callback_finished, + unknown: config.callback_unknown, + }, + }) +} + +#[cfg(windows)] +fn system_machine_guid() -> Result { + super::machine_guid::read_machine_guid().map_err(|detail| CoreError::failed("account.no_machine_id", detail)) +} + +#[cfg(not(windows))] +fn system_machine_guid() -> Result { + Err(CoreError::failed( + "account.no_machine_id", + "this platform's machine ID is not read by the core", + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config() -> AccountConfig { + AccountConfig { + account_url: None, + api_url: None, + entitlement_keys: Vec::new(), + device_name: "Lab".to_owned(), + app_version: "1.0.0".to_owned(), + os_version: "Windows 11".to_owned(), + account_file: "account.json".to_owned(), + callback_finished: String::new(), + callback_unknown: String::new(), + machine_guid: Some("d3b07384-d113-4ec6-a2f1-6a3f0c2e9b7a".to_owned()), + } + } + + #[test] + fn no_urls_is_tablepro_app_and_both_name_a_local_stack() { + let production = settings(config()).unwrap(); + let local = settings(AccountConfig { + account_url: Some("http://account.localhost:5284".to_owned()), + api_url: Some("http://api.localhost:5284/v2".to_owned()), + ..config() + }) + .unwrap(); + + assert_eq!(production.endpoints, Endpoints::production()); + assert_eq!( + local.endpoints, + Endpoints::new("http://account.localhost:5284", "http://api.localhost:5284/v2").unwrap() + ); + assert_eq!(production.client, AppClient::WINDOWS); + } + + #[test] + fn half_a_local_stack_a_bad_key_or_a_bad_guid_is_refused() { + let half = settings(AccountConfig { + api_url: Some("http://api.localhost:5284/v2".to_owned()), + ..config() + }); + let keyless = settings(AccountConfig { + entitlement_keys: vec!["not a key".to_owned()], + ..config() + }); + let guidless = settings(AccountConfig { + machine_guid: Some("not a guid".to_owned()), + ..config() + }); + + assert_eq!(half.unwrap_err().code(), "ffi.account_config"); + assert_eq!(keyless.unwrap_err().code(), "ffi.account_config"); + assert_eq!(guidless.unwrap_err().code(), "account.no_machine_id"); + } + + #[test] + fn the_machine_id_is_the_guid_s_hmac() { + let settings = settings(config()).unwrap(); + + assert_eq!( + settings.machine_id.as_str(), + "304a889059f4befc83a542069ca52d990fd963e22766f6db230543bfddf7e336" + ); + } +} diff --git a/core/crates/ffi/src/account/host_browser.rs b/core/crates/ffi/src/account/host_browser.rs new file mode 100644 index 0000000000..b43b31cceb --- /dev/null +++ b/core/crates/ffi/src/account/host_browser.rs @@ -0,0 +1,117 @@ +use std::sync::Arc; + +use async_trait::async_trait; +use tablepro_account::{BrowserLauncher, Url}; +use tablepro_session::runtime::Tasks; + +// The app opens the sign-in page in the user's browser. The core calls it on a thread it lets block. Not `open`: +// UniFFI's Swift generator escapes that name in the C header too, which then does not compile. +#[uniffi::export(callback_interface)] +pub trait HostBrowser: Send + Sync { + fn open_url(&self, url: String) -> Result<(), HostBrowserError>; +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)] +pub enum HostBrowserError { + #[error("the browser did not open: {detail}")] + Failed { detail: String }, +} + +impl From for HostBrowserError { + fn from(error: uniffi::UnexpectedUniFFICallbackError) -> Self { + Self::Failed { detail: error.reason } + } +} + +pub(crate) struct HostBrowserBridge { + host: Arc, + tasks: Tasks, +} + +impl HostBrowserBridge { + pub(crate) fn new(host: Box, tasks: Tasks) -> Self { + Self { + host: Arc::from(host), + tasks, + } + } +} + +impl std::fmt::Debug for HostBrowserBridge { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HostBrowserBridge").finish_non_exhaustive() + } +} + +#[async_trait] +impl BrowserLauncher for HostBrowserBridge { + async fn open(&self, url: &Url) -> Result<(), String> { + let host = self.host.clone(); + let url = url.to_string(); + match self.tasks.spawn_blocking_task(move || host.open_url(url)).await { + Ok(opened) => opened.map_err(|error| error.to_string()), + Err(failure) => Err(failure.to_string()), + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use super::*; + use crate::runtime; + + #[derive(Default)] + struct Recording(Arc>>); + + impl HostBrowser for Recording { + fn open_url(&self, url: String) -> Result<(), HostBrowserError> { + self.0.lock().unwrap().push(url); + Ok(()) + } + } + + struct Refusing; + + impl HostBrowser for Refusing { + fn open_url(&self, _: String) -> Result<(), HostBrowserError> { + Err(HostBrowserError::Failed { + detail: "no default browser".to_owned(), + }) + } + } + + struct Throwing; + + impl HostBrowser for Throwing { + fn open_url(&self, _: String) -> Result<(), HostBrowserError> { + panic!("the app's callback threw"); + } + } + + fn bridge(host: impl HostBrowser + 'static) -> HostBrowserBridge { + HostBrowserBridge::new(Box::new(host), runtime::tasks().unwrap()) + } + + #[tokio::test] + async fn the_app_is_given_the_whole_url() { + let opened = Arc::new(Mutex::new(Vec::new())); + let url = Url::parse("https://account.tablepro.app/oauth/authorize?state=a%20b&client_id=x").unwrap(); + + bridge(Recording(opened.clone())).open(&url).await.unwrap(); + + assert_eq!(*opened.lock().unwrap(), [url.to_string()]); + } + + #[tokio::test] + async fn a_refusal_or_a_throw_reaches_the_account_as_its_text() { + let url = Url::parse("https://account.tablepro.app/").unwrap(); + + let refused = bridge(Refusing).open(&url).await.unwrap_err(); + let thrown = bridge(Throwing).open(&url).await; + + assert!(refused.contains("no default browser"), "{refused}"); + assert!(thrown.is_err()); + } +} diff --git a/core/crates/ffi/src/account/machine_guid.rs b/core/crates/ffi/src/account/machine_guid.rs new file mode 100644 index 0000000000..38b4fca66b --- /dev/null +++ b/core/crates/ffi/src/account/machine_guid.rs @@ -0,0 +1,49 @@ +use windows_sys::Win32::Foundation::ERROR_SUCCESS; +use windows_sys::Win32::System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ, RRF_SUBKEY_WOW6464KEY, RegGetValueW}; + +// 36 characters and the NUL, with room to spare. +const UNITS: usize = 64; + +// The 64-bit view holds it; a 32-bit process would otherwise read WOW6432Node, which has none. +pub(crate) fn read_machine_guid() -> Result { + let key = wide(r"SOFTWARE\Microsoft\Cryptography"); + let value = wide("MachineGuid"); + let mut buffer = [0u16; UNITS]; + let mut size = u32::try_from(std::mem::size_of_val(&buffer)).unwrap_or(u32::MAX); + // SAFETY: both names are NUL-terminated and outlive the call; `size` is the buffer's length in bytes. + let status = unsafe { + RegGetValueW( + HKEY_LOCAL_MACHINE, + key.as_ptr(), + value.as_ptr(), + RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY, + std::ptr::null_mut(), + buffer.as_mut_ptr().cast(), + &raw mut size, + ) + }; + if status != ERROR_SUCCESS { + return Err(format!("MachineGuid could not be read (error {status})")); + } + let units = (size as usize / 2).min(UNITS); + let text = String::from_utf16(&buffer[..units]).map_err(|_| "MachineGuid is not UTF-16 text".to_owned())?; + Ok(text.trim_end_matches('\0').to_owned()) +} + +fn wide(text: &str) -> Vec { + text.encode_utf16().chain(std::iter::once(0)).collect() +} + +#[cfg(test)] +mod tests { + use tablepro_account::MachineId; + + use super::*; + + #[test] + fn this_machine_has_a_guid_the_account_derives_an_id_from() { + let guid = read_machine_guid().unwrap(); + + assert!(MachineId::derive_machine_guid(&guid).is_some(), "{guid:?}"); + } +} diff --git a/core/crates/ffi/src/account/mod.rs b/core/crates/ffi/src/account/mod.rs new file mode 100644 index 0000000000..ae2c98b9de --- /dev/null +++ b/core/crates/ffi/src/account/mod.rs @@ -0,0 +1,21 @@ +mod account_info; +mod account_service; +mod host_browser; +#[cfg(windows)] +mod machine_guid; +mod secret_scan; +pub(crate) mod share; + +pub use account_info::{ + AccountStateTag, AccountStatusInfo, DeviceInfo, EntitlementProblemTag, FeatureAccessTag, LicenseInfo, + MembershipInfo, ProfileInfo, TeamInfo, +}; +pub use account_service::{AccountConfig, AccountListener, AccountService}; +pub use host_browser::{HostBrowser, HostBrowserError}; +pub use secret_scan::{ + SecretHitInfo, SecretHitKindTag, scan_columns_for_secrets, scan_sql_for_secrets, share_token_from_link, +}; +pub use share::{ + CreatedShareInfo, ShareExpiryTag, ShareInfo, ShareKindTag, ShareLimitsInfo, SharePageInfo, ShareRequestArg, + ShareTeamInfo, SharedLinkInfo, +}; diff --git a/core/crates/ffi/src/account/secret_scan.rs b/core/crates/ffi/src/account/secret_scan.rs new file mode 100644 index 0000000000..c97a079677 --- /dev/null +++ b/core/crates/ffi/src/account/secret_scan.rs @@ -0,0 +1,108 @@ +use tablepro_core::secret_scan::{self, SecretHit, SecretHitKind}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SecretHitKindTag { + AwsAccessKey, + PrivateKey, + JsonWebToken, + GitHubToken, + SlackToken, + StripeKey, + GoogleApiKey, + UrlCredentials, + AssignedSecret, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)] +pub struct SecretHitInfo { + pub kind: SecretHitKindTag, + // From 1. + pub line: u32, +} + +// Each kind once per line, by line. A hit warns before a share and never blocks it. +#[uniffi::export] +pub fn scan_sql_for_secrets(sql: String) -> Vec { + secret_scan::scan_sql(&sql) + .into_iter() + .map(SecretHitInfo::from) + .collect() +} + +// The names of the columns that may hold a secret, in their order, each once. +#[uniffi::export] +pub fn scan_columns_for_secrets(names: Vec) -> Vec { + secret_scan::scan_columns(&names) +} + +// The token of `tablepro://share?token=`, None for any other link or a malformed token. +#[uniffi::export] +pub fn share_token_from_link(link: String) -> Option { + tablepro_account::share_token_from_link(&link) +} + +impl From for SecretHitInfo { + fn from(hit: SecretHit) -> Self { + Self { + kind: hit.kind.into(), + line: hit.line, + } + } +} + +impl From for SecretHitKindTag { + fn from(kind: SecretHitKind) -> Self { + match kind { + SecretHitKind::AwsAccessKey => Self::AwsAccessKey, + SecretHitKind::PrivateKey => Self::PrivateKey, + SecretHitKind::JsonWebToken => Self::JsonWebToken, + SecretHitKind::GitHubToken => Self::GitHubToken, + SecretHitKind::SlackToken => Self::SlackToken, + SecretHitKind::StripeKey => Self::StripeKey, + SecretHitKind::GoogleApiKey => Self::GoogleApiKey, + SecretHitKind::UrlCredentials => Self::UrlCredentials, + SecretHitKind::AssignedSecret => Self::AssignedSecret, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_hit_crosses_with_its_kind_and_line() { + let hits = scan_sql_for_secrets("SELECT 1;\nSELECT 'AKIAIOSFODNN7EXAMPLE';".to_owned()); + + assert_eq!( + hits, + [SecretHitInfo { + kind: SecretHitKindTag::AwsAccessKey, + line: 2 + }] + ); + } + + #[test] + fn every_kind_has_a_tag() { + let tags: Vec = SecretHitKind::ALL.into_iter().map(SecretHitKindTag::from).collect(); + + assert_eq!(tags.len(), 9); + assert_eq!(tags[8], SecretHitKindTag::AssignedSecret); + } + + #[test] + fn secret_columns_and_the_deep_link_token_cross() { + let token = "Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK"; + + assert_eq!( + scan_columns_for_secrets(vec!["id".to_owned(), "api_key".to_owned()]), + ["api_key"] + ); + assert_eq!( + share_token_from_link(format!("tablepro://share?token={token}")).as_deref(), + Some(token) + ); + assert_eq!(share_token_from_link("tablepro://share?token=x".to_owned()), None); + } +} diff --git a/core/crates/ffi/src/account/share.rs b/core/crates/ffi/src/account/share.rs new file mode 100644 index 0000000000..0729c47320 --- /dev/null +++ b/core/crates/ffi/src/account/share.rs @@ -0,0 +1,638 @@ +use std::sync::Arc; + +use chrono::{DateTime, Utc}; +use secrecy::SecretString; +use tablepro_account::{ + CreatedShare, MAX_SHARE_COLUMNS, Share, ShareExpiry, ShareKind, ShareLimits, SharePage, ShareRequest, ShareTeam, + SharedLink, +}; +use tablepro_core::Value; +use tablepro_core::column::ResultColumn; +use tablepro_core::export::{ResultExtent, Snapshot, SnapshotRefusal, build_snapshot}; +use tablepro_core::masking::{ShareChoice, SharePlan, ShareSummary}; + +use super::account_service::AccountService; +use crate::error::CoreError; +use crate::export::held_value; +use crate::masking::ShareColumnChoice; +use crate::results::ResultSet; +use crate::runtime::on_runtime; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum ShareKindTag { + Query, + Result, +} + +// The server counts the expiry from its own clock. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum ShareExpiryTag { + OneDay, + SevenDays, + ThirtyDays, + Never, +} + +// Plan, kind, scope and state stay strings, as the account crate keeps them. Times are seconds from the Unix epoch. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ShareLimitsInfo { + pub plan: String, + pub live: u64, + pub live_limit: u64, + pub max_rows: u64, + // A result with more visible columns shares the first ones, on every plan. + pub max_columns: u64, + pub expiries: Vec, + pub default_expiry: Option, + pub password: bool, + pub disable_download: bool, + pub team: bool, + pub email_verified: bool, + pub sharing_disabled: bool, + // The teams the account holds a seat in, for a team link; empty on Free. + pub teams: Vec, +} + +// A team link counts against the team's own `live_limit`. `public_links` false: the team turned them off. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ShareTeamInfo { + pub id: String, + pub name: String, + pub live: u64, + pub live_limit: u64, + pub public_links: bool, +} + +#[derive(Clone, uniffi::Record)] +pub struct ShareRequestArg { + pub kind: ShareKindTag, + pub sql: String, + pub title: Option, + pub note: Option, + pub dialect: Option, + // None takes the plan's default. + pub expiry: Option, + // Only for a result. + pub hide_sql: bool, + // None leaves downloads on. + pub allow_download: Option, + pub password: Option, + pub team_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ShareInfo { + pub id: String, + pub kind: String, + pub scope: String, + pub team_id: Option, + pub title: String, + pub note: String, + pub dialect: String, + // Only when one link is read on its own. + pub sql: Option, + pub has_snapshot: bool, + pub row_count: Option, + pub truncated: Option, + pub hide_sql: bool, + pub allow_download: bool, + pub has_password: bool, + pub state: String, + pub removed_reason: Option, + // The link does not resolve until its switch is on again; `suspended_by` is account, team or team_deleted. + pub suspended: bool, + pub suspended_by: Option, + pub view_count: u64, + pub created_at_secs: i64, + pub updated_at_secs: i64, + pub expires_at_secs: Option, + pub revoked_at_secs: Option, + pub removed_at_secs: Option, + pub url: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct CreatedShareInfo { + pub share: ShareInfo, + pub url: String, + // Only the first `max_columns` of the visible columns were shared. + pub columns_truncated: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SharePageInfo { + pub shares: Vec, + pub next_cursor: Option, +} + +// A link as anyone with it reads it. The app opens its SQL in a new tab and never runs it. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct SharedLinkInfo { + pub kind: String, + pub title: String, + pub note: String, + pub dialect: String, + // None when the owner hid it, so there is nothing to open. + pub sql: Option, + pub created_at_secs: i64, + pub expires_at_secs: Option, + pub allow_download: bool, + pub row_count: Option, + pub truncated: Option, +} + +#[uniffi::export] +impl AccountService { + pub async fn share_limits(&self) -> Result { + let account = self.account.clone(); + on_runtime(&self.tasks, async move { Ok(account.share_limits().await?.into()) }).await + } + + // A result share takes the set's first `visible_columns` columns and its first `max_rows` rows, the plan's + // limit from `share_limits`; the set must have all its rows. A query share takes no set. For a table page, the + // SQL is the page's `view_sql` and `total_rows` what `table_row_count` counts, since the set holds one page. + // `columns` is the sheet's choice for each visible column, in order, Keep for any it leaves out. + pub async fn create_share( + &self, + request: ShareRequestArg, + result: Option>, + visible_columns: u32, + max_rows: u32, + total_rows: Option, + columns: Vec, + ) -> Result { + let account = self.account.clone(); + let tasks = self.tasks.clone(); + on_runtime(&self.tasks, async move { + let (snapshot, cut) = match (request.kind, result) { + (ShareKindTag::Query, _) => (None, false), + (ShareKindTag::Result, None) => { + return Err(CoreError::failed( + "ffi.share_needs_result", + "a result share needs its result set", + )); + } + (ShareKindTag::Result, Some(set)) => { + let (built, cut) = tasks + .spawn_blocking_task(move || snapshot_of(&set, visible_columns, max_rows, total_rows, &columns)) + .await + .map_err(|failure| CoreError::failed("ffi.panicked", failure.to_string()))??; + (Some(built), cut) + } + }; + let created = account.create_share(share_request(request, snapshot)).await?; + let mut info = CreatedShareInfo::from(created); + info.columns_truncated |= cut; + Ok(info) + }) + .await + } + + // The account's own links, or with `team_id` a team's, newest first, without their SQL. + pub async fn list_shares( + &self, + live_only: bool, + team_id: Option, + cursor: Option, + ) -> Result { + let account = self.account.clone(); + on_runtime(&self.tasks, async move { + let page = account + .list_shares(live_only, team_id.as_deref(), cursor.as_deref()) + .await?; + Ok(page.into()) + }) + .await + } + + pub async fn revoke_share(&self, share_id: String) -> Result<(), CoreError> { + let account = self.account.clone(); + on_runtime(&self.tasks, async move { + account.revoke_share(&share_id).await.map_err(CoreError::from) + }) + .await + } + + // A new expiry from now; Free extends a link this way. + pub async fn extend_share(&self, share_id: String, expiry: ShareExpiryTag) -> Result { + let account = self.account.clone(); + on_runtime(&self.tasks, async move { + Ok(account.extend_share(&share_id, expiry.into()).await?.into()) + }) + .await + } + + // Public: it works signed out. `account.share_password_required` asks for the password, + // `account.share_password_wrong` for it again. + pub async fn fetch_shared( + &self, + token: String, + password: Option, + ) -> Result { + let account = self.account.clone(); + on_runtime(&self.tasks, async move { + Ok(account.fetch_shared(&token, password.as_ref()).await?.into()) + }) + .await + } +} + +// Also whether columns past the server's cap were left out. A removed column is never read; a masked one leaves +// masked, and the snapshot says how. +fn snapshot_of( + set: &ResultSet, + visible_columns: u32, + max_rows: u32, + total_rows: Option, + choices: &[ShareColumnChoice], +) -> Result<(Snapshot, bool), CoreError> { + // A set still reading would share the rows held so far as if they were all of them. + if !set.is_finished() { + return Err(CoreError::failed("ffi.share_unfinished", "the rows are still arriving")); + } + let (visible, plan) = share_plan(set, visible_columns, choices); + let ended = set.extent(); + let rows = (0..ended.held).map(|row| sent_row(set, &visible, &plan, row)); + // A count the app made of a table view outranks what the page's own read knew. + let extent = ResultExtent { + total: total_rows.or(ended.total), + ..ended + }; + let mut snapshot = build_snapshot( + &plan.columns(&visible), + rows, + extent, + usize::try_from(max_rows).unwrap_or(usize::MAX), + ) + .map_err(refused)?; + for (column, style) in snapshot.columns.iter_mut().zip(plan.masked()) { + column.masked = style; + } + Ok((snapshot, plan.columns_cut())) +} + +// How many rows a share of `max_rows` sends with `plan`: the prefix the snapshot keeps under the plan's rows and its +// body budget, masked values weighed, so detection and the preview read the same rows the snapshot sends. +pub(crate) fn rows_sent( + set: &ResultSet, + visible: &[ResultColumn], + plan: &SharePlan, + max_rows: u32, +) -> Result { + let summary = summary_of(set, visible, plan, max_rows); + match summary.refused { + Some(refusal) => Err(refused(refusal)), + None => Ok(summary.rows_sent as u64), + } +} + +pub(crate) fn summary_of(set: &ResultSet, visible: &[ResultColumn], plan: &SharePlan, max_rows: u32) -> ShareSummary { + plan.summary( + visible, + usize::try_from(set.extent().held).unwrap_or(usize::MAX), + |row, index| held_value(set, row as u64, index, &visible[index]), + usize::try_from(max_rows).unwrap_or(usize::MAX), + ) +} + +pub(crate) fn sent_row(set: &ResultSet, visible: &[ResultColumn], plan: &SharePlan, row: u64) -> Vec { + plan.row(visible, |index| held_value(set, row, index, &visible[index])) +} + +// A body too large is worded as the server's own refusal, which every app already words. +fn refused(refusal: SnapshotRefusal) -> CoreError { + let code = match refusal { + SnapshotRefusal::Cell { .. } | SnapshotRefusal::FirstRow => "account.snapshot_too_large", + SnapshotRefusal::NoColumns => "ffi.share_no_columns", + }; + CoreError::failed(code, refusal.to_string()) +} + +pub(crate) fn visible_columns_of(set: &ResultSet, visible_columns: u32) -> Vec { + let held = set.result_columns(); + let count = usize::try_from(visible_columns).unwrap_or(usize::MAX).min(held.len()); + held[..count].to_vec() +} + +// The set's first `visible_columns` columns and how a share sends them, by the sheet's choices. +pub(crate) fn share_plan( + set: &ResultSet, + visible_columns: u32, + choices: &[ShareColumnChoice], +) -> (Vec, SharePlan) { + let visible = visible_columns_of(set, visible_columns); + let choices: Vec = choices.iter().copied().map(ShareChoice::from).collect(); + let plan = SharePlan::new(visible.len(), &choices, MAX_SHARE_COLUMNS); + (visible, plan) +} + +fn share_request(request: ShareRequestArg, snapshot: Option) -> ShareRequest { + ShareRequest { + kind: match request.kind { + ShareKindTag::Query => ShareKind::Query, + ShareKindTag::Result => ShareKind::Result, + }, + sql: request.sql, + title: request.title, + note: request.note, + dialect: request.dialect, + expiry: request.expiry.map(ShareExpiry::from), + hide_sql: request.hide_sql, + allow_download: request.allow_download, + password: request.password, + team_id: request.team_id, + snapshot, + } +} + +impl From for ShareExpiry { + fn from(expiry: ShareExpiryTag) -> Self { + match expiry { + ShareExpiryTag::OneDay => Self::OneDay, + ShareExpiryTag::SevenDays => Self::SevenDays, + ShareExpiryTag::ThirtyDays => Self::ThirtyDays, + ShareExpiryTag::Never => Self::Never, + } + } +} + +impl From for ShareExpiryTag { + fn from(expiry: ShareExpiry) -> Self { + match expiry { + ShareExpiry::OneDay => Self::OneDay, + ShareExpiry::SevenDays => Self::SevenDays, + ShareExpiry::ThirtyDays => Self::ThirtyDays, + ShareExpiry::Never => Self::Never, + } + } +} + +impl From for ShareLimitsInfo { + fn from(limits: ShareLimits) -> Self { + Self { + plan: limits.plan, + live: limits.live, + live_limit: limits.live_limit, + max_rows: limits.max_rows, + max_columns: limits.max_columns, + expiries: limits.expiries.into_iter().map(ShareExpiryTag::from).collect(), + default_expiry: limits.default_expiry.map(ShareExpiryTag::from), + password: limits.password, + disable_download: limits.disable_download, + team: limits.team, + email_verified: limits.email_verified, + sharing_disabled: limits.sharing_disabled, + teams: limits.teams.into_iter().map(ShareTeamInfo::from).collect(), + } + } +} + +impl From for ShareTeamInfo { + fn from(team: ShareTeam) -> Self { + Self { + id: team.id, + name: team.name, + live: team.live, + live_limit: team.live_limit, + public_links: team.public_links, + } + } +} + +impl From for ShareInfo { + fn from(share: Share) -> Self { + Self { + id: share.id, + kind: share.kind, + scope: share.scope, + team_id: share.team_id, + title: share.title, + note: share.note, + dialect: share.dialect, + sql: share.sql, + has_snapshot: share.has_snapshot, + row_count: share.row_count, + truncated: share.truncated, + hide_sql: share.hide_sql, + allow_download: share.allow_download, + has_password: share.has_password, + state: share.state, + removed_reason: share.removed_reason, + suspended: share.suspended, + suspended_by: share.suspended_by, + view_count: share.view_count, + created_at_secs: seconds(share.created_at), + updated_at_secs: seconds(share.updated_at), + expires_at_secs: share.expires_at.map(seconds), + revoked_at_secs: share.revoked_at.map(seconds), + removed_at_secs: share.removed_at.map(seconds), + url: share.url, + } + } +} + +impl From for CreatedShareInfo { + fn from(created: CreatedShare) -> Self { + Self { + share: created.share.into(), + url: created.url, + columns_truncated: created.columns_truncated, + } + } +} + +impl From for SharePageInfo { + fn from(page: SharePage) -> Self { + Self { + shares: page.shares.into_iter().map(ShareInfo::from).collect(), + next_cursor: page.next_cursor, + } + } +} + +impl From for SharedLinkInfo { + fn from(shared: SharedLink) -> Self { + Self { + kind: shared.kind, + title: shared.title, + note: shared.note, + dialect: shared.dialect, + sql: shared.sql, + created_at_secs: seconds(shared.created_at), + expires_at_secs: shared.expires_at.map(seconds), + allow_download: shared.allow_download, + row_count: shared.row_count, + truncated: shared.truncated, + } + } +} + +fn seconds(at: DateTime) -> i64 { + at.timestamp() +} + +impl std::fmt::Debug for ShareRequestArg { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ShareRequestArg") + .field("kind", &self.kind) + .field("expiry", &self.expiry) + .field("hide_sql", &self.hide_sql) + .field("allow_download", &self.allow_download) + .field("has_password", &self.password.is_some()) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use tablepro_core::column::ColumnType; + use tablepro_core::masking::MaskingStyle; + use tablepro_core::{Truncation, Value}; + + use super::*; + use crate::masking::MaskStyleTag; + use crate::results::ResultStore; + + fn cut_set() -> ResultSet { + let columns: Arc<[ResultColumn]> = vec![ResultColumn::new("n", ColumnType::untyped_text("int"))].into(); + let store = Arc::new(ResultStore::new(columns)); + store.append(&[vec![Value::Int(1)], vec![Value::Int(2)]]); + store.finish_as(None, Truncation::ReadPastLimit); + ResultSet::new(0, store) + } + + #[test] + fn a_set_cut_with_no_count_shares_that_more_rows_exist() { + let (uncounted, _) = snapshot_of(&cut_set(), 1, 1_000, None, &[]).unwrap(); + let (counted, _) = snapshot_of(&cut_set(), 1, 1_000, Some(48_210), &[]).unwrap(); + + assert_eq!((uncounted.row_count, uncounted.more_rows), (None, true)); + assert_eq!(uncounted.rows.len(), 2); + assert_eq!((counted.row_count, counted.more_rows), (Some(48_210), false)); + } + + fn people() -> ResultSet { + let columns: Arc<[ResultColumn]> = ["id", "email", "phone", "notes"] + .iter() + .map(|name| ResultColumn::new(*name, ColumnType::untyped_text("text"))) + .collect::>() + .into(); + let store = Arc::new(ResultStore::new(columns)); + let text = |value: &str| Value::Text(value.to_owned()); + store.append(&[ + vec![text("1"), text("ann@example.com"), text("+1 555 0100"), text("vip")], + vec![text("2"), Value::Null, Value::Null, Value::Null], + ]); + store.finish(); + ResultSet::new(0, store) + } + + fn cells(snapshot: &Snapshot, row: usize) -> Vec<&str> { + snapshot.rows[row].iter().map(|cell| cell.get()).collect() + } + + #[test] + fn the_sheet_masks_and_removes_columns_and_the_snapshot_names_each_style() { + let mask = |style| ShareColumnChoice::Mask { style }; + let choices = [ + ShareColumnChoice::Remove, + mask(MaskStyleTag::Email), + mask(MaskStyleTag::LastFour), + mask(MaskStyleTag::Null), + ]; + + let (snapshot, cut) = snapshot_of(&people(), 4, 10, None, &choices).unwrap(); + + let names: Vec<&str> = snapshot.columns.iter().map(|column| column.name.as_str()).collect(); + assert_eq!(names, ["email", "phone", "notes"]); + assert_eq!(cells(&snapshot, 0), [r#""a•••@example.com""#, r#""••••0100""#, "null"]); + assert_eq!( + cells(&snapshot, 1), + ["null", "null", "null"], + "a NULL was masked into a value" + ); + let masked: Vec> = snapshot.columns.iter().map(|column| column.masked).collect(); + assert_eq!( + masked, + [ + Some(MaskingStyle::Email), + Some(MaskingStyle::LastFour), + Some(MaskingStyle::Null) + ] + ); + assert!(!cut); + } + + #[test] + fn a_kept_column_goes_as_held_and_names_no_style() { + let (snapshot, _) = snapshot_of(&people(), 2, 10, None, &[]).unwrap(); + + assert_eq!(cells(&snapshot, 0), [r#""1""#, r#""ann@example.com""#]); + assert!(snapshot.columns.iter().all(|column| column.masked.is_none())); + } + + fn notes(rows: usize, chars: usize) -> Arc { + let columns: Arc<[ResultColumn]> = vec![ResultColumn::new("note", ColumnType::untyped_text("text"))].into(); + let store = Arc::new(ResultStore::new(columns)); + let held: Vec> = (0..rows).map(|_| vec![Value::Text("x".repeat(chars))]).collect(); + store.append(&held); + store.finish(); + Arc::new(ResultSet::new(0, store)) + } + + #[test] + fn a_big_share_is_cut_at_the_budget_and_the_preview_keeps_the_same_rows() { + // 32 bytes of header, then 200,005 a row: 22 rows fit in 4,500,000. + let set = notes(30, 200_000); + let full = [ShareColumnChoice::Mask { + style: MaskStyleTag::Full, + }]; + + let (snapshot, _) = snapshot_of(&set, 1, 1_000, None, &[]).unwrap(); + let preview = crate::masking::share_preview(&set, 1, 1_000, &[]).unwrap(); + let (masked, _) = snapshot_of(&set, 1, 1_000, None, &full).unwrap(); + + let summary = crate::masking::share_summary(&set, 1, 1_000, &[]).unwrap(); + assert_eq!(snapshot.rows.len(), 22); + assert_eq!(summary.rows_sent, snapshot.rows.len() as u64); + assert_eq!( + (summary.columns_sent, summary.columns_truncated, summary.refused), + (1, false, None) + ); + assert_eq!(snapshot.row_count, Some(30), "the server would not mark the share cut"); + assert_eq!(preview.row_count(), 22); + assert_eq!(masked.rows.len(), 30, "masked text was not what was weighed"); + } + + #[test] + fn a_share_that_cannot_go_even_cut_is_refused_as_too_large() { + let over = snapshot_of(¬es(1, 300_000), 1, 1_000, None, &[]).err().unwrap(); + let preview = crate::masking::share_preview(¬es(1, 300_000), 1, 1_000, &[]) + .err() + .unwrap(); + + let summary = crate::masking::share_summary(¬es(1, 300_000), 1, 1_000, &[]).unwrap(); + assert_eq!(over.code(), "account.snapshot_too_large"); + assert_eq!(summary.rows_sent, 0); + assert_eq!( + summary.refused, + Some(crate::masking::ShareRefusal::Cell { + column: "note".to_owned() + }) + ); + assert_eq!(preview.code(), "account.snapshot_too_large"); + } + + #[test] + fn a_share_with_every_column_removed_is_refused_before_the_server_sees_it() { + let removed = [ShareColumnChoice::Remove; 4]; + + let refused = snapshot_of(&people(), 4, 10, None, &removed).err().unwrap(); + let summary = crate::masking::share_summary(&people(), 4, 10, &removed).unwrap(); + + assert_eq!(refused.code(), "ffi.share_no_columns"); + assert_eq!(summary.rows_sent, 0); + assert_eq!(summary.columns_sent, 0); + assert_eq!(summary.refused, Some(crate::masking::ShareRefusal::NoColumns)); + } +} diff --git a/core/crates/ffi/src/core_handle.rs b/core/crates/ffi/src/core_handle.rs index 3395c4acfe..0581165a1c 100644 --- a/core/crates/ffi/src/core_handle.rs +++ b/core/crates/ffi/src/core_handle.rs @@ -4,6 +4,7 @@ use std::sync::{Arc, Mutex}; use futures::future::BoxFuture; use secrecy::SecretString; +use tablepro_account::{AccountSettings, RefreshTokenVault}; use tablepro_core::credentials::{CredentialInteraction, CredentialPrompter, SecretItems, SecretKind, SecretVault}; use tablepro_core::{ ConnectEnvironment, Credentials, DatabaseDriver, DriverError, DriverRegistry, FileEndpoint, LivenessPolicy, @@ -40,6 +41,8 @@ pub struct Core { deadlines: Arc, vault: Arc, items: Arc, + // The TablePro account's, in the same store as every other secret. + refresh_tokens: RefreshTokens, paths: Option, store: Option, writes: LibraryWrites, @@ -66,15 +69,24 @@ impl Core { pub fn new(config: HostConfig, secrets: Box) -> Result, CoreError> { let tasks = runtime::tasks()?; let host = Arc::new(HostSecretStore::new(secrets, tasks.clone())); - Ok(Self::build(config, host.clone(), host, tasks)) + Ok(Self::build( + config, + SystemSecrets { + vault: host.clone(), + items: host.clone(), + // A host keeps one item for it, whichever server the sign-in is with. + refresh_tokens: Arc::new(move |_: &AccountSettings| host.clone() as Arc), + }, + tasks, + )) } // Secrets go to the platform's own store: Credential Manager on Windows. #[uniffi::constructor] pub fn with_system_secrets(config: HostConfig) -> Result, CoreError> { let tasks = runtime::tasks()?; - let (vault, items) = system_secrets(&tasks)?; - Ok(Self::build(config, vault, items, tasks)) + let secrets = system_secrets(&tasks)?; + Ok(Self::build(config, secrets, tasks)) } pub fn drivers(&self) -> Vec { @@ -291,7 +303,7 @@ impl Core { } impl Core { - fn build(config: HostConfig, vault: Arc, items: Arc, tasks: Tasks) -> Arc { + fn build(config: HostConfig, secrets: SystemSecrets, tasks: Tasks) -> Arc { let liveness = LivenessPolicy::DESKTOP; let deadlines = Arc::new(DefaultDeadlines::new(liveness)); let ssh = Arc::new(InProcessSsh::system()); @@ -309,8 +321,9 @@ impl Core { registry: Arc::new(drivers::registry()), connector: Arc::new(DriverConnector::new(services, deadlines.clone())), deadlines, - vault, - items, + vault: secrets.vault, + items: secrets.items, + refresh_tokens: secrets.refresh_tokens, paths, store, writes: LibraryWrites::default(), @@ -331,6 +344,10 @@ impl Core { pub fn secret_items(&self) -> Arc { self.items.clone() } + + pub(crate) fn refresh_tokens(&self) -> RefreshTokens { + self.refresh_tokens.clone() + } } impl std::fmt::Debug for Core { @@ -356,7 +373,14 @@ fn no_storage() -> CoreError { CoreError::failed("ffi.no_storage", "the core was started without a storage folder") } -type SystemSecrets = (Arc, Arc); +// Where one sign-in keeps its refresh token, chosen by its settings. +pub(crate) type RefreshTokens = Arc Arc + Send + Sync>; + +struct SystemSecrets { + vault: Arc, + items: Arc, + refresh_tokens: RefreshTokens, +} #[cfg(windows)] fn system_secrets(tasks: &Tasks) -> Result { @@ -364,7 +388,14 @@ fn system_secrets(tasks: &Tasks) -> Result { "TablePro", tasks.clone(), )); - Ok((manager.clone(), manager)) + Ok(SystemSecrets { + vault: manager.clone(), + items: manager.clone(), + refresh_tokens: Arc::new(move |settings: &AccountSettings| { + Arc::new(manager.refresh_token(&settings.sign_in_key(), settings.is_production())) + as Arc + }), + }) } #[cfg(not(windows))] @@ -564,6 +595,21 @@ mod tests { struct NoItems; + #[async_trait] + impl RefreshTokenVault for NoItems { + async fn load_refresh_token(&self) -> Result, SecretError> { + Ok(None) + } + + async fn store_refresh_token(&self, _: &SecretString) -> Result<(), SecretError> { + Ok(()) + } + + async fn delete_refresh_token(&self) -> Result<(), SecretError> { + Ok(()) + } + } + #[async_trait] impl SecretItems for NoItems { async fn load_item(&self, _: SecretItem) -> Result, SecretError> { @@ -587,8 +633,11 @@ mod tests { client_version: "test".to_owned(), storage_dir: Some(dir.path().display().to_string()), }, - Arc::new(Vault::default()), - Arc::new(NoItems), + SystemSecrets { + vault: Arc::new(Vault::default()), + items: Arc::new(NoItems), + refresh_tokens: Arc::new(|_: &AccountSettings| Arc::new(NoItems) as Arc), + }, runtime::tasks().unwrap(), ); let mut stored = blank(Uuid::new_v4()); diff --git a/core/crates/ffi/src/credential_manager.rs b/core/crates/ffi/src/credential_manager.rs index 001d5d5d32..a056040406 100644 --- a/core/crates/ffi/src/credential_manager.rs +++ b/core/crates/ffi/src/credential_manager.rs @@ -1,6 +1,9 @@ +use std::sync::Arc; + use async_trait::async_trait; use secrecy::zeroize::{Zeroize, Zeroizing}; use secrecy::{ExposeSecret, SecretString}; +use tablepro_account::RefreshTokenVault; use tablepro_core::AiProvider; use tablepro_core::credentials::{SecretError, SecretItem, SecretItems, SecretKind, SecretLookup, SecretVault}; use tablepro_session::runtime::Tasks; @@ -25,6 +28,11 @@ const COMMENT_UNITS: usize = CRED_MAX_STRING_LENGTH as usize - 1; // An attribute keyword of the form CREDENTIAL_ATTRIBUTEW asks for, _. const LAYOUT_KEYWORD: &str = "TablePro_Parts"; +// Before a sign-in had a key, every one shared this target, and only tablepro.app's ever wrote it. +const LEGACY_REFRESH_TOKEN_ITEM: &str = "account-refresh-token"; +// Credential Manager shows it as the credential's comment; Linux's keyring item has the same label. +const REFRESH_TOKEN_LABEL: &str = "TablePro account sign-in"; + // Generic credentials under one prefix, so Credential Manager lists TablePro's together and a test keeps to its own. pub(crate) struct CredentialManager { prefix: String, @@ -47,6 +55,16 @@ impl CredentialManager { format!("{}/{}", self.prefix, item_name(item)) } + // One sign-in's refresh token, by `AccountSettings::sign_in_key`, so another server or another build's state + // folder never reads or overwrites it. tablepro.app's first read moves a token the shared target holds. + pub(crate) fn refresh_token(self: &Arc, sign_in_key: &str, production: bool) -> SignInToken { + SignInToken { + manager: self.clone(), + target: format!("{}/account/{sign_in_key}/refresh-token", self.prefix), + legacy: production.then(|| format!("{}/{LEGACY_REFRESH_TOKEN_ITEM}", self.prefix)), + } + } + // One call at a time: concurrent writes from one process lost each other's changes on both CI runners. async fn blocking(&self, work: F) -> Result where @@ -107,13 +125,10 @@ fn failure(action: &str) -> SecretError { // The blob holds UTF-16, as cmdkey and the Credential Manager control panel write it. fn decode(blob: &[u8]) -> Result { - if blob.len() % 2 != 0 { + let (pairs, []) = blob.as_chunks::<2>() else { return Err(SecretError::InvalidEncoding); - } - let units: Vec = blob - .chunks_exact(2) - .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) - .collect(); + }; + let units: Vec = pairs.iter().map(|pair| u16::from_le_bytes(*pair)).collect(); let units = Zeroizing::new(units); // Sized exactly, so neither a push nor SecretString's shrink to fit leaves a copy in freed memory. let mut size = 0; @@ -325,6 +340,63 @@ impl SecretItems for CredentialManager { } } +pub(crate) struct SignInToken { + manager: Arc, + target: String, + legacy: Option, +} + +impl std::fmt::Debug for SignInToken { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SignInToken") + .field("target", &self.target) + .finish_non_exhaustive() + } +} + +#[async_trait] +impl RefreshTokenVault for SignInToken { + async fn load_refresh_token(&self) -> Result, SecretError> { + let (target, legacy) = (self.target.clone(), self.legacy.clone()); + self.manager + .blocking(move || { + if let Some(token) = read(&target)? { + return Ok(Some(token)); + } + let Some(legacy) = legacy else { + return Ok(None); + }; + let Some(token) = read(&legacy)? else { + return Ok(None); + }; + write(&target, token.expose_secret(), REFRESH_TOKEN_LABEL)?; + if let Err(error) = delete(&legacy) { + tracing::warn!(%error, "the moved refresh token stays at its old target too"); + } + Ok(Some(token)) + }) + .await + } + + async fn store_refresh_token(&self, token: &SecretString) -> Result<(), SecretError> { + let target = self.target.clone(); + let token = token.clone(); + self.manager + .blocking(move || write(&target, token.expose_secret(), REFRESH_TOKEN_LABEL)) + .await + } + + // The old target goes too, or the next start would move a signed-out token back. + async fn delete_refresh_token(&self) -> Result<(), SecretError> { + let targets: Vec = std::iter::once(self.target.clone()) + .chain(self.legacy.clone()) + .collect(); + self.manager + .blocking(move || targets.iter().try_for_each(|target| delete(target))) + .await + } +} + #[cfg(test)] mod tests { use super::*; @@ -496,6 +568,89 @@ mod tests { assert!(gone.is_none()); } + #[tokio::test] + async fn the_refresh_token_is_kept_apart_from_the_items_and_removed_whole() { + let manager = Arc::new(manager()); + let signed_in = manager.refresh_token("0123456789abcdef", false); + let token = format!("{}tail", "r".repeat(PART_SIZE)); + manager + .store_item(SecretItem::McpToken, &SecretString::from("mcp")) + .await + .unwrap(); + + signed_in + .store_refresh_token(&SecretString::from(token.clone())) + .await + .unwrap(); + let found = signed_in.load_refresh_token().await.unwrap(); + signed_in.delete_refresh_token().await.unwrap(); + let gone = signed_in.load_refresh_token().await.unwrap(); + let continued = Credentials.read(&format!("{}/1", signed_in.target)).unwrap(); + let kept = manager.load_item(SecretItem::McpToken).await.unwrap(); + manager.delete_item(SecretItem::McpToken).await.unwrap(); + + assert_eq!(found.map(|found| found.expose_secret().to_owned()), Some(token)); + assert!(gone.is_none()); + assert!(continued.is_none()); + assert_eq!(kept.map(|kept| kept.expose_secret().to_owned()), Some("mcp".to_owned())); + } + + #[tokio::test] + async fn each_sign_in_keeps_its_own_refresh_token() { + let manager = Arc::new(manager()); + let production = manager.refresh_token("aaaaaaaaaaaaaaaa", true); + let local = manager.refresh_token("bbbbbbbbbbbbbbbb", false); + + production + .store_refresh_token(&SecretString::from("prod")) + .await + .unwrap(); + local.store_refresh_token(&SecretString::from("local")).await.unwrap(); + let read_back = ( + production.load_refresh_token().await.unwrap(), + local.load_refresh_token().await.unwrap(), + ); + production.delete_refresh_token().await.unwrap(); + local.delete_refresh_token().await.unwrap(); + + assert_eq!( + ( + read_back.0.map(|token| token.expose_secret().to_owned()), + read_back.1.map(|token| token.expose_secret().to_owned()) + ), + (Some("prod".to_owned()), Some("local".to_owned())) + ); + } + + #[tokio::test] + async fn tablepro_app_s_first_read_moves_the_token_every_sign_in_once_shared() { + let manager = Arc::new(manager()); + let legacy = format!("{}/{LEGACY_REFRESH_TOKEN_ITEM}", manager.prefix); + write(&legacy, "kept from before", REFRESH_TOKEN_LABEL).unwrap(); + let local = manager.refresh_token("bbbbbbbbbbbbbbbb", false); + let production = manager.refresh_token("aaaaaaaaaaaaaaaa", true); + + let not_local = local.load_refresh_token().await.unwrap(); + let moved = production.load_refresh_token().await.unwrap(); + let left = read(&legacy).unwrap(); + let again = production.load_refresh_token().await.unwrap(); + write(&legacy, "stale", REFRESH_TOKEN_LABEL).unwrap(); + production.delete_refresh_token().await.unwrap(); + let after_sign_out = (production.load_refresh_token().await.unwrap(), read(&legacy).unwrap()); + + assert!(not_local.is_none()); + assert_eq!( + moved.map(|token| token.expose_secret().to_owned()), + Some("kept from before".to_owned()) + ); + assert!(left.is_none()); + assert_eq!( + again.map(|token| token.expose_secret().to_owned()), + Some("kept from before".to_owned()) + ); + assert!(after_sign_out.0.is_none() && after_sign_out.1.is_none()); + } + #[tokio::test] async fn writes_from_many_tasks_at_once_all_hold() { let managers: Vec = (0..16).map(|_| manager()).collect(); diff --git a/core/crates/ffi/src/error.rs b/core/crates/ffi/src/error.rs index ef326cf51d..04221c5410 100644 --- a/core/crates/ffi/src/error.rs +++ b/core/crates/ffi/src/error.rs @@ -1,6 +1,7 @@ use std::path::Path; use std::sync::Arc; +use tablepro_account::AccountError; use tablepro_core::{DriverError, ServerDiagnostics, SshFailure, TlsFailure, TransportError}; use tablepro_session::{ConnectError, OperationError}; @@ -318,6 +319,26 @@ impl From for CoreError { } } +// A cancelled sign-in is a cancel. A problem the account service answered keeps its own code in `server`. +impl From for CoreError { + fn from(error: AccountError) -> Self { + let server = match &error { + AccountError::SignInCanceled => return Self::Cancelled, + AccountError::Refused { code, detail, .. } => Some(ServerMessage { + code: Some(code.clone()), + ..named_only(detail) + }), + _ => None, + }; + Self::Failed { + info: Box::new(ErrorInfo { + server, + ..ErrorInfo::plain(&[error.code()], error.to_string()) + }), + } + } +} + #[cfg(test)] mod tests { use std::path::PathBuf; @@ -473,6 +494,27 @@ mod tests { assert!(info.path.is_none()); } + #[test] + fn an_account_error_keeps_its_code_and_a_refusal_the_server_s_own() { + let limited = info(AccountError::DeviceLimitReached { devices: Vec::new() }.into()); + let refused = info( + AccountError::Refused { + status: 409, + code: "offline_file_active".to_owned(), + detail: "The device holds an offline file".to_owned(), + } + .into(), + ); + + assert_eq!(limited.codes, ["account.device_limit_reached"]); + assert_eq!(limited.server, None); + assert_eq!(refused.code, "account.refused"); + let server = refused.server.expect("the server's problem"); + assert_eq!(server.code.as_deref(), Some("offline_file_active")); + assert_eq!(server.message, "The device holds an offline file"); + assert_eq!(CoreError::from(AccountError::SignInCanceled), CoreError::Cancelled); + } + #[test] fn every_kind_of_cancel_is_a_cancel() { assert_eq!(CoreError::from(DriverError::Cancelled), CoreError::Cancelled); diff --git a/core/crates/ffi/src/export.rs b/core/crates/ffi/src/export.rs index c07ad3ec92..248417bb42 100644 --- a/core/crates/ffi/src/export.rs +++ b/core/crates/ffi/src/export.rs @@ -6,8 +6,9 @@ use std::sync::{Arc, Mutex, PoisonError}; use async_trait::async_trait; use tablepro_core::browse::{DeclaredPrecisionSink, ExportFields, ExportRequest, SortKey, build_export}; -use tablepro_core::column::ResultColumn; +use tablepro_core::column::{ColumnKind, ColumnType, ResultColumn}; use tablepro_core::dialect::SqlDialect; +use tablepro_core::edit::parse_filter_text; use tablepro_core::export::{ CsvEncoder, CsvOptions, EncodeError, HtmlEncoder, JsonArrayEncoder, MarkdownEncoder, RenderError, RowEncoder, SqlInsertEncoder, XLSX_MAX_DATA_ROWS, XlsxSheetWriter, XmlEncoder, @@ -473,7 +474,7 @@ async fn feed( Ok(()) } -fn held_row(set: &ResultSet, row: u64, columns: &[ResultColumn]) -> Vec { +pub(crate) fn held_row(set: &ResultSet, row: u64, columns: &[ResultColumn]) -> Vec { columns .iter() .enumerate() @@ -482,7 +483,7 @@ fn held_row(set: &ResultSet, row: u64, columns: &[ResultColumn]) -> Vec { } // The value where the store kept it exactly, else read back from the text the core's export wrote for it on arrival. -fn held_value(set: &ResultSet, row: u64, index: usize, column: &ResultColumn) -> Value { +pub(crate) fn held_value(set: &ResultSet, row: u64, index: usize, column: &ResultColumn) -> Value { if let Some(value) = set.stored_value(row, index) { return value; } @@ -502,6 +503,7 @@ fn held_value(set: &ResultSet, row: u64, index: usize, column: &ResultColumn) -> Ok(json) => Value::Json(json), Err(_) => other(text), }, + Some(ValueKind::Array) => array_value(&text, &column.column_type).unwrap_or_else(|| other(text)), // Refused by every encoder, as a streamed export refuses it. Some(ValueKind::Undecodable) => Value::Undecodable(Box::new(UndecodedValue { type_name: column.column_type.name.clone(), @@ -511,6 +513,40 @@ fn held_value(set: &ResultSet, row: u64, index: usize, column: &ResultColumn) -> } } +// The store keeps an array as JSON whose items are each element's text (`value_text`), so each is read back by the +// element's kind: a number stays a number and a binary value its bytes, as a streamed read gives them. +fn array_value(text: &str, column: &ColumnType) -> Option { + items(&serde_json::from_str(text).ok()?, &element_of(column)) +} + +fn items(json: &serde_json::Value, element: &ColumnType) -> Option { + let serde_json::Value::Array(list) = json else { + return None; + }; + list.iter() + .map(|item| match item { + serde_json::Value::Null => Some(Value::Null), + serde_json::Value::String(text) => { + Some(parse_filter_text(text, element).unwrap_or_else(|_| Value::Text(text.clone()))) + } + // An inner dimension, which a declared kind such as PostgreSQL's int4[][] does not name again. + serde_json::Value::Array(_) => items(item, &element_of(element)), + _ => None, + }) + .collect::>>() + .map(Value::Array) +} + +fn element_of(column: &ColumnType) -> ColumnType { + match &column.kind { + ColumnKind::Array { element } => ColumnType { + kind: (**element).clone(), + ..column.clone() + }, + _ => column.clone(), + } +} + // The sink's own failure explains why the read stopped, so it goes before the read's. async fn settle( part: Arc, @@ -660,3 +696,80 @@ fn file_gone() -> CoreError { fn not_connected() -> CoreError { CoreError::failed("ffi.not_connected", "the session has no connection") } + +#[cfg(test)] +mod tests { + use tablepro_core::column::{IntegerKind, IntegerWidth, ReadForm, TextLength}; + use tablepro_core::export::{ResultExtent, build_snapshot}; + + use super::*; + use crate::results::ResultStore; + + fn array_of(name: &str, element: ColumnKind) -> ResultColumn { + ResultColumn::new( + name, + ColumnType { + name: format!("{name}[]"), + kind: ColumnKind::Array { + element: Box::new(element), + }, + catalog: None, + dynamic_storage: false, + read_form: ReadForm::Native, + }, + ) + } + + fn bigint() -> ColumnKind { + ColumnKind::Integer(IntegerKind { + width: IntegerWidth::W64, + signed: true, + }) + } + + #[test] + fn an_array_comes_back_element_by_element_as_a_streamed_read_gives_it() { + let columns: Arc<[ResultColumn]> = vec![ + array_of("ids", bigint()), + array_of( + "blobs", + ColumnKind::Bytes { + length: TextLength::Unbounded, + }, + ), + array_of("grid", bigint()), + ] + .into(); + let row = vec![ + Value::Array(vec![Value::Int(1), Value::Int(9_007_199_254_740_993), Value::Null]), + Value::Array(vec![Value::Bytes(vec![0xca, 0xfe])]), + Value::Array(vec![ + Value::Array(vec![Value::Int(1), Value::Int(2)]), + Value::Array(vec![Value::Int(3), Value::Int(4)]), + ]), + ]; + let store = Arc::new(ResultStore::new(columns.clone())); + store.append(std::slice::from_ref(&row)); + store.finish(); + let set = ResultSet::new(0, store); + + let held = held_row(&set, 0, &columns); + let snapshot = build_snapshot(&columns, [held.clone()], ResultExtent::complete(1), 10).expect("a snapshot"); + + assert_eq!(held, row); + let cells: Vec<&str> = snapshot.rows[0].iter().map(|cell| cell.get()).collect(); + assert_eq!( + cells, + ["[1,9007199254740993,null]", r#"["(binary, 2 bytes)"]"#, "[[1,2],[3,4]]"] + ); + } + + #[test] + fn an_array_whose_text_does_not_read_back_stays_its_text() { + let column = array_of("odd", bigint()); + + let value = array_value("{1,2,3}", &column.column_type); + + assert_eq!(value, None); + } +} diff --git a/core/crates/ffi/src/host.rs b/core/crates/ffi/src/host.rs index 6c319ff5c4..f7edab2e2e 100644 --- a/core/crates/ffi/src/host.rs +++ b/core/crates/ffi/src/host.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use async_trait::async_trait; use secrecy::SecretString; +use tablepro_account::RefreshTokenVault; use tablepro_core::AiProvider; use tablepro_core::credentials::{SecretError, SecretItem, SecretItems, SecretKind, SecretLookup, SecretVault}; use tablepro_session::runtime::Tasks; @@ -58,6 +59,8 @@ pub enum SecretItemTag { AnthropicKey, OpenAiKey, OpenAiCompatibleKey, + // The TablePro account's refresh token, which only the account asks for (core ADR 0016). + AccountRefreshToken, } #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)] @@ -192,6 +195,25 @@ impl SecretItems for HostSecretStore { } } +#[async_trait] +impl RefreshTokenVault for HostSecretStore { + async fn load_refresh_token(&self) -> Result, SecretError> { + self.call(|host| host.load_item(SecretItemTag::AccountRefreshToken)) + .await + } + + async fn store_refresh_token(&self, token: &SecretString) -> Result<(), SecretError> { + let token = token.clone(); + self.call(move |host| host.store_item(SecretItemTag::AccountRefreshToken, token)) + .await + } + + async fn delete_refresh_token(&self) -> Result<(), SecretError> { + self.call(|host| host.delete_item(SecretItemTag::AccountRefreshToken)) + .await + } +} + #[cfg(test)] mod tests { use std::collections::HashMap; @@ -304,6 +326,29 @@ mod tests { ); } + #[tokio::test] + async fn the_account_s_refresh_token_is_an_item_of_its_own() { + let store = store(MemorySecrets::default()); + let ai = SecretItem::AiKey(AiProvider::Anthropic); + store.store_item(ai, &SecretString::from("sk-test")).await.unwrap(); + + store.store_refresh_token(&SecretString::from("refresh")).await.unwrap(); + let found = store.load_refresh_token().await.unwrap(); + store.delete_refresh_token().await.unwrap(); + let gone = store.load_refresh_token().await.unwrap(); + let kept = store.load_item(ai).await.unwrap(); + + assert_eq!( + found.map(|token| token.expose_secret().to_owned()), + Some("refresh".to_owned()) + ); + assert!(gone.is_none()); + assert_eq!( + kept.map(|secret| secret.expose_secret().to_owned()), + Some("sk-test".to_owned()) + ); + } + #[tokio::test] async fn the_host_s_refusal_reaches_the_core_as_its_secret_error() { let store = store(MemorySecrets { diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index 5561e6d81c..f1a22133b6 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -1,5 +1,6 @@ // Foreign code is called only from a runtime thread, never under a lock (core/ARCHITECTURE.md, Bindings). +mod account; mod cancel_token; mod catalog; mod cloud; @@ -19,6 +20,7 @@ mod history; mod host; mod host_key; mod library; +mod masking; mod prompter; mod results; mod row_edits; @@ -31,6 +33,13 @@ mod structure; mod syntax; pub mod window_abi; +pub use account::{ + AccountConfig, AccountListener, AccountService, AccountStateTag, AccountStatusInfo, CreatedShareInfo, DeviceInfo, + EntitlementProblemTag, FeatureAccessTag, HostBrowser, HostBrowserError, LicenseInfo, MembershipInfo, ProfileInfo, + SecretHitInfo, SecretHitKindTag, ShareExpiryTag, ShareInfo, ShareKindTag, ShareLimitsInfo, SharePageInfo, + ShareRequestArg, ShareTeamInfo, SharedLinkInfo, TeamInfo, scan_columns_for_secrets, scan_sql_for_secrets, + share_token_from_link, +}; pub use cancel_token::CancelToken; pub use catalog::{ColumnEntry, ObjectEntry, ObjectKindTag, ObjectScopeArg, SchemaEntry, TableName}; pub use cloud::{CloudConnectionFields, CloudGroupFields, CloudLibraryPull, CloudLibraryRecords}; @@ -52,6 +61,10 @@ pub use library::{ ConnectionLibrary, ConnectionRecord, ConnectionSecrets, GroupRecord, ImportSummary, LibrarySnapshot, SafeModeTag, SshAuthTag, SshSettings, TagRecord, TlsModeTag, TlsSettings, }; +pub use masking::{ + MaskReason, MaskStyleTag, MaskSuggestionInfo, PersonalDataHitInfo, SensitiveKindTag, ShareColumnChoice, + ShareColumnMasking, ShareRefusal, ShareSummary, +}; pub use prompter::{HostPrompter, PromptAnswer, PromptFieldInfo, PromptPurposeTag, PromptReasonTag, PromptRequest}; pub use results::{ResultColumnInfo, ResultSet, ValueKind}; pub use row_edits::{ diff --git a/core/crates/ffi/src/masking.rs b/core/crates/ffi/src/masking.rs new file mode 100644 index 0000000000..db9895708d --- /dev/null +++ b/core/crates/ffi/src/masking.rs @@ -0,0 +1,454 @@ +// Masking a shared result for the Windows app: the share sheet's column choices, what the detectors suggest, the +// preview as sent and its summary. The engine is `tablepro_core::masking` (core ADR 0028). + +use std::sync::Arc; + +use tablepro_account::MAX_SHARE_COLUMNS; +use tablepro_core::Truncation; +use tablepro_core::column::ResultColumn; +use tablepro_core::export::SnapshotRefusal; +use tablepro_core::masking::detect::{ + MaskSuggestion, PersonalDataHit, SensitiveKind, SuggestionReason, scan_sql_personal_data, +}; +use tablepro_core::masking::{MaskingStyle, ShareChoice, share_suggestions}; + +use crate::account::share::{rows_sent, sent_row, share_plan, summary_of, visible_columns_of}; +use crate::error::CoreError; +use crate::export::held_row; +use crate::results::{ResultSet, ResultStore}; +use crate::runtime::on_runtime; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum MaskStyleTag { + Full, + LastFour, + Email, + Hash, + Null, +} + +// What the share sheet does with one shared column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum ShareColumnChoice { + Keep, + Mask { style: MaskStyleTag }, + Remove, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum SensitiveKindTag { + Card, + Iban, + Jwt, + ApiKey, + Email, + Phone, + Ip, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum MaskReason { + // The term as its words join, such as "apikey" for `stripe_api_key`. + ColumnName { term: String }, + Values { kind: SensitiveKindTag }, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct MaskSuggestionInfo { + pub style: MaskStyleTag, + pub reason: MaskReason, +} + +// One shared column as the sheet starts it: with a suggestion, Mask in that style by default, which the user may Keep. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ShareColumnMasking { + pub name: String, + pub suggestion: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Record)] +pub struct PersonalDataHitInfo { + pub kind: SensitiveKindTag, + // Where the literal starts, from 1. + pub line: u32, +} + +// Why a share cannot go even cut. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum ShareRefusal { + // A value of this column is over 256 KiB. + Cell { column: String }, + // The first row alone is over the 4.5 MB a share's body may weigh. + FirstRow, + // The sheet removed every column. + NoColumns, +} + +// What a share with the sheet's choices sends, for its note: `rows_sent` is what the snapshot keeps under the plan's +// row limit and the body budget, so it can be fewer than `max_rows`. +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] +pub struct ShareSummary { + pub rows_sent: u64, + pub columns_sent: u32, + pub columns_truncated: bool, + pub refused: Option, +} + +// Personal data in the SQL's single-quoted literals, each kind once per line: the sheet suggests Hide SQL. +#[uniffi::export] +pub fn scan_sql_for_personal_data(sql: String) -> Vec { + scan_sql_personal_data(&sql) + .into_iter() + .map(PersonalDataHitInfo::from) + .collect() +} + +#[uniffi::export] +impl ResultSet { + // The share sheet's columns as it starts them, from the set's first `visible_columns` columns and its first + // `max_rows` rows (`tablepro_core::masking::share_suggestions`). + pub async fn share_masking( + self: Arc, + visible_columns: u32, + max_rows: u32, + ) -> Result, CoreError> { + off_the_caller(move || Ok(share_masking(&self, visible_columns, max_rows))).await + } + + // The rows a share of `max_rows` with the sheet's `columns` would send, as a finished set: removed columns left out + // and every value masked as the snapshot masks it. The sheet previews from it, since a Stable Hash is the core's to + // compute. + pub async fn share_preview( + self: Arc, + visible_columns: u32, + max_rows: u32, + columns: Vec, + ) -> Result, CoreError> { + off_the_caller(move || share_preview(&self, visible_columns, max_rows, &columns)).await + } + + // What `create_share` with the same arguments would send, by the same plan and budget: cheap enough for each change + // of the sheet's choices, run off the UI thread. + pub async fn share_summary( + self: Arc, + visible_columns: u32, + max_rows: u32, + columns: Vec, + ) -> Result { + off_the_caller(move || share_summary(&self, visible_columns, max_rows, &columns)).await + } +} + +async fn off_the_caller(work: F) -> Result +where + T: Send + 'static, + F: FnOnce() -> Result + Send + 'static, +{ + let tasks = crate::runtime::tasks()?; + let blocking = tasks.clone(); + on_runtime(&tasks, async move { + blocking + .spawn_blocking_task(work) + .await + .map_err(|failure| CoreError::failed("ffi.panicked", failure.to_string()))? + }) + .await +} + +fn share_masking(set: &ResultSet, visible_columns: u32, max_rows: u32) -> Vec { + let columns = visible_columns_of(set, visible_columns); + let held = (0..set.extent().held).map(|row| held_row(set, row, &columns)); + share_suggestions( + &columns, + held, + usize::try_from(max_rows).unwrap_or(usize::MAX), + MAX_SHARE_COLUMNS, + ) + .into_iter() + .zip(&columns) + .map(|(suggestion, column)| ShareColumnMasking { + name: column.name.clone(), + suggestion: suggestion.map(MaskSuggestionInfo::from), + }) + .collect() +} + +pub(crate) fn share_preview( + set: &ResultSet, + visible_columns: u32, + max_rows: u32, + choices: &[ShareColumnChoice], +) -> Result, CoreError> { + if !set.is_finished() { + return Err(CoreError::failed("ffi.share_unfinished", "the rows are still arriving")); + } + let (visible, plan) = share_plan(set, visible_columns, choices); + let ended = set.extent(); + let taken = rows_sent(set, &visible, &plan, max_rows)?; + let rows: Vec> = (0..taken).map(|row| sent_row(set, &visible, &plan, row)).collect(); + let columns: Arc<[ResultColumn]> = plan.columns(&visible).into(); + let store = ResultStore::new(columns); + store.append(&rows); + let truncation = match taken < ended.held || ended.cut { + true => Truncation::ReadPastLimit, + false => Truncation::Complete, + }; + store.finish_as(ended.total, truncation); + Ok(Arc::new(ResultSet::new(0, Arc::new(store)))) +} + +pub(crate) fn share_summary( + set: &ResultSet, + visible_columns: u32, + max_rows: u32, + choices: &[ShareColumnChoice], +) -> Result { + if !set.is_finished() { + return Err(CoreError::failed("ffi.share_unfinished", "the rows are still arriving")); + } + let (visible, plan) = share_plan(set, visible_columns, choices); + let summary = summary_of(set, &visible, &plan, max_rows); + Ok(ShareSummary { + rows_sent: summary.rows_sent as u64, + columns_sent: u32::try_from(summary.columns_sent).unwrap_or(u32::MAX), + columns_truncated: summary.columns_cut, + refused: summary.refused.map(ShareRefusal::from), + }) +} + +impl From for ShareRefusal { + fn from(refused: SnapshotRefusal) -> Self { + match refused { + SnapshotRefusal::Cell { column } => Self::Cell { column }, + SnapshotRefusal::FirstRow => Self::FirstRow, + SnapshotRefusal::NoColumns => Self::NoColumns, + } + } +} + +impl From for MaskStyleTag { + fn from(style: MaskingStyle) -> Self { + match style { + MaskingStyle::Full => Self::Full, + MaskingStyle::LastFour => Self::LastFour, + MaskingStyle::Email => Self::Email, + MaskingStyle::Hash => Self::Hash, + MaskingStyle::Null => Self::Null, + } + } +} + +impl From for MaskingStyle { + fn from(tag: MaskStyleTag) -> Self { + match tag { + MaskStyleTag::Full => Self::Full, + MaskStyleTag::LastFour => Self::LastFour, + MaskStyleTag::Email => Self::Email, + MaskStyleTag::Hash => Self::Hash, + MaskStyleTag::Null => Self::Null, + } + } +} + +impl From for ShareChoice { + fn from(choice: ShareColumnChoice) -> Self { + match choice { + ShareColumnChoice::Keep => Self::Keep, + ShareColumnChoice::Mask { style } => Self::Mask(style.into()), + ShareColumnChoice::Remove => Self::Remove, + } + } +} + +impl From for SensitiveKindTag { + fn from(kind: SensitiveKind) -> Self { + match kind { + SensitiveKind::Card => Self::Card, + SensitiveKind::Iban => Self::Iban, + SensitiveKind::Jwt => Self::Jwt, + SensitiveKind::ApiKey => Self::ApiKey, + SensitiveKind::Email => Self::Email, + SensitiveKind::Phone => Self::Phone, + SensitiveKind::Ip => Self::Ip, + } + } +} + +impl From for MaskSuggestionInfo { + fn from(suggestion: MaskSuggestion) -> Self { + Self { + style: suggestion.style.into(), + reason: match suggestion.reason { + SuggestionReason::ColumnName { term } => MaskReason::ColumnName { term: term.to_owned() }, + SuggestionReason::Values { kind } => MaskReason::Values { kind: kind.into() }, + }, + } + } +} + +impl From for PersonalDataHitInfo { + fn from(hit: PersonalDataHit) -> Self { + Self { + kind: hit.kind.into(), + line: hit.line, + } + } +} + +#[cfg(test)] +mod tests { + use tablepro_core::column::ColumnType; + use tablepro_core::masking::stable_hash; + + use super::*; + + fn text(value: &str) -> tablepro_core::Value { + tablepro_core::Value::Text(value.to_owned()) + } + + fn set(names: &[&str], rows: &[Vec]) -> ResultSet { + let columns: Arc<[ResultColumn]> = names + .iter() + .map(|name| ResultColumn::new(*name, ColumnType::untyped_text("text"))) + .collect::>() + .into(); + let store = Arc::new(ResultStore::new(columns)); + store.append(rows); + store.finish(); + ResultSet::new(0, store) + } + + #[test] + fn personal_data_in_the_sql_crosses_with_its_kind_and_line() { + let hits = scan_sql_for_personal_data("SELECT 1;\nWHERE email = 'ann@example.com'".to_owned()); + + assert_eq!( + hits, + [PersonalDataHitInfo { + kind: SensitiveKindTag::Email, + line: 2 + }] + ); + } + + #[test] + fn the_sheet_starts_from_what_the_detectors_see() { + let people = set( + &["id", "phone", "note"], + &[vec![text("1"), text("x"), text("4111 1111 1111 1111")]], + ); + + let started = share_masking(&people, 3, 1_000); + + assert_eq!(started[0].suggestion, None); + assert_eq!( + started[1].suggestion, + Some(MaskSuggestionInfo { + style: MaskStyleTag::LastFour, + reason: MaskReason::ColumnName { + term: "phone".to_owned() + }, + }) + ); + assert_eq!( + started[2].suggestion, + Some(MaskSuggestionInfo { + style: MaskStyleTag::LastFour, + reason: MaskReason::Values { + kind: SensitiveKindTag::Card + }, + }) + ); + } + + #[test] + fn detection_reads_only_the_rows_a_share_sends() { + let contacts = set( + &["contact"], + &[ + vec![text("ann@example.com")], + vec![text("x")], + vec![text("y")], + vec![text("z")], + ], + ); + + let sent_one = share_masking(&contacts, 1, 1); + let sent_all = share_masking(&contacts, 1, 4); + + assert_eq!( + sent_one[0].suggestion.as_ref().map(|found| found.style), + Some(MaskStyleTag::Email) + ); + assert_eq!(sent_all[0].suggestion, None, "rows past the share counted"); + } + + #[test] + fn a_first_row_too_large_to_send_still_has_its_values_read() { + let notes = set( + &["blob", "notes"], + &[ + vec![text(&"x".repeat(300 * 1_024)), text("ann@example.com")], + vec![text("small"), text("bob@example.com")], + ], + ); + + let started = share_masking(¬es, 2, 1_000); + + assert_eq!( + started[1].suggestion.as_ref().map(|found| found.style), + Some(MaskStyleTag::Email) + ); + } + + #[test] + fn values_in_rows_that_go_only_once_a_wide_column_is_removed_are_read() { + // 22 rows fit the budget with the blob kept; the e-mails are in the 8 after them. + let rows: Vec> = (0..30) + .map(|row| { + let notes = match row < 22 { + true => tablepro_core::Value::Null, + false => text(&format!("person{row}@example.com")), + }; + vec![text(&"x".repeat(200_000)), notes] + }) + .collect(); + + let started = share_masking(&set(&["blob", "notes"], &rows), 2, 1_000); + + assert_eq!( + started[1].suggestion.as_ref().map(|found| found.style), + Some(MaskStyleTag::Email) + ); + } + + #[test] + fn the_preview_shows_what_the_snapshot_sends() { + let people = set( + &["id", "email", "phone", "note"], + &[ + vec![text("1"), text("ann@example.com"), text("+1 555 0100"), text("vip")], + vec![text("2"), text("bob@example.com"), text("+1 555 0199"), text("new")], + ], + ); + let choices = [ + ShareColumnChoice::Remove, + ShareColumnChoice::Mask { + style: MaskStyleTag::Email, + }, + ShareColumnChoice::Mask { + style: MaskStyleTag::Hash, + }, + ]; + + let preview = share_preview(&people, 4, 1, &choices).unwrap(); + + let names: Vec = preview.columns().into_iter().map(|column| column.name).collect(); + assert_eq!(names, ["email", "phone", "note"]); + assert_eq!(preview.row_count(), 1); + assert!(preview.is_finished()); + assert_eq!(preview.cell_text(0, 0).unwrap().as_deref(), Some("a•••@example.com")); + assert_eq!(preview.cell_text(0, 1).unwrap(), Some(stable_hash(b"+1 555 0100"))); + assert_eq!(preview.cell_text(0, 2).unwrap().as_deref(), Some("vip")); + } +} diff --git a/core/crates/ffi/src/results/result_set.rs b/core/crates/ffi/src/results/result_set.rs index 6b00c83580..203a24f0da 100644 --- a/core/crates/ffi/src/results/result_set.rs +++ b/core/crates/ffi/src/results/result_set.rs @@ -32,6 +32,10 @@ impl ResultSet { self.store.columns() } + pub(crate) fn extent(&self) -> tablepro_core::export::ResultExtent { + self.store.extent() + } + pub(crate) fn stored_value(&self, row: u64, column: usize) -> Option { self.store.stored_value(self.stored_row(row), column) } diff --git a/core/crates/ffi/src/results/store.rs b/core/crates/ffi/src/results/store.rs index 740977e727..cc89924481 100644 --- a/core/crates/ffi/src/results/store.rs +++ b/core/crates/ffi/src/results/store.rs @@ -1,8 +1,9 @@ use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard}; -use tablepro_core::Value; use tablepro_core::column::ResultColumn; +use tablepro_core::export::ResultExtent; use tablepro_core::value::order::{row_order, sorts_as_text}; +use tablepro_core::{Truncation, Value}; use super::column_cells::{Cell, ColumnCells, cell_value, stored_value}; use super::{ValueKind, cell_text}; @@ -23,6 +24,9 @@ pub(super) struct StoreState { pub(super) chunks: Vec, pub(super) rows: u64, pub(super) finished: bool, + // As the set's end reported them: every row when counted, and whether rows may follow those held. + pub(super) total: Option, + pub(super) cut: bool, } #[derive(Debug)] @@ -41,6 +45,8 @@ impl ResultStore { chunks: Vec::new(), rows: 0, finished: false, + total: None, + cut: false, }), } } @@ -118,15 +124,43 @@ impl ResultStore { state.rows } - // A set the last chunk holds would otherwise keep the slack its arrays grew by. + #[cfg(test)] pub(crate) fn finish(&self) { + self.finish_as(None, Truncation::Complete); + } + + // A set the last chunk holds would otherwise keep the slack its arrays grew by. + pub(crate) fn finish_as(&self, total_rows: Option, truncation: Truncation) { let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner); state.finished = true; + state.total = total_rows; + state.cut = truncation != Truncation::Complete; if let Some(chunk) = state.chunks.last_mut() { chunk.columns.iter_mut().for_each(ColumnCells::shrink); } } + // The run ended, as a cancel or an error ends it, before the set said it was finished: rows may follow. + pub(crate) fn finish_with_run(&self) { + let mut state = self.state.write().unwrap_or_else(PoisonError::into_inner); + if !state.finished { + state.finished = true; + state.cut = true; + } + if let Some(chunk) = state.chunks.last_mut() { + chunk.columns.iter_mut().for_each(ColumnCells::shrink); + } + } + + pub(crate) fn extent(&self) -> ResultExtent { + let state = self.read(); + ResultExtent { + held: state.rows, + total: state.total, + cut: state.cut, + } + } + // `Some(None)` for null, and every byte of a binary value as hex. pub(crate) fn full_text(&self, row: u64, column: usize) -> Option> { let state = self.read(); diff --git a/core/crates/ffi/src/run/run_sink.rs b/core/crates/ffi/src/run/run_sink.rs index 1fb41da928..15ea1ba8fc 100644 --- a/core/crates/ffi/src/run/run_sink.rs +++ b/core/crates/ffi/src/run/run_sink.rs @@ -71,7 +71,7 @@ impl ResultSink for RunSink { } => { let (set_index, row_count) = match self.current.take() { Some((set_index, store)) => { - store.finish(); + store.finish_as(total_rows, truncation); (set_index, store.row_count()) } None => (u32::MAX, 0), @@ -104,7 +104,7 @@ mod tests { use tablepro_core::{ServerNotice, Truncation, Value}; use super::*; - use crate::run::{RunListener, TruncationTag}; + use crate::run::{RunListener, RunOutcome, TransactionStateTag, TruncationTag}; struct Quiet; @@ -150,6 +150,38 @@ mod tests { ); } + #[tokio::test] + async fn a_set_keeps_how_it_ended_and_one_a_run_ended_first_is_cut() { + let columns: Arc<[ResultColumn]> = vec![ResultColumn::new("n", ColumnType::untyped_text(""))].into(); + let ended = Arc::new(RunState::new(Box::new(Quiet))); + let mut sink = RunSink::new(ended.clone(), ByteLimit::EDITOR_DEFAULT); + sink.accept(ResultEvent::ResultSetStarted { + columns: columns.clone(), + }) + .await; + sink.accept(ResultEvent::Rows(vec![vec![Value::Int(1)]])).await; + sink.accept(ResultEvent::ResultSetFinished { + retained: 1, + total_rows: None, + truncation: Truncation::ReadPastLimit, + }) + .await; + let cancelled = Arc::new(RunState::new(Box::new(Quiet))); + let mut sink = RunSink::new(cancelled.clone(), ByteLimit::EDITOR_DEFAULT); + sink.accept(ResultEvent::ResultSetStarted { columns }).await; + sink.accept(ResultEvent::Rows(vec![vec![Value::Int(1)]])).await; + + cancelled.finish(RunOutcome::Completed { elapsed_ms: 0 }, TransactionStateTag::Idle); + + let cut = tablepro_core::export::ResultExtent { + held: 1, + total: None, + cut: true, + }; + assert_eq!(ended.set(0).unwrap().extent(), cut); + assert_eq!(cancelled.set(0).unwrap().extent(), cut); + } + #[tokio::test] async fn the_notice_limit_reaches_the_app_after_the_notices_kept() { let state = Arc::new(RunState::new(Box::new(Quiet))); diff --git a/core/crates/ffi/src/run/run_state.rs b/core/crates/ffi/src/run/run_state.rs index 1ce87835a1..23307a592c 100644 --- a/core/crates/ffi/src/run/run_state.rs +++ b/core/crates/ffi/src/run/run_state.rs @@ -122,7 +122,7 @@ impl RunState { Slot::Released(store) => store.upgrade(), }) .collect(); - sets.iter().for_each(|store| store.finish()); + sets.iter().for_each(|store| store.finish_with_run()); self.enqueue(RunEvent::Finished { outcome: outcome.clone(), transaction, diff --git a/core/crates/ffi/src/session.rs b/core/crates/ffi/src/session.rs index 153d2a5313..5362a5eec0 100644 --- a/core/crates/ffi/src/session.rs +++ b/core/crates/ffi/src/session.rs @@ -1,7 +1,10 @@ use std::sync::Arc; use std::time::Instant; -use tablepro_core::browse::{PageRequest, PagingMode, SortKey, build_count, build_page, paging_mode, read_page}; +use tablepro_core::browse::{ + ExportFields, ExportRequest, PageRequest, PagingMode, SortKey, build_count, build_page, build_view_sql, + paging_mode, read_page, +}; use tablepro_core::filter::FilterSet; use tablepro_core::meta::{ObjectInfo, ObjectScope, PagePosition, RowCountEstimate, RowIdentity, TableRef}; use tablepro_core::sql_syntax::{SortReference, sort_reference, with_order_by}; @@ -36,6 +39,7 @@ pub struct TablePageRead { run: Arc, visible_columns: u32, can_seek: bool, + view_sql: Option, } #[uniffi::export] @@ -51,6 +55,12 @@ impl TablePageRead { pub fn can_seek(&self) -> bool { self.can_seek } + + // The query the table view stands for: every row its filter and sort select, with no row window and the + // filter's values written in, for a share link or the editor. None when the engine cannot write it that way. + pub fn view_sql(&self) -> Option { + self.view_sql.clone() + } } impl std::fmt::Debug for TablePageRead { @@ -558,6 +568,7 @@ struct PagePlan { limit: u64, visible_columns: u32, can_seek: bool, + view_sql: Option, } async fn plan_page( @@ -607,9 +618,21 @@ async fn plan_page( }, ) .map_err(OperationError::from)?; + let view = ExportRequest { + table: &table, + columns: &columns, + filter: &filter, + sort: &sort, + identity: &identity, + fields: ExportFields::Listed, + }; + let view_sql = build_view_sql(&*dialect, &view) + .inspect_err(|error| tracing::debug!(%error, "the table view has no SQL of its own")) + .ok(); Ok(PagePlan { visible_columns: u32::try_from(spec.visible_columns()).unwrap_or(u32::MAX), can_seek, + view_sql, table, columns, identity, @@ -624,6 +647,7 @@ fn start_page(session: Arc, tasks: &Tasks, plan: PagePlan, listener: Bo let state = Arc::new(RunState::new(listener)); let visible_columns = plan.visible_columns; let can_seek = plan.can_seek; + let view_sql = plan.view_sql.clone(); let run = state.clone(); drop(tasks.spawn_task(async move { let started = Instant::now(); @@ -644,6 +668,7 @@ fn start_page(session: Arc, tasks: &Tasks, plan: PagePlan, listener: Bo run: Arc::new(QueryRun::new(state, tasks.clone())), visible_columns, can_seek, + view_sql, } } diff --git a/core/crates/ffi/tests/account.rs b/core/crates/ffi/tests/account.rs new file mode 100644 index 0000000000..92d64b2847 --- /dev/null +++ b/core/crates/ffi/tests/account.rs @@ -0,0 +1,557 @@ +#![expect( + clippy::unwrap_used, + reason = "the setup helpers fail a test the way the test functions themselves do" +)] + +use std::collections::HashMap; +use std::io::{BufRead as _, Read as _, Write as _}; +use std::net::{TcpListener, TcpStream}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use chrono::{TimeDelta, Utc}; +use secrecy::{ExposeSecret as _, SecretString}; +use tablepro_account::{MachineId, fakes}; +use tablepro_ffi::{ + AccountConfig, AccountListener, AccountService, AccountStateTag, CancelToken, Core, CoreError, FeatureAccessTag, + HostBrowser, HostBrowserError, HostConfig, HostSecretError, HostSecrets, SecretItemTag, SecretKindTag, +}; + +const GUID: &str = "d3b07384-d113-4ec6-a2f1-6a3f0c2e9b7a"; +const TOKEN: &str = "Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK"; +const DEVICE: &str = "dev_01k8d6wpggfd68tbhz818p4ww4"; +const TOKENS: &str = + r#"{"access_token":"stub-access","token_type":"Bearer","expires_in":900,"refresh_token":"stub-refresh"}"#; + +type Items = Arc>>; + +#[derive(Default)] +struct MemorySecrets(Items); + +impl HostSecrets for MemorySecrets { + fn load(&self, _: String, _: SecretKindTag) -> Result, HostSecretError> { + Ok(None) + } + + fn store(&self, _: String, _: SecretKindTag, _: SecretString, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn relabel(&self, _: String, _: SecretKindTag, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn delete(&self, _: String, _: SecretKindTag) -> Result<(), HostSecretError> { + Ok(()) + } + + fn delete_connection(&self, _: String) -> Result<(), HostSecretError> { + Ok(()) + } + + fn load_item(&self, item: SecretItemTag) -> Result, HostSecretError> { + Ok(self.0.lock().unwrap().get(&item).cloned()) + } + + fn store_item(&self, item: SecretItemTag, secret: SecretString) -> Result<(), HostSecretError> { + self.0.lock().unwrap().insert(item, secret); + Ok(()) + } + + fn delete_item(&self, item: SecretItemTag) -> Result<(), HostSecretError> { + self.0.lock().unwrap().remove(&item); + Ok(()) + } +} + +#[derive(Default)] +struct Counting(Arc); + +impl AccountListener for Counting { + fn status_changed(&self) { + self.0.fetch_add(1, Ordering::SeqCst); + } +} + +// Keeps the sign-in page's URL for the test to answer. +#[derive(Default)] +struct Browser(Arc>>); + +impl HostBrowser for Browser { + fn open_url(&self, url: String) -> Result<(), HostBrowserError> { + *self.0.lock().unwrap() = Some(url); + Ok(()) + } +} + +struct Opened { + service: Arc, + items: Items, + changes: Arc, + browser: Arc>>, + _dir: tempfile::TempDir, +} + +async fn open(base: &str) -> Opened { + let dir = tempfile::tempdir().unwrap(); + let items = Items::default(); + let core = Core::new( + HostConfig { + client_version: "test".to_owned(), + storage_dir: None, + }, + Box::new(MemorySecrets(items.clone())), + ) + .unwrap(); + let changes = Arc::new(AtomicUsize::new(0)); + let browser = Arc::new(Mutex::new(None)); + let config = AccountConfig { + account_url: Some(base.to_owned()), + api_url: Some(format!("{base}/v2")), + entitlement_keys: vec![fakes::PUBLIC_X.to_owned()], + device_name: "Lab".to_owned(), + app_version: "1.0.0".to_owned(), + os_version: "Windows 11".to_owned(), + account_file: dir.path().join("account.json").display().to_string(), + callback_finished: "Done".to_owned(), + callback_unknown: "Unknown".to_owned(), + machine_guid: Some(GUID.to_owned()), + }; + let service = core + .open_account( + config, + Box::new(Browser(browser.clone())), + Box::new(Counting(changes.clone())), + ) + .await + .unwrap(); + Opened { + service, + items, + changes, + browser, + _dir: dir, + } +} + +// Nothing listens once the listener is dropped, so every request is refused. +fn unreachable() -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + format!("http://{}", listener.local_addr().unwrap()) +} + +// Stands in for tablepro-cloud: `answer` gives the status and body for a method, path and request body. +fn cloud(answer: impl Fn(&str, &str, &str) -> (u16, String) + Send + 'static) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + serve(stream, &answer); + } + }); + base +} + +fn serve(stream: TcpStream, answer: &dyn Fn(&str, &str, &str) -> (u16, String)) { + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + let mut words = line.split_whitespace(); + let (method, path) = (words.next().unwrap_or_default(), words.next().unwrap_or_default()); + let mut length = 0; + loop { + let mut header = String::new(); + reader.read_line(&mut header).unwrap(); + if header.trim().is_empty() { + break; + } + if let Some(value) = header.to_ascii_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap(); + } + } + let mut body = vec![0; length]; + reader.read_exact(&mut body).unwrap(); + let (status, body) = answer(method, path, &String::from_utf8_lossy(&body)); + let mut stream = stream; + write!( + stream, + "HTTP/1.1 {status} Stub\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ) + .unwrap(); +} + +async fn eventually(what: &str, done: impl Fn() -> bool) { + for _ in 0..500 { + if done() { + return; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(done(), "{what} did not happen"); +} + +// What the browser does once the user approves: the redirect to the app's loopback listener. +async fn approve(browser: &Arc>>) { + eventually("the sign-in page opening", || browser.lock().unwrap().is_some()).await; + let opened = browser.lock().unwrap().clone().unwrap(); + let url = tablepro_account::Url::parse(&opened).unwrap(); + let asked = |name: &str| { + url.query_pairs() + .find(|(key, _)| key == name) + .map(|(_, value)| value.into_owned()) + .unwrap() + }; + let mut redirect = tablepro_account::Url::parse(&asked("redirect_uri")).unwrap(); + redirect + .query_pairs_mut() + .append_pair("code", "stub-code") + .append_pair("state", &asked("state")); + let address = format!("{}:{}", redirect.host_str().unwrap(), redirect.port().unwrap()); + let target = format!("{}?{}", redirect.path(), redirect.query().unwrap()); + // Blocking is fine here: the listener answers on the core's own runtime. + let mut stream = TcpStream::connect(address).unwrap(); + write!( + stream, + "GET {target} HTTP/1.1\r\nhost: 127.0.0.1\r\nconnection: close\r\n\r\n" + ) + .unwrap(); + let mut answer = String::new(); + let _ = stream.read_to_string(&mut answer); +} + +fn entitlement_answer() -> String { + let mut claims = fakes::claims(Utc::now(), TimeDelta::days(14), &["shared_links"]); + claims.mid = MachineId::derive_machine_guid(GUID).unwrap().as_str().to_owned(); + claims.dev = DEVICE.to_owned(); + format!( + r#"{{"token":"{}","expires_at":"2026-12-01T00:00:00Z","refresh_after":"2026-11-20T00:00:00Z"}}"#, + fakes::sign(&claims).unwrap() + ) +} + +fn device_answer() -> String { + format!( + r#"{{"id":"{DEVICE}","machine_id":"{}","platform":"windows","name":"Lab","app_version":"1.0.0","os_version":"Windows 11","created_at":"2026-11-13T00:00:00Z","last_seen_at":"2026-11-13T00:00:00Z"}}"#, + MachineId::derive_machine_guid(GUID).unwrap().as_str() + ) +} + +fn refresh_token(items: &Items) -> Option { + items + .lock() + .unwrap() + .get(&SecretItemTag::AccountRefreshToken) + .map(|token| token.expose_secret().to_owned()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_new_machine_starts_signed_out_and_the_app_is_told() { + let opened = open(&unreachable()).await; + + eventually("the first status change", || opened.changes.load(Ordering::SeqCst) > 0).await; + let profile = opened.service.profile().await; + + assert_eq!(opened.service.status().state, AccountStateTag::SignedOut); + assert_eq!( + opened.service.feature_access("shared_links".to_owned()), + FeatureAccessTag::SignedOut + ); + assert_eq!(profile.unwrap_err().code(), "account.signed_out"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_sign_in_through_the_browser_registers_the_device_and_unlocks_its_features() { + let requests = Arc::new(Mutex::new(Vec::new())); + let base = cloud({ + let requests = requests.clone(); + let device = device_answer(); + let entitlement = entitlement_answer(); + move |method, path, _| { + requests.lock().unwrap().push(format!("{method} {path}")); + match (method, path) { + ("POST", "/oauth/token") => (200, TOKENS.to_owned()), + ("POST", "/oauth/revoke") => (200, String::new()), + ("POST", "/v2/devices") => (201, device.clone()), + ("POST", p) if p == format!("/v2/devices/{DEVICE}/entitlement") => (200, entitlement.clone()), + _ => (404, String::new()), + } + } + }); + let opened = open(&base).await; + + let (signed_in, ()) = tokio::join!(opened.service.sign_in(None), approve(&opened.browser)); + signed_in.unwrap(); + let status = opened.service.status(); + let kept = refresh_token(&opened.items); + opened.service.sign_out().await.unwrap(); + + assert_eq!(status.state, AccountStateTag::SignedIn); + assert_eq!(status.features, ["shared_links"]); + assert!(status.remembered); + assert_eq!(kept.as_deref(), Some("stub-refresh")); + assert_eq!(opened.service.status().state, AccountStateTag::SignedOut); + assert_eq!(refresh_token(&opened.items), None); + let requests = requests.lock().unwrap().clone(); + assert!(requests.contains(&"POST /v2/devices".to_owned()), "{requests:?}"); + assert!(requests.contains(&"POST /oauth/revoke".to_owned()), "{requests:?}"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_cancel_ends_the_wait_for_the_browser() { + let opened = open(&unreachable()).await; + let cancel = CancelToken::new(); + let cancelling = async { + eventually("the sign-in page opening", || opened.browser.lock().unwrap().is_some()).await; + cancel.cancel(); + }; + + let (ended, ()) = tokio::join!(opened.service.sign_in(Some(cancel.clone())), cancelling); + + assert_eq!(ended, Err(CoreError::Cancelled)); + assert_eq!(opened.service.status().state, AccountStateTag::SignedOut); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_shared_link_opens_signed_out_and_the_owner_s_calls_do_not() { + let path = format!("/v2/shared/{TOKEN}"); + let base = cloud(move |method, requested, _| match (method, requested) { + ("GET", p) if p == path => ( + 200, + r#"{"kind":"query","title":"Orders","note":"","dialect":"postgres","sql":"SELECT 1", + "created_at":"2026-11-13T00:00:00Z","allow_download":true,"made_with":"TablePro"}"# + .to_owned(), + ), + _ => (404, String::new()), + }); + let opened = open(&base).await; + + let shared = opened.service.fetch_shared(TOKEN.to_owned(), None).await.unwrap(); + let limits = opened.service.share_limits().await; + let malformed = opened.service.fetch_shared("short".to_owned(), None).await; + + assert_eq!(shared.sql.as_deref(), Some("SELECT 1")); + assert_eq!((shared.row_count, shared.expires_at_secs), (None, None)); + assert_eq!(limits.unwrap_err().code(), "account.signed_out"); + assert_eq!(malformed.unwrap_err().code(), "account.not_found"); +} + +#[cfg(feature = "engines")] +mod shares { + use std::path::Path; + + use tablepro_ffi::{ + DatabaseSession, FileOpenRequest, ResultSet, RunListener, RunOutcome, RunSettings, ShareKindTag, + ShareRequestArg, TableName, + }; + + use super::*; + + struct Quiet; + + impl RunListener for Quiet { + fn events_pending(&self) {} + } + + async fn run(session: &DatabaseSession, sql: &str) -> Option> { + let editor = session.open_editor(None).await.unwrap(); + let run = editor.run(sql.to_owned(), RunSettings::default(), Box::new(Quiet)); + let outcome = run.outcome().await.unwrap(); + assert!(matches!(outcome, RunOutcome::Completed { .. }), "{outcome:?}"); + let set = run.result_set(0); + editor.close().await.unwrap(); + set + } + + // Signed in against a stub cloud that keeps every create's body. + async fn signed_in(bodies: &Arc>>) -> Opened { + let base = cloud({ + let bodies = bodies.clone(); + let device = device_answer(); + let entitlement = entitlement_answer(); + let created = created(); + move |method, path, body| match (method, path) { + ("POST", "/oauth/token") => (200, TOKENS.to_owned()), + ("POST", "/v2/devices") => (201, device.clone()), + ("POST", p) if p == format!("/v2/devices/{DEVICE}/entitlement") => (200, entitlement.clone()), + ("POST", "/v2/shares") => { + bodies.lock().unwrap().push(body.to_owned()); + (201, created.clone()) + } + _ => (404, String::new()), + } + }); + let opened = open(&base).await; + let (signed_in, ()) = tokio::join!(opened.service.sign_in(None), approve(&opened.browser)); + signed_in.unwrap(); + opened + } + + async fn sqlite(dir: &Path) -> (Arc, Arc) { + let core = Core::new( + HostConfig { + client_version: "test".to_owned(), + storage_dir: None, + }, + Box::new(MemorySecrets::default()), + ) + .unwrap(); + let file = FileOpenRequest { + path: dir.join("shop.sqlite").display().to_string(), + driver_id: None, + read_only: false, + create: true, + }; + let session = core.open_file(file, None).await.unwrap(); + (core, session) + } + + fn created() -> String { + format!( + r#"{{"share":{{"id":"shr_01","kind":"result","scope":"account","title":"Orders","note":"","dialect":"sqlite", + "has_snapshot":true,"row_count":2,"truncated":true,"hide_sql":true,"allow_download":true,"has_password":false, + "state":"live","suspended":false,"view_count":0,"created_at":"2026-11-13T00:00:00Z","updated_at":"2026-11-13T00:00:00Z", + "expires_at":"2026-12-13T00:00:00Z","url":"https://s.tablepro.app/{TOKEN}"}}, + "token":"{TOKEN}","url":"https://s.tablepro.app/{TOKEN}"}}"# + ) + } + + fn request(kind: ShareKindTag) -> ShareRequestArg { + ShareRequestArg { + kind, + sql: "SELECT * FROM orders".to_owned(), + title: Some("Orders".to_owned()), + note: None, + dialect: Some("sqlite".to_owned()), + expiry: None, + hide_sql: kind == ShareKindTag::Result, + allow_download: None, + password: None, + team_id: None, + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_result_share_sends_the_visible_columns_and_the_plan_s_rows() { + let bodies = Arc::new(Mutex::new(Vec::new())); + let opened = signed_in(&bodies).await; + let dir = tempfile::tempdir().unwrap(); + let (_core, session) = sqlite(dir.path()).await; + let set = run( + &session, + "SELECT 9007199254740993 AS big, 'a' AS name, x'cafe' AS hidden UNION ALL SELECT 2, 'b', NULL", + ) + .await + .unwrap(); + + let shared = opened + .service + .create_share(request(ShareKindTag::Result), Some(set), 2, 1, None, Vec::new()) + .await + .unwrap(); + let team_query = ShareRequestArg { + team_id: Some("team_01".to_owned()), + ..request(ShareKindTag::Query) + }; + let query = opened + .service + .create_share(team_query, None, 0, 0, None, Vec::new()) + .await + .unwrap(); + let needs_set = opened + .service + .create_share(request(ShareKindTag::Result), None, 0, 1_000, None, Vec::new()) + .await; + + assert_eq!(shared.url, format!("https://s.tablepro.app/{TOKEN}")); + assert_eq!(shared.share.row_count, Some(2)); + assert_eq!(shared.share.expires_at_secs, Some(1_797_120_000)); + assert_eq!(query.share.id, "shr_01"); + assert_eq!(needs_set.unwrap_err().code(), "ffi.share_needs_result"); + let bodies = bodies.lock().unwrap(); + assert!( + bodies[0].contains(r#""rows":[[9007199254740993,"a"]]"#), + "{}", + bodies[0] + ); + assert!(bodies[0].contains(r#""row_count":2"#), "{}", bodies[0]); + assert!(!bodies[0].contains("hidden"), "{}", bodies[0]); + assert!(bodies[0].contains(r#""hide_sql":true"#), "{}", bodies[0]); + assert!(!bodies[1].contains("snapshot"), "{}", bodies[1]); + assert!(bodies[1].contains(r#""team_id":"team_01""#), "{}", bodies[1]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_table_page_shares_its_view_sql_its_visible_columns_and_the_view_s_count() { + let bodies = Arc::new(Mutex::new(Vec::new())); + let opened = signed_in(&bodies).await; + let dir = tempfile::tempdir().unwrap(); + let (_core, session) = sqlite(dir.path()).await; + run( + &session, + "CREATE TABLE notes (body TEXT); INSERT INTO notes VALUES ('first'), ('second'), ('third')", + ) + .await; + let notes = TableName { + schema: None, + name: "notes".to_owned(), + }; + let page = session + .read_table_page(notes.clone(), None, None, 2, 0, Box::new(Quiet), None) + .await + .unwrap(); + let outcome = page.run().outcome().await.unwrap(); + let total = session.table_row_count(notes, None, None).await.unwrap(); + let set = page.run().result_set(0).unwrap(); + + let shared = ShareRequestArg { + sql: page.view_sql().unwrap(), + ..request(ShareKindTag::Result) + }; + opened + .service + .create_share( + shared, + Some(set), + page.visible_columns(), + 1_000, + Some(total), + Vec::new(), + ) + .await + .unwrap(); + + assert!(matches!(outcome, RunOutcome::Completed { .. }), "{outcome:?}"); + assert_eq!(page.visible_columns(), 1, "the page also reads each row's rowid"); + let body = bodies.lock().unwrap()[0].clone(); + assert!( + body.contains(r#""sql":"SELECT \"body\" FROM \"notes\" ORDER BY \"rowid\" ASC""#), + "{body}" + ); + assert!(body.contains(r#""columns":[{"name":"body","type":"TEXT"}]"#), "{body}"); + assert!(body.contains(r#""rows":[["first"],["second"]]"#), "{body}"); + assert!(body.contains(r#""row_count":3"#), "{body}"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_result_past_the_column_cap_shares_its_first_columns_and_says_so() { + let bodies = Arc::new(Mutex::new(Vec::new())); + let opened = signed_in(&bodies).await; + let dir = tempfile::tempdir().unwrap(); + let (_core, session) = sqlite(dir.path()).await; + let wide: Vec = (0..101).map(|index| format!("{index} AS c{index}")).collect(); + let set = run(&session, &format!("SELECT {}", wide.join(", "))).await.unwrap(); + + let created = opened + .service + .create_share(request(ShareKindTag::Result), Some(set), 101, 1_000, None, Vec::new()) + .await + .unwrap(); + + assert!(created.columns_truncated); + let body = bodies.lock().unwrap()[0].clone(); + assert!(body.contains(r#""name":"c99""#), "{body}"); + assert!(!body.contains(r#""c100""#), "{body}"); + } +} diff --git a/core/crates/ffi/tests/browse.rs b/core/crates/ffi/tests/browse.rs index a4b4064d32..1e60a1f88a 100644 --- a/core/crates/ffi/tests/browse.rs +++ b/core/crates/ffi/tests/browse.rs @@ -159,6 +159,39 @@ fn texts(values: &[&str]) -> Vec> { values.iter().map(|value| Some((*value).to_owned())).collect() } +#[tokio::test] +async fn a_page_s_view_sql_selects_every_page_with_its_filter_written_in() { + let dir = tempfile::tempdir().unwrap(); + let (_core, session) = fixture(dir.path(), PEOPLE).await; + let filter = all(vec![ + rule("age", FilterOpTag::Gt, Some("40")), + rule("name", FilterOpTag::Contains, Some("a")), + ]); + let by_name = Some(ColumnSort { + column: 1, + ascending: false, + }); + + let page = read(&session, by_name, filter, 1, 1).await.unwrap(); + let names = column(&page, 1).await; + let sql = page.view_sql().unwrap(); + let editor = session.open_editor(None).await.unwrap(); + let run = editor.run(sql.clone(), RunSettings::default(), Box::new(Quiet)); + let outcome = run.outcome().await.unwrap(); + let set = run.result_set(0).unwrap(); + let every: Vec> = (0..set.row_count()).map(|row| set.cell_text(row, 1).unwrap()).collect(); + editor.close().await.unwrap(); + session.close().await.unwrap(); + + assert_eq!(names, texts(&["Barbara"])); + assert_eq!( + sql, + r#"SELECT "id", "name", "age" FROM "people" WHERE "age" > 40 AND "name" LIKE '%a%' ESCAPE '!' ORDER BY "people"."name" DESC, "people"."id" ASC"# + ); + assert!(matches!(outcome, RunOutcome::Completed { .. }), "{outcome:?}"); + assert_eq!(every, texts(&["Grace", "Barbara"])); +} + #[tokio::test] async fn a_filtered_page_reads_only_the_matching_rows_and_counts_them() { let dir = tempfile::tempdir().unwrap(); diff --git a/core/docs/decisions/0016-tablepro-accounts.md b/core/docs/decisions/0016-tablepro-accounts.md index f0e5927546..0ac5ea6f68 100644 --- a/core/docs/decisions/0016-tablepro-accounts.md +++ b/core/docs/decisions/0016-tablepro-accounts.md @@ -1,6 +1,6 @@ # 0016: TablePro accounts live in the core, with features gated by the entitlement -- **Status**: Accepted +- **Status**: Accepted; the Windows app amended by [0026](0026-the-windows-app-signs-in-through-the-ffi.md), share links amended by [0027](0027-share-links.md) - **Date**: 2026-11-05 ## Context diff --git a/core/docs/decisions/0026-the-windows-app-signs-in-through-the-ffi.md b/core/docs/decisions/0026-the-windows-app-signs-in-through-the-ffi.md new file mode 100644 index 0000000000..ec88eddc88 --- /dev/null +++ b/core/docs/decisions/0026-the-windows-app-signs-in-through-the-ffi.md @@ -0,0 +1,37 @@ +# 0026: The Windows app signs in to its TablePro account through the FFI + +- **Status**: Accepted +- **Date**: 2026-11-13 + +## Context + +[0016](0016-tablepro-accounts.md) put the account in `tablepro-account` and left the Windows app to adopt it through `ffi` once tablepro-cloud registered a Windows client. On 2026-11-13 the maintainer decided that Windows gets account sign-in in the share-links round, since a share link needs a signed-in account. tablepro-cloud registers the public client `tablepro-windows`, with a loopback redirect on any port as `tablepro-linux` has, and the device platform `windows` (its `docs/design/clients.md`, Windows). + +## Decision + +`ffi` builds the account from `tablepro-account` and passes in what Windows does its own way: + +| Seam | Windows app | +| --- | --- | +| `RefreshTokenVault` | the Core's own secret store: under `Core::with_system_secrets`, the generic credential `TablePro/account//refresh-token` in Credential Manager, `` being `AccountSettings::sign_in_key`; under `Core::new`, the host's one `SecretItemTag::AccountRefreshToken` | +| `BrowserLauncher` | the `HostBrowser` callback, on a thread the core lets block | +| `MachineId` | `MachineId::derive_machine_guid` of `HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid`, read from the 64-bit registry view with `RegGetValueW` | +| `AppClient` | `AppClient::WINDOWS`: client `tablepro-windows`, platform `windows` | +| `AccountSettings::account_file` | the path the app gives in `AccountConfig` | + +- **Machine ID.** HMAC-SHA256 keyed with `app.tablepro.TablePro` over the 16 bytes the GUID's 32 hex digits write, in the order they are written, as 64 lowercase hex characters: Linux's rule for `/etc/machine-id`, so the same 16 bytes name the same device on both. The written order, not the mixed-endian layout of a Windows `GUID` struct, since the value is text in the registry and nothing reads it as a struct. A host off Windows gives the GUID in `AccountConfig::machine_guid`. +- **The object.** `Core::open_account(config, browser, listener)` returns an `AccountService`, which restores the last sign-in and runs the refresh schedule until it is dropped. Its calls are the account's: sign-in with a `CancelToken` that ends only the wait for the browser, sign-out, refresh, the refresh past the device limit, profile, devices, remove device, and `feature_access`. +- **Status.** `status()` is a snapshot record: the state, the entitlement's account, features and licenses, its expiry and the problem with its code or the devices that hold the license. `AccountListener::status_changed` only signals, on a runtime thread, as `RunListener` does; the app reads `status()` on its own thread. +- **One token per sign-in.** `sign_in_key` is 16 hex characters of SHA-256 over the API endpoint and the account file's path. A development build against a local stack, or a second build with its own state folder, would otherwise overwrite the one token every sign-in shares, and a rotated token read by the other is a reuse that revokes the whole family. A sign-in with tablepro.app whose own target is empty moves a token from `TablePro/account-refresh-token`, the target before keys, so a user signed in then stays signed in; a sign-out removes both. +- **Errors.** `From for CoreError` keeps `AccountError::code()`. A cancelled sign-in is `CoreError::Cancelled`. A refusal keeps the server's problem code and detail in `ErrorInfo::server`. + +## Consequences + +- `SecretItemTag` gains `AccountRefreshToken`, which only the account asks for; `tablepro_core::credentials::SecretItem` does not, so the Linux keyring keeps its own item ([0016](0016-tablepro-accounts.md), Alternatives). +- The C# bindings change with the new objects, records and callbacks, and the Windows app words every `account.*` code. +- The Mac keeps its own Swift account service; its client's redirect is a custom scheme this crate does not listen on. + +## Alternatives considered + +- **The app reads MachineGuid in C# and passes the text in, as Linux reads `/etc/machine-id`.** The registry view and the parsing are then the app's to get right, and the GUID would cross the FFI on every start. The core already holds the Windows calls for Credential Manager. +- **A separate `HostTokenVault` callback for the refresh token.** The Core already owns the secret store each host chose; one more callback would let the token land in a different store from every other secret. diff --git a/core/docs/decisions/0027-share-links.md b/core/docs/decisions/0027-share-links.md new file mode 100644 index 0000000000..379e020a5b --- /dev/null +++ b/core/docs/decisions/0027-share-links.md @@ -0,0 +1,30 @@ +# 0027: Share links go through the account, with the snapshot and the secret scan in the core + +- **Status**: Accepted; masked columns and the secret scan's definition amended by [0028](0028-data-masking.md) +- **Date**: 2026-11-13 + +## Context + +On 2026-11-13 the maintainer decided that every app shares a query or a result as a public link on tablepro-cloud, from a signed-in account with a verified email: Free with 5 live links, 1,000 rows and an expiry of 1, 7 or 30 days, Pro with 1,000 links, 10,000 rows, no expiry, a password, viewer downloads off and team links. A link opens in a browser viewer, and its deep link `tablepro://share?token=` opens its SQL in the app. The macOS, Linux and Windows apps show the same sheet, so what they share and how they read the answers must not drift. tablepro-cloud's `docs/design/api.md` is the contract. + +## Decision + +- **Calls.** `tablepro-account` adds `share_limits`, `create_share`, `list_shares`, `revoke_share`, `extend_share` and `fetch_shared` to `Account`, through the generated `/v2` client. The owner calls take the session, the bearer and the 429 hold every other call takes. A create, rate limited apart on the server, holds only further creates. It holds the session only to take its token, and has five minutes of its own (`Bearer::lasting`) for a body of up to 8 MiB on a slow link; the client's 30 seconds stay for every other call. A sign-in or sign-out during the upload owns the session afterwards, so the answer does not touch it. `fetch_shared` is public: the same HTTP client, no bearer, no session, and the password in `X-Share-Password`. `share_limits` lists the teams the account holds a seat in, each with its own live count and limit, and `list_shares` takes a team for a team's links. +- **Problem codes.** A refusal stays `AccountError::Refused` with the server's code, and `code()` names the ones an app words: `account.email_unverified`, `account.pro_required`, `account.sharing_disabled`, `account.team_sharing_disabled`, `account.seat_required`, `account.not_found`, `account.share_limit_reached`, `account.share_revoked`, `account.share_removed`, `account.validation_failed`, `account.snapshot_too_large`, `account.share_password_required` and `account.share_password_wrong`. A 413, whose body is the framework's, reads as `snapshot_too_large`. No new variant, so a match on the variants keeps compiling. +- **Snapshot.** `tablepro_core::export::build_snapshot` writes each cell by the JSON export's lossless rules: integers and decimals as the digits the server sent, a JSON column as its document, arrays element by element, timestamps in ISO form, an unreadable value as null; bytes as `"(binary, N bytes)"`. Each cell is a raw JSON token, since the workspace's `serde_json::Value` would round big numbers and reorder a document's keys. It takes at most the plan's `max_rows` and keeps the result's true row count; the server derives `truncated` itself. A result cut with no count (a row or byte limit, a table page nobody counted, a run that ended first) sends no `row_count` and `more_rows: true`, from a `ResultExtent` of its finish, so a viewer shows the first rows of a larger result rather than reading them as all of it. The server takes 100 columns and names of 256 characters, so a result shares its first 100 columns (`MAX_SHARE_COLUMNS`, which `ShareLimits` also carries) and `CreatedShare::columns_truncated` says so; a name or type is cut to 256. +- **Secret scan.** `tablepro_core::secret_scan` finds AWS access keys, private key PEM headers, JWTs, GitHub, Slack, Stripe and Google keys, URLs with credentials and a quoted literal assigned to a password, secret, token or API key, each kind once per line; and columns named for passwords, secrets, tokens, API keys, social security or card numbers. It warns; it never blocks a share. +- **Deep link.** `share_token_from_link` takes only `tablepro://share?token=` with one token of 43 base62 characters, the format the server mints. The app opens the SQL in a new tab, never runs it and carries no connection. +- **FFI.** `AccountService` gives the calls to the Windows app. `create_share` builds the snapshot from a finished `ResultSet` in Rust, from its visible columns, so no row crosses the FFI to come back. The result store keeps an array as the JSON of its elements' text, so each element is read back by the element's kind, and Windows sends the same cells as Linux, which holds the values. +- **A table tab's query.** A table page has no SQL the user wrote, so `TablePageRead::view_sql` gives the query its view stands for: `browse::build_view_sql`, the export's statement with no row window, each filter value written as the dialect's literal (`StatementBuilder::inlining`; a shell literal on MongoDB). The page's own statement would carry bound parameters, the hidden row-address columns and one page's window. `create_share` takes the view's count from `table_row_count` as `total_rows`, since the set holds one page. + +## Consequences + +- Linux and Windows build the same snapshot and scan the same way. The Mac shares through its own Swift service until its account moves onto the core ([0010](0010-macos-on-the-core.md)). +- `openapi/v2.openapi-3.0.json` carries the share endpoints; `linux/build-aux/update-cloud-api.sh` copies it in as before. +- A pattern added to the secret scan changes the warnings in Linux and Windows together, and the Mac's list follows by hand. + +## Alternatives considered + +- **New `AccountError` variants for the share problems.** Every exhaustive match in the apps would break for codes they word as strings anyway. +- **A snapshot of `serde_json::Value` with serde_json's `arbitrary_precision` and `preserve_order`.** Both features change `Value` for every crate in the workspace. +- **The app sends its grid's text.** Text loses which cells are numbers, so a viewer could not align them or export them as numbers. diff --git a/core/docs/decisions/0028-data-masking.md b/core/docs/decisions/0028-data-masking.md new file mode 100644 index 0000000000..4ddd62de58 --- /dev/null +++ b/core/docs/decisions/0028-data-masking.md @@ -0,0 +1,27 @@ +# 0028: A shared result masks its columns before it leaves the machine, with the macOS app's output + +- **Status**: Accepted +- **Date**: 2026-11-14 + +## Context + +A share link ([0027](0027-share-links.md)) sends a result's rows to tablepro-cloud for anyone with the link to read. On 2026-11-13 the maintainer decided that the share sheet hides sensitive values before they leave the machine: each shared column can be kept, masked in a style or removed, and columns that look sensitive start masked. The macOS app masks values in five styles (Full, Last 4 Characters, Email, Stable Hash, NULL); a link from any app must read the same. On 2026-11-14 the maintainer limited masking in the Linux and Windows apps to sharing: no per-connection rules, and no masking of the grid, exports, MCP or the assistant. + +## Decision + +- **Styles.** `tablepro_core::masking::mask_value` gives the macOS app's output byte for byte, from the text `export::value_text` writes at the column's declared precision: four U+2022 bullets; Last 4 Characters and Email by extended grapheme cluster, Email on the last `@`; Stable Hash as the first 6 bytes of HMAC-SHA256 under a key drawn once per process and never stored; NULL stays NULL under every style; bytes hash raw and otherwise show bullets. +- **The plan.** `masking::SharePlan` takes the sheet's Keep, Mask(style) or Remove for each visible column. A removed column is never read, a masked one is masked as it is sent, and the snapshot names each masked column's style (`SnapshotColumn::masked`, the share link's `columns[].masked`). `create_share`, `ResultSet::share_preview` and `ResultSet::share_summary` all go through it, so the sheet shows and counts what is sent. +- **The body budget.** As on macOS, `build_snapshot` weighs each masked cell as the macOS app does and stops before the row that would take the body past 4,500,000 bytes, keeping the row count so the server marks the share cut. A cell over 256 KiB, or a first row past the budget, refuses the share (`SnapshotRefusal::Cell` and `FirstRow`, worded as `account.snapshot_too_large`), and so does a plan that removes every column (`SnapshotRefusal::NoColumns`, `ffi.share_no_columns`), which the server would refuse. `snapshot_row_count` gives the preview and the summary that same prefix. +- **Detectors.** `masking::detect` suggests a style per column from its name (whole words), from the values of a text-like column (card with Luhn, IBAN with mod-97, JWT, API keys, email, phone, IP), and finds personal data in the SQL's single-quoted literals, comments skipped, to suggest Hide SQL. The lists, thresholds and edge cases are PLAN-MASKING 8.3 and 8.3.1; `detect/fixtures.rs` pins them and the macOS app mirrors the same table. `masking::share_suggestions` reads the values in two windows of the held rows and flags a column either window flags: the first `max_rows` rows whatever they weigh, so a row that goes only once a wide column is masked or removed is read, and the rows a share keeping every column sends, none when it is refused. Each window keeps its thresholds, and the first kind in table order wins. `secret_scan` follows the same definition: no lookaround or possessive runs, CR, LF and CRLF line breaks, the name splitting the detectors use. + +## Consequences + +- A suggestion is only a starting point: the user may keep a detected column, and nothing masks a column the user keeps. +- The macOS app keeps its per-connection masking rules, which also apply to its Share Result; the Linux and Windows apps have none. +- A pattern or threshold added to the detectors changes all three apps only once the macOS lane mirrors the fixtures. + +## Alternatives considered + +- **Per-connection rules in the core, applied to the grid, exports, MCP and the assistant on Linux and Windows.** Built first, then dropped by the maintainer's 2026-11-14 decision to keep masking to sharing. +- **The app masks each value before sending it.** Three engines would drift on grapheme counting and hashing, and a share link would read differently by the app that made it. +- **A stored hash key.** A hash could then be looked up across launches and apps; the macOS key is per launch on purpose. diff --git a/core/docs/decisions/README.md b/core/docs/decisions/README.md index b0556c6abb..e197123ccc 100644 --- a/core/docs/decisions/README.md +++ b/core/docs/decisions/README.md @@ -23,7 +23,7 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0013](0013-catalog-operations.md) | Truncating a table and creating or dropping a schema or database | Accepted | `DdlDialect` plans TRUNCATE and CREATE and DROP for schemas and databases per engine, MongoDB through its shell; a database change runs outside any transaction as `WriteKind::DatabaseChanges`; a login to a missing database fails as `DatabaseNotFound` and parks. | | [0014](0014-tls-mode-of-a-new-connection.md) | A new connection starts on the TLS mode the engine's own client starts on | Accepted | `TlsMode::Prefer` for PostgreSQL and MySQL, Verify full for SQL Server, Disable for the engines that decide TLS by the port, with a DNS seed list and ClickHouse's HTTPS ports on Verify full; the core holds the rule, and every TLS failure a mode change fixes offers Change Encryption. | | [0015](0015-editing-a-query-result.md) | A query result edits when its statement reads one table and its driver traces the columns | Accepted | The parser accepts one row-preserving SELECT over one table; each driver sets `ResultColumn::origin` only for a direct column of a permanent base table, from the wire or a lookup on its own connection; the result maps to the catalog with its full primary key and saves through `plan_save`. | -| [0016](0016-tablepro-accounts.md) | TablePro accounts live in the core, with features gated by the entitlement | Accepted | `tablepro-account` signs in through the browser with OAuth and a loopback redirect, registers the device, verifies the Ed25519 entitlement and gates features by its codes; each app passes its keyring, browser, machine ID and OAuth client in. | +| [0016](0016-tablepro-accounts.md) | TablePro accounts live in the core, with features gated by the entitlement | Accepted; the Windows app amended by 0026, share links amended by 0027 | `tablepro-account` signs in through the browser with OAuth and a loopback redirect, registers the device, verifies the Ed25519 entitlement and gates features by its codes; each app passes its keyring, browser, machine ID and OAuth client in. | | [0017](0017-favourites.md) | Favourites keep folders and keywords on saved queries, and the tables and databases a user marks | Accepted | One migration in the history's database adds per-connection folders that nest, a keyword and an order on saved queries, and favourite tables and databases with the four macOS environments; stable error codes, no UUID ids, and a database an older build wrote is copied first. | | [0018](0018-command-line.md) | One command line for the apps on the core | Accepted | `tablepro-cli` parses with clap, writes the macOS command's formats and exit status, and reaches the app's MCP server with the token the app's host reads; `classify` leaves files, links and GUI options to the app. | | [0019](0019-row-edits-through-the-ffi.md) | A table tab's row edits cross the FFI as typed text, and the core plans and runs the save | Accepted | `TableEditor` over the catalog's primary key reads keys and stored values from the result set, parses typed text with `parse_edit_text` and plans with `plan_save`; `RowSave` shows its statements with their values, gates at `SafeModeLevel::gate(Write)`, plans again on the writing lease and reports saved, rolled back or unknown. | @@ -33,3 +33,6 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0023](0023-mcp-client-setup-from-one-catalog.md) | Both apps set up MCP clients from one catalog | Accepted | `core/crates/mcp/clients.json`, bundled, lists each client per OS; install by deeplink, then the client's CLI by argv, then a comment-keeping splice into its config file with a `.tablepro-backup`, else copy; macOS writes the stdio bridge and no token, Linux the URL and token, and the Linux server serves only the user's own account; brand marks from Simple Icons or the brand, still their owners' trademarks. | | [0024](0024-copy-rows-through-copy-in.md) | An imported COPY block loads through PostgreSQL's copy-in | Accepted | The `ScriptReader` gives a `COPY ... FROM stdin` then its rows as written in pieces of at most 256 KiB, up to `\.`, which is never sent; `run_sql_import` streams them through `EditorSession::copy_in`, in the import's transaction or the driver's own; binary is refused; tokio-postgres comes from a fork with the copy-in fix (rust-postgres#1402) until a release has it. | | [0025](0025-linux-and-windows-link-their-drivers.md) | Linux and Windows link their drivers at compile time for good | Accepted | The Linux and Windows apps link every driver at compile time and never load one at runtime, so a new engine reaches them in an app release; 0004's downloadable drivers stay for macOS, and Linux 0001 is in force again. | +| [0026](0026-the-windows-app-signs-in-through-the-ffi.md) | The Windows app signs in to its TablePro account through the FFI | Accepted | `Core::open_account` builds the account with `AppClient::WINDOWS`, the Core's secret store for the refresh token, a `HostBrowser` callback and `MachineId::derive_machine_guid` of the registry's MachineGuid, keyed as Linux keys `/etc/machine-id`; `status()` is a snapshot and `AccountListener` only signals. | +| [0027](0027-share-links.md) | Share links go through the account, with the snapshot and the secret scan in the core | Accepted; masked columns and the secret scan amended by 0028 | `Account` adds the share calls through the generated `/v2` client, `fetch_shared` without a token; problem codes stay `Refused` with their own `code()`; `build_snapshot` writes raw JSON cells by the export's lossless rules up to the plan's rows; a table page shares `build_view_sql`, its export with the filter's values written in; `secret_scan` warns; the deep link takes one 43-character base62 token. | +| [0028](0028-data-masking.md) | A shared result masks its columns before it leaves the machine, with the macOS app's output | Accepted | `tablepro_core::masking` gives the macOS styles byte for byte; `SharePlan` applies the sheet's Keep, Mask or Remove per column for the snapshot, its preview and summary; the snapshot names each masked column's style and keeps to the macOS body budget; `masking::detect` suggests masks from names, values and the SQL by PLAN-MASKING 8.3. | diff --git a/linux/ARCHITECTURE.md b/linux/ARCHITECTURE.md index 37a8c70a1b..4609f5f7db 100644 --- a/linux/ARCHITECTURE.md +++ b/linux/ARCHITECTURE.md @@ -214,6 +214,10 @@ The account publishes an `AccountStatus` on a `watch`. `feature_access` reads a Preferences > Account (`crates/app/src/ui/preferences_dialog/account_page.rs`) works through the `AccountHandle` the service hands out: the status, whether the account started, and the address of the account pages ([ADR 0038](docs/decisions/0038-account-page-and-license-ask.md)). `account_view.rs` turns the status, `Account::profile` (`/v2/me`) and `Account::devices` (`/v2/devices`) into the page's rows and notices, as plain data the unit tests read; the page fetches the two while it is shown. Over the device limit, `device_limit_dialog.rs` lists the devices `device_limit_reached` names, with their `offline_until`, and removes one through `Account::remove_device`, which refreshes the entitlement after any removal. `Account::import_offline_file` verifies an offline file as it would an online entitlement; signed in, it refuses a file of another account than the sign-in's, and signed out, the status is `AccountStatus::Offline` and the gate reads that file. +### Share links + +Share Query… and Share Result… in the SQL editor, Share Result… in an editor result grid's or a table tab's grid menu and Share… on a favorite each send the workspace a `ShareSubject` (`services/share_subject.rs`): the SQL, the driver as its dialect, and for a result the rows an export of the shown rows writes, or for a table tab its view (`services/share_table.rs`), which the sheet reads up to the plan's rows once it has the limits. The workspace opens the `ShareDialog` (`ui/share_dialog/`), an `AdwDialog` subclass over the `AccountHandle`, which reads `Account::share_limits`, shows the page the limits call for, builds the snapshot on the runtime cut to the plan's rows, and creates the link with `Account::create_share` ([ADR 0046](docs/decisions/0046-share-links-and-the-tablepro-scheme.md), [core ADR 0027](../core/docs/decisions/0027-share-links.md)). Its Columns list offers Keep, Mask as a style or Remove for each shared column and starts the columns the core's detectors flag as masked; the preview, the notes and the snapshot all come from the core's `SharePlan` over those choices ([core ADR 0028](../core/docs/decisions/0028-data-masking.md)). A `tablepro://share?token=` link reaches `open_files` like a file and goes to `open_share_link.rs`, which reads it with `Account::fetch_shared`, asks for a password when the link has one, and sends its SQL to a window the way a SQL file's script goes, as `ScriptInput::Shared`. Manage Shared Links… opens the portal's list. + The license ask (`application/license_ask_prompt.rs`) counts each local day of use in GSettings at startup and whenever a window takes the focus, and `services/license_ask.rs` says when the ask is due: from the 30th day without a license, then 90 days after the last ask, or a year after I Use It Personally. It shows a toast (`LaunchNotice::LicenseAsk`) on the focused `SessionWindow` five minutes or more after launch, never over a dialog or a tab whose page is loading. diff --git a/linux/changelog.d/4253.added.1.md b/linux/changelog.d/4253.added.1.md new file mode 100644 index 0000000000..b672a0a553 --- /dev/null +++ b/linux/changelog.d/4253.added.1.md @@ -0,0 +1 @@ +Share Result masks the columns that look sensitive before a link is made, with Keep, Mask or Remove for each column. diff --git a/linux/changelog.d/4253.added.md b/linux/changelog.d/4253.added.md new file mode 100644 index 0000000000..f5189e7f49 --- /dev/null +++ b/linux/changelog.d/4253.added.md @@ -0,0 +1 @@ +Share a query or a result as a public link, and open shared links in TablePro. diff --git a/linux/crates/app/src/application/app_actions.rs b/linux/crates/app/src/application/app_actions.rs index 8aa4678072..9a7e16f735 100644 --- a/linux/crates/app/src/application/app_actions.rs +++ b/linux/crates/app/src/application/app_actions.rs @@ -26,13 +26,24 @@ pub fn install_app_actions(app: &TableProApplication) { let buy_license = gio::ActionEntry::builder("buy-license") .activate(|app: &TableProApplication, _, _| open_pricing(app)) .build(); + let shared_links = gio::ActionEntry::builder("manage-shared-links") + .activate(|app: &TableProApplication, _, _| open_shared_links(app)) + .build(); // A notification's default action, with the window and the tab it // is about. let focus_tab = gio::ActionEntry::builder("focus-tab") .parameter_type(Some(&<(u32, String)>::static_variant_type())) .activate(|app: &TableProApplication, _, target| focus_tab(app, target)) .build(); - app.add_action_entries([new_window, quit, preferences, about, buy_license, focus_tab]); + app.add_action_entries([ + new_window, + quit, + preferences, + about, + buy_license, + shared_links, + focus_tab, + ]); } /// Bring the tab forward in its window. A notification can outlive both, @@ -93,9 +104,43 @@ fn open_pricing(app: &TableProApplication) { ); } +// The account portal the build signs in to keeps the list of links. +fn shared_links_page(portal: &str) -> String { + format!("{}/shared-links", portal.trim_end_matches('/')) +} + +fn open_shared_links(app: &TableProApplication) { + let Some(services) = app.services() else { + return; + }; + let page = shared_links_page(&services.account().portal); + gtk4::UriLauncher::new(&page).launch(app.active_window().as_ref(), gio::Cancellable::NONE, |launched| { + if let Err(error) = launched { + tracing::warn!(%error, "the shared links page was not opened"); + } + }); +} + fn present_about(app: &TableProApplication) { let Some(services) = app.services() else { return; }; build_about_dialog(&services.drivers).present(app.active_window().as_ref()); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_shared_links_page_is_on_the_portal_the_build_signs_in_to() { + assert_eq!( + shared_links_page("https://account.tablepro.app"), + "https://account.tablepro.app/shared-links" + ); + assert_eq!( + shared_links_page("http://account.localhost:5284/"), + "http://account.localhost:5284/shared-links" + ); + } +} diff --git a/linux/crates/app/src/application/mod.rs b/linux/crates/app/src/application/mod.rs index 629804da7b..6ea32ae173 100644 --- a/linux/crates/app/src/application/mod.rs +++ b/linux/crates/app/src/application/mod.rs @@ -19,6 +19,7 @@ mod mcp_bridge; mod metainfo_release; mod open_files; mod open_links; +mod open_share_link; mod quit_sequence; mod runtime_versions; mod session_signals; diff --git a/linux/crates/app/src/application/open_files.rs b/linux/crates/app/src/application/open_files.rs index a9c3a1e4f8..e617b8a599 100644 --- a/linux/crates/app/src/application/open_files.rs +++ b/linux/crates/app/src/application/open_files.rs @@ -3,8 +3,8 @@ use gtk4::prelude::*; use tablepro_session::SessionKey; use super::{TableProApplication, WindowLaunch}; -use crate::services::connection_link; use crate::services::file_resolution::{FileTarget, ResolvedFile, resolve_file_blocking}; +use crate::services::{connection_link, share_link}; use crate::ui::{ScriptInput, SessionWindow, SessionWindowInput}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -37,6 +37,10 @@ impl TableProApplication { pub fn open_files(&self, files: &[gio::File], placement: Placement) { for file in files { // A link names no file, and file resolution would show its text, password and all. + if let Some(link) = share_link::share_link_text(file) { + self.open_share_link(&link, placement); + continue; + } match connection_link::link_text(file) { Some(link) => self.open_link(&link, placement), None => self.open_file(file.clone(), placement), @@ -107,32 +111,44 @@ impl TableProApplication { if SessionWindow::focus_tab_bound_to(self, &file) { return; } + self.route_script(self.script_windows(placement), ScriptInput::Open(file)); + } + + // A shared link's SQL takes the way a script does, never running and carrying no connection. + pub(super) fn place_shared_sql(&self, title: String, sql: String, placement: Placement) { + self.route_script(self.script_windows(placement), ScriptInput::Shared { title, sql }); + } + + // GTK lists the windows most recently focused first. While any window settles, a tab bound to the + // file may still appear, so a picker asks rather than opening a second one beside it. + fn script_windows(&self, placement: Placement) -> Vec { if placement == Placement::NewWindow { - return self.route_script(Vec::new(), file); + return Vec::new(); } - // GTK lists the windows most recently focused first. let windows: Vec = self .windows() .into_iter() .filter_map(|window| window.downcast::().ok()) .collect(); - // While any window settles, a tab bound to the file may still appear, so a picker asks rather - // than opening a second one beside it. if windows.iter().any(SessionWindow::settling) { - let idle = windows.into_iter().next().filter(SessionWindow::is_idle); - return self.route_script(idle.into_iter().collect(), file); + return windows + .into_iter() + .next() + .filter(SessionWindow::is_idle) + .into_iter() + .collect(); } - self.route_script(windows, file); + windows } - fn route_script(&self, windows: Vec, file: gio::File) { + fn route_script(&self, windows: Vec, script: ScriptInput) { let window = match windows.into_iter().next() { Some(window) => Some(window), None => self.open_window(WindowLaunch::Picker).and_downcast::(), }; match window { Some(window) => { - window.send(SessionWindowInput::Script(ScriptInput::Open(file))); + window.send(SessionWindowInput::Script(script)); window.present(); } None => tracing::warn!("no window to open a SQL file in"), diff --git a/linux/crates/app/src/application/open_share_link.rs b/linux/crates/app/src/application/open_share_link.rs new file mode 100644 index 0000000000..f6bcc82493 --- /dev/null +++ b/linux/crates/app/src/application/open_share_link.rs @@ -0,0 +1,300 @@ +use gtk4::glib; +use gtk4::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use secrecy::SecretString; +use tablepro_account::{Account, AccountError, SharedLink, share_token_from_link}; +use tablepro_session::runtime::TaskFailure; + +use super::TableProApplication; +use super::open_files::Placement; +use super::open_links::{CANCEL, OPEN}; +use crate::i18n::gettext; +use crate::services::account_service::AccountStart; +use crate::ui::error_text::{account_unavailable_message, shared_link_message}; +use crate::ui::{SessionWindow, SessionWindowInput}; + +type Fetched = Result, TaskFailure>; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum PasswordAsk { + First, + AfterWrongOne, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum SharedOutcome { + Open { title: String, sql: String }, + AskPassword(PasswordAsk), + Say(String), +} + +pub(super) fn outcome(fetched: Result) -> SharedOutcome { + match fetched { + // Anyone can write a link, and GTK refuses text with a NUL in it. + Ok(SharedLink { + title, sql: Some(sql), .. + }) if !sql.replace('\0', "").trim().is_empty() => SharedOutcome::Open { + title: title.replace('\0', ""), + sql: sql.replace('\0', ""), + }, + // Hidden, or a result shared without SQL: an empty editor tab would open nothing anyone asked for. + Ok(SharedLink { .. }) => SharedOutcome::Say(gettext( + "This shared result hides its SQL, so there is nothing to open.", + )), + Err(error) => match error.code() { + "account.share_password_required" => SharedOutcome::AskPassword(PasswordAsk::First), + "account.share_password_wrong" => SharedOutcome::AskPassword(PasswordAsk::AfterWrongOne), + _ => SharedOutcome::Say(shared_link_message(&error)), + }, + } +} + +impl TableProApplication { + pub(super) fn open_share_link(&self, link: &str, placement: Placement) { + let Some(token) = share_token_from_link(link) else { + tracing::warn!("a share link without a token TablePro reads"); + return self.say_about_share(&gettext("This shared link is no longer available.")); + }; + let Some(services) = self.services() else { + tracing::warn!("no share link opened: the application has no services"); + return; + }; + let mut start = services.account().start.clone(); + // An instance D-Bus started for this link would otherwise exit before its window opens. + let hold = self.hold(); + let app = self.downgrade(); + glib::spawn_future_local(async move { + // The account starts on the runtime at launch, which a link can beat. + let started = loop { + let current = start.borrow_and_update().clone(); + if !matches!(current, AccountStart::Starting) || start.changed().await.is_err() { + break current; + } + }; + if let Some(app) = app.upgrade() { + match started { + AccountStart::Ready(account) => app.fetch_shared(account, token, None, placement), + other => { + let reason = account_unavailable_message(&other) + .unwrap_or_else(|| gettext("This shared link is no longer available.")); + app.say_about_share(&reason); + } + } + } + drop(hold); + }); + } + + fn fetch_shared(&self, account: Account, token: String, password: Option, placement: Placement) { + let Some(services) = self.services() else { + return; + }; + let hold = self.hold(); + let app = self.downgrade(); + let fetching = account.clone(); + let asked = token.clone(); + crate::runtime::spawn_and_deliver( + &services.tasks, + async move { fetching.fetch_shared(&asked, password.as_ref()).await }, + move |fetched: Fetched| { + if let Some(app) = app.upgrade() { + app.shared_fetched(account, token, fetched, placement); + } + drop(hold); + }, + ); + } + + fn shared_fetched(&self, account: Account, token: String, fetched: Fetched, placement: Placement) { + let fetched = match fetched { + Ok(fetched) => fetched, + Err(failure) => Err(AccountError::Protocol(failure.to_string())), + }; + match outcome(fetched) { + SharedOutcome::Open { title, sql } => self.place_shared_sql(title, sql, placement), + SharedOutcome::AskPassword(ask) => { + let app = self.downgrade(); + glib::spawn_future_local(async move { + if let Some(app) = app.upgrade() { + app.ask_share_password(account, token, ask, placement).await; + } + }); + } + SharedOutcome::Say(message) => self.say_about_share(&message), + } + } + + async fn ask_share_password(&self, account: Account, token: String, ask: PasswordAsk, placement: Placement) { + let Some(parent) = self.share_window() else { + return; + }; + let (dialog, entry) = password_dialog(ask); + let hold = self.hold(); + let answer = crate::workspace::respond(&dialog, parent.upcast_ref()).await; + let password = entry.text().to_string(); + if answer == OPEN && !password.is_empty() { + self.fetch_shared(account, token, Some(SecretString::from(password)), placement); + } + drop(hold); + } + + fn say_about_share(&self, message: &str) { + match self.share_window() { + Some(window) => { + window.send(SessionWindowInput::ShowToast(message.to_owned())); + window.present(); + } + None => tracing::warn!("no window to say why a share link did not open"), + } + } + + // A word about a link goes on a window already open; a picker opens only when there is none. + fn share_window(&self) -> Option { + self.active_window() + .and_downcast::() + .or_else(|| { + self.windows() + .into_iter() + .find_map(|window| window.downcast::().ok()) + }) + .or_else(|| { + self.open_window(super::WindowLaunch::Picker) + .and_downcast::() + }) + } +} + +// Enter opens with the typed password; Escape and closing cancel. +pub(super) fn password_dialog(ask: PasswordAsk) -> (adw::AlertDialog, adw::PasswordEntryRow) { + let body = match ask { + PasswordAsk::First => gettext("This link is password protected."), + PasswordAsk::AfterWrongOne => gettext("That password is not correct."), + }; + let dialog = adw::AlertDialog::new(Some(&gettext("Open Shared Link")), Some(&body)); + let entry = adw::PasswordEntryRow::builder() + .title(gettext("Password")) + .activates_default(true) + .build(); + let group = adw::PreferencesGroup::new(); + group.add(&entry); + dialog.set_extra_child(Some(&group)); + dialog.add_response(CANCEL, &gettext("_Cancel")); + dialog.add_response(OPEN, &gettext("_Open")); + dialog.set_response_appearance(OPEN, adw::ResponseAppearance::Suggested); + dialog.set_default_response(Some(OPEN)); + dialog.set_close_response(CANCEL); + // A password may be spaces, so only an empty one keeps Open off. + dialog.set_response_enabled(OPEN, false); + let waiting = dialog.downgrade(); + entry.connect_changed(move |entry| { + if let Some(dialog) = waiting.upgrade() { + dialog.set_response_enabled(OPEN, !entry.text().is_empty()); + } + }); + dialog.set_focus(Some(&entry)); + (dialog, entry) +} + +#[cfg(test)] +mod tests { + use chrono::Utc; + + use super::*; + + fn link(sql: Option<&str>) -> SharedLink { + SharedLink { + kind: "query".to_owned(), + title: "Orders".to_owned(), + note: String::new(), + dialect: "postgres".to_owned(), + sql: sql.map(str::to_owned), + created_at: Utc::now(), + expires_at: None, + allow_download: true, + row_count: None, + truncated: None, + } + } + + fn refused(status: u16, code: &str) -> AccountError { + AccountError::Refused { + status, + code: code.to_owned(), + detail: String::new(), + } + } + + #[test] + fn a_link_with_sql_opens_it_and_one_that_hides_it_says_so() { + assert_eq!( + outcome(Ok(link(Some("SELECT 1")))), + SharedOutcome::Open { + title: "Orders".to_owned(), + sql: "SELECT 1".to_owned() + } + ); + assert_eq!( + outcome(Ok(link(None))), + SharedOutcome::Say("This shared result hides its SQL, so there is nothing to open.".to_owned()) + ); + } + + #[test] + fn a_nul_in_a_links_title_or_sql_is_dropped_before_gtk_sees_it() { + let mut shared = link(Some("SELECT\0 1")); + shared.title = "Ord\0ers".to_owned(); + + assert_eq!( + outcome(Ok(shared)), + SharedOutcome::Open { + title: "Orders".to_owned(), + sql: "SELECT 1".to_owned() + } + ); + } + + #[test] + fn a_result_shared_with_blank_sql_opens_nothing() { + for sql in ["", " \n\t", "\0"] { + assert_eq!( + outcome(Ok(link(Some(sql)))), + SharedOutcome::Say("This shared result hides its SQL, so there is nothing to open.".to_owned()), + "{sql:?}" + ); + } + } + + #[test] + fn a_password_is_asked_for_and_asked_again_after_a_wrong_one() { + assert_eq!( + outcome(Err(refused(401, "share_password_required"))), + SharedOutcome::AskPassword(PasswordAsk::First) + ); + assert_eq!( + outcome(Err(refused(401, "share_password_wrong"))), + SharedOutcome::AskPassword(PasswordAsk::AfterWrongOne) + ); + } + + #[test] + fn a_gone_link_says_it_is_no_longer_available() { + assert_eq!( + outcome(Err(refused(404, "not_found"))), + SharedOutcome::Say("This shared link is no longer available.".to_owned()) + ); + } + + #[gtk4::test] + fn the_password_dialog_opens_on_enter_once_typed_and_closes_as_cancel() { + let (dialog, entry) = password_dialog(PasswordAsk::AfterWrongOne); + + assert_eq!(dialog.body(), "That password is not correct."); + assert_eq!(dialog.default_response().as_deref(), Some(OPEN)); + assert_eq!(dialog.close_response(), CANCEL); + assert!(!dialog.is_response_enabled(OPEN)); + entry.set_text("hunter2"); + assert!(dialog.is_response_enabled(OPEN)); + assert_eq!(crate::test_support::assert_labelled(&entry), Ok(())); + } +} diff --git a/linux/crates/app/src/application/tests.rs b/linux/crates/app/src/application/tests.rs index aef0fdecd0..130a9eb3e8 100644 --- a/linux/crates/app/src/application/tests.rs +++ b/linux/crates/app/src/application/tests.rs @@ -378,7 +378,14 @@ fn a_file_without_a_hint_opens_in_the_idle_picker() { fn startup_installs_the_app_actions_and_their_accels() { let test = TestApp::started("Actions"); - for action in ["new-window", "quit", "preferences", "about", "buy-license"] { + for action in [ + "new-window", + "quit", + "preferences", + "about", + "buy-license", + "manage-shared-links", + ] { assert!(test.app.lookup_action(action).is_some(), "app.{action} is missing"); } } @@ -1673,3 +1680,49 @@ mod links { assert_eq!(window.page_name(), "picker"); } } + +mod share_links { + use super::*; + use crate::services::share_link::share_link_text; + use crate::ui::SessionWindow; + + const TOKEN: &str = "Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK"; + + fn link(text: &str) -> gio::File { + crate::services::connection_link::register_link_schemes().expect("register the links"); + gio::File::for_uri(text) + } + + #[gtk4::test] + fn a_share_link_keeps_its_text_through_gio() { + let text = format!("tablepro://share?token={TOKEN}"); + + let file = link(&text); + + assert_eq!(file.uri(), text); + assert_eq!(share_link_text(&file).as_deref(), Some(text.as_str())); + } + + #[gtk4::test] + fn a_share_link_without_a_token_says_it_is_gone_and_opens_nothing() { + let test = TestApp::started("ShareLinkMalformed"); + test.app.activate(); + wait_until(WAIT, || test.app.windows().len() == 1).expect("the picker"); + let window = test + .app + .active_window() + .and_downcast::() + .expect("the picker"); + + test.app.open(&[link("tablepro://share?token=short")], ""); + + wait_until(WAIT, || { + window + .toast_titles() + .contains(&"This shared link is no longer available.".to_owned()) + }) + .expect("the toast saying why"); + assert_eq!(test.app.windows().len(), 1); + assert_eq!(window.page_name(), "picker"); + } +} diff --git a/linux/crates/app/src/lib.rs b/linux/crates/app/src/lib.rs index b76158bab6..8de1a18184 100644 --- a/linux/crates/app/src/lib.rs +++ b/linux/crates/app/src/lib.rs @@ -21,6 +21,7 @@ pub mod storage; pub use services::{change_tracker, tab_tracker_handle, tracker_edit}; // Public for the desktop entry's test, which claims each of them. pub use services::connection_link::LINK_SCHEMES; +pub use services::share_link::SHARE_LINK_SCHEME; #[cfg(test)] mod test_support; mod ui; diff --git a/linux/crates/app/src/services/connection_link.rs b/linux/crates/app/src/services/connection_link.rs index 871307c515..e7f718e2a2 100644 --- a/linux/crates/app/src/services/connection_link.rs +++ b/linux/crates/app/src/services/connection_link.rs @@ -3,6 +3,8 @@ use tablepro_core::connection_url::ConnectionUrl; use tablepro_core::{DriverCapabilities, is_local_socket_host}; use tablepro_storage::{ConnectionStore, SavedConnection}; +use super::share_link::{SHARE_LINK_SCHEME, is_share_link}; + // The schemes tablepro_core::connection_url::parse reads; the desktop entry claims each one. pub const LINK_SCHEMES: [&str; 22] = [ "cassandra", @@ -53,7 +55,8 @@ fn link_vfs() -> Result { .map_err(|_| glib::bool_error!("GIO's local implementation is not a VFS")) } -// gvfs reads these into a mount spec that drops the password and all but one MongoDB host. +// gvfs reads these into a mount spec that drops the password and all but one MongoDB host. A share link +// keeps its text the same way, so its token reaches the app as the viewer page wrote it. pub fn register_link_schemes() -> Result<(), glib::BoolError> { static REGISTERED: std::sync::OnceLock> = std::sync::OnceLock::new(); REGISTERED @@ -61,14 +64,14 @@ pub fn register_link_schemes() -> Result<(), glib::BoolError> { let vfs = gio::Vfs::default(); // Backend construction registers a scheme and cannot run under a lookup callback's scheme lock. let local = link_vfs()?; - for scheme in LINK_SCHEMES.into_iter().chain([JDBC_SCHEME]) { + for scheme in LINK_SCHEMES.into_iter().chain([JDBC_SCHEME, SHARE_LINK_SCHEME]) { let uri_vfs = local.clone(); let parse_vfs = local.clone(); let registered = vfs.register_uri_scheme( scheme, Some(Box::new(move |_, uri| Some(uri_vfs.file_for_uri(uri)))), Some(Box::new(move |_, name| { - is_link(name).then(|| parse_vfs.file_for_uri(name)) + (is_link(name) || is_share_link(name)).then(|| parse_vfs.file_for_uri(name)) })), ); if !registered { diff --git a/linux/crates/app/src/services/grid/mod.rs b/linux/crates/app/src/services/grid/mod.rs index 339e6350be..17fc6c1fa4 100644 --- a/linux/crates/app/src/services/grid/mod.rs +++ b/linux/crates/app/src/services/grid/mod.rs @@ -26,7 +26,7 @@ mod row_snapshot; mod selection_summary; pub mod special_characters; #[cfg(test)] -mod test_columns; +pub(crate) mod test_columns; pub use self::cell_editability::cell_editability; pub use self::cell_editor_kind::{CellEditorKind, EDIT_MAX_BYTES, TextPurpose}; diff --git a/linux/crates/app/src/services/mod.rs b/linux/crates/app/src/services/mod.rs index ea2d997613..52d9371a7c 100644 --- a/linux/crates/app/src/services/mod.rs +++ b/linux/crates/app/src/services/mod.rs @@ -39,6 +39,9 @@ pub mod secret_changes; pub mod secret_labels; pub mod secret_save_report; pub mod session_context; +pub mod share_link; +pub(crate) mod share_subject; +pub(crate) mod share_table; pub mod snippet_library; pub mod ssh_environment; pub mod structure_tracker; diff --git a/linux/crates/app/src/services/share_link.rs b/linux/crates/app/src/services/share_link.rs new file mode 100644 index 0000000000..8cfe2d4b18 --- /dev/null +++ b/linux/crates/app/src/services/share_link.rs @@ -0,0 +1,29 @@ +use gio::prelude::FileExt; + +pub const SHARE_LINK_SCHEME: &str = "tablepro"; + +// Read from the text, as a connection link is: a GFile a VFS rewrote can report no scheme at all. +pub fn is_share_link(uri: &str) -> bool { + glib::Uri::peek_scheme(uri).is_some_and(|scheme| scheme == SHARE_LINK_SCHEME) +} + +pub fn share_link_text(file: &gio::File) -> Option { + let uri = file.uri(); + is_share_link(&uri).then(|| uri.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TOKEN: &str = "Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK"; + + #[test] + fn only_the_tablepro_scheme_is_a_share_link() { + assert!(is_share_link(&format!("tablepro://share?token={TOKEN}"))); + assert!(is_share_link("TablePro://share")); + assert!(!is_share_link(&format!("https://s.tablepro.app/{TOKEN}"))); + assert!(!is_share_link("postgresql://localhost/shop")); + assert!(!is_share_link("/home/ada/tablepro://share")); + } +} diff --git a/linux/crates/app/src/services/share_subject.rs b/linux/crates/app/src/services/share_subject.rs new file mode 100644 index 0000000000..b8dc56bb6b --- /dev/null +++ b/linux/crates/app/src/services/share_subject.rs @@ -0,0 +1,495 @@ +use std::sync::Arc; + +use secrecy::{ExposeSecret as _, SecretString}; +use tablepro_account::{ShareExpiry, ShareKind, ShareLimits, ShareRequest}; +use tablepro_core::Value; +use tablepro_core::column::ResultColumn; +use tablepro_core::export::{ResultExtent, Snapshot, SnapshotRefusal, build_snapshot}; +use tablepro_core::masking::detect::{MaskSuggestion, PersonalDataHit, scan_sql_personal_data}; +use tablepro_core::masking::{ShareChoice, SharePlan, ShareSummary, share_suggestions}; +use tablepro_core::secret_scan::{self, SecretHitKind}; + +use crate::services::grid::RowSnapshot; +use crate::services::share_table::TableShare; + +#[derive(Debug, Clone)] +pub struct ShareSubject { + pub title: String, + pub sql: String, + pub dialect: Option, + pub rows: Option, + pub table: Option, + // Why a result goes without SQL, which the sheet says. + pub no_sql: Option, +} + +#[derive(Debug, Clone)] +pub struct SharedRows { + pub columns: Arc<[ResultColumn]>, + pub rows: Vec, + // What the result knows of its rows, which the link names as the whole. + pub extent: ResultExtent, +} + +#[derive(Debug, Clone)] +pub struct ShareForm { + pub title: String, + pub note: String, + pub expiry: ShareExpiry, + pub hide_sql: bool, + pub password: SecretString, + pub allow_download: bool, + // None shares a personal link. + pub team: Option, + // The sheet's choice for each shared column, in order; Keep past its end. + pub columns: Vec, +} + +impl ShareSubject { + pub(crate) fn query(title: String, sql: String, dialect: Option) -> Self { + Self { + title, + sql, + dialect, + rows: None, + table: None, + no_sql: None, + } + } + + pub(crate) fn kind(&self) -> ShareKind { + match self.rows.is_some() || self.table.is_some() { + true => ShareKind::Result, + false => ShareKind::Query, + } + } + + pub(crate) fn has_sql(&self) -> bool { + !self.sql.trim().is_empty() + } + + // A plan's options it lacks are left out rather than refused by the server. + pub(crate) fn request(&self, form: &ShareForm, limits: &ShareLimits, snapshot: Option) -> ShareRequest { + let result = self.kind() == ShareKind::Result; + let password = form.password.expose_secret(); + ShareRequest { + kind: self.kind(), + sql: self.sql.clone(), + title: Some(form.title.trim().to_owned()).filter(|title| !title.is_empty()), + note: Some(form.note.trim().to_owned()).filter(|note| !note.is_empty()), + dialect: self.dialect.clone().filter(|dialect| !dialect.is_empty()), + expiry: Some(form.expiry).filter(|expiry| limits.expiries.contains(expiry)), + hide_sql: result && self.has_sql() && form.hide_sql, + allow_download: (limits.disable_download && !form.allow_download).then_some(false), + password: (limits.password && !password.is_empty()).then(|| form.password.clone()), + team_id: form + .team + .clone() + .filter(|team| limits.team && limits.teams.iter().any(|known| known.id == *team)), + snapshot: snapshot.filter(|_| result), + } + } + + pub(crate) fn secret_kinds(&self) -> Vec { + let mut kinds: Vec = secret_scan::scan_sql(&self.sql) + .into_iter() + .map(|hit| hit.kind) + .collect(); + kinds.sort_unstable(); + kinds.dedup(); + kinds + } + + pub(crate) fn secret_columns(&self) -> Vec { + secret_scan::scan_columns(&self.column_names()) + } + + // Personal data in the SQL's literals, which Hide SQL keeps off the link; each kind once. + pub(crate) fn personal_data(&self) -> Vec { + let mut hits = scan_sql_personal_data(&self.sql); + hits.sort_by_key(|hit| hit.kind); + hits.dedup_by_key(|hit| hit.kind); + hits + } + + // The columns the link carries, in their order, before the server's column cap. + pub(crate) fn column_names(&self) -> Vec { + match (&self.rows, &self.table) { + (Some(rows), _) => rows.columns.iter().map(|column| column.name.clone()).collect(), + (None, Some(table)) => table + .shown + .iter() + .filter_map(|index| table.columns.get(*index)) + .map(|column| column.name.clone()) + .collect(), + (None, None) => Vec::new(), + } + } +} + +impl SharedRows { + // The sheet's choices; at most the server's columns are kept. + pub(crate) fn plan(&self, choices: &[ShareChoice], max_columns: u64) -> SharePlan { + SharePlan::new( + self.columns.len(), + choices, + usize::try_from(max_columns).unwrap_or(usize::MAX), + ) + } + + // Cut to the plan's rows and the body's budget before upload, masked values weighed; removed columns are never read. + pub(crate) fn snapshot(&self, max_rows: u64, plan: &SharePlan) -> Result { + let max_rows = usize::try_from(max_rows).unwrap_or(usize::MAX); + let columns = plan.columns(&self.columns); + let rows = self.rows.iter().map(|row| self.sent_row(plan, row)); + let mut snapshot = build_snapshot(&columns, rows, self.extent, max_rows)?; + for (column, masked) in snapshot.columns.iter_mut().zip(plan.masked()) { + column.masked = masked; + } + Ok(snapshot) + } + + // What the snapshot of `plan` sends, so the preview, the notes and the detectors read the rows that go. + pub(crate) fn summary(&self, plan: &SharePlan, max_rows: u64) -> ShareSummary { + plan.summary( + &self.columns, + self.rows.len(), + |row, column| self.rows[row].value(column).clone(), + usize::try_from(max_rows).unwrap_or(usize::MAX), + ) + } + + // The first `count` rows as the link carries them, for the sheet's preview. + pub(crate) fn sent(&self, plan: &SharePlan, count: usize) -> (Vec, Vec) { + let rows = self + .rows + .iter() + .take(count) + .map(|row| RowSnapshot::new(self.sent_row(plan, row).into(), Vec::new())) + .collect(); + (plan.columns(&self.columns), rows) + } + + fn sent_row(&self, plan: &SharePlan, row: &RowSnapshot) -> Vec { + plan.row(&self.columns, |index| row.value(index).clone()) + } + + // What the detectors suggest for the sheet as it starts, by the core's windows of the held rows. + pub(crate) fn suggestions(&self, max_rows: u64, max_columns: u64) -> Vec> { + share_suggestions( + &self.columns, + self.rows.iter().map(RowSnapshot::to_values), + usize::try_from(max_rows).unwrap_or(usize::MAX), + usize::try_from(max_columns).unwrap_or(usize::MAX), + ) + } + + pub(crate) fn total(&self) -> u64 { + self.extent + .total + .unwrap_or(self.extent.held) + .max(self.rows.len() as u64) + } +} + +#[cfg(test)] +mod tests { + use tablepro_core::column::{ColumnType, classify_type_name}; + use tablepro_core::masking::MaskingStyle; + + use super::*; + + fn limits(plan: &str) -> ShareLimits { + let pro = plan == "pro"; + ShareLimits { + plan: plan.to_owned(), + live: 1, + live_limit: if pro { 1_000 } else { 5 }, + max_rows: if pro { 10_000 } else { 1_000 }, + expiries: match pro { + true => ShareExpiry::ALL.to_vec(), + false => vec![ShareExpiry::OneDay, ShareExpiry::SevenDays, ShareExpiry::ThirtyDays], + }, + default_expiry: Some(if pro { + ShareExpiry::Never + } else { + ShareExpiry::ThirtyDays + }), + password: pro, + disable_download: pro, + team: pro, + email_verified: true, + sharing_disabled: false, + max_columns: 100, + teams: vec![tablepro_account::ShareTeam { + id: "team_01".to_owned(), + name: "Data".to_owned(), + live: 2, + live_limit: 1_000, + public_links: true, + }], + } + } + + fn column(name: &str) -> ResultColumn { + ResultColumn::new( + name, + ColumnType { + kind: classify_type_name("bigint"), + ..ColumnType::untyped_text("bigint") + }, + ) + } + + fn rows(count: i64, total: Option) -> SharedRows { + SharedRows { + columns: vec![column("id"), column("api_token")].into(), + rows: (0..count) + .map(|id| RowSnapshot::new(vec![Value::Int(id), Value::Int(id * 10)].into(), Vec::new())) + .collect(), + extent: ResultExtent { + held: count as u64, + total, + cut: total.is_some_and(|total| total > count as u64), + }, + } + } + + fn form() -> ShareForm { + ShareForm { + title: " Orders ".to_owned(), + note: " ".to_owned(), + expiry: ShareExpiry::Never, + hide_sql: true, + password: SecretString::from("hunter2"), + allow_download: false, + team: Some("team_01".to_owned()), + columns: Vec::new(), + } + } + + fn query(sql: &str) -> ShareSubject { + ShareSubject::query(String::new(), sql.to_owned(), Some("postgres".to_owned())) + } + + #[test] + fn a_free_plan_sends_none_of_the_pro_options() { + let subject = ShareSubject { + rows: Some(rows(2, None)), + ..query("SELECT 1") + }; + + let request = subject.request(&form(), &limits("free"), None); + + assert_eq!(request.kind, ShareKind::Result); + assert_eq!(request.title.as_deref(), Some("Orders")); + assert_eq!(request.note, None); + assert_eq!(request.expiry, None, "never is a Pro expiry"); + assert!(request.password.is_none()); + assert_eq!(request.allow_download, None); + assert!(request.hide_sql); + assert_eq!(request.team_id, None, "a team link needs Pro"); + } + + #[test] + fn a_pro_plan_sends_its_password_downloads_and_expiry() { + let subject = ShareSubject { + rows: Some(rows(2, None)), + ..query("SELECT 1") + }; + + let request = subject.request(&form(), &limits("pro"), None); + + assert_eq!(request.expiry, Some(ShareExpiry::Never)); + assert_eq!( + request + .password + .as_ref() + .map(|password| password.expose_secret().to_owned()), + Some("hunter2".to_owned()) + ); + assert_eq!(request.allow_download, Some(false)); + assert_eq!(request.dialect.as_deref(), Some("postgres")); + assert_eq!(request.team_id.as_deref(), Some("team_01")); + } + + #[test] + fn a_result_without_sql_sends_none_to_hide_and_no_team_the_plan_does_not_list() { + let subject = ShareSubject { + rows: Some(rows(1, None)), + ..query(" ") + }; + let stranger = ShareForm { + team: Some("team_99".to_owned()), + ..form() + }; + + let request = subject.request(&stranger, &limits("pro"), None); + + assert!(!subject.has_sql()); + assert!(!request.hide_sql); + assert_eq!(request.team_id, None); + } + + #[test] + fn a_query_always_shows_its_sql_and_carries_no_rows() { + let shared = rows(1, None); + let snapshot = shared.snapshot(10, &shared.plan(&[], 100)).expect("a snapshot"); + let empty_password = ShareForm { + password: SecretString::from(""), + allow_download: true, + ..form() + }; + + let request = query("SELECT 1").request(&empty_password, &limits("pro"), Some(snapshot)); + + assert_eq!(request.kind, ShareKind::Query); + assert!(!request.hide_sql); + assert!(request.snapshot.is_none()); + assert!(request.password.is_none()); + assert_eq!(request.allow_download, None); + } + + #[test] + fn the_snapshot_is_cut_to_the_plan_and_keeps_the_true_count() { + let shared = rows(12, Some(48_210)); + + let snapshot = shared.snapshot(5, &shared.plan(&[], 100)).expect("a snapshot"); + + assert_eq!(snapshot.rows.len(), 5); + assert_eq!(snapshot.row_count, Some(48_210)); + assert!(snapshot.truncated()); + assert_eq!(snapshot.rows[4][1].get(), "40"); + assert_eq!(shared.total(), 48_210); + assert_eq!(rows(3, Some(0)).total(), 3, "a count below the rows held is never sent"); + } + + #[test] + fn a_result_cut_with_no_count_shares_that_more_rows_exist() { + let shared = SharedRows { + extent: ResultExtent { + held: 2, + total: None, + cut: true, + }, + ..rows(2, None) + }; + + let snapshot = shared.snapshot(10, &shared.plan(&[], 100)).expect("a snapshot"); + + assert_eq!((snapshot.row_count, snapshot.more_rows), (None, true)); + assert!(snapshot.truncated()); + } + + fn text_column(name: &str) -> ResultColumn { + ResultColumn::new(name, ColumnType::untyped_text("text")) + } + + fn people() -> SharedRows { + let text = |value: &str| Value::Text(value.to_owned()); + SharedRows { + columns: vec![text_column("id"), text_column("email"), text_column("note")].into(), + rows: vec![RowSnapshot::new( + vec![text("1"), text("ann@example.com"), text("+1 555 0100")].into(), + Vec::new(), + )], + extent: ResultExtent::complete(1), + } + } + + #[test] + fn kept_columns_go_as_held() { + let shared = people(); + + let snapshot = shared.snapshot(10, &shared.plan(&[], 100)).expect("a snapshot"); + + let cells: Vec<&str> = snapshot.rows[0].iter().map(|cell| cell.get()).collect(); + assert_eq!(cells, [r#""1""#, r#""ann@example.com""#, r#""+1 555 0100""#]); + assert!(snapshot.columns.iter().all(|column| column.masked.is_none())); + } + + #[test] + fn removed_columns_are_never_sent_and_masked_ones_say_how() { + let shared = people(); + let choices = [ + ShareChoice::Remove, + ShareChoice::Mask(MaskingStyle::Email), + ShareChoice::Mask(MaskingStyle::LastFour), + ]; + + let plan = shared.plan(&choices, 100); + let snapshot = shared.snapshot(10, &plan).expect("a snapshot"); + let (columns, preview) = shared.sent(&plan, 5); + + let names: Vec<&str> = snapshot.columns.iter().map(|column| column.name.as_str()).collect(); + assert_eq!(names, ["email", "note"]); + let cells: Vec<&str> = snapshot.rows[0].iter().map(|cell| cell.get()).collect(); + assert_eq!(cells, [r#""a•••@example.com""#, r#""••••0100""#]); + assert_eq!(snapshot.columns[1].masked, Some(MaskingStyle::LastFour)); + assert_eq!(columns.len(), 2); + assert_eq!(preview[0].value(1), &Value::Text("••••0100".to_owned())); + } + + #[test] + fn detection_reads_the_names_and_the_values() { + let shared = people(); + + let styles: Vec> = shared + .suggestions(1_000, 100) + .iter() + .map(|suggestion| suggestion.map(|suggestion| suggestion.style)) + .collect(); + + assert_eq!(styles, [None, Some(MaskingStyle::Email), Some(MaskingStyle::LastFour)]); + } + + #[test] + fn a_first_row_too_large_to_send_still_has_its_values_read() { + let text = |value: &str| Value::Text(value.to_owned()); + let shared = SharedRows { + columns: vec![text_column("blob"), text_column("notes")].into(), + rows: vec![ + RowSnapshot::new( + vec![text(&"x".repeat(300 * 1_024)), text("ann@example.com")].into(), + Vec::new(), + ), + RowSnapshot::new(vec![text("small"), text("bob@example.com")].into(), Vec::new()), + ], + extent: ResultExtent::complete(2), + }; + + let styles: Vec> = shared + .suggestions(1_000, 100) + .iter() + .map(|suggestion| suggestion.map(|suggestion| suggestion.style)) + .collect(); + + assert_eq!(styles, [None, Some(MaskingStyle::Email)]); + } + + #[test] + fn personal_data_in_the_sql_is_named_once_per_kind() { + let subject = query("SELECT * FROM users WHERE email = 'ann@example.com' OR email = 'bo@example.com'"); + + let kinds: Vec<_> = subject.personal_data().iter().map(|hit| hit.kind).collect(); + + assert_eq!(kinds, [tablepro_core::masking::detect::SensitiveKind::Email]); + assert!(query("SELECT 1 -- 'ann@example.com'").personal_data().is_empty()); + } + + #[test] + fn secrets_are_found_in_the_sql_and_the_columns() { + let subject = ShareSubject { + rows: Some(rows(1, None)), + ..query("SELECT 'AKIAABCDEFGHIJKLMNOP';\nSELECT 'AKIAABCDEFGHIJKLMNOQ', password = 'x'") + }; + + assert_eq!( + subject.secret_kinds(), + vec![SecretHitKind::AwsAccessKey, SecretHitKind::AssignedSecret] + ); + assert_eq!(subject.secret_columns(), vec!["api_token".to_owned()]); + assert!(query("SELECT 1").secret_kinds().is_empty()); + assert!(query("SELECT 1").secret_columns().is_empty()); + } +} diff --git a/linux/crates/app/src/services/share_table.rs b/linux/crates/app/src/services/share_table.rs new file mode 100644 index 0000000000..bedee9244f --- /dev/null +++ b/linux/crates/app/src/services/share_table.rs @@ -0,0 +1,239 @@ +use std::sync::{Arc, Mutex, PoisonError}; + +use async_trait::async_trait; +use tablepro_core::browse::{DeclaredPrecisionSink, ExportFields, ExportRequest, SortKey, build_export}; +use tablepro_core::column::ResultColumn; +use tablepro_core::export::ResultExtent; +use tablepro_core::meta::{RowIdentity, TableRef}; +use tablepro_core::{ColumnInfo, FilterSet, ReadStatement, ResultEvent, ResultSink, SinkFlow, Value}; +use tablepro_session::{OperationError, OperationKind, Session}; + +use super::grid::RowSnapshot; +use super::share_subject::SharedRows; + +// A table tab's view, read from its first row once the plan says how many rows a link carries. +#[derive(Debug, Clone)] +pub struct TableShare { + pub session: Arc, + pub table: TableRef, + // Every column, so the filter and the sort find theirs; `shown` picks what the link carries. + pub columns: Arc<[ColumnInfo]>, + pub shown: Vec, + pub filter: FilterSet, + pub sort: Vec, + pub identity: RowIdentity, + // What the tab counted or estimated, which the link names as the whole. + pub total: Option, +} + +#[derive(Default)] +struct Collected { + columns: Option>, + rows: Vec>, + full: bool, +} + +// Stops the read once it holds the plan's rows; a link carries no more. +struct FirstRows { + state: Arc>, + max_rows: usize, +} + +impl TableShare { + pub fn request(&self) -> ExportRequest<'_> { + ExportRequest { + table: &self.table, + columns: &self.columns, + filter: &self.filter, + sort: &self.sort, + identity: &self.identity, + fields: ExportFields::Listed, + } + } + + pub(crate) async fn read(self: Arc, max_rows: u64) -> Result { + let max_rows = usize::try_from(max_rows).unwrap_or(usize::MAX); + let state = Arc::new(Mutex::new(Collected::default())); + let (share, reading) = (self.clone(), state.clone()); + let ran = self + .session + .run(OperationKind::Export, move |lease, options| { + let (share, state) = (share.clone(), reading.clone()); + async move { + *state.lock().unwrap_or_else(PoisonError::into_inner) = Collected::default(); + let read = ReadStatement::Generated(build_export(&*lease.dialect(), &share.request())?); + let sink = + DeclaredPrecisionSink::new(Box::new(FirstRows { state, max_rows }), share.columns.clone()); + Ok(lease.stream_read(&read, Box::new(sink), options).await?) + } + }) + .await; + let collected = std::mem::take(&mut *state.lock().unwrap_or_else(PoisonError::into_inner)); + match ran { + Ok(_) => {} + // The sink ends a read it has had enough of, which some drivers report as a failure. + Err(_) if collected.full => {} + Err(error) => return Err(error), + } + Ok(self.shared(collected)) + } + + fn shared(&self, collected: Collected) -> SharedRows { + let read: Arc<[ResultColumn]> = collected + .columns + .unwrap_or_else(|| self.columns.iter().map(ColumnInfo::result_column).collect()); + let shown: Vec = self.shown.iter().copied().filter(|index| *index < read.len()).collect(); + let columns: Arc<[ResultColumn]> = shown.iter().map(|index| read[*index].clone()).collect(); + let full = collected.full; + let rows: Vec = collected + .rows + .into_iter() + .map(|row| { + let cells: Vec = shown + .iter() + .map(|index| row.get(*index).cloned().unwrap_or(Value::Null)) + .collect(); + RowSnapshot::new(cells.into(), Vec::new()) + }) + .collect(); + let held = rows.len() as u64; + let extent = match self.total { + Some(total) => ResultExtent { + held, + total: Some(total), + cut: true, + }, + None => ResultExtent { + held, + total: None, + cut: full, + }, + }; + SharedRows { columns, rows, extent } + } +} + +#[async_trait] +impl ResultSink for FirstRows { + async fn accept(&mut self, event: ResultEvent) -> SinkFlow { + let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner); + match event { + ResultEvent::ResultSetStarted { columns } if state.columns.is_none() => state.columns = Some(columns), + ResultEvent::ColumnsResolved { set_index: 0, columns } => state.columns = Some(columns), + ResultEvent::Rows(rows) => { + let room = self.max_rows.saturating_sub(state.rows.len()); + state.rows.extend(rows.into_iter().take(room)); + } + _ => {} + } + if state.rows.len() >= self.max_rows { + state.full = true; + return SinkFlow::ConsumerGone; + } + SinkFlow::Continue + } +} + +#[cfg(test)] +mod tests { + use tablepro_core::column::{ColumnType, classify_type_name}; + use tablepro_core::{ResultEvent, Truncation}; + use tablepro_test_support::{ConnectionScript, FakeReply}; + + use super::*; + use crate::test_support::{FakeSession, paused_tasks}; + + fn column(name: &str) -> ColumnInfo { + crate::services::grid::test_columns::info(name, "text") + } + + fn table(session: Arc, total: Option) -> Arc { + Arc::new(TableShare { + session, + table: TableRef::new(None, "orders"), + columns: vec![column("id"), column("secret"), column("name")].into(), + shown: vec![2, 0], + filter: FilterSet::default(), + sort: Vec::new(), + identity: RowIdentity::UniqueKey { + columns: vec!["id".to_owned()], + }, + total, + }) + } + + fn events(rows: usize) -> Vec { + let columns: Arc<[ResultColumn]> = ["id", "secret", "name"] + .into_iter() + .map(|name| { + ResultColumn::new( + name, + ColumnType { + kind: classify_type_name("text"), + ..ColumnType::untyped_text("text") + }, + ) + }) + .collect(); + vec![ + ResultEvent::ResultSetStarted { columns }, + ResultEvent::Rows( + (0..rows) + .map(|row| { + vec![ + Value::Text(row.to_string()), + Value::Text("hidden".to_owned()), + Value::Text(format!("name {row}")), + ] + }) + .collect(), + ), + ResultEvent::ResultSetFinished { + retained: rows as u64, + total_rows: Some(rows as u64), + truncation: Truncation::Complete, + }, + ] + } + + #[tokio::test] + async fn a_table_share_reads_the_plans_rows_under_the_shown_columns_with_the_tabs_total() { + let mut script = ConnectionScript::default(); + script.stream_read.always(FakeReply::ok(events(8))); + let fake = FakeSession::start(script, [], paused_tasks()); + let share = table(fake.session.clone(), Some(48_210)); + + let shared = share.read(5).await.expect("the rows read"); + + assert_eq!( + shared + .columns + .iter() + .map(|column| column.name.as_str()) + .collect::>(), + ["name", "id"] + ); + assert_eq!(shared.rows.len(), 5); + assert_eq!( + shared.rows[4].to_values(), + [Value::Text("name 4".to_owned()), Value::Text("4".to_owned())] + ); + assert_eq!(shared.total(), 48_210); + } + + #[tokio::test] + async fn without_a_count_the_whole_is_the_rows_read() { + let mut script = ConnectionScript::default(); + script.stream_read.always(FakeReply::ok(events(3))); + let fake = FakeSession::start(script, [], paused_tasks()); + + let shared = table(fake.session.clone(), None) + .read(1_000) + .await + .expect("the rows read"); + + assert_eq!(shared.rows.len(), 3); + assert_eq!(shared.total(), 3); + assert_eq!((shared.extent.total, shared.extent.cut), (None, false)); + } +} diff --git a/linux/crates/app/src/test_support/cloud_stub.rs b/linux/crates/app/src/test_support/cloud_stub.rs index 6c6a55cab0..a3f931dfc7 100644 --- a/linux/crates/app/src/test_support/cloud_stub.rs +++ b/linux/crates/app/src/test_support/cloud_stub.rs @@ -9,7 +9,8 @@ type Answer = dyn Fn(&str, &str) -> (u16, String) + Send + Sync; // Stands in for tablepro-cloud: `answer` gives the status and JSON body for a method and path. pub(crate) struct CloudStub { pub(crate) url: String, - requests: Arc>>, + // "METHOD /path" and the body sent with it. + requests: Arc>>, _accepting: AcceptLoop, } @@ -32,11 +33,27 @@ impl CloudStub { // "METHOD /path" for each request, in the order they came. pub(crate) fn requests(&self) -> Vec { - self.requests.lock().expect("the requests").clone() + self.requests + .lock() + .expect("the requests") + .iter() + .map(|(request, _)| request.clone()) + .collect() + } + + // The bodies sent with `wanted`, such as "POST /v2/shares", in the order they came. + pub(crate) fn bodies(&self, wanted: &str) -> Vec { + self.requests + .lock() + .expect("the requests") + .iter() + .filter(|(request, _)| request == wanted) + .map(|(_, body)| body.clone()) + .collect() } } -fn serve(stream: TcpStream, kept: &Mutex>, answer: &Answer) { +fn serve(stream: TcpStream, kept: &Mutex>, answer: &Answer) { let mut reader = BufReader::new(stream.try_clone().expect("a second handle")); let mut line = String::new(); if reader.read_line(&mut line).unwrap_or(0) == 0 { @@ -68,7 +85,9 @@ fn serve(stream: TcpStream, kept: &Mutex>, answer: &Answer) { if reader.read_exact(&mut body).is_err() { return; } - kept.lock().expect("the requests").push(format!("{method} {path}")); + kept.lock() + .expect("the requests") + .push((format!("{method} {path}"), String::from_utf8_lossy(&body).into_owned())); let (status, body) = answer(&method, &path); let reply = format!( "HTTP/1.1 {status} Stub\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", diff --git a/linux/crates/app/src/ui/browse_tab/grid_handlers.rs b/linux/crates/app/src/ui/browse_tab/grid_handlers.rs index d48daafada..6fe5c8fea9 100644 --- a/linux/crates/app/src/ui/browse_tab/grid_handlers.rs +++ b/linux/crates/app/src/ui/browse_tab/grid_handlers.rs @@ -1,10 +1,13 @@ use gtk4::prelude::*; +use tablepro_core::browse::{ExportFields, ExportRequest, build_view_sql}; use super::{BrowseModel, BrowseTabOutput, Effects, GridInput, qualified}; use crate::i18n::gettext; use crate::services::grid::{ DeleteAvailability, EditPolicy, EditRefusal, GridRowId, delete_availability, edit_policy, selection_hint, }; +use crate::services::share_subject::ShareSubject; +use crate::services::share_table::TableShare; use crate::ui::data_grid::{GridRequest, GridRow}; use crate::ui::export::{ExportOffer, ExportOrigin, ExportQuery, ExportSource}; @@ -28,6 +31,7 @@ impl BrowseModel { GridRequest::FollowReference(reference) => fx.output(BrowseTabOutput::FollowReference(reference)), GridRequest::FilterByValue(rule) => self.filter_strip.add_and_apply(rule), GridRequest::Toast(text) => fx.output(BrowseTabOutput::ShowToast(text)), + GridRequest::Share(_) => self.offer_share(fx), GridRequest::PendingChanged => { self.sync_pending_chrome(self.tracker.pending_count(), fx); self.sync_selection(); @@ -127,4 +131,47 @@ impl BrowseModel { target: Some(self.sql_target()), }))); } + + // From the first row, as the tab filters and sorts it, read up to the plan's rows once the sheet knows them. + pub(super) fn offer_share(&self, fx: &mut Effects) { + let Some(export) = self.table_export() else { + fx.output(BrowseTabOutput::ShowToast(gettext("Nothing to share"))); + return; + }; + let view = ExportRequest { + table: &export.table, + columns: &export.columns, + filter: &export.filter, + sort: &export.sort, + identity: &export.identity, + fields: ExportFields::Listed, + }; + let sql = self.dialect.as_deref().and_then(|dialect| { + build_view_sql(dialect, &view) + .inspect_err(|error| tracing::debug!(%error, "the table view has no SQL of its own")) + .ok() + }); + let no_sql = sql + .is_none() + .then(|| gettext("This view has no SQL of its own, so the link shares its rows without it.")); + let table = TableShare { + session: self.session.clone(), + table: export.table, + columns: export.columns, + shown: self.grid.shown_columns(), + filter: export.filter, + sort: export.sort, + identity: export.identity, + // An estimate would name a count no one made as the link's whole. + total: self.total.exact(), + }; + fx.output(BrowseTabOutput::Share(Box::new(ShareSubject { + title: String::new(), + sql: sql.unwrap_or_default(), + dialect: Some(self.session.metadata().driver_id.clone()), + rows: None, + table: Some(table), + no_sql, + }))); + } } diff --git a/linux/crates/app/src/ui/browse_tab/imp.rs b/linux/crates/app/src/ui/browse_tab/imp.rs index f97ee577ed..15631070a9 100644 --- a/linux/crates/app/src/ui/browse_tab/imp.rs +++ b/linux/crates/app/src/ui/browse_tab/imp.rs @@ -141,6 +141,9 @@ impl ObjectImpl for BrowseTab { Signal::builder("export-results") .param_types([glib::BoxedAnyObject::static_type()]) .build(), + Signal::builder("share-requested") + .param_types([glib::BoxedAnyObject::static_type()]) + .build(), Signal::builder("alert") .param_types([String::static_type(), String::static_type()]) .build(), diff --git a/linux/crates/app/src/ui/browse_tab/layout.rs b/linux/crates/app/src/ui/browse_tab/layout.rs index 886ccb4629..5e12df7429 100644 --- a/linux/crates/app/src/ui/browse_tab/layout.rs +++ b/linux/crates/app/src/ui/browse_tab/layout.rs @@ -198,6 +198,7 @@ pub(super) fn grid(tab: &BrowseTab, init: GridInit) -> DataGrid { // Ctrl+F is the filter strip's in a table tab. find: false, filter_by_value: true, + share: true, tasks: init.tasks, label: init.label, }); diff --git a/linux/crates/app/src/ui/browse_tab/mod.rs b/linux/crates/app/src/ui/browse_tab/mod.rs index fdaf96e7bd..77d10d6ad3 100644 --- a/linux/crates/app/src/ui/browse_tab/mod.rs +++ b/linux/crates/app/src/ui/browse_tab/mod.rs @@ -88,6 +88,7 @@ use super::data_grid::{DataGrid, GridSorting, KeysHandle}; use super::filter_strip::FilterStrip; use super::tab_load::{ContentLoad, FirstLoad, start_first_load}; use crate::runtime::{FailedRequests, RequestSequencer}; +use crate::services::share_subject::ShareSubject; use crate::services::tab_tracker_handle::TabTrackerHandle; use crate::ui::export::ExportOffer; @@ -383,6 +384,16 @@ impl BrowseTab { ) } + pub(crate) fn connect_share_requested(&self, f: F) -> glib::SignalHandlerId { + self.connect_closure( + "share-requested", + false, + glib::closure_local!(move |tab: &Self, payload: glib::BoxedAnyObject| { + f(tab, payload.borrow::().clone()); + }), + ) + } + /// The grid asked to open the rows a foreign key leads to. pub(crate) fn connect_follow_reference(&self, f: F) -> glib::SignalHandlerId { self.connect_closure( @@ -588,6 +599,9 @@ impl BrowseTab { BrowseTabOutput::Export(offer) => { self.emit_by_name::<()>("export-results", &[&glib::BoxedAnyObject::new(*offer)]); } + BrowseTabOutput::Share(subject) => { + self.emit_by_name::<()>("share-requested", &[&glib::BoxedAnyObject::new(*subject)]); + } BrowseTabOutput::ShowAlert { title, body } => self.emit_by_name::<()>("alert", &[&title, &body]), BrowseTabOutput::ShowToast(text) => self.emit_by_name::<()>("toast", &[&text]), BrowseTabOutput::DirtyChanged(dirty) => self.emit_by_name::<()>("dirty-changed", &[&dirty]), @@ -704,6 +718,7 @@ pub(crate) enum BrowseTabOutput { /// sort, the page size. StateChanged, Export(Box), + Share(Box), /// What a toast is too short to say, as why a save failed. ShowAlert { title: String, diff --git a/linux/crates/app/src/ui/browse_tab/tests/mod.rs b/linux/crates/app/src/ui/browse_tab/tests/mod.rs index cf28bc18e1..07a767e3d8 100644 --- a/linux/crates/app/src/ui/browse_tab/tests/mod.rs +++ b/linux/crates/app/src/ui/browse_tab/tests/mod.rs @@ -2103,3 +2103,30 @@ fn the_view_switch_keeps_its_names_in_a_1200_px_window() { ); structure.shutdown(); } + +// The view goes out whole, filter and sort included, for the sheet to read up to the plan's rows. +#[gtk4::test] +fn share_result_hands_over_the_tables_view_with_its_sql() { + let mut script = serving_table(); + script.query_bound.always(FakeReply::ok(rows(&["Ada", "Grace"]))); + let harness = Harness::open(script, []); + wait_until(WAIT, || harness.shown().len() == 2).expect("the first page"); + let subjects = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let sink = subjects.clone(); + harness + .tab() + .connect_share_requested(move |_, subject| sink.borrow_mut().push(subject)); + + harness.activate_grid("share"); + + let subjects = subjects.borrow(); + let [subject] = subjects.as_slice() else { + panic!("one share, not {}", subjects.len()); + }; + let table = subject.table.as_ref().expect("the table's view"); + assert_eq!(table.table.name, "users"); + assert!(subject.rows.is_none(), "the rows are read once the plan is known"); + assert!(subject.sql.contains("users"), "{}", subject.sql); + assert_eq!(subject.no_sql, None); + assert_eq!(subject.kind(), tablepro_account::ShareKind::Result); +} diff --git a/linux/crates/app/src/ui/browse_tab/tests/total.rs b/linux/crates/app/src/ui/browse_tab/tests/total.rs index e7501e574c..5379413f66 100644 --- a/linux/crates/app/src/ui/browse_tab/tests/total.rs +++ b/linux/crates/app/src/ui/browse_tab/tests/total.rs @@ -503,3 +503,29 @@ fn an_estimate_started_before_saving_cannot_restore_an_old_total() { assert!(count_button(&harness).is_sensitive()); assert_eq!(count_calls(&harness), 0); } + +fn shared_total(harness: &Harness) -> Option { + let subjects = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let sink = subjects.clone(); + harness + .tab() + .connect_share_requested(move |_, subject| sink.borrow_mut().push(subject)); + harness.activate_grid("share"); + let subjects = subjects.borrow(); + let [subject] = subjects.as_slice() else { + panic!("one share, not {}", subjects.len()); + }; + subject.table.as_ref().expect("the table's view").total +} + +// A link names its whole only from a count someone made; an estimate can be far off. +#[gtk4::test] +fn a_share_takes_an_exact_count_and_never_an_estimate() { + let estimated_only = Harness::open(estimated(RowCountEstimate::Approximate(5_000_000)), []); + wait_until(WAIT, || paginator(&estimated_only).contains("of about")).expect("the estimate in the paginator"); + let counted = Harness::open(estimated(RowCountEstimate::Approximate(40)), []); + wait_until(WAIT, || paginator(&counted) == "Rows 1 – 2 of 2").expect("the exact total"); + + assert_eq!(shared_total(&estimated_only), None); + assert_eq!(shared_total(&counted), Some(2)); +} diff --git a/linux/crates/app/src/ui/clipboard/clipboard_copy.rs b/linux/crates/app/src/ui/clipboard/clipboard_copy.rs index 4f4e41d5c7..4d8b99154d 100644 --- a/linux/crates/app/src/ui/clipboard/clipboard_copy.rs +++ b/linux/crates/app/src/ui/clipboard/clipboard_copy.rs @@ -150,15 +150,24 @@ pub(crate) fn copy_text(widget: &impl IsA, text: String, report: im /// Put a payload rendered already on `widget`'s clipboard, and tell /// `report`. pub(crate) fn copy_payload(widget: &impl IsA, payload: ClipboardPayload, report: impl Fn(&str)) { - if holds_nul(&payload.text) { - return report(&ClipboardError::ContainsNul.message()); - } - match write(&widget.as_ref().clipboard(), payload) { + match put_payload(widget, payload) { Ok(()) => report(&gettext("Copied to clipboard")), Err(error) => report(&error.message()), } } +// For a caller that words the outcome itself. +pub(crate) fn put_text(widget: &impl IsA, text: String) -> Result<(), ClipboardError> { + put_payload(widget, ClipboardPayload::plain(text)) +} + +fn put_payload(widget: &impl IsA, payload: ClipboardPayload) -> Result<(), ClipboardError> { + if holds_nul(&payload.text) { + return Err(ClipboardError::ContainsNul); + } + write(&widget.as_ref().clipboard(), payload) +} + fn copy_error_text(error: &CopyError) -> String { match error { CopyError::Encode(EncodeError::Undecodable { column }) => gettext_f( diff --git a/linux/crates/app/src/ui/clipboard/mod.rs b/linux/crates/app/src/ui/clipboard/mod.rs index 26a11047d2..a161b1c94c 100644 --- a/linux/crates/app/src/ui/clipboard/mod.rs +++ b/linux/crates/app/src/ui/clipboard/mod.rs @@ -7,7 +7,7 @@ mod clipboard_payload; mod clipboard_writer; mod copy_renderer; -pub(crate) use clipboard_copy::{copy_payload, copy_rows, copy_text}; +pub(crate) use clipboard_copy::{copy_payload, copy_rows, copy_text, put_text}; pub(crate) use clipboard_format::{CELLS_MIME_TYPE, ClipboardFormat}; pub(crate) use clipboard_payload::ClipboardPayload; pub(crate) use clipboard_writer::ClipboardError; diff --git a/linux/crates/app/src/ui/data_grid/copy/mod.rs b/linux/crates/app/src/ui/data_grid/copy/mod.rs index 83e432fc9d..80d0cd91f0 100644 --- a/linux/crates/app/src/ui/data_grid/copy/mod.rs +++ b/linux/crates/app/src/ui/data_grid/copy/mod.rs @@ -4,6 +4,7 @@ use gtk4::prelude::*; use gtk4::{self as gtk, glib}; use tablepro_core::column::{ColumnInfo, ResultColumn}; use tablepro_core::edit::CellInput; +use tablepro_core::export::ResultExtent; use tablepro_core::{FilterRule, Value}; use tablepro_linux_platform::settings::RowCopyFormat; @@ -12,6 +13,7 @@ use super::selection::Resolved; use super::{DataGrid, GridRequest, GridRow, RowJsonRequest, present_row_json}; use crate::i18n::gettext; use crate::services::grid::{CopyScope, GridColumn, GridRowId, RowSnapshot, cell_filter_rule, copy_scope}; +use crate::services::share_subject::SharedRows; use crate::ui::clipboard::{CopyKind, CopyRequest, InClauseRows, InsertCopy, InsertRow}; use crate::ui::export::ExportSource; use crate::ui::filter_strip::FilterVocabulary; @@ -60,6 +62,9 @@ pub fn install_actions(grid: &DataGrid) { add(grid, "export", |grid| { grid.request(GridRequest::Export(export_source(grid))) }); + add(grid, "share", |grid| { + grid.request(GridRequest::Share(shared_rows(grid))) + }); add(grid, "filter-by-value", |grid| filter_by_value(grid, false)); add(grid, "exclude-value", |grid| filter_by_value(grid, true)); } @@ -84,6 +89,11 @@ pub fn refresh_actions(grid: &DataGrid, target: Option<&Resolved>) { enable(grid, "copy-column-name", cell.is_some()); enable(grid, "show-row-json", target.and_then(json_row).is_some()); enable(grid, "export", grid.row_count() > 0); + enable( + grid, + "share", + grid.row_count() > 0 && grid.config().is_some_and(|config| config.share), + ); for (name, exclude) in [("filter-by-value", false), ("exclude-value", true)] { let rule = cell.and_then(|(row, column)| value_rule(grid, row, *column, exclude)); enable(grid, name, rule.is_some()); @@ -93,15 +103,17 @@ pub fn refresh_actions(grid: &DataGrid, target: Option<&Resolved>) { /// The rows the grid shows, pending edits included, under the columns /// on screen in their order. pub fn export_source(grid: &DataGrid) -> ExportSource { - let shown = ShownColumns::of(grid); - let tracked = grid.tracked(); - ExportSource::Rows { - columns: shown.columns.clone(), - rows: grid - .shown_rows() - .iter() - .map(|row| shown.project(tracked.snapshot(row))) - .collect(), + let (columns, rows) = shown_rows(grid, &grid.shown_rows()); + ExportSource::Rows { columns, rows } +} + +// What a share link takes: the rows an export of the shown rows would write. +pub fn shared_rows(grid: &DataGrid) -> SharedRows { + let (columns, rows) = shown_rows(grid, &grid.shown_rows()); + SharedRows { + columns, + extent: ResultExtent::complete(rows.len() as u64), + rows, } } diff --git a/linux/crates/app/src/ui/data_grid/grid_config.rs b/linux/crates/app/src/ui/data_grid/grid_config.rs index af32a0200a..eb478c33aa 100644 --- a/linux/crates/app/src/ui/data_grid/grid_config.rs +++ b/linux/crates/app/src/ui/data_grid/grid_config.rs @@ -63,6 +63,8 @@ pub struct GridConfig { pub find: bool, /// The host can add a filter rule from a cell's value. pub filter_by_value: bool, + // The host can share the rows as a link: an editor's results and a table tab's rows. + pub share: bool, pub tasks: Tasks, /// What a screen reader calls the grid. pub label: String, diff --git a/linux/crates/app/src/ui/data_grid/grid_menu.rs b/linux/crates/app/src/ui/data_grid/grid_menu.rs index af035cf326..3898bf7bfd 100644 --- a/linux/crates/app/src/ui/data_grid/grid_menu.rs +++ b/linux/crates/app/src/ui/data_grid/grid_menu.rs @@ -184,6 +184,9 @@ fn cell_menu(grid: &DataGrid, references: &gio::Menu, expressions: &gio::Menu) - export.set_attribute_value("accel", Some(&key.to_variant())); } let rows = section([export]); + if config.as_ref().is_some_and(|config| config.share) { + rows.append_item(&item(&gettext("_Share Result…"), "grid.share")); + } if editable { rows.append_item(&item(&gettext("_Insert Row"), "grid.insert-row")); rows.append_item(&item(&gettext("D_uplicate"), "grid.duplicate-rows")); diff --git a/linux/crates/app/src/ui/data_grid/grid_request.rs b/linux/crates/app/src/ui/data_grid/grid_request.rs index aaf3436756..351b7e2df2 100644 --- a/linux/crates/app/src/ui/data_grid/grid_request.rs +++ b/linux/crates/app/src/ui/data_grid/grid_request.rs @@ -1,6 +1,7 @@ use tablepro_core::FilterRule; use tablepro_core::browse::RowReference; +use crate::services::share_subject::SharedRows; use crate::ui::export::ExportSource; /// What a grid asks of its host: only what the grid cannot do itself. @@ -9,6 +10,7 @@ pub enum GridRequest { /// Read the rows again in this order, `None` in the server's own. Sort(Option<(usize, bool)>), Export(ExportSource), + Share(SharedRows), FollowReference(RowReference), FilterByValue(FilterRule), Toast(String), diff --git a/linux/crates/app/src/ui/data_grid/mod.rs b/linux/crates/app/src/ui/data_grid/mod.rs index e8c3c94ad7..a72f1a5384 100644 --- a/linux/crates/app/src/ui/data_grid/mod.rs +++ b/linux/crates/app/src/ui/data_grid/mod.rs @@ -379,6 +379,10 @@ impl DataGrid { copy::export_source(self) } + pub(crate) fn shared_rows(&self) -> crate::services::share_subject::SharedRows { + copy::shared_rows(self) + } + /// Put the sort on the headers without asking for the rows again, as /// a restored tab does. pub fn set_sort(&self, sort: Option<(usize, bool)>) { diff --git a/linux/crates/app/src/ui/data_grid/test_grid.rs b/linux/crates/app/src/ui/data_grid/test_grid.rs index 17610f1e67..0e711320b7 100644 --- a/linux/crates/app/src/ui/data_grid/test_grid.rs +++ b/linux/crates/app/src/ui/data_grid/test_grid.rs @@ -111,6 +111,7 @@ pub(crate) struct GridSpec { pub layout: Option, pub find: bool, pub filter_by_value: bool, + pub share: bool, pub policy: Option, pub references: Option, pub dialect: Option, @@ -130,6 +131,7 @@ impl GridSpec { layout: None, find: false, filter_by_value: true, + share: false, policy: None, references: None, dialect: None, @@ -144,6 +146,7 @@ impl GridSpec { sorting: GridSorting::Client, find: true, filter_by_value: false, + share: true, ..Self::table(columns) } } @@ -235,6 +238,7 @@ impl Grid { table: spec.table, find: spec.find, filter_by_value: spec.filter_by_value, + share: spec.share, tasks: runtime.tasks(), label: "test grid".to_owned(), }; diff --git a/linux/crates/app/src/ui/data_grid/tests/menus.rs b/linux/crates/app/src/ui/data_grid/tests/menus.rs index 5c8c0231cf..9b7c23d149 100644 --- a/linux/crates/app/src/ui/data_grid/tests/menus.rs +++ b/linux/crates/app/src/ui/data_grid/tests/menus.rs @@ -403,3 +403,44 @@ fn the_grid_takes_its_menus_with_it() { "a menu outlived its grid" ); } + +#[gtk4::test] +fn a_grid_whose_host_shares_offers_share_result_with_the_columns_on_screen_in_their_order() { + let table = two_text_rows(); + let shown = Grid::build(GridSpec::results(two_text_columns()), results(&two_text_values())); + shown.grid.set_column_visible(0, false); + drain_main_context(); + + assert!(!action_names(&cell_menu(&table)).contains(&"grid.share".to_owned())); + let actions = action_names(&cell_menu(&shown)); + let export = actions.iter().position(|action| action == "grid.export"); + let share = actions.iter().position(|action| action == "grid.share"); + assert_eq!( + share, + export.map(|export| export + 1), + "Share Result follows Export: {actions:?}" + ); + assert_access_keys(&cell_menu(&shown)); + assert!(shown.is_enabled("share")); + + shown.activate("share"); + + let shared = shown.take_requests().into_iter().find_map(|request| match request { + crate::ui::data_grid::GridRequest::Share(rows) => Some(rows), + _ => None, + }); + let shared = shared.expect("the grid asked its host to share"); + assert_eq!( + shared + .columns + .iter() + .map(|column| column.name.as_str()) + .collect::>(), + ["name"] + ); + assert_eq!(shared.total(), 2); + assert_eq!( + shared.rows.iter().map(|row| row.to_values()).collect::>(), + [vec![Value::Text("A".into())], vec![Value::Text("B".into())]] + ); +} diff --git a/linux/crates/app/src/ui/editor/editor_actions.rs b/linux/crates/app/src/ui/editor/editor_actions.rs index b13a22e02a..85ed3480c0 100644 --- a/linux/crates/app/src/ui/editor/editor_actions.rs +++ b/linux/crates/app/src/ui/editor/editor_actions.rs @@ -32,6 +32,8 @@ impl SqlEditor { entry("run-statement", SqlEditor::run_at_cursor), entry("cancel", SqlEditor::close_popup_or_stop), entry("format", SqlEditor::format), + entry("share-query", SqlEditor::share_query), + entry("share-result", SqlEditor::share_shown_result), entry("toggle-comment", SqlEditor::toggle_comment), entry("find", |editor| editor.imp().find_bar.open(false)), entry("find-replace", |editor| editor.imp().find_bar.open(true)), diff --git a/linux/crates/app/src/ui/editor/imp.rs b/linux/crates/app/src/ui/editor/imp.rs index 1d30be8356..233f8e35d7 100644 --- a/linux/crates/app/src/ui/editor/imp.rs +++ b/linux/crates/app/src/ui/editor/imp.rs @@ -146,6 +146,9 @@ impl ObjectImpl for SqlEditor { Signal::builder("export-results") .param_types([glib::BoxedAnyObject::static_type()]) .build(), + Signal::builder("share-requested") + .param_types([glib::BoxedAnyObject::static_type()]) + .build(), Signal::builder("transaction-changed") .param_types([bool::static_type()]) .build(), diff --git a/linux/crates/app/src/ui/editor/mod.rs b/linux/crates/app/src/ui/editor/mod.rs index 4c3d37e30c..801e1e07aa 100644 --- a/linux/crates/app/src/ui/editor/mod.rs +++ b/linux/crates/app/src/ui/editor/mod.rs @@ -68,6 +68,7 @@ use super::result_pane::ResultGridDeps; use super::write_confirmation::{self, WriteConfirmation}; use crate::services::active_session::ActiveSession; use crate::services::history_service::HistoryService; +use crate::services::share_subject::{ShareSubject, SharedRows}; use crate::services::snippet_library::SnippetLibrary; use crate::workspace::WorkOutcome; @@ -389,6 +390,16 @@ impl SqlEditor { ) } + pub(crate) fn connect_share_requested(&self, f: F) -> glib::SignalHandlerId { + self.connect_closure( + "share-requested", + false, + glib::closure_local!(move |editor: &Self, payload: glib::BoxedAnyObject| { + f(editor, payload.borrow::().clone()); + }), + ) + } + pub fn connect_transaction_changed(&self, f: F) -> glib::SignalHandlerId { self.connect_closure( "transaction-changed", @@ -665,6 +676,7 @@ impl SqlEditor { fn grid_request(&self, index: u32, request: GridRequest) { match request { GridRequest::Export(shown) => self.offer_export(index, shown), + GridRequest::Share(rows) => self.offer_share(index, rows), GridRequest::Toast(text) => self.emit_by_name::<()>("toast", &[&text]), GridRequest::PendingChanged => self.on_rows_pending_changed(), GridRequest::Sort(_) | GridRequest::FollowReference(_) | GridRequest::FilterByValue(_) => {} @@ -947,6 +959,78 @@ impl SqlEditor { }) } + // The selection, else the whole text; the workspace names it after the tab. + pub(crate) fn share_query(&self) { + let buffer = self.buffer(); + let text = buffer_text(&buffer); + let selection = buffer.selection_bounds().map(|(start, end)| { + let start = usize::try_from(start.offset()).unwrap_or_default(); + let end = usize::try_from(end.offset()).unwrap_or_default(); + start..end + }); + let Some(scoped) = run_scope::for_run(&text, selection) else { + let message = crate::i18n::gettext("There is nothing in the editor to share."); + self.emit_by_name::<()>("toast", &[&message]); + return; + }; + self.request_share(ShareSubject::query(String::new(), scoped.text, self.driver_id())); + } + + pub(crate) fn share_shown_result(&self) { + let results = &self.imp().results; + let grid = results + .selected() + .and_then(|index| Some((index, results.kept_grid(index)?))) + .filter(|(_, grid)| grid.row_count() > 0); + match grid { + Some((index, grid)) => self.offer_share(index, grid.shared_rows()), + None => { + let message = crate::i18n::gettext("Run a query that returns rows to share its result."); + self.emit_by_name::<()>("toast", &[&message]); + } + } + } + + // Named as the results list names it: Hide SQL keeps the statement off the link, so its title may not carry it. + fn offer_share(&self, index: u32, mut rows: SharedRows) { + let Ok(position) = usize::try_from(index) else { + return; + }; + let subject = { + let log = self.imp().log.borrow(); + let Some(entry) = log.as_ref().and_then(|log| log.entries().get(position)) else { + return; + }; + let EntryKind::ResultSet(result) = &entry.kind else { + return; + }; + // The run's limits can cut a result the server never counted, which the link then says. + rows.extent = tablepro_core::export::ResultExtent { + held: result.summary.retained.max(rows.rows.len() as u64), + total: result.summary.total_rows, + cut: result.summary.is_truncated(), + }; + ShareSubject { + title: result.summary.tab_label(position), + sql: result.statement.as_str().to_owned(), + dialect: self.driver_id(), + rows: Some(rows), + table: None, + no_sql: None, + } + }; + self.request_share(subject); + } + + fn request_share(&self, subject: ShareSubject) { + self.emit_by_name::<()>("share-requested", &[&glib::BoxedAnyObject::new(subject)]); + } + + fn driver_id(&self) -> Option { + let session = self.deps()?.session.get()?; + Some(session.metadata().driver_id.clone()) + } + fn install_drop_target(&self) { let target = gtk4::DropTarget::new(gio::File::static_type(), gtk4::gdk::DragAction::COPY); let weak = self.downgrade(); diff --git a/linux/crates/app/src/ui/editor/tests.rs b/linux/crates/app/src/ui/editor/tests.rs index 1061d9ff82..c22a742521 100644 --- a/linux/crates/app/src/ui/editor/tests.rs +++ b/linux/crates/app/src/ui/editor/tests.rs @@ -3448,3 +3448,82 @@ fn the_divider_keeps_the_editor_in_view() { assert!(harness.editor.imp().source_view.height() >= 120); assert!(results.height() > 0); } + +fn shares(harness: &Harness) -> std::rc::Rc>> { + let heard: std::rc::Rc>> = std::rc::Rc::default(); + let sink = heard.clone(); + harness + .editor + .connect_share_requested(move |_, subject| sink.borrow_mut().push(subject)); + heard +} + +#[gtk4::test] +fn share_query_takes_the_selection_else_the_whole_text() { + let harness = editor_with(answering(), "SELECT 1;\nSELECT 2;"); + let heard = shares(&harness); + let buffer = harness.editor.buffer(); + buffer.select_range(&buffer.iter_at_offset(10), &buffer.iter_at_offset(18)); + + harness.editor.share_query(); + buffer.place_cursor(&buffer.start_iter()); + harness.editor.share_query(); + + let heard = heard.borrow(); + assert_eq!( + heard.iter().map(|subject| subject.sql.as_str()).collect::>(), + ["SELECT 2", "SELECT 1;\nSELECT 2;"] + ); + assert!( + heard + .iter() + .all(|subject| subject.rows.is_none() && subject.title.is_empty()) + ); + assert!(heard.iter().all(|subject| subject.dialect.is_some())); +} + +#[gtk4::test] +fn an_empty_editor_shares_nothing_and_says_so() { + let harness = editor_with(answering(), " \n"); + let heard = shares(&harness); + let toasts = SignalLog::connect(&harness.editor, "toast", |values| { + values[1].get::().expect("a message") + }); + + harness.editor.share_query(); + harness.editor.share_shown_result(); + + assert!(heard.borrow().is_empty()); + assert_eq!( + toasts.take(), + [ + "There is nothing in the editor to share.", + "Run a query that returns rows to share its result.", + ] + ); +} + +#[gtk4::test] +fn share_result_shares_the_rows_and_the_statement_in_front() { + let mut runs = Replies::default(); + runs.always(result_set(3, None, Truncation::Complete)); + let harness = editor_with(runs, "SELECT n FROM numbers"); + let heard = shares(&harness); + run_and_wait(&harness); + + harness.editor.share_shown_result(); + + let heard = heard.borrow(); + let [subject] = heard.as_slice() else { + panic!("one share asked for: {}", heard.len()); + }; + assert_eq!(subject.sql, "SELECT n FROM numbers"); + assert_eq!(subject.title, "Result 1 (3)"); + assert!( + !subject.title.contains("SELECT"), + "the title carries the SQL Hide SQL keeps back" + ); + let rows = subject.rows.as_ref().expect("the result's rows"); + assert_eq!(rows.total(), 3); + assert_eq!(rows.columns[0].name, "n"); +} diff --git a/linux/crates/app/src/ui/error_text/account.rs b/linux/crates/app/src/ui/error_text/account.rs index 898268f292..df2ca8a157 100644 --- a/linux/crates/app/src/ui/error_text/account.rs +++ b/linux/crates/app/src/ui/error_text/account.rs @@ -1,6 +1,7 @@ use tablepro_account::{AccountError, EntitlementError, OfflineFileError}; use crate::i18n::{gettext, gettext_f, ngettext_f}; +use crate::services::account_service::AccountStart; // The OAuth error a person gets by pressing Cancel on the confirmation screen. const ACCESS_DENIED: &str = "access_denied"; @@ -37,7 +38,9 @@ pub fn account_error_message(error: &AccountError) -> String { AccountError::OtherAccount => gettext( "This file was made for another account. Make one with the account signed in here, or sign out first.", ), - AccountError::Refused { status, code, .. } => refused_message(*status, code), + AccountError::Refused { status, code, .. } => { + share_refusal(error.code()).unwrap_or_else(|| refused_message(*status, code)) + } AccountError::RateLimited { retry_after: Some(wait), } => { @@ -64,6 +67,75 @@ pub fn account_error_message(error: &AccountError) -> String { } } +pub fn account_unavailable_message(start: &AccountStart) -> Option { + match start { + AccountStart::Starting | AccountStart::Ready(_) => None, + AccountStart::NoMachineId(detail) => Some(gettext_f( + "TablePro accounts need this computer’s machine ID, which could not be read: {detail}", + &[("detail", detail)], + )), + AccountStart::Misconfigured(detail) => Some(gettext_f( + "This development build’s account settings are not valid: {detail}", + &[("detail", detail)], + )), + AccountStart::Failed(error) => Some(account_error_message(error)), + } +} + +// The share sheet's own words for a failed create, the share plan's section 6. +pub fn share_error_message(error: &AccountError) -> String { + match (error, error.code()) { + (AccountError::SignedOut, _) => gettext("Sign in to your TablePro account to share links."), + (AccountError::Unreachable(_), _) => offline_message(), + (AccountError::RateLimited { .. }, _) => gettext("Too many links just now. Try again in a moment."), + ( + _, + "account.email_unverified" + | "account.pro_required" + | "account.sharing_disabled" + | "account.team_sharing_disabled" + | "account.seat_required" + | "account.share_limit_reached" + | "account.snapshot_too_large", + ) => share_refusal(error.code()).unwrap_or_default(), + _ => gettext("The link couldn’t be created. Try again."), + } +} + +pub fn shared_link_message(error: &AccountError) -> String { + match (error, error.code()) { + (AccountError::Unreachable(_), _) => offline_message(), + (_, "account.not_found") => gettext("This shared link is no longer available."), + _ => account_error_message(error), + } +} + +fn offline_message() -> String { + gettext("You appear to be offline. Try again once you’re connected.") +} + +fn share_refusal(code: &str) -> Option { + Some(match code { + "account.email_unverified" => gettext("Verify your email address to share links."), + "account.pro_required" => gettext("This option needs TablePro Pro."), + "account.sharing_disabled" => gettext("Sharing is turned off for this account."), + "account.team_sharing_disabled" => gettext("Public links are turned off for this team."), + "account.seat_required" => gettext("A team link needs a seat on the team."), + "account.share_limit_reached" => { + gettext("You have reached your plan’s limit of live links. Revoke one to share another.") + } + "account.share_revoked" => gettext("This link was revoked."), + "account.share_removed" => gettext("TablePro removed this link."), + "account.validation_failed" => { + gettext("The account service did not accept what was sent. Check the fields and try again.") + } + "account.snapshot_too_large" => gettext("This result is too large to share."), + "account.share_password_required" => gettext("This link is password protected."), + "account.share_password_wrong" => gettext("That password is not correct."), + _ => return None, + }) +} + pub fn offline_file_message(error: &OfflineFileError) -> String { match error { OfflineFileError::Read { .. } => gettext("The offline file could not be read."), @@ -157,6 +229,17 @@ mod tests { refused(400, "revoke"), refused(503, "unavailable"), refused(422, "validation_failed"), + refused(403, "email_unverified"), + refused(403, "pro_required"), + refused(403, "sharing_disabled"), + refused(403, "team_sharing_disabled"), + refused(403, "seat_required"), + refused(409, "share_limit_reached"), + refused(409, "share_revoked"), + refused(409, "share_removed"), + refused(413, "snapshot_too_large"), + refused(401, "share_password_required"), + refused(401, "share_password_wrong"), AccountError::Entitlement(EntitlementError::Machine), AccountError::Entitlement(EntitlementError::Expired(Utc::now())), AccountError::Entitlement(EntitlementError::NotYetValid(Utc::now())), @@ -236,4 +319,77 @@ mod tests { "The account service is busy. Try again in a few minutes." ); } + + #[test] + fn a_failed_share_reads_in_the_share_plans_words() { + let cases = [ + ( + AccountError::SignedOut, + "Sign in to your TablePro account to share links.", + ), + ( + refused(403, "email_unverified"), + "Verify your email address to share links.", + ), + (refused(403, "pro_required"), "This option needs TablePro Pro."), + ( + refused(403, "sharing_disabled"), + "Sharing is turned off for this account.", + ), + ( + refused(403, "team_sharing_disabled"), + "Public links are turned off for this team.", + ), + (refused(422, "snapshot_too_large"), "This result is too large to share."), + ( + AccountError::RateLimited { retry_after: None }, + "Too many links just now. Try again in a moment.", + ), + ( + AccountError::Unreachable("dns".to_owned()), + "You appear to be offline. Try again once you’re connected.", + ), + ( + refused(422, "validation_failed"), + "The link couldn’t be created. Try again.", + ), + (refused(500, "internal"), "The link couldn’t be created. Try again."), + ( + AccountError::Protocol("secret detail".to_owned()), + "The link couldn’t be created. Try again.", + ), + ]; + + for (error, expected) in cases { + assert_eq!(share_error_message(&error), expected, "{error:?}"); + } + } + + #[test] + fn a_shared_link_that_will_not_open_says_why() { + assert_eq!( + shared_link_message(&refused(404, "not_found")), + "This shared link is no longer available." + ); + assert_eq!( + shared_link_message(&refused(401, "share_password_wrong")), + "That password is not correct." + ); + assert_eq!( + shared_link_message(&refused(401, "share_password_required")), + "This link is password protected." + ); + assert_eq!( + shared_link_message(&AccountError::Unreachable("dns".to_owned())), + "You appear to be offline. Try again once you’re connected." + ); + } + + #[test] + fn an_account_that_did_not_start_says_why_and_one_that_did_says_nothing() { + let missing = account_unavailable_message(&AccountStart::NoMachineId("no /etc/machine-id".to_owned())); + + assert!(missing.is_some_and(|message| message.contains("/etc/machine-id"))); + assert_eq!(account_unavailable_message(&AccountStart::Starting), None); + } } diff --git a/linux/crates/app/src/ui/error_text/mod.rs b/linux/crates/app/src/ui/error_text/mod.rs index 5ed43fc8e6..28283b7339 100644 --- a/linux/crates/app/src/ui/error_text/mod.rs +++ b/linux/crates/app/src/ui/error_text/mod.rs @@ -26,7 +26,9 @@ mod tls_remedy; mod transfer; mod unsupported; -pub use account::{account_error_message, offline_file_message}; +pub use account::{ + account_error_message, account_unavailable_message, offline_file_message, share_error_message, shared_link_message, +}; pub use connection_url::connection_url_message; pub use ddl::{build_error_text, refusal_text, save_blocker_text}; pub use driver::{config_message, driver_message}; diff --git a/linux/crates/app/src/ui/key_tab/mod.rs b/linux/crates/app/src/ui/key_tab/mod.rs index 2a80fb94e0..e1dd714965 100644 --- a/linux/crates/app/src/ui/key_tab/mod.rs +++ b/linux/crates/app/src/ui/key_tab/mod.rs @@ -275,6 +275,7 @@ fn key_grid(key: &str, settings: Rc, tasks: Tasks) -> DataGrid { table: None, find: true, filter_by_value: false, + share: false, tasks, label: key.to_owned(), }); @@ -666,6 +667,7 @@ impl Inner { GridRequest::Sort(_) | GridRequest::FollowReference(_) | GridRequest::FilterByValue(_) + | GridRequest::Share(_) | GridRequest::PendingChanged => {} } } diff --git a/linux/crates/app/src/ui/mod.rs b/linux/crates/app/src/ui/mod.rs index 40b0673dda..e835aeaf2e 100644 --- a/linux/crates/app/src/ui/mod.rs +++ b/linux/crates/app/src/ui/mod.rs @@ -47,6 +47,7 @@ pub(crate) mod safe_mode; mod saved_queries_dialog; mod session_target; mod session_window; +mod share_dialog; mod shell; mod source_dialog; mod sql_import_dialog; diff --git a/linux/crates/app/src/ui/preferences_dialog/account_page.rs b/linux/crates/app/src/ui/preferences_dialog/account_page.rs index b1ee1ce06f..bcdbf48c9b 100644 --- a/linux/crates/app/src/ui/preferences_dialog/account_page.rs +++ b/linux/crates/app/src/ui/preferences_dialog/account_page.rs @@ -20,7 +20,7 @@ use super::device_limit_dialog::DeviceLimitDialog; use crate::i18n::{gettext, gettext_f}; use crate::services::account_service::{AccountHandle, AccountStart}; use crate::services::telemetry::Telemetry; -use crate::ui::error_text::{account_error_message, offline_file_message}; +use crate::ui::error_text::{account_error_message, account_unavailable_message, offline_file_message}; use crate::ui::icons; const CANCEL: &str = "cancel"; @@ -537,18 +537,7 @@ impl AccountPage { let imp = self.imp(); let group = imp.account_group.get(); let start = imp.deps.get().map(|deps| deps.handle.start.borrow().clone()); - let unavailable = match &start { - None | Some(AccountStart::Starting | AccountStart::Ready(_)) => None, - Some(AccountStart::NoMachineId(detail)) => Some(gettext_f( - "TablePro accounts need this computer’s machine ID, which could not be read: {detail}", - &[("detail", detail)], - )), - Some(AccountStart::Misconfigured(detail)) => Some(gettext_f( - "This development build’s account settings are not valid: {detail}", - &[("detail", detail)], - )), - Some(AccountStart::Failed(error)) => Some(account_error_message(error)), - }; + let unavailable = start.as_ref().and_then(account_unavailable_message); if let Some(reason) = unavailable { self.add(&group, &warning_row(&gettext("Accounts Unavailable"), &reason)); return; @@ -1378,7 +1367,7 @@ mod tests { Some("Use your plan on this computer. Everything else works without an account.") ); assert!(!imp.plan_group.is_visible()); - assert!(!imp.features_group.is_visible()); + assert_eq!(harness.titles(&imp.features_group), ["Pro Options for Shared Links"]); assert!(!imp.devices_group.is_visible()); assert!(!imp.teams_group.is_visible()); assert_eq!( @@ -1543,7 +1532,11 @@ mod tests { assert!(imp.features_group.is_visible()); assert_eq!(imp.features_group.title(), "Features"); - assert_eq!(harness.titles(&imp.features_group), ["Data Rewind", "Result Charts"]); + // The page's own render lists the features Linux has, Pro's share options among them. + assert_eq!( + harness.titles(&imp.features_group), + ["Pro Options for Shared Links", "Data Rewind", "Result Charts"] + ); assert_eq!(marked("Data Rewind"), (true, false)); assert_eq!(marked("Result Charts"), (false, true)); harness.audit(); diff --git a/linux/crates/app/src/ui/preferences_dialog/account_view.rs b/linux/crates/app/src/ui/preferences_dialog/account_view.rs index 965eb92881..2f44b6e390 100644 --- a/linux/crates/app/src/ui/preferences_dialog/account_view.rs +++ b/linux/crates/app/src/ui/preferences_dialog/account_view.rs @@ -13,7 +13,7 @@ const EXPIRING_SOON: TimeDelta = TimeDelta::days(3); const OWNER: &str = "owner"; // product.md's codes, and whether TablePro for Linux has the feature yet. -const FEATURES: [(&str, bool); 10] = [ +const FEATURES: [(&str, bool); 11] = [ ("icloud_sync", false), ("encrypted_export", false), ("env_var_references", false), @@ -24,6 +24,8 @@ const FEATURES: [(&str, bool); 10] = [ ("data_rewind", false), ("team_catalog", false), ("team_library", false), + // Every account shares links; the plan only lifts the Free limits. + ("shared_links", true), ]; #[derive(Default)] @@ -641,6 +643,7 @@ fn feature_name(code: &str) -> String { "data_rewind" => gettext("Data Rewind"), "team_catalog" => gettext("Team Catalog"), "team_library" => gettext("Team Library"), + "shared_links" => gettext("Pro Options for Shared Links"), other => other.to_owned(), } } diff --git a/linux/crates/app/src/ui/result_pane/mod.rs b/linux/crates/app/src/ui/result_pane/mod.rs index c8bc659026..be31fa900a 100644 --- a/linux/crates/app/src/ui/result_pane/mod.rs +++ b/linux/crates/app/src/ui/result_pane/mod.rs @@ -88,6 +88,7 @@ pub(crate) fn result_set_page( table, find: true, filter_by_value: false, + share: true, tasks: deps.tasks.clone(), label: name.to_owned(), }); diff --git a/linux/crates/app/src/ui/session_window/imp.rs b/linux/crates/app/src/ui/session_window/imp.rs index 8d5d76a60e..6adfbd2823 100644 --- a/linux/crates/app/src/ui/session_window/imp.rs +++ b/linux/crates/app/src/ui/session_window/imp.rs @@ -108,7 +108,7 @@ pub struct SessionWindow { pub(super) opened_for_file: Cell, // Read while no relational session was in front; the next one the // window adopts opens them. - pub(super) waiting_scripts: RefCell>, + pub(super) waiting_scripts: RefCell>, /// Reads which filesystem a database file is on. `None` reads the /// real one; a test stands in for a network share. pub(super) classify_location: Cell>, diff --git a/linux/crates/app/src/ui/session_window/mod.rs b/linux/crates/app/src/ui/session_window/mod.rs index 972836dce2..4c3031bbd8 100644 --- a/linux/crates/app/src/ui/session_window/mod.rs +++ b/linux/crates/app/src/ui/session_window/mod.rs @@ -69,7 +69,7 @@ pub(super) use self::picker_page::PickerPage; use self::resolve_file_identity::{FileResolveError, FileTarget, ResolvedFile, resolve_file_blocking}; use self::session_page::{FailedConnect, OpenSession, PendingConnect, SessionPage, TakenFailure, source_key}; use self::session_window_command::{AttemptError, ConnectFailure, Connected, SessionWindowCommand}; -pub(crate) use self::session_window_input::{LibraryEdit, MovedTab, ScriptInput, SessionWindowInput}; +pub(crate) use self::session_window_input::{LibraryEdit, MovedTab, ScriptInput, SessionWindowInput, WaitingScript}; use crate::application::{AppServices, WindowHost, WindowLaunch}; use crate::runtime::{DeliverInput, InputSender}; use crate::services::connection_link::without_password; @@ -1237,6 +1237,10 @@ impl SessionWindow { match input { ScriptInput::Open(file) => self.on_open_script(file), ScriptInput::Loaded { file, text, target } => self.on_script_loaded(file, text, target), + ScriptInput::Shared { title, sql } => { + let target = self.relational_front().and_then(|workspace| workspace.key()); + self.place_waiting_script(WaitingScript::Shared { title, sql }, target); + } ScriptInput::For { key, scripts } => self.on_scripts_for(key, scripts), ScriptInput::DropWaiting => { self.imp().waiting_scripts.borrow_mut().clear(); @@ -1245,22 +1249,23 @@ impl SessionWindow { } } + fn relational_front(&self) -> Option { + self.workspace() + .filter(|workspace| workspace.data_model() == Some(DataModel::Relational)) + } + // The session in front now is the one it goes to, even if another comes forward during a slow read. fn on_open_script(&self, file: gio::File) { let Some(input) = self.input() else { return; }; - let target = self - .workspace() - .filter(|workspace| workspace.data_model() == Some(DataModel::Relational)) - .and_then(|workspace| workspace.key()); + let target = self.relational_front().and_then(|workspace| workspace.key()); glib::spawn_future_local(async move { let text = crate::ui::editor::load_text(&file).await; input.deliver(SessionWindowInput::Script(ScriptInput::Loaded { file, text, target })); }); } - // A script opens in the relational session in front and is never run. fn on_script_loaded(&self, file: gio::File, text: Result, target: Option) { let text = match text { Ok(text) => text, @@ -1276,6 +1281,11 @@ impl SessionWindow { if self.focus_bound_tab(&file) { return; } + self.place_waiting_script(WaitingScript::File { file, text }, target); + } + + // A script opens in the relational session in front and is never run. + fn place_waiting_script(&self, script: WaitingScript, target: Option) { let chosen = target.and_then(|key| { self.workspaces() .into_iter() @@ -1286,24 +1296,24 @@ impl SessionWindow { .filter(|workspace| workspace.data_model() == Some(DataModel::Relational)) .and_then(|workspace| workspace.sender()); match front { - Some(input) => input.deliver(WorkspaceInput::OpenScript { file, text }), - None if self.page() != SessionPage::Shell => self.wait_for_session(file, text), - None => self.ask_elsewhere(vec![(file, text)]), + Some(input) => input.deliver(script_input(script)), + None if self.page() != SessionPage::Shell => self.wait_for_session(script), + None => self.ask_elsewhere(vec![script]), } } - fn wait_for_session(&self, file: gio::File, text: String) { + fn wait_for_session(&self, script: WaitingScript) { { let mut waiting = self.imp().waiting_scripts.borrow_mut(); - waiting.retain(|(kept, _)| !kept.equal(&file)); - waiting.push((file, text)); + waiting.retain(|kept| !kept.same_as(&script)); + waiting.push(script); } self.show_waiting_scripts(); } // A session that holds keys or documents runs no SQL, so the script // asks for a connection in a window of its own. - fn ask_elsewhere(&self, scripts: Vec<(gio::File, String)>) { + fn ask_elsewhere(&self, scripts: Vec) { if scripts.is_empty() { return; } @@ -1316,11 +1326,14 @@ impl SessionWindow { tracing::warn!("no window to open a SQL file in"); return; }; - for (file, text) in scripts { - window.send(SessionWindowInput::Script(ScriptInput::Loaded { - file, - text: Ok(text), - target: None, + for script in scripts { + window.send(SessionWindowInput::Script(match script { + WaitingScript::File { file, text } => ScriptInput::Loaded { + file, + text: Ok(text), + target: None, + }, + WaitingScript::Shared { title, sql } => ScriptInput::Shared { title, sql }, })); } } @@ -1357,7 +1370,7 @@ impl SessionWindow { } // The session left between the hand-over and now: they wait here instead, behind the picker's banner. - fn on_scripts_for(&self, key: SessionKey, scripts: Vec<(gio::File, String)>) { + fn on_scripts_for(&self, key: SessionKey, scripts: Vec) { match self .workspaces() .into_iter() @@ -1365,26 +1378,26 @@ impl SessionWindow { { Some(workspace) => self.open_scripts_in(&workspace, scripts), None => { - for (file, text) in scripts { - self.wait_for_session(file, text); + for script in scripts { + self.wait_for_session(script); } } } } // A session that runs no SQL leaves them waiting for one that does. - fn open_scripts_in(&self, workspace: &Workspace, scripts: Vec<(gio::File, String)>) { - let scripts: Vec<(gio::File, String)> = scripts + fn open_scripts_in(&self, workspace: &Workspace, scripts: Vec) { + let scripts: Vec = scripts .into_iter() - .filter(|(file, _)| !self.focus_bound_tab(file)) + .filter(|script| !script.file().is_some_and(|file| self.focus_bound_tab(file))) .collect(); let input = workspace .sender() .filter(|_| workspace.data_model() == Some(DataModel::Relational)); match input { Some(input) => { - for (file, text) in scripts { - input.deliver(WorkspaceInput::OpenScript { file, text }); + for script in scripts { + input.deliver(script_input(script)); } } None => self.ask_elsewhere(scripts), @@ -1396,22 +1409,7 @@ impl SessionWindow { return; }; let banner = picker.script_banner(); - let title = match self.imp().waiting_scripts.borrow().as_slice() { - [] => None, - [(file, _)] => Some(crate::i18n::gettext_f( - "Choose a connection to open “{name}”", - &[("name", &file_display_name(&file.uri()))], - )), - waiting => { - let count = waiting.len(); - Some(crate::i18n::ngettext_f( - "Choose a connection to open {n} SQL file", - "Choose a connection to open {n} SQL files", - u32::try_from(count).unwrap_or(u32::MAX), - &[("n", &count.to_string())], - )) - } - }; + let title = waiting_title(&self.imp().waiting_scripts.borrow()); match title { Some(title) => { banner.set_title(&title); @@ -1426,6 +1424,16 @@ impl SessionWindow { self.imp().picker.get().map(PickerPage::script_banner) } + #[cfg(test)] + pub(crate) fn toast_titles(&self) -> Vec { + self.imp() + .toasts + .borrow() + .iter() + .filter_map(|toast| toast.title().map(String::from)) + .collect() + } + /// The dialog may be editing a connection the window shows or already /// connects, or one open in another window: its edits are kept for /// that connection's next connect. @@ -2123,6 +2131,46 @@ fn source_name(source: &ConnectSource) -> String { } } +fn script_input(script: WaitingScript) -> WorkspaceInput { + match script { + WaitingScript::File { file, text } => WorkspaceInput::OpenScript { file, text }, + WaitingScript::Shared { sql, .. } => WorkspaceInput::OpenInEditor { sql, database: None }, + } +} + +fn waiting_title(waiting: &[WaitingScript]) -> Option { + match waiting { + [] => None, + [WaitingScript::File { file, .. }] => Some(crate::i18n::gettext_f( + "Choose a connection to open “{name}”", + &[("name", &file_display_name(&file.uri()))], + )), + [WaitingScript::Shared { title, .. }] if !title.trim().is_empty() => Some(crate::i18n::gettext_f( + "Choose a connection to open “{name}”", + &[("name", title.trim())], + )), + [WaitingScript::Shared { .. }] => Some(crate::i18n::gettext("Choose a connection to open the shared query")), + waiting if waiting.iter().all(|script| script.file().is_some()) => { + let count = waiting.len(); + Some(crate::i18n::ngettext_f( + "Choose a connection to open {n} SQL file", + "Choose a connection to open {n} SQL files", + u32::try_from(count).unwrap_or(u32::MAX), + &[("n", &count.to_string())], + )) + } + waiting => { + let count = waiting.len(); + Some(crate::i18n::ngettext_f( + "Choose a connection to open {n} query", + "Choose a connection to open {n} queries", + u32::try_from(count).unwrap_or(u32::MAX), + &[("n", &count.to_string())], + )) + } + } +} + fn file_display_name(uri: &str) -> String { let file = gio::File::for_uri(uri); file.basename() diff --git a/linux/crates/app/src/ui/session_window/session_window_input.rs b/linux/crates/app/src/ui/session_window/session_window_input.rs index 81fcbeab54..d40a89d2c6 100644 --- a/linux/crates/app/src/ui/session_window/session_window_input.rs +++ b/linux/crates/app/src/ui/session_window/session_window_input.rs @@ -1,3 +1,4 @@ +use gio::prelude::FileExt; use gtk4::glib; use libadwaita as adw; use tablepro_core::SafeModeLevel; @@ -259,11 +260,40 @@ pub(crate) enum ScriptInput { /// The session in front when the read began, which takes the script if it is still open. target: Option, }, + // A shared link's SQL, which opens as a script does with no file behind it. + Shared { + title: String, + sql: String, + }, /// The waiting scripts banner's Cancel. DropWaiting, /// Scripts another window's user chose this window's session for. For { key: SessionKey, - scripts: Vec<(gio::File, String)>, + scripts: Vec, }, } + +#[derive(Debug, Clone)] +pub(crate) enum WaitingScript { + File { file: gio::File, text: String }, + Shared { title: String, sql: String }, +} + +impl WaitingScript { + pub(crate) fn file(&self) -> Option<&gio::File> { + match self { + Self::File { file, .. } => Some(file), + Self::Shared { .. } => None, + } + } + + // A second ask for the same file or the same shared SQL replaces the first. + pub(crate) fn same_as(&self, other: &Self) -> bool { + match (self, other) { + (Self::File { file, .. }, Self::File { file: other, .. }) => file.equal(other), + (Self::Shared { sql, .. }, Self::Shared { sql: other, .. }) => sql == other, + _ => false, + } + } +} diff --git a/linux/crates/app/src/ui/session_window/tests/open_file.rs b/linux/crates/app/src/ui/session_window/tests/open_file.rs index a466a3a718..636b9a0cbf 100644 --- a/linux/crates/app/src/ui/session_window/tests/open_file.rs +++ b/linux/crates/app/src/ui/session_window/tests/open_file.rs @@ -321,3 +321,78 @@ fn a_sql_file_already_open_brings_its_tab_forward() { assert_eq!(bound, 1, "a second tab opened on the file"); assert_eq!(test.app.windows().len(), 1); } + +fn shared(window: &SessionWindow, title: &str, sql: &str) { + window.send(SessionWindowInput::Script(ScriptInput::Shared { + title: title.to_owned(), + sql: sql.to_owned(), + })); +} + +fn editor_with_text(window: &SessionWindow, text: &str) -> crate::ui::editor::SqlEditor { + let mut found = None; + wait_until(WAIT, || { + found = editors(window).into_iter().find(|editor| text_of(editor) == text); + found.is_some() + }) + .expect("an editor tab with the shared SQL"); + found.expect("the editor") +} + +#[gtk4::test] +fn a_shared_query_opens_in_a_new_tab_of_the_session_in_front_without_running() { + let test = TestWindow::connected("SharedQuery"); + wait_until(WAIT, || !test.window.settling()).expect("the saved tabs read"); + let counters = test.connection().counters(); + let before = editors(&test.window).len(); + + shared(&test.window, "Orders", "DELETE FROM orders;"); + let editor = editor_with_text(&test.window, "DELETE FROM orders;"); + drain_main_context(); + + assert_eq!(editors(&test.window).len(), before + 1, "the SQL took over a tab"); + assert!(editor.file().is_none(), "a shared query is bound to a file"); + assert!(!editor.is_running(), "the shared query ran"); + assert_eq!( + CallCounters::get(&counters.open_editor_session), + 0, + "the shared query ran" + ); + assert_eq!(test.app.windows().len(), 1); +} + +#[gtk4::test] +fn a_shared_query_on_the_picker_waits_for_a_connection() { + let test = TestWindow::picker("SharedQueryWaits"); + let banner = script_banner(&test); + + shared(&test.window, "Orders", "SELECT 1;"); + wait_until(WAIT, || banner.is_revealed()).expect("the banner asking for a connection"); + assert_eq!(banner.title(), "Choose a connection to open “Orders”"); + shared(&test.window, "", "SELECT 2;"); + wait_until(WAIT, || banner.title() == "Choose a connection to open 2 queries").expect("both waiting"); + + test.window + .send(SessionWindowInput::OpenSaved(Box::new(test.saved.clone()))); + test.wait_for_page("workspace"); + editor_with_text(&test.window, "SELECT 1;"); + editor_with_text(&test.window, "SELECT 2;"); + + assert!(!banner.is_revealed(), "the banner stayed once the queries opened"); +} + +#[gtk4::test] +fn a_share_link_that_cannot_open_says_so_in_the_window_in_front() { + let test = TestWindow::connected("ShareLinkToast"); + crate::services::connection_link::register_link_schemes().expect("register the links"); + + open(&test, &[gio::File::for_uri("tablepro://share?token=short")]); + + wait_until(WAIT, || { + test.window + .toast_titles() + .contains(&"This shared link is no longer available.".to_owned()) + }) + .expect("the toast in the window in front"); + assert_eq!(test.app.windows().len(), 1, "a picker opened only to say it"); +} diff --git a/linux/crates/app/src/ui/share_dialog/form.rs b/linux/crates/app/src/ui/share_dialog/form.rs new file mode 100644 index 0000000000..04b6e8f200 --- /dev/null +++ b/linux/crates/app/src/ui/share_dialog/form.rs @@ -0,0 +1,688 @@ +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +use gtk4 as gtk; +use gtk4::glib; +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use secrecy::{ExposeSecret as _, SecretString}; +use tablepro_account::{ShareExpiry, ShareLimits}; +use tablepro_core::export::SnapshotRefusal; +use tablepro_core::masking::{ShareChoice, SharePlan, ShareSummary}; + +use super::ShareDialog; +use super::masking_text::personal_data_kind; +use super::preview::{PREVIEW_ROWS, preview_table}; +use super::share_columns::{self, ShareColumn}; +use super::sheet_view::{self, ExpiryChoice}; +use crate::i18n::{gettext, gettext_f}; +use crate::services::share_subject::{ShareForm, ShareSubject, SharedRows}; +use crate::ui::icons; + +pub(super) const PRICING: &str = "https://tablepro.app/?ref=app-share#pricing"; + +pub(super) struct FormFields { + pub(super) page: adw::PreferencesPage, + // Each choice of Share As and its button; empty without a team. + targets: Vec<(Option, gtk::CheckButton)>, + title: adw::EntryRow, + note: adw::EntryRow, + expiry: adw::ToggleGroup, + default_expiry: ShareExpiry, + hide_sql: Option, + password: Option, + allow_download: Option, + // What a field holds that the core refuses at create, said under the options. + problems: adw::PreferencesGroup, + problem_rows: Rc>>, + // The Columns list's choice for each shared column. + // The Columns list and the preview, which live as long as the form. + sheet: Option>, +} + +impl FormFields { + pub(super) fn values(&self) -> ShareForm { + let expiry = self + .expiry + .active_name() + .and_then(|name| ShareExpiry::from_code(&name)) + .unwrap_or(self.default_expiry); + ShareForm { + title: self.title.text().to_string(), + note: self.note.text().to_string(), + expiry, + hide_sql: self.hide_sql.as_ref().is_some_and(adw::SwitchRow::is_active), + password: SecretString::from( + self.password + .as_ref() + .map(|row| row.text().to_string()) + .unwrap_or_default(), + ), + allow_download: self.allow_download.as_ref().is_none_or(adw::SwitchRow::is_active), + team: self + .targets + .iter() + .find(|(_, button)| button.is_active()) + .and_then(|(team, _)| team.clone()), + columns: self + .sheet + .as_ref() + .map(|sheet| sheet.choices.borrow().clone()) + .unwrap_or_default(), + } + } +} + +// What the form keeps across a re-read: the fields as typed and the team chosen. +pub(super) struct Kept<'a> { + pub(super) draft: Option<&'a ShareForm>, + pub(super) team: Option<&'a str>, +} + +// A draft is the form as the user left it, which a re-read of the limits brings back. +pub(super) fn build_form( + dialog: &ShareDialog, + subject: &ShareSubject, + limits: &ShareLimits, + kept: Kept<'_>, +) -> FormFields { + let draft = kept.draft; + let page = adw::PreferencesPage::new(); + let targets = add_targets(dialog, &page, limits, kept.team); + let title = adw::EntryRow::builder() + .title(gettext("Title")) + .text(draft.map_or(subject.title.as_str(), |draft| draft.title.as_str())) + .build(); + let note = adw::EntryRow::builder() + .title(gettext("Note")) + .text(draft.map_or("", |draft| draft.note.as_str())) + .build(); + let about = adw::PreferencesGroup::new(); + about.add(&title); + about.add(¬e); + page.add(&about); + + let options = adw::PreferencesGroup::new(); + if let Some(reason) = &subject.no_sql { + options.set_description(Some(reason)); + } + let (expiry_row, expiry) = expiry_row(dialog, limits, draft.map(|draft| draft.expiry)); + options.add(&expiry_row); + let result = subject.kind() == tablepro_account::ShareKind::Result; + let hide_sql = (result && subject.has_sql()).then(|| { + let row = adw::SwitchRow::builder() + .title(gettext("Hide SQL")) + .active(draft.is_some_and(|draft| draft.hide_sql)) + .build(); + options.add(&row); + row + }); + let password = password_row(dialog, &options, limits, draft); + let allow_download = download_row(dialog, &options, limits, draft); + page.add(&options); + let problems = adw::PreferencesGroup::builder().visible(false).build(); + page.add(&problems); + if let Some(hide_sql) = &hide_sql { + add_hide_sql_notice(&page, subject, hide_sql); + } + + let sheet = subject.rows.as_ref().map(|_| add_columns(dialog, &page, limits, draft)); + add_warnings(&page, subject, hide_sql.as_ref()); + FormFields { + page, + targets, + title, + note, + expiry, + default_expiry: sheet_view::default_expiry(limits), + hide_sql, + password, + allow_download, + problems, + problem_rows: Rc::default(), + sheet, + } +} + +// The preview shows the rows as the link carries them, and follows every choice in the Columns list below it. +// The detectors and the summary run off the main loop; the list and the preview fill in once they land. +fn add_columns( + dialog: &ShareDialog, + page: &adw::PreferencesPage, + limits: &ShareLimits, + draft: Option<&ShareForm>, +) -> Rc { + let choices = Rc::new(RefCell::new( + draft.map(|draft| draft.columns.clone()).unwrap_or_default(), + )); + let preview = Preview::new(); + let summary = share_columns::summary_label(); + let group = share_columns::columns_group(&summary); + page.add(&preview.group); + page.add(&group); + let sheet = Rc::new(Sheet { + limits: limits.clone(), + preview, + summary, + group, + choices, + rows: RefCell::new(None), + }); + dialog.detect(&sheet); + sheet +} + +// The Columns list and the preview of one form. +struct Sheet { + limits: ShareLimits, + preview: Preview, + summary: gtk::Label, + group: adw::PreferencesGroup, + choices: Rc>>, + rows: RefCell>>, +} + +// What the detectors found for a subject's rows under a plan's caps, kept so a form built again reads it. +pub(super) struct Detected { + subject: Arc, + rows: Arc, + caps: (u64, u64), + columns: Vec, +} + +// A share as the plan sends it, worked out off the main loop, kept with what it was worked out from. +pub(super) struct Sent { + rows: Arc, + caps: (u64, u64), + plan: SharePlan, + choices: Vec, + summary: ShareSummary, + columns: Vec, + sent: Vec, + total: u64, +} + +fn summarize_rows(rows: &Arc, choices: Vec, caps: (u64, u64)) -> Sent { + let (max_rows, max_columns) = caps; + let plan = rows.plan(&choices, max_columns); + let summary = rows.summary(&plan, max_rows); + let (columns, sent) = rows.sent(&plan, summary.rows_sent.min(PREVIEW_ROWS)); + Sent { + rows: rows.clone(), + caps, + plan, + choices, + summary, + columns, + sent, + total: rows.total(), + } +} + +impl ShareDialog { + // Create stays off while a field holds what the core refuses at create, and the form says why, as macOS does. + pub(super) fn check_fields(&self) { + let imp = self.imp(); + let Some(subject) = self.current_subject() else { + return; + }; + let problems = { + let form = imp.form.borrow(); + let Some(fields) = form.as_ref() else { + return; + }; + let password = fields.password.as_ref().map(|row| row.text()); + let problems = sheet_view::field_problems(&subject.sql, password.as_deref()); + fill_notices( + &fields.problems, + &fields.problem_rows, + &problems, + icons::DIALOG_ERROR, + "error", + ); + problems + }; + imp.field_problem.set(!problems.is_empty()); + self.update_create(); + } + + // The subject's detection is reused while the subject and the caps stay; otherwise it runs with the first summary. + fn detect(&self, sheet: &Rc) { + let imp = self.imp(); + let (Some(deps), Some(subject)) = (imp.deps.get(), self.current_subject()) else { + return; + }; + let caps = (sheet.limits.max_rows, sheet.limits.max_columns); + let known = imp.detected.borrow().as_ref().and_then(|detected| { + (Arc::ptr_eq(&detected.subject, &subject) && detected.caps == caps) + .then(|| (detected.rows.clone(), detected.columns.clone())) + }); + if let Some((rows, columns)) = known { + sheet.rows.replace(Some(rows)); + self.show_columns(sheet, &columns); + self.summarize(sheet); + return; + } + let Some(rows) = subject.rows.clone().map(Arc::new) else { + return; + }; + let ticket = self.next_summary(); + let kept = sheet.choices.borrow().clone(); + let working = deps.tasks.spawn_blocking_task(move || { + let columns = share_columns::share_columns(&rows, caps.0, caps.1); + let choices: Vec = match kept.len() == columns.len() { + true => kept, + false => columns.iter().map(ShareColumn::initial).collect(), + }; + let sent = summarize_rows(&rows, choices, caps); + (columns, sent) + }); + let (dialog, sheet) = (self.downgrade(), Rc::downgrade(sheet)); + glib::spawn_future_local(async move { + let landed = working.await; + let (Some(dialog), Some(sheet)) = (dialog.upgrade(), sheet.upgrade()) else { + return; + }; + if dialog.imp().summaries.get() != ticket { + return; + } + let (columns, sent) = match landed { + Ok(landed) => landed, + Err(failure) => { + tracing::warn!(%failure, "the shared columns were not read"); + return; + } + }; + dialog.imp().detected.replace(Some(Detected { + subject, + rows: sent.rows.clone(), + caps, + columns: columns.clone(), + })); + sheet.rows.replace(Some(sent.rows.clone())); + sheet.choices.replace(sent.choices.clone()); + dialog.show_columns(&sheet, &columns); + dialog.show_sent(&sheet, Rc::new(sent), ticket); + }); + } + + fn show_columns(&self, sheet: &Rc, columns: &[ShareColumn]) { + if sheet.choices.borrow().len() != columns.len() { + sheet + .choices + .replace(columns.iter().map(ShareColumn::initial).collect()); + } + let changed: Rc = { + let (dialog, sheet) = (self.downgrade(), Rc::downgrade(sheet)); + Rc::new(move || { + if let (Some(dialog), Some(sheet)) = (dialog.upgrade(), sheet.upgrade()) { + dialog.summarize(&sheet); + } + }) + }; + share_columns::fill_columns(&sheet.group, columns, &sheet.choices, &changed, &sheet.summary); + } + + fn next_summary(&self) -> u64 { + let imp = self.imp(); + let ticket = imp.summaries.get() + 1; + imp.summaries.set(ticket); + self.set_sendable(false); + ticket + } + + // The same plan and budget as the snapshot, so the notes and the preview say what Create sends; Create waits. + fn summarize(&self, sheet: &Rc) { + let imp = self.imp(); + let (Some(deps), Some(rows)) = (imp.deps.get(), sheet.rows.borrow().clone()) else { + return; + }; + let choices = sheet.choices.borrow().clone(); + let caps = (sheet.limits.max_rows, sheet.limits.max_columns); + let ticket = self.next_summary(); + let known = imp + .sent + .borrow() + .clone() + .filter(|sent| Arc::ptr_eq(&sent.rows, &rows) && sent.caps == caps && sent.choices == choices); + if let Some(sent) = known { + self.show_sent(sheet, sent, ticket); + return; + } + let working = deps + .tasks + .spawn_blocking_task(move || summarize_rows(&rows, choices, caps)); + let (dialog, sheet) = (self.downgrade(), Rc::downgrade(sheet)); + glib::spawn_future_local(async move { + let sent = working.await; + let (Some(dialog), Some(sheet)) = (dialog.upgrade(), sheet.upgrade()) else { + return; + }; + match sent { + Ok(sent) => dialog.show_sent(&sheet, Rc::new(sent), ticket), + Err(failure) => tracing::warn!(%failure, "the share was not summarized"), + } + }); + } + + fn show_sent(&self, sheet: &Sheet, sent: Rc, ticket: u64) { + let imp = self.imp(); + if imp.summaries.get() != ticket { + return; + } + sheet.preview.show(&sent, &sheet.limits); + sheet + .summary + .set_label(&share_columns::summary(&sent.plan, &sent.choices)); + imp.summarized.set(ticket); + self.set_sendable(sent.summary.refused.is_none()); + imp.sent.replace(Some(sent)); + } +} + +// The first rows as sent, with what the plan's caps leave out. +struct Preview { + group: adw::PreferencesGroup, + table: RefCell>, +} + +impl Preview { + fn new() -> Self { + Self { + group: adw::PreferencesGroup::builder() + .title(gettext("Rows that will be shared")) + .build(), + table: RefCell::new(None), + } + } + + fn show(&self, sent: &Sent, limits: &ShareLimits) { + let notes: Vec = [ + match &sent.summary.refused { + None => sheet_view::cap_note(sent.total, sent.summary.rows_sent as u64), + Some(SnapshotRefusal::NoColumns) => Some(sheet_view::no_columns_note()), + Some(SnapshotRefusal::Cell { .. } | SnapshotRefusal::FirstRow) => { + Some(gettext("This result is too large to share.")) + } + }, + sheet_view::column_note(sent.summary.columns_cut, limits.max_columns), + ] + .into_iter() + .flatten() + .collect(); + self.group.set_description( + Some(¬es.join(" ")) + .filter(|notes| !notes.is_empty()) + .map(String::as_str), + ); + let table = preview_table(&sent.columns, &sent.sent); + if let Some(old) = self.table.replace(Some(table.clone())) { + self.group.remove(&old); + } + self.group.add(&table); + } +} + +// Personal data in the SQL's literals suggests Hide SQL, which the notice turns on; it goes once Hide SQL is on. +fn add_hide_sql_notice(page: &adw::PreferencesPage, subject: &ShareSubject, hide_sql: &adw::SwitchRow) { + let hits = subject.personal_data(); + if hits.is_empty() { + return; + } + let kinds: Vec = hits.iter().map(|hit| personal_data_kind(hit.kind)).collect(); + let row = adw::ActionRow::builder() + .title(gettext_f( + "This query contains what looks like personal data ({kind}). Turn on Hide SQL to keep the query private.", + &[("kind", &kinds.join(", "))], + )) + .use_markup(false) + .title_lines(0) + .build(); + let icon = gtk::Image::builder() + .icon_name(icons::DIALOG_WARNING) + .valign(gtk::Align::Center) + .accessible_role(gtk::AccessibleRole::Presentation) + .css_classes(["warning"]) + .build(); + row.add_prefix(&icon); + let button = gtk::Button::builder() + .label(gettext("Hide SQL")) + .valign(gtk::Align::Center) + .build(); + let switch = hide_sql.downgrade(); + button.connect_clicked(move |_| { + if let Some(switch) = switch.upgrade() { + switch.set_active(true); + } + }); + row.add_suffix(&button); + let group = adw::PreferencesGroup::new(); + group.add(&row); + group.set_visible(!hide_sql.is_active()); + let shown = group.downgrade(); + hide_sql.connect_active_notify(move |hide_sql| { + if let Some(group) = shown.upgrade() { + group.set_visible(!hide_sql.is_active()); + } + }); + page.add(&group); +} + +// Personal first, then each team the account holds a seat in; a team without public links shows but cannot be picked. +pub(super) fn add_targets( + dialog: &ShareDialog, + page: &adw::PreferencesPage, + limits: &ShareLimits, + chosen: Option<&str>, +) -> Vec<(Option, gtk::CheckButton)> { + let targets = sheet_view::share_targets(limits); + if targets.len() < 2 { + return Vec::new(); + } + let group = adw::PreferencesGroup::builder().title(gettext("Share As")).build(); + let chosen = sheet_view::chosen_team(limits, chosen).map(|team| team.id.as_str()); + let mut buttons: Vec<(Option, gtk::CheckButton)> = Vec::new(); + for target in targets { + let button = gtk::CheckButton::builder() + .active(target.team.as_deref() == chosen) + .valign(gtk::Align::Center) + .build(); + if let Some((_, first)) = buttons.first() { + button.set_group(Some(first)); + } + let row = adw::ActionRow::builder() + .title(&target.name) + .use_markup(false) + .activatable_widget(&button) + .sensitive(target.enabled) + .build(); + if !target.subtitle.is_empty() { + row.set_subtitle(&target.subtitle); + } + row.add_prefix(&button); + group.add(&row); + buttons.push((target.team, button)); + } + for (team, button) in &buttons { + let (team, dialog) = (team.clone(), dialog.downgrade()); + button.connect_toggled(move |button| { + if let (true, Some(dialog)) = (button.is_active(), dialog.upgrade()) { + dialog.choose_target(team.clone()); + } + }); + } + page.add(&group); + buttons +} + +fn password_row( + dialog: &ShareDialog, + options: &adw::PreferencesGroup, + limits: &ShareLimits, + draft: Option<&ShareForm>, +) -> Option { + let title = gettext("Password"); + if !limits.password { + options.add(&pro_only_row(dialog, &title, None)); + return None; + } + let row = adw::PasswordEntryRow::builder().title(&title).build(); + if let Some(draft) = draft { + row.set_text(draft.password.expose_secret()); + } + let weak = dialog.downgrade(); + row.connect_changed(move |_| { + if let Some(dialog) = weak.upgrade() { + dialog.check_fields(); + } + }); + options.add(&row); + Some(row) +} + +fn download_row( + dialog: &ShareDialog, + options: &adw::PreferencesGroup, + limits: &ShareLimits, + draft: Option<&ShareForm>, +) -> Option { + let title = gettext("Allow viewers to download"); + if !limits.disable_download { + let switch = gtk::Switch::builder() + .active(true) + .sensitive(false) + .valign(gtk::Align::Center) + .build(); + switch.update_property(&[gtk::accessible::Property::Label(&title)]); + options.add(&pro_only_row(dialog, &title, Some(&switch))); + return None; + } + let row = adw::SwitchRow::builder() + .title(&title) + .active(draft.is_none_or(|draft| draft.allow_download)) + .build(); + options.add(&row); + Some(row) +} + +fn expiry_row( + dialog: &ShareDialog, + limits: &ShareLimits, + kept: Option, +) -> (adw::ActionRow, adw::ToggleGroup) { + let title = gettext("Expires"); + let row = adw::ActionRow::builder().title(&title).build(); + let group = adw::ToggleGroup::builder().valign(gtk::Align::Center).build(); + let choices = sheet_view::expiry_choices(limits); + for ExpiryChoice { expiry, allowed } in &choices { + let toggle = adw::Toggle::builder() + .name(expiry.code()) + .label(sheet_view::expiry_label(*expiry)) + .enabled(*allowed) + .build(); + group.add(toggle); + } + let active = kept + .filter(|kept| limits.expiries.contains(kept)) + .unwrap_or_else(|| sheet_view::default_expiry(limits)); + group.set_active_name(Some(active.code())); + group.update_property(&[gtk::accessible::Property::Label(&title)]); + row.add_suffix(&group); + if let Some(locked) = choices.iter().find(|choice| !choice.allowed) { + row.add_suffix(&pro_tag(dialog, &sheet_view::expiry_label(locked.expiry))); + } + (row, group) +} + +// Free shows Pro's options with the control off and a tag that opens the plans, never a modal. +fn pro_only_row(dialog: &ShareDialog, title: &str, control: Option<>k::Switch>) -> adw::ActionRow { + let row = adw::ActionRow::builder().title(title).build(); + if let Some(control) = control { + row.add_suffix(control); + } + row.add_suffix(&pro_tag(dialog, title)); + row +} + +// Every tag reads "Pro", so its description names the option it stands for. +fn pro_tag(dialog: &ShareDialog, option: &str) -> gtk::Button { + let tag = gtk::Button::builder() + .label(gettext("Pro")) + .valign(gtk::Align::Center) + .tooltip_text(gettext("Show the Pro plan in your browser")) + .css_classes(["flat", "accent", "caption-heading"]) + .build(); + tag.update_property(&[gtk::accessible::Property::Description(&gettext_f( + "{option} needs TablePro Pro.", + &[("option", option)], + ))]); + let dialog = dialog.downgrade(); + tag.connect_clicked(move |_| { + if let Some(dialog) = dialog.upgrade() { + dialog.open_uri(PRICING); + } + }); + tag +} + +// Inline and never blocking; Hide SQL takes back the SQL's own warnings. +fn add_warnings(page: &adw::PreferencesPage, subject: &ShareSubject, hide_sql: Option<&adw::SwitchRow>) { + let kinds = subject.secret_kinds(); + let columns = subject.secret_columns(); + if kinds.is_empty() && columns.is_empty() { + return; + } + let group = adw::PreferencesGroup::new(); + let rows: Rc>> = Rc::default(); + fill_warnings(&group, &rows, sheet_view::secret_warnings(&kinds, &columns, false)); + page.add(&group); + if let Some(hide_sql) = hide_sql { + hide_sql.connect_active_notify(move |hide_sql| { + fill_warnings( + &group, + &rows, + sheet_view::secret_warnings(&kinds, &columns, hide_sql.is_active()), + ); + }); + } +} + +fn fill_warnings(group: &adw::PreferencesGroup, rows: &RefCell>, warnings: Vec) { + fill_notices(group, rows, &warnings, icons::DIALOG_WARNING, "warning"); +} + +fn fill_notices( + group: &adw::PreferencesGroup, + rows: &RefCell>, + notices: &[String], + icon_name: &str, + class: &str, +) { + for row in rows.take() { + group.remove(&row); + } + let added: Vec = notices + .iter() + .map(|notice| { + let row = adw::ActionRow::builder() + .title(notice) + .use_markup(false) + .title_lines(0) + .build(); + let icon = gtk::Image::builder() + .icon_name(icon_name) + .valign(gtk::Align::Center) + .accessible_role(gtk::AccessibleRole::Presentation) + .css_classes([class]) + .build(); + row.add_prefix(&icon); + group.add(&row); + row + }) + .collect(); + group.set_visible(!added.is_empty()); + rows.replace(added); +} diff --git a/linux/crates/app/src/ui/share_dialog/imp.rs b/linux/crates/app/src/ui/share_dialog/imp.rs new file mode 100644 index 0000000000..24cec740f1 --- /dev/null +++ b/linux/crates/app/src/ui/share_dialog/imp.rs @@ -0,0 +1,70 @@ +use std::cell::{Cell, OnceCell, RefCell}; +use std::sync::Arc; + +use gtk4::glib; +use gtk4::subclass::prelude::*; +use libadwaita as adw; +use libadwaita::subclass::prelude::*; +use tablepro_account::{Share, ShareLimits}; +use tokio_util::sync::CancellationToken; + +use super::form::FormFields; +use super::sheet_view::SheetPage; +use super::{Chrome, Deps}; +use crate::services::share_subject::{ShareForm, ShareSubject}; + +#[derive(Default)] +pub struct ShareDialog { + pub(super) chrome: OnceCell, + pub(super) deps: OnceCell, + // Replaced once a table tab's rows are read. + pub(super) subject: RefCell>>, + // The team a link goes to; None is a personal link. + pub(super) target: RefCell>, + pub(super) page: RefCell>, + pub(super) limits: RefCell>, + pub(super) live: RefCell>, + pub(super) form: RefCell>, + // One create, revoke or sign-in at a time, however fast the buttons are pressed. + pub(super) busy: Cell, + // Moved by each read of the limits, so a read a later one replaced lands nowhere. + pub(super) read: Cell, + pub(super) signing_in: RefCell>, + // Moved by each sign-in, so one that a later one replaced ends without touching the sheet. + pub(super) sign_in_attempt: Cell, + // What the form held when the sheet left it, so a revoke or a refusal brings it back as typed. + pub(super) draft: RefCell>, + pub(super) following: RefCell>>, + // Moved by each change of the Columns list, so only the newest summary lands. + pub(super) summaries: Cell, + pub(super) summarized: Cell, + // What the detectors and the last summary found, which a form built again for the same subject reads. + pub(super) detected: RefCell>, + pub(super) sent: RefCell>>, + // The share as the sheet holds it is summarized and can go; false while a summary runs or it is too large. + pub(super) sendable: Cell, + // A field holds what the core refuses at create, such as a password of only spaces. + pub(super) field_problem: Cell, +} + +#[glib::object_subclass] +impl ObjectSubclass for ShareDialog { + const NAME: &'static str = "TableProShareDialog"; + type Type = super::ShareDialog; + type ParentType = adw::Dialog; +} + +impl ObjectImpl for ShareDialog { + fn dispose(&self) { + for following in self.following.take() { + following.abort(); + } + if let Some(signing_in) = self.signing_in.take() { + signing_in.cancel(); + } + } +} + +impl WidgetImpl for ShareDialog {} + +impl AdwDialogImpl for ShareDialog {} diff --git a/linux/crates/app/src/ui/share_dialog/masking_text.rs b/linux/crates/app/src/ui/share_dialog/masking_text.rs new file mode 100644 index 0000000000..74f1503e04 --- /dev/null +++ b/linux/crates/app/src/ui/share_dialog/masking_text.rs @@ -0,0 +1,41 @@ +use tablepro_core::masking::MaskingStyle; +use tablepro_core::masking::detect::SensitiveKind; + +use crate::i18n::gettext; + +// A masking style as the share sheet names it. +pub(crate) fn style_label(style: MaskingStyle) -> String { + match style { + MaskingStyle::Full => gettext("Full"), + MaskingStyle::LastFour => gettext("Last 4 Characters"), + MaskingStyle::Email => gettext("Email"), + MaskingStyle::Hash => gettext("Stable Hash"), + MaskingStyle::Null => gettext("NULL"), + } +} + +// What a column's values look like, for the share sheet's reason. +pub(crate) fn values_reason(kind: SensitiveKind) -> String { + match kind { + SensitiveKind::Card => gettext("Values look like card numbers"), + SensitiveKind::Iban => gettext("Values look like IBANs"), + SensitiveKind::Jwt => gettext("Values look like access tokens"), + SensitiveKind::ApiKey => gettext("Values look like API keys"), + SensitiveKind::Email => gettext("Values look like email addresses"), + SensitiveKind::Phone => gettext("Values look like phone numbers"), + SensitiveKind::Ip => gettext("Values look like IP addresses"), + } +} + +// One piece of personal data a query's text holds, for the Hide SQL notice. +pub(crate) fn personal_data_kind(kind: SensitiveKind) -> String { + match kind { + SensitiveKind::Card => gettext("a card number"), + SensitiveKind::Iban => gettext("an IBAN"), + SensitiveKind::Jwt => gettext("an access token"), + SensitiveKind::ApiKey => gettext("an API key"), + SensitiveKind::Email => gettext("an email address"), + SensitiveKind::Phone => gettext("a phone number"), + SensitiveKind::Ip => gettext("an IP address"), + } +} diff --git a/linux/crates/app/src/ui/share_dialog/mod.rs b/linux/crates/app/src/ui/share_dialog/mod.rs new file mode 100644 index 0000000000..de05a64d20 --- /dev/null +++ b/linux/crates/app/src/ui/share_dialog/mod.rs @@ -0,0 +1,613 @@ +mod form; +mod imp; +mod masking_text; +mod pages; +mod preview; +mod share_columns; +mod sheet_view; +mod table_read; +#[cfg(test)] +mod tests; + +use std::sync::Arc; + +use gtk4 as gtk; +use gtk4::glib; +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use tablepro_account::{Account, AccountError, CreatedShare, Share, ShareLimits}; +use tablepro_core::export::SnapshotRefusal; +use tablepro_session::runtime::{TaskFailure, Tasks}; +use tokio_util::sync::CancellationToken; + +use self::form::build_form; +use self::sheet_view::SheetPage; +use crate::i18n::gettext; +use crate::runtime::spawn_and_deliver; +use crate::services::account_service::{AccountHandle, AccountStart}; +use crate::services::share_subject::ShareSubject; +use crate::services::telemetry::Telemetry; +use crate::ui::error_text::{account_error_message, account_unavailable_message, share_error_message}; + +// Pages of live links read for the list at the limit; Pro's 1,000 links are ten pages of the core's 100. +const LIST_PAGES: usize = 10; + +pub(crate) struct ShareDialogInit { + pub subject: ShareSubject, + pub account: AccountHandle, + pub tasks: Tasks, + pub telemetry: Telemetry, +} + +pub(super) struct Deps { + account: AccountHandle, + tasks: Tasks, + telemetry: Telemetry, +} + +pub(super) struct Chrome { + toolbar: adw::ToolbarView, + header: adw::HeaderBar, + banner: adw::Banner, + cancel: gtk::Button, + create: gtk::Button, + footer: gtk::Label, +} + +type LimitsRead = Result<(ShareLimits, Vec), AccountError>; + +glib::wrapper! { + pub struct ShareDialog(ObjectSubclass) + @extends adw::Dialog, gtk::Widget, + @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget, gtk::ShortcutManager; +} + +impl ShareDialog { + pub(crate) fn new(init: ShareDialogInit) -> Self { + let dialog: Self = glib::Object::builder() + .property("title", sheet_view::title(init.subject.kind())) + .property("content-width", 560) + .property("content-height", 640) + .build(); + let imp = dialog.imp(); + let _ = imp.chrome.set(dialog.build_chrome()); + imp.subject.replace(Some(Arc::new(init.subject))); + let _ = imp.deps.set(Deps { + account: init.account, + tasks: init.tasks, + telemetry: init.telemetry, + }); + dialog.follow_account(); + dialog.begin(); + dialog + } + + #[cfg(test)] + pub(crate) fn subject(&self) -> Option> { + self.current_subject() + } + + fn build_chrome(&self) -> Chrome { + let cancel = gtk::Button::with_label(&gettext("Cancel")); + let create = gtk::Button::builder() + .label(gettext("Create Link")) + .css_classes(["suggested-action"]) + .build(); + let header = adw::HeaderBar::new(); + header.pack_start(&cancel); + header.pack_end(&create); + let banner = adw::Banner::builder().use_markup(false).revealed(false).build(); + let footer = gtk::Label::builder() + .css_classes(["dim-label", "caption"]) + .margin_top(6) + .margin_bottom(6) + .margin_start(12) + .margin_end(12) + .wrap(true) + .build(); + let toolbar = adw::ToolbarView::new(); + toolbar.add_top_bar(&header); + toolbar.add_top_bar(&banner); + toolbar.add_bottom_bar(&footer); + self.set_child(Some(&toolbar)); + let dialog = self.downgrade(); + cancel.connect_clicked(move |_| { + if let Some(dialog) = dialog.upgrade() { + dialog.close(); + } + }); + let dialog = self.downgrade(); + create.connect_clicked(move |_| { + if let Some(dialog) = dialog.upgrade() { + dialog.create(); + } + }); + // A create in flight would make a link nobody sees; the sheet stays until it answers. + self.connect_close_attempt(|dialog| { + dialog.alert(&gettext("The link is on its way. Wait for it before closing.")); + }); + Chrome { + toolbar, + header, + banner, + cancel, + create, + footer, + } + } + + fn follow_account(&self) { + let Some(deps) = self.imp().deps.get() else { + return; + }; + let mut status = deps.account.status.clone(); + let mut start = deps.account.start.clone(); + let dialog = self.downgrade(); + let following_status = glib::spawn_future_local(async move { + while status.changed().await.is_ok() { + let Some(dialog) = dialog.upgrade() else { + return; + }; + dialog.account_changed(); + } + }); + let dialog = self.downgrade(); + let following_start = glib::spawn_future_local(async move { + while start.changed().await.is_ok() { + let Some(dialog) = dialog.upgrade() else { + return; + }; + dialog.account_changed(); + } + }); + self.imp().following.replace(vec![following_status, following_start]); + } + + // A read in flight, or a page the limits decided, stays while the account stays signed in. + fn account_changed(&self) { + let reading = self.signed_in() && self.account().is_some(); + let keep = match self.page() { + Some(SheetPage::Created { .. }) => true, + Some( + SheetPage::Form + | SheetPage::AtLimit + | SheetPage::Unverified + | SheetPage::Disabled + | SheetPage::Failed(_) + | SheetPage::Loading, + ) => reading, + _ => false, + }; + if !keep { + self.begin(); + } + } + + fn begin(&self) { + let Some(deps) = self.imp().deps.get() else { + return; + }; + let start = deps.account.start.borrow().clone(); + if let Some(reason) = account_unavailable_message(&start) { + return self.show(SheetPage::Unavailable(reason)); + } + if matches!(start, AccountStart::Starting) { + return self.show(SheetPage::Loading); + } + match (self.signed_in(), self.imp().signing_in.borrow().is_some()) { + (true, _) => self.load_limits(), + (false, true) => self.show(SheetPage::SigningIn), + (false, false) => self.show(SheetPage::SignedOut), + } + } + + fn signed_in(&self) -> bool { + self.imp() + .deps + .get() + .is_some_and(|deps| sheet_view::signed_in(&deps.account.status.borrow())) + } + + fn account(&self) -> Option { + self.imp().deps.get()?.account.account() + } + + fn page(&self) -> Option { + self.imp().page.borrow().clone() + } + + pub(super) fn load_limits(&self) { + let imp = self.imp(); + let (Some(deps), Some(account)) = (imp.deps.get(), self.account()) else { + return; + }; + let read = imp.read.get() + 1; + imp.read.set(read); + self.show(SheetPage::Loading); + let team = imp.target.borrow().clone(); + let dialog = self.downgrade(); + spawn_and_deliver(&deps.tasks, read_limits(account, team), move |result| { + if let Some(dialog) = dialog.upgrade() { + dialog.limits_read(read, result); + } + }); + } + + fn limits_read(&self, read: u64, result: Result) { + let imp = self.imp(); + if imp.read.get() != read { + return; + } + match result { + Ok(Ok((limits, live))) => { + let target = imp.target.borrow().clone(); + let team = sheet_view::chosen_team(&limits, target.as_deref()); + let page = sheet_view::page_for(&limits, team); + if let Some(chrome) = imp.chrome.get() { + chrome.footer.set_label(&sheet_view::footer(&limits, team)); + } + let max_rows = limits.max_rows; + imp.limits.replace(Some(limits)); + imp.live.replace(live); + match page == SheetPage::Form && self.rows_to_read() { + true => self.read_table(max_rows), + false => self.show(page), + } + } + Ok(Err(AccountError::SignedOut)) => self.show(SheetPage::SignedOut), + Ok(Err(error)) => self.show(SheetPage::Failed(load_error_message(&error))), + Err(failure) => { + tracing::warn!(%failure, "the share limits were not read"); + self.show(SheetPage::Failed(load_error_message(&AccountError::Protocol( + failure.to_string(), + )))); + } + } + } + + fn show(&self, page: SheetPage) { + let imp = self.imp(); + let Some(chrome) = imp.chrome.get() else { + return; + }; + // A read still in flight answers a page the user has left. + if page != SheetPage::Loading { + imp.read.set(imp.read.get() + 1); + } + if let Some(left) = imp.form.borrow().as_ref() { + imp.draft.replace(Some(left.values())); + } + let form = matches!(page, SheetPage::Form); + imp.sendable.set(true); + imp.field_problem.set(false); + chrome.banner.set_revealed(false); + chrome.cancel.set_visible(form); + chrome.create.set_visible(form); + chrome.header.set_show_end_title_buttons(!form); + chrome + .toolbar + .set_reveal_bottom_bars(matches!(page, SheetPage::Form | SheetPage::AtLimit)); + let subject = self.current_subject(); + let (content, focus) = match (&page, imp.limits.borrow().as_ref(), subject) { + (SheetPage::Form, Some(limits), Some(subject)) => { + let target = imp.target.borrow().clone(); + let fields = build_form( + self, + &subject, + limits, + form::Kept { + draft: imp.draft.borrow().as_ref(), + team: target.as_deref(), + }, + ); + let page = fields.page.clone().upcast::(); + imp.form.replace(Some(fields)); + (page, None) + } + _ => { + imp.form.replace(None); + pages::page_widget(self, &page) + } + }; + chrome.toolbar.set_content(Some(&content)); + if let Some(focus) = focus { + self.set_focus(Some(&focus)); + } + imp.page.replace(Some(page)); + if form { + self.check_fields(); + } + self.set_busy(false); + } + + fn set_busy(&self, busy: bool) { + let imp = self.imp(); + imp.busy.set(busy); + self.set_can_close(!busy); + self.update_create(); + if let Some(chrome) = imp.chrome.get() { + chrome.cancel.set_sensitive(!busy); + match busy { + true => chrome.create.set_child(Some(&adw::Spinner::new())), + false => chrome.create.set_label(&gettext("Create Link")), + } + } + if let Some(form) = imp.form.borrow().as_ref() { + form.page.set_sensitive(!busy); + } + } + + pub(super) fn set_sendable(&self, sendable: bool) { + self.imp().sendable.set(sendable); + self.update_create(); + } + + pub(super) fn update_create(&self) { + let imp = self.imp(); + if let Some(chrome) = imp.chrome.get() { + chrome + .create + .set_sensitive(imp.sendable.get() && !imp.field_problem.get() && !imp.busy.get()); + } + } + + fn alert(&self, message: &str) { + if let Some(chrome) = self.imp().chrome.get() { + chrome.banner.set_title(message); + chrome.banner.set_revealed(true); + } + } + + fn create(&self) { + let imp = self.imp(); + if imp.busy.get() || !imp.sendable.get() || imp.field_problem.get() { + return; + } + let (Some(deps), Some(account), Some(subject)) = (imp.deps.get(), self.account(), self.current_subject()) + else { + return; + }; + let (Some(limits), Some(form)) = ( + imp.limits.borrow().clone(), + imp.form.borrow().as_ref().map(form::FormFields::values), + ) else { + return; + }; + self.set_busy(true); + let dialog = self.downgrade(); + spawn_and_deliver( + &deps.tasks, + async move { + let (snapshot, columns_cut) = match subject.rows.as_ref() { + Some(rows) => { + let plan = rows.plan(&form.columns, limits.max_columns); + let snapshot = rows.snapshot(limits.max_rows, &plan).map_err(refused)?; + (Some(snapshot), plan.columns_cut()) + } + None => (None, false), + }; + let mut created = account.create_share(subject.request(&form, &limits, snapshot)).await?; + // The plan cut the columns before the request, so the account saw no more than it sends. + created.columns_truncated |= columns_cut; + Ok(created) + }, + move |result| { + if let Some(dialog) = dialog.upgrade() { + dialog.created(result); + } + }, + ); + } + + fn created(&self, result: Result, TaskFailure>) { + self.set_busy(false); + let error = match result { + // A link GTK cannot show is no link to hand over. + Ok(Ok(created)) if created.url.chars().any(char::is_control) => { + AccountError::Protocol("the link holds a control character".to_owned()) + } + Ok(Ok(created)) => { + let copied = crate::ui::clipboard::put_text(self, created.url.clone()) + .inspect_err(|error| tracing::warn!(?error, "the new link did not reach the clipboard")) + .is_ok(); + self.imp().draft.replace(None); + self.imp().form.replace(None); + return self.show(SheetPage::Created { + url: created.url, + copied, + columns_truncated: created.columns_truncated, + }); + } + Ok(Err(error)) => error, + Err(failure) => AccountError::Protocol(failure.to_string()), + }; + match error.code() { + "account.signed_out" => self.show(SheetPage::SignedOut), + // The limits say what changed, and their page says it. + "account.share_limit_reached" | "account.email_unverified" | "account.sharing_disabled" => { + self.load_limits(); + } + _ => self.alert(&match &error { + AccountError::Refused { code, .. } if code == NO_COLUMNS => sheet_view::no_columns_note(), + _ => share_error_message(&error), + }), + } + } + + pub(super) fn revoke(&self, id: String) { + let imp = self.imp(); + let (Some(deps), Some(account)) = (imp.deps.get(), self.account()) else { + return; + }; + if imp.busy.replace(true) { + return; + } + self.show_busy_list(); + let dialog = self.downgrade(); + spawn_and_deliver( + &deps.tasks, + async move { account.revoke_share(&id).await }, + move |result| { + let Some(dialog) = dialog.upgrade() else { + return; + }; + dialog.imp().busy.set(false); + match result { + Ok(Ok(())) => dialog.load_limits(), + Ok(Err(error)) => { + dialog.show(SheetPage::AtLimit); + dialog.alert(&account_error_message(&error)); + } + Err(failure) => { + tracing::warn!(%failure, "the revoke did not finish"); + dialog.show(SheetPage::AtLimit); + } + } + }, + ); + } + + // The Revoke buttons go insensitive while one runs. + fn show_busy_list(&self) { + if let Some(chrome) = self.imp().chrome.get() { + let (list, _) = pages::page_widget(self, &SheetPage::AtLimit); + chrome.toolbar.set_content(Some(&list)); + } + } + + pub(super) fn sign_in(&self) { + let imp = self.imp(); + let (Some(deps), Some(account)) = (imp.deps.get(), self.account()) else { + return; + }; + let cancel = CancellationToken::new(); + if let Some(earlier) = imp.signing_in.replace(Some(cancel.clone())) { + earlier.cancel(); + } + let attempt = imp.sign_in_attempt.get() + 1; + imp.sign_in_attempt.set(attempt); + self.show(SheetPage::SigningIn); + let telemetry = deps.telemetry.clone(); + let dialog = self.downgrade(); + spawn_and_deliver( + &deps.tasks, + async move { account.sign_in(cancel.cancelled_owned()).await }, + move |result| { + let Some(dialog) = dialog.upgrade() else { + return; + }; + if dialog.imp().sign_in_attempt.get() != attempt { + return; + } + dialog.imp().signing_in.replace(None); + dialog.signed_in_with(result, &telemetry); + }, + ); + } + + fn signed_in_with(&self, result: Result, TaskFailure>, telemetry: &Telemetry) { + let account_id = self.imp().deps.get().and_then(|deps| { + let status = deps.account.status.borrow(); + status.entitlement().map(|entitlement| entitlement.claims().sub.clone()) + }); + if let (true, Some(account_id)) = (self.signed_in(), account_id) { + telemetry.signed_in(&account_id); + } + // The account's own watch may have moved the sheet on already. + if matches!(self.page(), Some(SheetPage::SigningIn | SheetPage::SignedOut)) { + self.begin(); + } + match result { + // Over the device limit the account is still signed in, and sharing needs no license. + Ok(Err(error)) if !self.signed_in() && !matches!(error, AccountError::SignInCanceled) => { + self.alert(&account_error_message(&error)); + } + Err(failure) => tracing::warn!(%failure, "the sign-in did not finish"), + Ok(_) => {} + } + } + + pub(super) fn cancel_sign_in(&self) { + if let Some(signing_in) = self.imp().signing_in.take() { + signing_in.cancel(); + } + self.begin(); + } + + pub(super) fn open_account(&self) { + if let Some(deps) = self.imp().deps.get() { + self.open_uri(&format!("{}/", deps.account.portal)); + } + } + + pub(super) fn copy_link(&self) { + if let Some(SheetPage::Created { url, .. }) = self.page() { + match crate::ui::clipboard::put_text(self, url) { + Ok(()) => self.alert(&gettext("Copied to clipboard")), + Err(error) => self.alert(&error.message()), + } + } + } + + pub(super) fn open_link(&self) { + if let Some(SheetPage::Created { url, .. }) = self.page() { + self.open_uri(&url); + } + } + + pub(super) fn open_uri(&self, uri: &str) { + let window = self.root().and_downcast::(); + let dialog = self.downgrade(); + gtk::UriLauncher::new(uri).launch(window.as_ref(), gio::Cancellable::NONE, move |launched| { + if let (Err(error), Some(dialog)) = (launched, dialog.upgrade()) { + tracing::warn!(%error, "the browser did not open"); + dialog.alert(&gettext("TablePro could not open the page in a web browser.")); + } + }); + } +} + +// At the limit, the live links the sheet offers to revoke: the team's for a team link. +async fn read_limits(account: Account, team: Option) -> LimitsRead { + let limits = account.share_limits().await?; + let team = sheet_view::chosen_team(&limits, team.as_deref()).map(|team| team.id.clone()); + if sheet_view::page_for(&limits, sheet_view::chosen_team(&limits, team.as_deref())) != SheetPage::AtLimit { + return Ok((limits, Vec::new())); + } + let mut live = Vec::new(); + let mut cursor: Option = None; + for _ in 0..LIST_PAGES { + let page = account.list_shares(true, team.as_deref(), cursor.as_deref()).await?; + live.extend(page.shares); + match page.next_cursor { + Some(next) => cursor = Some(next), + None => break, + } + } + Ok((limits, live)) +} + +// The core's refusal of a share before the upload. Never a server code: the server would refuse it with a 422. +const NO_COLUMNS: &str = "share_no_columns"; + +// A body too large is worded as the server's own refusal of one. +fn refused(refusal: SnapshotRefusal) -> AccountError { + let (status, code) = match refusal { + SnapshotRefusal::Cell { .. } | SnapshotRefusal::FirstRow => (413, "snapshot_too_large"), + SnapshotRefusal::NoColumns => (422, NO_COLUMNS), + }; + AccountError::Refused { + status, + code: code.to_owned(), + detail: refusal.to_string(), + } +} + +fn load_error_message(error: &AccountError) -> String { + match error { + AccountError::Unreachable(_) => share_error_message(error), + _ => account_error_message(error), + } +} diff --git a/linux/crates/app/src/ui/share_dialog/pages.rs b/linux/crates/app/src/ui/share_dialog/pages.rs new file mode 100644 index 0000000000..94e91de4a8 --- /dev/null +++ b/linux/crates/app/src/ui/share_dialog/pages.rs @@ -0,0 +1,258 @@ +use gtk4 as gtk; +use gtk4::glib; +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use tablepro_account::{ShareLimits, ShareTeam}; + +use super::ShareDialog; +use super::form::add_targets; +use super::sheet_view::{self, SheetPage}; +use crate::i18n::{gettext, gettext_f}; +use crate::ui::icons; + +// The page, and what takes the focus when it shows. +pub(super) fn page_widget(dialog: &ShareDialog, page: &SheetPage) -> (gtk::Widget, Option) { + let widget = match page { + SheetPage::Unavailable(reason) => status(icons::DIALOG_WARNING, &gettext("Accounts Unavailable"), reason, None), + SheetPage::SignedOut => status( + icons::ACCOUNT, + "", + &gettext("Sign in to your TablePro account to share links."), + Some(button(dialog, &gettext("Sign In…"), true, ShareDialog::sign_in)), + ), + SheetPage::SigningIn => { + let waiting = gtk::Box::builder() + .orientation(gtk::Orientation::Vertical) + .spacing(12) + .halign(gtk::Align::Center) + .build(); + waiting.append(&adw::Spinner::builder().width_request(32).height_request(32).build()); + waiting.append(&button(dialog, &gettext("Cancel"), false, ShareDialog::cancel_sign_in)); + status( + icons::ACCOUNT, + "", + &gettext("Finish signing in in the web browser that opened."), + Some(waiting.upcast()), + ) + } + SheetPage::Loading | SheetPage::Form => adw::Spinner::builder() + .width_request(32) + .height_request(32) + .halign(gtk::Align::Center) + .valign(gtk::Align::Center) + .vexpand(true) + .build() + .upcast(), + SheetPage::Failed(message) => status( + icons::NETWORK_ERROR, + "", + message, + Some(button(dialog, &gettext("Try Again"), false, ShareDialog::load_limits)), + ), + SheetPage::Unverified => status( + icons::ACCOUNT, + "", + &gettext("Verify your email address to share links."), + Some(button( + dialog, + &gettext("Open Account"), + true, + ShareDialog::open_account, + )), + ), + SheetPage::Disabled => status( + icons::ACTION_UNAVAILABLE, + "", + &gettext("Sharing is turned off for this account."), + None, + ), + SheetPage::AtLimit => at_limit(dialog), + SheetPage::Created { + url, + copied, + columns_truncated, + } => { + let columns = columns_truncated.then(|| { + let max = dialog + .imp() + .limits + .borrow() + .as_ref() + .map_or(100, |limits| limits.max_columns); + sheet_view::columns_left_out(max) + }); + return created(dialog, url, *copied, columns); + } + }; + (widget, None) +} + +fn status(icon: &str, title: &str, body: &str, child: Option) -> gtk::Widget { + let page = adw::StatusPage::builder() + .icon_name(icon) + .title(title) + .vexpand(true) + .build(); + // The body can quote the server or a path, which is never markup. + let body = gtk::Label::builder() + .label(body) + .wrap(true) + .wrap_mode(gtk::pango::WrapMode::WordChar) + .justify(gtk::Justification::Center) + .build(); + let content = gtk::Box::builder() + .orientation(gtk::Orientation::Vertical) + .spacing(18) + .build(); + content.append(&body); + if let Some(child) = child { + content.append(&child); + } + page.set_child(Some(&content)); + page.add_css_class("compact"); + page.upcast() +} + +fn button(dialog: &ShareDialog, label: &str, suggested: bool, act: fn(&ShareDialog)) -> gtk::Widget { + let button = gtk::Button::builder() + .label(label) + .halign(gtk::Align::Center) + .css_classes(["pill"]) + .build(); + if suggested { + button.add_css_class("suggested-action"); + } + let dialog = dialog.downgrade(); + button.connect_clicked(move |_| { + if let Some(dialog) = dialog.upgrade() { + act(&dialog); + } + }); + button.upcast() +} + +fn at_limit(dialog: &ShareDialog) -> gtk::Widget { + let imp = dialog.imp(); + let page = adw::PreferencesPage::new(); + let limits = imp.limits.borrow(); + let Some(limits) = limits.as_ref() else { + return page.upcast(); + }; + let target = imp.target.borrow().clone(); + let team = sheet_view::chosen_team(limits, target.as_deref()); + // Another owner may have a free slot, so the picker stays where the form has it. + add_targets(dialog, &page, limits, target.as_deref()); + // The description is markup, and a team's name is the server's text. + let group = adw::PreferencesGroup::builder() + .description(glib::markup_escape_text(&description(limits, team))) + .build(); + let busy = imp.busy.get(); + for row in sheet_view::live_link_rows(&imp.live.borrow()) { + let shown = adw::ActionRow::builder() + .title(&row.title) + .use_markup(false) + .subtitle(&row.subtitle) + .build(); + let revoke = gtk::Button::builder() + .label(gettext("Revoke")) + .valign(gtk::Align::Center) + .sensitive(!busy) + .css_classes(["destructive-action"]) + .build(); + revoke.update_property(&[gtk::accessible::Property::Label(&gettext_f( + "Revoke {title}", + &[("title", &row.title)], + ))]); + let (dialog, id) = (dialog.downgrade(), row.id.clone()); + revoke.connect_clicked(move |_| { + if let Some(dialog) = dialog.upgrade() { + dialog.revoke(id.clone()); + } + }); + shown.add_suffix(&revoke); + group.add(&shown); + } + page.add(&group); + page.upcast() +} + +fn description(limits: &ShareLimits, team: Option<&ShareTeam>) -> String { + let message = sheet_view::at_limit_message(limits, team); + match sheet_view::at_limit_upsell(limits, team) { + Some(upsell) => format!("{message} {upsell}"), + None => message, + } +} + +fn created( + dialog: &ShareDialog, + url: &str, + copied: bool, + columns: Option, +) -> (gtk::Widget, Option) { + let link = gtk::Label::builder() + .label(url) + .selectable(true) + .wrap(true) + .wrap_mode(gtk::pango::WrapMode::Char) + .justify(gtk::Justification::Center) + .css_classes(["monospace"]) + .build(); + let copy = gtk::Button::builder() + .label(gettext("Copy")) + .css_classes(["pill"]) + .build(); + let open = gtk::Button::builder() + .label(gettext("Open in Browser")) + .css_classes(["pill", "suggested-action"]) + .build(); + let weak = dialog.downgrade(); + copy.connect_clicked(move |_| { + if let Some(dialog) = weak.upgrade() { + dialog.copy_link(); + } + }); + let weak = dialog.downgrade(); + open.connect_clicked(move |_| { + if let Some(dialog) = weak.upgrade() { + dialog.open_link(); + } + }); + let buttons = gtk::Box::builder() + .spacing(12) + .halign(gtk::Align::Center) + .homogeneous(true) + .build(); + buttons.append(©); + buttons.append(&open); + let content = gtk::Box::builder() + .orientation(gtk::Orientation::Vertical) + .spacing(18) + .build(); + content.append(&link); + content.append(&buttons); + let (title, icon) = match copied { + true => (gettext("Link copied"), icons::SUCCESS), + false => (gettext("Link created"), icons::DIALOG_WARNING), + }; + let page = adw::StatusPage::builder() + .icon_name(icon) + .title(title) + .child(&content) + .vexpand(true) + .build(); + let notes: Vec = [ + (!copied).then(|| gettext("The link could not be copied to the clipboard. Copy it with the button below.")), + columns, + ] + .into_iter() + .flatten() + .collect(); + if !notes.is_empty() { + page.set_description(Some(&glib::markup_escape_text(¬es.join(" ")))); + } + page.add_css_class("compact"); + (page.upcast(), Some(copy.upcast())) +} diff --git a/linux/crates/app/src/ui/share_dialog/preview.rs b/linux/crates/app/src/ui/share_dialog/preview.rs new file mode 100644 index 0000000000..689425a61d --- /dev/null +++ b/linux/crates/app/src/ui/share_dialog/preview.rs @@ -0,0 +1,161 @@ +use gtk4 as gtk; +use gtk4::prelude::*; +use gtk4::{gio, glib}; +use tablepro_core::column::ResultColumn; + +use crate::i18n::gettext; +use crate::services::grid::{RowSnapshot, display_text}; + +pub(crate) const PREVIEW_ROWS: usize = 5; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct PreviewCell { + pub text: String, + // NULL, a blob's size or an unreadable value: shown dimmed, as the grid shows it. + pub placeholder: bool, +} + +pub(crate) fn preview_cells(columns: &[ResultColumn], rows: &[RowSnapshot]) -> Vec> { + let mut scratch = String::new(); + rows.iter() + .take(PREVIEW_ROWS) + .map(|row| { + columns + .iter() + .enumerate() + .map(|(index, column)| { + let shown = display_text(row.value(index), &column.column_type, &mut scratch); + PreviewCell { + text: first_line(shown.text), + placeholder: shown.placeholder, + } + }) + .collect() + }) + .collect() +} + +// One line per cell, as the grid draws it. +fn first_line(text: &str) -> String { + match text.split_once(['\n', '\r']) { + Some((first, _)) => format!("{first}…"), + None => text.to_owned(), + } +} + +// A sample of what the link carries, so it takes no selection, menu or edit, which a DataGrid would offer. +pub(crate) fn preview_table(columns: &[ResultColumn], rows: &[RowSnapshot]) -> gtk::Widget { + let store = gio::ListStore::new::(); + for row in preview_cells(columns, rows) { + store.append(&glib::BoxedAnyObject::new(row)); + } + let view = gtk::ColumnView::builder() + .model(>k::NoSelection::new(Some(store))) + .reorderable(false) + .css_classes(["data-table"]) + .build(); + for (index, column) in columns.iter().enumerate() { + let shown = gtk::ColumnViewColumn::new(Some(&column.name), Some(cell_factory(index))); + shown.set_resizable(true); + view.append_column(&shown); + } + view.update_property(&[gtk::accessible::Property::Label(&gettext("Rows that will be shared"))]); + gtk::ScrolledWindow::builder() + .vscrollbar_policy(gtk::PolicyType::Never) + .hscrollbar_policy(gtk::PolicyType::Automatic) + .propagate_natural_height(true) + .css_classes(["card"]) + .overflow(gtk::Overflow::Hidden) + .child(&view) + .build() + .upcast() +} + +fn cell_factory(index: usize) -> gtk::SignalListItemFactory { + let factory = gtk::SignalListItemFactory::new(); + factory.connect_setup(|_, object| { + if let Some(item) = object.downcast_ref::() { + let label = gtk::Label::builder() + .xalign(0.0) + .ellipsize(gtk::pango::EllipsizeMode::End) + .max_width_chars(32) + .single_line_mode(true) + .build(); + item.set_child(Some(&label)); + } + }); + factory.connect_bind(move |_, object| { + let Some(item) = object.downcast_ref::() else { + return; + }; + let (Some(label), Some(row)) = ( + item.child().and_downcast::(), + item.item().and_downcast::(), + ) else { + return; + }; + let row = row.borrow::>(); + let Some(cell) = row.get(index) else { + return; + }; + label.set_label(&cell.text); + if cell.placeholder { + label.add_css_class("dim-label"); + } else { + label.remove_css_class("dim-label"); + } + }); + factory +} + +#[cfg(test)] +mod tests { + use tablepro_core::Value; + use tablepro_core::column::ColumnType; + + use super::*; + + #[test] + fn the_preview_takes_five_rows_and_writes_cells_as_the_grid_does() { + let columns = [ + ResultColumn::new("name", ColumnType::untyped_text("text")), + ResultColumn::new("note", ColumnType::untyped_text("text")), + ]; + let rows: Vec = (0..8) + .map(|index| { + RowSnapshot::new( + vec![Value::Text(format!("row {index}")), Value::Null].into(), + vec![(1, Value::Text("first\nsecond".to_owned()))], + ) + }) + .collect(); + + let cells = preview_cells(&columns, &rows); + + assert_eq!(cells.len(), PREVIEW_ROWS); + assert_eq!( + cells[4], + [ + PreviewCell { + text: "row 4".to_owned(), + placeholder: false + }, + PreviewCell { + text: "first…".to_owned(), + placeholder: false + }, + ] + ); + } + + #[test] + fn a_null_cell_is_a_placeholder() { + let columns = [ResultColumn::new("note", ColumnType::untyped_text("text"))]; + let rows = [RowSnapshot::new(vec![Value::Null].into(), Vec::new())]; + + let cells = preview_cells(&columns, &rows); + + assert_eq!(cells[0][0].text, "NULL"); + assert!(cells[0][0].placeholder); + } +} diff --git a/linux/crates/app/src/ui/share_dialog/share_columns.rs b/linux/crates/app/src/ui/share_dialog/share_columns.rs new file mode 100644 index 0000000000..0d4bb6d525 --- /dev/null +++ b/linux/crates/app/src/ui/share_dialog/share_columns.rs @@ -0,0 +1,265 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use gtk4 as gtk; +use gtk4::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use tablepro_core::masking::detect::{MaskSuggestion, SuggestionReason}; +use tablepro_core::masking::{MaskingStyle, ShareChoice, SharePlan}; + +use super::masking_text::{style_label, values_reason}; +use crate::i18n::{gettext, gettext_f, ngettext_f}; +use crate::services::share_subject::SharedRows; + +// One shared column as the sheet starts it (PLAN-MASKING 8.4). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ShareColumn { + pub name: String, + pub suggestion: Option, +} + +impl ShareColumn { + // A share hides what looks sensitive unless the user keeps it. + pub(crate) fn initial(&self) -> ShareChoice { + match self.suggestion { + Some(suggestion) => ShareChoice::Mask(suggestion.style), + None => ShareChoice::Keep, + } + } + + // What the picker offers, in order: Keep, each style, then Remove. + pub(crate) fn options() -> Vec { + [ShareChoice::Keep] + .into_iter() + .chain(MaskingStyle::ALL.into_iter().map(ShareChoice::Mask)) + .chain([ShareChoice::Remove]) + .collect() + } + + pub(crate) fn reason(&self) -> Option { + Some(match self.suggestion?.reason { + SuggestionReason::ColumnName { .. } => gettext("The name looks like personal data"), + SuggestionReason::Values { kind } => values_reason(kind), + }) + } +} + +pub(crate) fn share_columns(rows: &SharedRows, max_rows: u64, max_columns: u64) -> Vec { + rows.suggestions(max_rows, max_columns) + .into_iter() + .zip(rows.columns.iter()) + .map(|(suggestion, column)| ShareColumn { + name: column.name.clone(), + suggestion, + }) + .collect() +} + +// The line under the list. +pub(crate) fn summary(plan: &SharePlan, choices: &[ShareChoice]) -> String { + let masked = plan.masked().iter().filter(|style| style.is_some()).count() as u64; + let removed = choices.iter().filter(|choice| **choice == ShareChoice::Remove).count(); + ngettext_f( + "{n} column masked, {m} removed.", + "{n} columns masked, {m} removed.", + masked, + &[("n", &masked.to_string()), ("m", &removed.to_string())], + ) +} + +pub(crate) fn detection_note(columns: &[ShareColumn]) -> Option { + columns + .iter() + .any(|column| column.suggestion.is_some()) + .then(|| gettext("TablePro masked columns that look sensitive. Check them before sharing.")) +} + +// The Columns group with its counts line; the rows go in once the detectors have read the columns. +pub(super) fn columns_group(summary: >k::Label) -> adw::PreferencesGroup { + let group = adw::PreferencesGroup::builder().title(gettext("Columns")).build(); + group.add(summary); + group +} + +// Each shared column with Keep, Mask or Remove and, for Mask, its style, above the counts line. +pub(super) fn fill_columns( + group: &adw::PreferencesGroup, + columns: &[ShareColumn], + choices: &Rc>>, + changed: &Rc, + summary: >k::Label, +) { + if let Some(note) = detection_note(columns) { + group.set_description(Some(¬e)); + } + group.remove(summary); + for (index, column) in columns.iter().enumerate() { + let choice = choices.borrow().get(index).copied().unwrap_or(ShareChoice::Keep); + group.add(&column_row(column, index, choice, choices, changed)); + } + group.add(summary); +} + +pub(super) fn summary_label() -> gtk::Label { + gtk::Label::builder() + .xalign(0.0) + .wrap(true) + .margin_top(12) + .css_classes(["dimmed", "caption"]) + .build() +} + +// One picker per column, Keep, Mask as each style, then Remove. The row shows the short form of the choice, +// so it fits the sheet's width; the list names each in full. +fn column_row( + column: &ShareColumn, + index: usize, + choice: ShareChoice, + choices: &Rc>>, + changed: &Rc, +) -> adw::ComboRow { + let options = ShareColumn::options(); + let labels: Vec = options.iter().map(|option| choice_label(*option)).collect(); + let refs: Vec<&str> = labels.iter().map(String::as_str).collect(); + let row = adw::ComboRow::builder() + .title(&column.name) + .use_markup(false) + .model(>k::StringList::new(&refs)) + .expression(gtk::PropertyExpression::new( + gtk::StringObject::static_type(), + None::, + "string", + )) + .build(); + let short: Vec<(String, String)> = options + .iter() + .map(|option| (choice_label(*option), short_label(*option))) + .collect(); + row.set_factory(Some(&label_factory(move |full| { + short + .iter() + .find(|(long, _)| long == full) + .map_or_else(|| full.to_owned(), |(_, short)| short.clone()) + }))); + row.set_list_factory(Some(&label_factory(str::to_owned))); + if let Some(reason) = column.reason() { + row.set_subtitle(&reason); + } + let at = options + .iter() + .position(|option| *option == choice) + .or_else(|| options.iter().position(|option| *option == column.initial())) + .unwrap_or_default(); + row.set_selected(at as u32); + let (choices, changed) = (choices.clone(), changed.clone()); + row.connect_selected_notify(move |row| { + let Some(picked) = options.get(row.selected() as usize).copied() else { + return; + }; + if let Some(slot) = choices.borrow_mut().get_mut(index) { + *slot = picked; + } + changed(); + }); + row +} + +// A label per choice, from the full text the model holds. +fn label_factory(text: impl Fn(&str) -> String + 'static) -> gtk::SignalListItemFactory { + let factory = gtk::SignalListItemFactory::new(); + factory.connect_setup(|_, item| { + if let Some(item) = item.downcast_ref::() { + item.set_child(Some(>k::Label::builder().xalign(0.0).build())); + } + }); + factory.connect_bind(move |_, item| { + let Some(item) = item.downcast_ref::() else { + return; + }; + if let (Some(label), Some(full)) = ( + item.child().and_downcast::(), + item.item().and_downcast::(), + ) { + label.set_label(&text(&full.string())); + } + }); + factory +} + +// What the row shows of a choice: a style alone reads as masking under the column's name. +pub(crate) fn short_label(choice: ShareChoice) -> String { + match choice { + ShareChoice::Mask(style) => style_label(style), + other => choice_label(other), + } +} + +pub(crate) fn choice_label(choice: ShareChoice) -> String { + match choice { + ShareChoice::Keep => gettext("Keep"), + ShareChoice::Mask(style) => gettext_f("Mask as {style}", &[("style", &style_label(style))]), + ShareChoice::Remove => gettext("Remove"), + } +} + +#[cfg(test)] +mod tests { + use tablepro_core::masking::detect::SensitiveKind; + + use super::*; + + fn column(suggestion: Option) -> ShareColumn { + ShareColumn { + name: "c".to_owned(), + suggestion: suggestion.map(|style| MaskSuggestion { + style, + reason: SuggestionReason::Values { + kind: SensitiveKind::Email, + }, + }), + } + } + + #[test] + fn every_column_offers_keep_each_style_and_remove() { + assert_eq!( + ShareColumn::options(), + [ + ShareChoice::Keep, + ShareChoice::Mask(MaskingStyle::Full), + ShareChoice::Mask(MaskingStyle::LastFour), + ShareChoice::Mask(MaskingStyle::Email), + ShareChoice::Mask(MaskingStyle::Hash), + ShareChoice::Mask(MaskingStyle::Null), + ShareChoice::Remove + ] + ); + } + + #[test] + fn a_detected_column_starts_masked_and_may_be_kept() { + let detected = column(Some(MaskingStyle::Email)); + let plain = column(None); + + assert_eq!(detected.initial(), ShareChoice::Mask(MaskingStyle::Email)); + assert_eq!(detected.reason().as_deref(), Some("Values look like email addresses")); + assert_eq!(plain.initial(), ShareChoice::Keep); + assert_eq!(plain.reason(), None); + assert!(detection_note(std::slice::from_ref(&plain)).is_none()); + assert!(detection_note(&[plain, detected]).is_some()); + } + + #[test] + fn the_summary_counts_masked_and_removed_columns() { + let choices = [ + ShareChoice::Remove, + ShareChoice::Mask(MaskingStyle::Hash), + ShareChoice::Mask(MaskingStyle::Full), + ShareChoice::Keep, + ]; + let plan = SharePlan::new(4, &choices, 100); + + assert_eq!(summary(&plan, &choices), "2 columns masked, 1 removed."); + } +} diff --git a/linux/crates/app/src/ui/share_dialog/sheet_view.rs b/linux/crates/app/src/ui/share_dialog/sheet_view.rs new file mode 100644 index 0000000000..511c86161f --- /dev/null +++ b/linux/crates/app/src/ui/share_dialog/sheet_view.rs @@ -0,0 +1,629 @@ +use tablepro_account::{ + AccountStatus, MAX_SHARE_SQL_BYTES, Share, ShareExpiry, ShareKind, ShareLimits, ShareTeam, sent_share_password, +}; +use tablepro_core::secret_scan::SecretHitKind; + +use crate::i18n::{gettext, gettext_f, ngettext_f}; +use crate::ui::format::format_thousands; +use crate::ui::preferences_dialog::account_view::day; + +const PRO: &str = "pro"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum SheetPage { + Unavailable(String), + SignedOut, + SigningIn, + Loading, + Failed(String), + Unverified, + Disabled, + AtLimit, + Form, + // Whether the link reached the clipboard, and whether the server's column cap cut the result. + Created { + url: String, + copied: bool, + columns_truncated: bool, + }, +} + +// Who a link belongs to: the account, or one of the teams it holds a seat in. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ShareTarget { + pub team: Option, + pub name: String, + pub subtitle: String, + // False for a team that turned public links off. + pub enabled: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ExpiryChoice { + pub expiry: ShareExpiry, + // False for an expiry only Pro has, which shows with a Pro tag. + pub allowed: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct LiveLinkRow { + pub id: String, + pub title: String, + pub subtitle: String, + // It does not resolve until the account or the team turns sharing on again. + pub suspended: bool, +} + +// An offline file unlocks features but signs no request. +pub(crate) fn signed_in(status: &AccountStatus) -> bool { + matches!(status, AccountStatus::SignedIn(_)) +} + +// A team link counts against the team's limit, never the account's. +pub(crate) fn page_for(limits: &ShareLimits, team: Option<&ShareTeam>) -> SheetPage { + let at_limit = team.map_or_else(|| limits.at_limit(), ShareTeam::at_limit); + if !limits.email_verified { + SheetPage::Unverified + } else if limits.sharing_disabled { + SheetPage::Disabled + } else if at_limit { + SheetPage::AtLimit + } else { + SheetPage::Form + } +} + +// The team a choice names, when the plan still lists it and lets it share. +pub(crate) fn chosen_team<'a>(limits: &'a ShareLimits, team: Option<&str>) -> Option<&'a ShareTeam> { + let team = team?; + limits.teams.iter().find(|known| known.id == team && known.public_links) +} + +// Personal first, then each team, a team that turned public links off listed but not offered. +pub(crate) fn share_targets(limits: &ShareLimits) -> Vec { + let mut targets = vec![ShareTarget { + team: None, + name: gettext("Personal"), + subtitle: String::new(), + enabled: true, + }]; + targets.extend(limits.teams.iter().map(|team| ShareTarget { + team: Some(team.id.clone()), + name: team.name.replace('\0', ""), + subtitle: match team.public_links { + true => team_links(team), + false => gettext("Public links are off for this team."), + }, + enabled: team.public_links, + })); + targets +} + +fn team_links(team: &ShareTeam) -> String { + ngettext_f( + "{live} of {limit} link", + "{live} of {limit} links", + team.live_limit, + &[ + ("live", &format_thousands(team.live)), + ("limit", &format_thousands(team.live_limit)), + ], + ) +} + +pub(crate) fn is_pro(limits: &ShareLimits) -> bool { + limits.plan == PRO +} + +pub(crate) fn title(kind: ShareKind) -> String { + match kind { + ShareKind::Query => gettext("Share Query"), + ShareKind::Result => gettext("Share Result"), + } +} + +pub(crate) fn footer(limits: &ShareLimits, team: Option<&ShareTeam>) -> String { + if let Some(team) = team { + return gettext_f( + "{team} · {links}", + &[("team", &team.name.replace('\0', "")), ("links", &team_links(team))], + ); + } + let live = format_thousands(limits.live); + match is_pro(limits) { + true => ngettext_f( + "Pro · {live} link", + "Pro · {live} links", + limits.live, + &[("live", &live)], + ), + false => ngettext_f( + "Free · {live} of {limit} link · first {max_rows} rows", + "Free · {live} of {limit} links · first {max_rows} rows", + limits.live_limit, + &[ + ("live", &live), + ("limit", &format_thousands(limits.live_limit)), + ("max_rows", &format_thousands(limits.max_rows)), + ], + ), + } +} + +// The plan's expiries, then Never for a plan without it, which only Pro may pick. +pub(crate) fn expiry_choices(limits: &ShareLimits) -> Vec { + let mut choices: Vec = ShareExpiry::ALL + .into_iter() + .filter(|expiry| limits.expiries.contains(expiry)) + .map(|expiry| ExpiryChoice { expiry, allowed: true }) + .collect(); + if !limits.expiries.contains(&ShareExpiry::Never) { + choices.push(ExpiryChoice { + expiry: ShareExpiry::Never, + allowed: false, + }); + } + choices +} + +pub(crate) fn default_expiry(limits: &ShareLimits) -> ShareExpiry { + limits + .default_expiry + .filter(|expiry| limits.expiries.contains(expiry)) + .or_else(|| limits.expiries.last().copied()) + .unwrap_or(ShareExpiry::ThirtyDays) +} + +pub(crate) fn expiry_label(expiry: ShareExpiry) -> String { + match expiry { + ShareExpiry::OneDay => gettext("1 day"), + ShareExpiry::SevenDays => gettext("7 days"), + ShareExpiry::ThirtyDays => gettext("30 days"), + ShareExpiry::Never => gettext("Never"), + } +} + +pub(crate) fn cap_note(total: u64, max_rows: u64) -> Option { + (total > max_rows).then(|| { + gettext_f( + "Shares the first {shared} of {total} rows.", + &[ + ("shared", &format_thousands(max_rows)), + ("total", &format_thousands(total)), + ], + ) + }) +} + +// A downgrade can leave more live links than the plan allows, so the count and the limit are both named. +pub(crate) fn at_limit_message(limits: &ShareLimits, team: Option<&ShareTeam>) -> String { + if let Some(team) = team { + let (live, limit, name) = ( + format_thousands(team.live), + format_thousands(team.live_limit), + team.name.replace('\0', ""), + ); + return ngettext_f( + "{team} has {live} live link. The team allows {limit}. Revoke one to share another.", + "{team} has {live} live links. The team allows {limit}. Revoke one to share another.", + team.live, + &[("team", &name), ("live", &live), ("limit", &limit)], + ); + } + let (live, limit) = (format_thousands(limits.live), format_thousands(limits.live_limit)); + let args = [("live", live.as_str()), ("limit", limit.as_str())]; + match is_pro(limits) { + true => ngettext_f( + "You have {live} live link. Pro allows {limit}. Revoke one to share another.", + "You have {live} live links. Pro allows {limit}. Revoke one to share another.", + limits.live, + &args, + ), + false => ngettext_f( + "You have {live} live link. Free allows {limit}. Revoke one to share another.", + "You have {live} live links. Free allows {limit}. Revoke one to share another.", + limits.live, + &args, + ), + } +} + +// Pro's own cap, and a team's, need no pitch. +pub(crate) fn at_limit_upsell(limits: &ShareLimits, team: Option<&ShareTeam>) -> Option { + (!is_pro(limits) && team.is_none()).then(|| gettext("Pro allows up to 1,000.")) +} + +// The server takes the first `max_columns` columns of a result and leaves the rest out. +pub(crate) fn column_note(columns_cut: bool, max_columns: u64) -> Option { + columns_cut.then(|| { + ngettext_f( + "Shares the first {count} column.", + "Shares the first {count} columns.", + max_columns, + &[("count", &format_thousands(max_columns))], + ) + }) +} + +// What keeps Create off in the form's own fields, worded as macOS words it; the core refuses the same at create. +pub(crate) fn field_problems(sql: &str, password: Option<&str>) -> Vec { + let mut problems = Vec::new(); + if sql.len() > MAX_SHARE_SQL_BYTES { + problems.push(gettext( + "This query is too long to share. A link holds up to 256 KB of SQL.", + )); + } + if password.is_some_and(|password| !password.is_empty() && sent_share_password(password).is_empty()) { + problems.push(gettext("A password can’t be only spaces or tabs.")); + } + problems +} + +// macOS words it the same. +pub(crate) fn no_columns_note() -> String { + gettext("Keep or mask at least one column to share.") +} + +pub(crate) fn columns_left_out(max_columns: u64) -> String { + ngettext_f( + "The link shares the first {count} column.", + "The link shares the first {count} columns.", + max_columns, + &[("count", &format_thousands(max_columns))], + ) +} + +// Oldest first, so the link that has been out longest is the first offered. +pub(crate) fn live_link_rows(shares: &[Share]) -> Vec { + let mut live: Vec<&Share> = shares.iter().filter(|share| share.is_live()).collect(); + live.sort_by_key(|share| share.created_at); + live.into_iter() + .map(|share| LiveLinkRow { + id: share.id.clone(), + title: link_title(share), + subtitle: link_subtitle(share), + suspended: share.suspended, + }) + .collect() +} + +// GTK refuses text with a NUL in it, which the server passes through from whoever named the link. +fn link_title(share: &Share) -> String { + let title = share.title.replace('\0', ""); + match (title.trim(), share.kind.as_str()) { + ("", "result") => gettext("Shared result"), + ("", _) => gettext("Shared query"), + (title, _) => title.to_owned(), + } +} + +// A suspended link says so first, where a screen reader reads it with the row. +fn link_subtitle(share: &Share) -> String { + let created = gettext_f("Shared {date}", &[("date", &day(share.created_at))]); + let expires = match share.expires_at { + Some(at) => gettext_f("Expires {date}", &[("date", &day(at))]), + None => gettext("Never expires"), + }; + let suspended = share.suspended.then(|| gettext("Suspended")); + suspended + .into_iter() + .chain([created, expires]) + .collect::>() + .join(" · ") +} + +// Hidden SQL reaches no viewer, so only the columns warn then. +pub(crate) fn secret_warnings(kinds: &[SecretHitKind], columns: &[String], hide_sql: bool) -> Vec { + let mut warnings: Vec = match hide_sql { + true => Vec::new(), + false => kinds + .iter() + .map(|kind| { + gettext_f( + "This query may contain a secret ({kind}). Anyone with the link can read it.", + &[("kind", &secret_kind(*kind))], + ) + }) + .collect(), + }; + if !columns.is_empty() { + warnings.push(gettext_f( + "Some columns may hold secrets: {names}.", + &[("names", &columns.join(", "))], + )); + } + warnings +} + +fn secret_kind(kind: SecretHitKind) -> String { + match kind { + SecretHitKind::AwsAccessKey => gettext("an AWS access key"), + SecretHitKind::PrivateKey => gettext("a private key"), + SecretHitKind::JsonWebToken => gettext("a JSON Web Token"), + SecretHitKind::GitHubToken => gettext("a GitHub token"), + SecretHitKind::SlackToken => gettext("a Slack token"), + SecretHitKind::StripeKey => gettext("a Stripe key"), + SecretHitKind::GoogleApiKey => gettext("a Google API key"), + SecretHitKind::UrlCredentials => gettext("a password in a URL"), + SecretHitKind::AssignedSecret => gettext("a password or token"), + } +} + +#[cfg(test)] +mod tests { + use chrono::{TimeDelta, Utc}; + + use super::*; + + fn limits(plan: &str, live: u64) -> ShareLimits { + let pro = plan == PRO; + ShareLimits { + plan: plan.to_owned(), + live, + live_limit: if pro { 1_000 } else { 5 }, + max_rows: if pro { 10_000 } else { 1_000 }, + expiries: match pro { + true => ShareExpiry::ALL.to_vec(), + false => vec![ShareExpiry::OneDay, ShareExpiry::SevenDays, ShareExpiry::ThirtyDays], + }, + default_expiry: Some(if pro { + ShareExpiry::Never + } else { + ShareExpiry::ThirtyDays + }), + password: pro, + disable_download: pro, + team: pro, + email_verified: true, + sharing_disabled: false, + max_columns: 100, + teams: Vec::new(), + } + } + + fn team(id: &str, live: u64, public_links: bool) -> ShareTeam { + ShareTeam { + id: id.to_owned(), + name: format!("Team {id}"), + live, + live_limit: 1_000, + public_links, + } + } + + fn share(id: &str, title: &str, state: &str, created_days_ago: i64) -> Share { + let now = Utc::now(); + Share { + id: id.to_owned(), + kind: "result".to_owned(), + scope: "account".to_owned(), + team_id: None, + title: title.to_owned(), + note: String::new(), + dialect: String::new(), + sql: None, + has_snapshot: true, + row_count: Some(1), + truncated: Some(false), + hide_sql: false, + allow_download: true, + has_password: false, + state: state.to_owned(), + removed_reason: None, + suspended: false, + suspended_by: None, + view_count: 0, + created_at: now - TimeDelta::days(created_days_ago), + updated_at: now, + expires_at: None, + revoked_at: None, + removed_at: None, + url: None, + } + } + + #[test] + fn the_page_follows_the_accounts_state_in_the_plans_order() { + let mut unverified = limits("free", 5); + unverified.email_verified = false; + unverified.sharing_disabled = true; + let mut disabled = limits("free", 5); + disabled.sharing_disabled = true; + + assert_eq!(page_for(&unverified, None), SheetPage::Unverified); + assert_eq!(page_for(&disabled, None), SheetPage::Disabled); + assert_eq!(page_for(&limits("free", 5), None), SheetPage::AtLimit); + assert_eq!(page_for(&limits("free", 4), None), SheetPage::Form); + assert_eq!(page_for(&limits("pro", 5), None), SheetPage::Form); + } + + #[test] + fn the_footer_names_the_plan_its_links_and_free_rows() { + assert_eq!( + footer(&limits("free", 3), None), + "Free · 3 of 5 links · first 1,000 rows" + ); + assert_eq!(footer(&limits("pro", 12), None), "Pro · 12 links"); + assert_eq!(footer(&limits("pro", 1), None), "Pro · 1 link"); + } + + #[test] + fn free_sees_never_as_a_pro_expiry_and_defaults_to_thirty_days() { + let free = limits("free", 0); + let pro = limits("pro", 0); + + let free_choices = expiry_choices(&free); + + assert_eq!(free_choices.len(), 4); + assert!(free_choices[..3].iter().all(|choice| choice.allowed)); + assert_eq!( + free_choices[3], + ExpiryChoice { + expiry: ShareExpiry::Never, + allowed: false + } + ); + assert!(expiry_choices(&pro).iter().all(|choice| choice.allowed)); + assert_eq!(default_expiry(&free), ShareExpiry::ThirtyDays); + assert_eq!(default_expiry(&pro), ShareExpiry::Never); + } + + #[test] + fn a_default_the_plan_does_not_offer_falls_back_to_its_longest() { + let mut odd = limits("free", 0); + odd.default_expiry = Some(ShareExpiry::Never); + + assert_eq!(default_expiry(&odd), ShareExpiry::ThirtyDays); + odd.expiries.clear(); + assert_eq!(default_expiry(&odd), ShareExpiry::ThirtyDays); + } + + #[test] + fn only_a_result_past_the_plans_rows_gets_the_cap_note() { + assert_eq!( + cap_note(48_210, 1_000).as_deref(), + Some("Shares the first 1,000 of 48,210 rows.") + ); + assert_eq!(cap_note(1_000, 1_000), None); + } + + #[test] + fn at_the_limit_free_hears_about_pro_and_pro_does_not() { + assert_eq!( + at_limit_message(&limits("free", 5), None), + "You have 5 live links. Free allows 5. Revoke one to share another." + ); + assert_eq!( + at_limit_message(&limits("free", 12), None), + "You have 12 live links. Free allows 5. Revoke one to share another.", + "a downgrade left more links than Free allows" + ); + assert_eq!( + at_limit_upsell(&limits("free", 5), None).as_deref(), + Some("Pro allows up to 1,000.") + ); + assert_eq!( + at_limit_message(&limits("pro", 1_000), None), + "You have 1,000 live links. Pro allows 1,000. Revoke one to share another." + ); + assert_eq!(at_limit_upsell(&limits("pro", 1_000), None), None); + } + + #[test] + fn live_links_list_oldest_first_and_only_live_ones() { + let mut suspended = share("shr_new", "N\0ew", "live", 1); + suspended.suspended = true; + suspended.suspended_by = Some("team".to_owned()); + let shares = [ + suspended, + share("shr_gone", "Gone", "revoked", 9), + share("shr_old", "", "live", 5), + ]; + + let rows = live_link_rows(&shares); + + assert_eq!( + rows.iter().map(|row| row.id.as_str()).collect::>(), + ["shr_old", "shr_new"] + ); + assert_eq!(rows[0].title, "Shared result"); + assert_eq!(rows[1].title, "New"); + assert!(rows[1].suspended); + assert!(rows[1].subtitle.starts_with("Suspended · "), "{}", rows[1].subtitle); + assert!(!rows[0].suspended); + assert!(rows[0].subtitle.ends_with("Never expires"), "{}", rows[0].subtitle); + } + + #[test] + fn secret_warnings_name_each_kind_and_hidden_sql_drops_them() { + let kinds = [SecretHitKind::AwsAccessKey, SecretHitKind::UrlCredentials]; + let columns = ["password".to_owned(), "ssn".to_owned()]; + + let shown = secret_warnings(&kinds, &columns, false); + let hidden = secret_warnings(&kinds, &columns, true); + + assert_eq!( + shown, + [ + "This query may contain a secret (an AWS access key). Anyone with the link can read it.", + "This query may contain a secret (a password in a URL). Anyone with the link can read it.", + "Some columns may hold secrets: password, ssn.", + ] + ); + assert_eq!(hidden, ["Some columns may hold secrets: password, ssn."]); + assert!(secret_warnings(&[], &[], false).is_empty()); + } + + #[test] + fn only_a_signed_in_account_can_share() { + assert!(!signed_in(&AccountStatus::SignedOut)); + } + + #[test] + fn personal_comes_first_and_a_team_without_public_links_is_listed_but_not_offered() { + let mut pro = limits("pro", 3); + pro.teams = vec![team("team_a", 2, true), team("team_b", 0, false)]; + + let targets = share_targets(&pro); + + assert_eq!( + targets + .iter() + .map(|target| (target.team.as_deref(), target.enabled)) + .collect::>(), + [(None, true), (Some("team_a"), true), (Some("team_b"), false)] + ); + assert_eq!(targets[0].name, "Personal"); + assert_eq!(targets[1].subtitle, "2 of 1,000 links"); + assert_eq!(targets[2].subtitle, "Public links are off for this team."); + assert_eq!( + chosen_team(&pro, Some("team_b")), + None, + "a team without public links is never chosen" + ); + assert_eq!(chosen_team(&pro, Some("team_gone")), None); + assert!(share_targets(&limits("free", 0)).len() == 1); + } + + #[test] + fn a_team_choice_counts_against_the_teams_own_limit() { + let mut pro = limits("pro", 1_000); + pro.teams = vec![team("team_a", 1_000, true), team("team_b", 4, true)]; + let full = chosen_team(&pro, Some("team_a")); + let room = chosen_team(&pro, Some("team_b")); + + assert_eq!( + page_for(&pro, room), + SheetPage::Form, + "the account's own limit counts no team link" + ); + assert_eq!(page_for(&pro, full), SheetPage::AtLimit); + assert_eq!(footer(&pro, room), "Team team_b · 4 of 1,000 links"); + assert_eq!( + at_limit_message(&pro, full), + "Team team_a has 1,000 live links. The team allows 1,000. Revoke one to share another." + ); + assert_eq!(at_limit_upsell(&limits("free", 5), full), None); + } + + #[test] + fn only_a_result_past_the_column_cap_gets_the_column_note() { + assert_eq!(column_note(true, 100).as_deref(), Some("Shares the first 100 columns.")); + assert_eq!(column_note(false, 100), None); + assert_eq!(columns_left_out(100), "The link shares the first 100 columns."); + } + + #[test] + fn a_password_of_only_spaces_or_sql_past_256_kib_keeps_create_off() { + let blank = "A password can’t be only spaces or tabs."; + let too_long = "This query is too long to share. A link holds up to 256 KB of SQL."; + + assert_eq!(field_problems("SELECT 1", Some(" \t ")), [blank]); + assert!(field_problems("SELECT 1", Some(" pw\t")).is_empty()); + assert!(field_problems("SELECT 1", Some("")).is_empty()); + assert!(field_problems("SELECT 1", None).is_empty()); + // Two bytes a character: 131,073 of them are past 256 KiB though far fewer characters. + assert!(field_problems(&"é".repeat(131_072), None).is_empty()); + assert_eq!(field_problems(&"é".repeat(131_073), Some(" ")), [too_long, blank]); + } +} diff --git a/linux/crates/app/src/ui/share_dialog/table_read.rs b/linux/crates/app/src/ui/share_dialog/table_read.rs new file mode 100644 index 0000000000..8a4b4d3af3 --- /dev/null +++ b/linux/crates/app/src/ui/share_dialog/table_read.rs @@ -0,0 +1,72 @@ +use std::sync::Arc; + +use gtk4::prelude::*; +use gtk4::subclass::prelude::*; +use tablepro_session::OperationError; +use tablepro_session::runtime::TaskFailure; + +use super::ShareDialog; +use super::sheet_view::SheetPage; +use crate::runtime::spawn_and_deliver; +use crate::services::share_subject::{ShareSubject, SharedRows}; +use crate::ui::error_text::{operation_error_message, task_failure_message}; + +impl ShareDialog { + pub(super) fn current_subject(&self) -> Option> { + self.imp().subject.borrow().clone() + } + + // A table tab hands over its view, whose rows are read once the plan says how many. + pub(super) fn rows_to_read(&self) -> bool { + self.current_subject() + .is_some_and(|subject| subject.table.is_some() && subject.rows.is_none()) + } + + pub(super) fn read_table(&self, max_rows: u64) { + let imp = self.imp(); + let (Some(deps), Some(table)) = ( + imp.deps.get(), + self.current_subject().and_then(|subject| subject.table.clone()), + ) else { + return; + }; + let read = imp.read.get() + 1; + imp.read.set(read); + self.show(SheetPage::Loading); + let dialog = self.downgrade(); + spawn_and_deliver(&deps.tasks, Arc::new(table).read(max_rows), move |result| { + if let Some(dialog) = dialog.upgrade() { + dialog.table_read(read, result); + } + }); + } + + fn table_read(&self, read: u64, result: Result, TaskFailure>) { + let imp = self.imp(); + if imp.read.get() != read { + return; + } + match result { + Ok(Ok(rows)) => { + let read = self.current_subject().map(|subject| ShareSubject { + rows: Some(rows), + ..(*subject).clone() + }); + imp.subject.replace(read.map(Arc::new)); + self.show(SheetPage::Form); + } + Ok(Err(error)) => self.show(SheetPage::Failed(operation_error_message(&error))), + Err(failure) => self.show(SheetPage::Failed(task_failure_message(&failure))), + } + } + + // A team link counts against the team, so its limits and its links are read again for it. + pub(super) fn choose_target(&self, team: Option) { + let imp = self.imp(); + if *imp.target.borrow() == team { + return; + } + imp.target.replace(team); + self.load_limits(); + } +} diff --git a/linux/crates/app/src/ui/share_dialog/tests.rs b/linux/crates/app/src/ui/share_dialog/tests.rs new file mode 100644 index 0000000000..e2a0c19e28 --- /dev/null +++ b/linux/crates/app/src/ui/share_dialog/tests.rs @@ -0,0 +1,1267 @@ +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use chrono::{TimeDelta, Utc}; +use gtk4 as gtk; +use gtk4::prelude::*; +use libadwaita as adw; +use libadwaita::prelude::*; +use tablepro_account::{ + Account, AccountSettings, AccountStatus, AppClient, BrowserLauncher, CallbackPage, DeviceDescription, Endpoints, + MachineId, Url, fakes, +}; +use tablepro_core::Value; +use tablepro_core::column::{ColumnType, ResultColumn}; +use tokio::sync::watch; + +use super::*; +use crate::runtime::AppRuntime; +use crate::services::grid::RowSnapshot; +use crate::services::share_subject::SharedRows; +use crate::test_support::{ + Approving, CloudStub, MemoryKeyring, OwnedWindow, assert_labelled, descendants, finish_on_main, test_runtime, + unlabelled_icon_buttons, wait_until, +}; + +const WAIT: Duration = Duration::from_secs(20); +const URL: &str = "https://s.tablepro.app/Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK"; + +struct Cloud { + pro: bool, + max_rows: u64, + live: AtomicU64, + verified: AtomicBool, + disabled: AtomicBool, + offline: AtomicBool, + hold_limits: AtomicBool, + hold_create: AtomicBool, + create: Mutex<(u16, String)>, + // What a create changes on the server before it answers. + after_create: Mutex>, + teams: Mutex, + suspended: AtomicBool, +} + +impl Cloud { + fn free(live: u64) -> Self { + Self { + pro: false, + max_rows: 1_000, + live: AtomicU64::new(live), + verified: AtomicBool::new(true), + disabled: AtomicBool::new(false), + offline: AtomicBool::new(false), + hold_limits: AtomicBool::new(false), + hold_create: AtomicBool::new(false), + create: Mutex::new((201, created(URL))), + after_create: Mutex::new(None), + teams: Mutex::new("[]".to_owned()), + suspended: AtomicBool::new(false), + } + } + + fn limits(&self) -> String { + let (plan, limit, expiries, default) = match self.pro { + true => ("pro", 1_000, r#"["1d","7d","30d","never"]"#, "never"), + false => ("free", 5, r#"["1d","7d","30d"]"#, "30d"), + }; + format!( + r#"{{"plan":"{plan}","live":{},"live_limit":{limit},"max_rows":{},"expiries":{expiries},"default_expiry":"{default}","password":{pro},"disable_download":{pro},"team":{pro},"email_verified":{},"sharing_disabled":{},"teams":{}}}"#, + self.live.load(Ordering::SeqCst), + self.max_rows, + self.verified.load(Ordering::SeqCst), + self.disabled.load(Ordering::SeqCst), + self.teams.lock().expect("the teams"), + pro = self.pro, + ) + } + + fn answer(&self, method: &str, path: &str) -> Option<(u16, String)> { + match (method, path) { + ("GET", "/v2/share-limits") => { + wait_out(&self.hold_limits); + // Not an HTTP status, so the client sees no answer it can read, as offline. + Some(match self.offline.load(Ordering::SeqCst) { + true => (0, String::new()), + false => (200, self.limits()), + }) + } + ("GET", "/v2/shares") => Some(( + 200, + format!( + r#"{{"data":[{},{}]}}"#, + view_of("shr_new", "Newest", 1, self.suspended.load(Ordering::SeqCst)), + view("shr_old", "Oldest", 9) + ), + )), + ("POST", "/v2/shares") => { + wait_out(&self.hold_create); + if let Some(change) = *self.after_create.lock().expect("the change") { + change(self); + } + Some(self.create.lock().expect("the create answer").clone()) + } + ("DELETE", "/v2/shares/shr_old") => { + self.live.fetch_sub(1, Ordering::SeqCst); + Some((204, String::new())) + } + _ => None, + } + } +} + +// The stub serves each request on a thread of its own, so a held answer holds only its request. +fn wait_out(hold: &AtomicBool) { + while hold.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(10)); + } +} + +fn view(id: &str, title: &str, days_ago: i64) -> String { + view_of(id, title, days_ago, false) +} + +fn view_of(id: &str, title: &str, days_ago: i64, suspended: bool) -> String { + let at = (Utc::now() - TimeDelta::days(days_ago)).to_rfc3339(); + format!( + r#"{{"id":"{id}","kind":"query","scope":"account","title":"{title}","note":"","dialect":"postgres","has_snapshot":false,"hide_sql":false,"allow_download":true,"has_password":false,"state":"live","suspended":{suspended},"view_count":0,"created_at":"{at}","updated_at":"{at}"}}"# + ) +} + +fn created(url: &str) -> String { + format!( + r#"{{"share":{},"token":"Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK","url":"{url}"}}"#, + view("shr_made", "Orders", 0) + ) +} + +// Opens nothing, so a sign-in waits until it is canceled. +struct Silent; + +#[async_trait::async_trait] +impl BrowserLauncher for Silent { + async fn open(&self, _url: &Url) -> Result<(), String> { + Ok(()) + } +} + +fn problem(status: u16, code: &str) -> (u16, String) { + ( + status, + format!(r#"{{"type":"about:blank","title":"Refused","status":{status},"code":"{code}"}}"#), + ) +} + +fn stub(machine: &MachineId, cloud: Arc) -> CloudStub { + let mut claims = fakes::claims(Utc::now(), TimeDelta::days(14), &[]); + claims.mid = machine.as_str().to_owned(); + claims.dev = "dev_here".to_owned(); + let entitlement = format!( + r#"{{"token":"{}","expires_at":"2026-11-12T00:00:00Z","refresh_after":"2026-10-30T00:00:00Z"}}"#, + fakes::sign(&claims).expect("a token") + ); + let device = format!( + r#"{{"id":"dev_here","machine_id":"{}","platform":"linux","name":"Ada's laptop","app_version":"0.1.0","os_version":"Ubuntu 26.04","created_at":"2026-10-29T00:00:00Z","last_seen_at":"2026-10-29T00:00:00Z"}}"#, + machine.as_str() + ); + let tokens = + r#"{"access_token":"stub-access","token_type":"Bearer","expires_in":3600,"refresh_token":"stub-refresh"}"#; + CloudStub::start(move |method, path| { + if let Some(answer) = cloud.answer(method, path) { + return answer; + } + match (method, path) { + ("POST", "/oauth/token") => (200, tokens.to_owned()), + ("POST", "/v2/devices") => (201, device.clone()), + ("POST", "/v2/devices/dev_here/entitlement") => (200, entitlement.clone()), + _ => (404, String::new()), + } + }) +} + +struct Harness { + window: OwnedWindow, + dialog: ShareDialog, + stub: CloudStub, + cloud: Arc, + _runtime: AppRuntime, + _dir: tempfile::TempDir, +} + +impl Harness { + fn new(cloud: Cloud, subject: ShareSubject, sign_in: bool) -> Self { + Self::with_browser(cloud, subject, sign_in, Arc::new(Approving)) + } + + fn with_browser(cloud: Cloud, subject: ShareSubject, sign_in: bool, browser: Arc) -> Self { + crate::register_test_resources(); + let runtime = test_runtime(); + let dir = tempfile::tempdir().expect("a temporary directory"); + let machine = MachineId::derive("4c4f5e2a0b6d4f3c9e8a7b6c5d4e3f20\n").expect("a machine ID"); + let cloud = Arc::new(cloud); + let stub = stub(&machine, cloud.clone()); + let (status, receiver) = watch::channel(AccountStatus::SignedOut); + let account = Account::new( + settings(&stub, machine, &dir), + Arc::new(MemoryKeyring::default()), + browser, + status, + ) + .expect("an account"); + if sign_in { + let signing_in = account.clone(); + finish_on_main( + WAIT, + runtime + .tasks() + .spawn_task(async move { signing_in.sign_in(std::future::pending()).await }), + ) + .expect("the sign-in finished") + .expect("the task ran") + .expect("signed in"); + } + let handle = AccountHandle { + status: receiver, + start: watch::channel(AccountStart::Ready(account)).1, + portal: stub.url.clone(), + }; + let window = OwnedWindow::presented(adw::Window::builder().default_width(720).default_height(800).build()); + let dialog = ShareDialog::new(ShareDialogInit { + subject, + account: handle, + tasks: runtime.tasks(), + telemetry: Telemetry::default(), + }); + dialog.present(Some(&*window)); + let harness = Self { + window, + dialog, + stub, + cloud, + _runtime: runtime, + _dir: dir, + }; + harness.settle(); + harness + } + + fn settle(&self) { + let _ = wait_until(Duration::from_millis(50), || false); + crate::test_support::drain_main_context(); + } + + fn page(&self) -> Option { + self.dialog.page() + } + + // A form waits for its rows' summary, which says what Create sends. + fn wait_for(&self, wanted: impl Fn(&SheetPage) -> bool) { + wait_until(WAIT, || self.page().as_ref().is_some_and(&wanted)) + .unwrap_or_else(|_| panic!("the sheet stayed on {:?}", self.page())); + self.summarized(); + } + + fn summarized(&self) { + let imp = self.dialog.imp(); + wait_until(WAIT, || imp.summaries.get() == imp.summarized.get()).expect("the share summarized"); + } + + fn chrome(&self) -> &Chrome { + self.dialog.imp().chrome.get().expect("the chrome") + } + + fn content(&self) -> gtk::Widget { + self.chrome().toolbar.content().expect("a page") + } + + fn buttons(&self, label: &str) -> Vec { + descendants(&self.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .filter(|button| button.label().is_some_and(|text| text == label)) + .collect() + } + + fn row_titles(&self) -> Vec { + descendants(&self.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .map(|row| row.title().to_string()) + .collect() + } + + fn requested(&self, wanted: &str) -> usize { + self.stub.requests().iter().filter(|request| *request == wanted).count() + } + + fn entry(&self, title: &str) -> adw::EntryRow { + descendants(&self.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|row| row.title() == title) + .unwrap_or_else(|| panic!("no {title} field")) + } + + fn posts(&self) -> usize { + self.stub + .requests() + .iter() + .filter(|request| *request == "POST /v2/shares") + .count() + } + + fn audit(&self) { + let content = self.content(); + for row in descendants(&content) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + { + assert_labelled(&row).unwrap_or_else(|problem| panic!("{}: {problem}", row.title())); + } + // libadwaita names a password row's peek button with a tooltip alone (testing.md, Application tests). + let peeks: Vec = descendants(&content) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .flat_map(|row| unlabelled_icon_buttons(&row)) + .collect(); + assert_eq!(unlabelled_icon_buttons(&content), peeks); + } +} + +impl Drop for Harness { + fn drop(&mut self) { + self.dialog.force_close(); + self.window.close(); + } +} + +fn settings(stub: &CloudStub, machine: MachineId, dir: &tempfile::TempDir) -> AccountSettings { + AccountSettings { + client: AppClient::LINUX, + endpoints: Endpoints::new(&stub.url, &format!("{}/v2", stub.url)).expect("the endpoints"), + device: DeviceDescription { + name: "Ada's laptop".to_owned(), + app_version: "0.1.0".to_owned(), + os_version: "Ubuntu 26.04".to_owned(), + }, + machine_id: machine, + keys: fakes::keys().expect("the test key"), + account_file: dir.path().join("account.json"), + callback_page: CallbackPage { + finished: String::new(), + unknown: String::new(), + }, + } +} + +fn query() -> ShareSubject { + ShareSubject::query( + "Orders".to_owned(), + "SELECT * FROM orders".to_owned(), + Some("postgres".to_owned()), + ) +} + +fn result(rows: usize) -> ShareSubject { + let columns: Arc<[ResultColumn]> = vec![ + ResultColumn::new("id", ColumnType::untyped_text("text")), + ResultColumn::new("password", ColumnType::untyped_text("text")), + ] + .into(); + ShareSubject { + rows: Some(SharedRows { + columns, + rows: (0..rows) + .map(|id| RowSnapshot::new(vec![Value::Text(id.to_string()), Value::Null].into(), Vec::new())) + .collect(), + extent: tablepro_core::export::ResultExtent::complete(rows as u64), + }), + ..query() + } +} + +#[gtk4::test] +fn signed_out_the_sheet_offers_sign_in_and_nothing_else() { + let harness = Harness::new(Cloud::free(0), query(), false); + + assert_eq!(harness.page(), Some(SheetPage::SignedOut)); + assert_eq!(harness.buttons("Sign In…").len(), 1); + assert!(!harness.chrome().create.is_visible()); + assert!(harness.row_titles().is_empty()); + assert!(harness.stub.requests().iter().all(|request| !request.contains("share"))); +} + +#[gtk4::test] +fn a_free_result_shows_its_fields_pro_tags_preview_and_footer() { + let mut cloud = Cloud::free(2); + cloud.max_rows = 3; + let harness = Harness::new(cloud, result(8), true); + + harness.wait_for(|page| *page == SheetPage::Form); + + assert_eq!( + harness.row_titles(), + [ + "Title", + "Note", + "Expires", + "Hide SQL", + "Password", + "Allow viewers to download", + "id", + "password", + "Some columns may hold secrets: password.", + ] + ); + let form = harness.dialog.imp().form.borrow(); + let values = form.as_ref().expect("the form").values(); + assert_eq!(values.title, "Orders"); + assert_eq!(values.expiry, tablepro_account::ShareExpiry::ThirtyDays); + drop(form); + let tags = harness.buttons("Pro"); + assert_eq!(tags.len(), 3, "Never, Password and downloads carry the tag"); + if crate::test_support::test_backend_records_properties() { + for tag in &tags { + assert!( + gtk::test_accessible_has_property(tag, gtk::AccessibleProperty::Description), + "a Pro tag does not say which option it is for" + ); + } + } + let never = descendants(&harness.content()) + .into_iter() + .find_map(|widget| widget.downcast::().ok()) + .and_then(|group| group.toggle_by_name("never")) + .expect("the Never toggle"); + assert!(!never.is_enabled()); + let preview = descendants(&harness.content()) + .into_iter() + .find_map(|widget| widget.downcast::().ok()) + .expect("the preview"); + // The preview shows only rows the link sends: the plan's 3. + assert_eq!(preview.model().map(|model| model.n_items()), Some(3)); + let groups: Vec = descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .collect(); + assert!( + groups + .iter() + .any(|group| group.description().as_deref() == Some("Shares the first 3 of 8 rows.")) + ); + assert_eq!(harness.chrome().footer.label(), "Free · 2 of 5 links · first 3 rows"); + assert!(harness.chrome().create.is_visible()); + harness.audit(); +} + +#[gtk4::test] +fn create_copies_the_link_once_however_often_it_is_pressed() { + let harness = Harness::new(Cloud::free(0), result(2), true); + harness.wait_for(|page| *page == SheetPage::Form); + + harness.chrome().create.emit_clicked(); + harness.dialog.create(); + harness.wait_for(|page| matches!(page, SheetPage::Created { .. })); + + assert_eq!( + harness.page(), + Some(SheetPage::Created { + url: URL.to_owned(), + copied: true, + columns_truncated: false, + }) + ); + assert_eq!(harness.posts(), 1); + assert_eq!(harness.buttons("Copy").len(), 1); + assert_eq!( + harness.dialog.focus(), + harness.buttons("Copy").first().map(|copy| copy.clone().upcast()), + "Copy does not take the focus" + ); + assert_eq!(harness.buttons("Open in Browser").len(), 1); + let clipboard = harness.dialog.clipboard(); + let copied = finish_on_main(WAIT, async move { clipboard.read_text_future().await }) + .expect("the clipboard to answer") + .expect("text on the clipboard"); + assert_eq!(copied.as_deref(), Some(URL)); +} + +#[gtk4::test] +fn a_refused_create_keeps_the_form_and_says_why_in_the_plans_words() { + let cloud = Cloud::free(0); + *cloud.create.lock().expect("the create answer") = problem(403, "pro_required"); + let harness = Harness::new(cloud, query(), true); + harness.wait_for(|page| *page == SheetPage::Form); + + harness.chrome().create.emit_clicked(); + wait_until(WAIT, || harness.chrome().banner.is_revealed()).expect("the refusal shown"); + + assert_eq!(harness.chrome().banner.title(), "This option needs TablePro Pro."); + assert_eq!(harness.page(), Some(SheetPage::Form)); + assert!(harness.chrome().create.is_sensitive()); +} + +#[gtk4::test] +fn at_the_limit_the_oldest_link_is_offered_first_and_a_revoke_brings_the_form_back() { + let harness = Harness::new(Cloud::free(5), query(), true); + harness.wait_for(|page| *page == SheetPage::AtLimit); + + assert_eq!(harness.row_titles(), ["Oldest", "Newest"]); + let groups: Vec = descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .collect(); + assert_eq!( + groups[0].description().as_deref(), + Some("You have 5 live links. Free allows 5. Revoke one to share another. Pro allows up to 1,000.") + ); + harness.audit(); + + harness.buttons("Revoke")[0].emit_clicked(); + harness.wait_for(|page| *page == SheetPage::Form); + + assert!( + harness + .stub + .requests() + .contains(&"DELETE /v2/shares/shr_old".to_owned()) + ); + assert_eq!( + harness.chrome().footer.label(), + "Free · 4 of 5 links · first 1,000 rows" + ); +} + +#[gtk4::test] +fn an_unverified_email_offers_the_account_page_and_no_create() { + let cloud = Cloud::free(0); + cloud.verified.store(false, Ordering::SeqCst); + let harness = Harness::new(cloud, query(), true); + + harness.wait_for(|page| *page == SheetPage::Unverified); + + assert_eq!(harness.buttons("Open Account").len(), 1); + assert!(!harness.chrome().create.is_visible()); + assert_eq!(harness.posts(), 0); +} + +#[gtk4::test] +fn a_query_share_has_no_hide_sql_and_pro_gets_its_own_options() { + let mut cloud = Cloud::free(12); + cloud.pro = true; + let harness = Harness::new(cloud, query(), true); + + harness.wait_for(|page| *page == SheetPage::Form); + + assert_eq!( + harness.row_titles(), + ["Title", "Note", "Expires", "Password", "Allow viewers to download"] + ); + assert!(harness.buttons("Pro").is_empty()); + assert_eq!(harness.chrome().footer.label(), "Pro · 12 links"); + harness.audit(); +} + +#[gtk4::test] +fn offline_the_sheet_says_so_and_try_again_reads_the_limits_again() { + let cloud = Cloud::free(1); + cloud.offline.store(true, Ordering::SeqCst); + let harness = Harness::new(cloud, query(), true); + harness.wait_for(|page| matches!(page, SheetPage::Failed(_))); + + assert_eq!( + harness.page(), + Some(SheetPage::Failed( + "You appear to be offline. Try again once you’re connected.".to_owned() + )) + ); + harness.cloud.offline.store(false, Ordering::SeqCst); + harness.buttons("Try Again")[0].emit_clicked(); + harness.wait_for(|page| *page == SheetPage::Form); + + assert_eq!(harness.requested("GET /v2/share-limits"), 2); +} + +#[gtk4::test] +fn sharing_turned_off_says_so_and_offers_no_create() { + let cloud = Cloud::free(0); + cloud.disabled.store(true, Ordering::SeqCst); + let harness = Harness::new(cloud, query(), true); + + harness.wait_for(|page| *page == SheetPage::Disabled); + + assert!(!harness.chrome().create.is_visible()); + assert_eq!(harness.posts(), 0); +} + +#[gtk4::test] +fn closing_while_the_link_is_made_keeps_the_sheet_until_the_link_is_there() { + let cloud = Cloud::free(0); + cloud.hold_create.store(true, Ordering::SeqCst); + let harness = Harness::new(cloud, query(), true); + harness.wait_for(|page| *page == SheetPage::Form); + + harness.chrome().create.emit_clicked(); + wait_until(WAIT, || harness.posts() == 1).expect("the create sent"); + harness.dialog.close(); + harness.settle(); + + assert!( + harness + .window + .visible_dialog() + .is_some_and(|shown| shown == harness.dialog), + "the sheet closed with its link on the way" + ); + assert!(harness.chrome().banner.is_revealed()); + harness.cloud.hold_create.store(false, Ordering::SeqCst); + harness.wait_for(|page| matches!(page, SheetPage::Created { .. })); + assert!(harness.dialog.can_close()); +} + +// The account holds its session through a call, so a real sign-out would wait for the read; the sheet +// leaving the read's page is what the read must respect. +#[gtk4::test] +fn a_read_that_lands_after_the_sheet_left_its_page_changes_nothing() { + let cloud = Cloud::free(0); + cloud.hold_limits.store(true, Ordering::SeqCst); + let harness = Harness::new(cloud, query(), true); + wait_until(WAIT, || harness.requested("GET /v2/share-limits") == 1).expect("the read sent"); + + harness.dialog.show(SheetPage::SignedOut); + harness.cloud.hold_limits.store(false, Ordering::SeqCst); + let _ = wait_until(Duration::from_millis(500), || false); + harness.settle(); + + assert_eq!(harness.page(), Some(SheetPage::SignedOut)); +} + +#[gtk4::test] +fn a_sign_in_a_later_one_replaced_leaves_the_later_one_waiting() { + let harness = Harness::with_browser(Cloud::free(0), query(), false, Arc::new(Silent)); + + harness.buttons("Sign In…")[0].emit_clicked(); + harness.wait_for(|page| *page == SheetPage::SigningIn); + harness.dialog.sign_in(); + let _ = wait_until(Duration::from_millis(500), || false); + harness.settle(); + + assert_eq!(harness.page(), Some(SheetPage::SigningIn)); + assert!( + harness.dialog.imp().signing_in.borrow().is_some(), + "the later sign-in lost its Cancel" + ); + harness.dialog.cancel_sign_in(); + harness.wait_for(|page| *page == SheetPage::SignedOut); +} + +#[gtk4::test] +fn a_create_refused_for_an_unverified_email_moves_to_that_page() { + let cloud = Cloud::free(0); + *cloud.create.lock().expect("the create answer") = problem(403, "email_unverified"); + *cloud.after_create.lock().expect("the change") = Some(|cloud| cloud.verified.store(false, Ordering::SeqCst)); + let harness = Harness::new(cloud, query(), true); + harness.wait_for(|page| *page == SheetPage::Form); + + harness.chrome().create.emit_clicked(); + harness.wait_for(|page| *page == SheetPage::Unverified); + + assert_eq!(harness.buttons("Open Account").len(), 1); +} + +#[gtk4::test] +fn a_revoke_after_the_limit_brings_the_form_back_as_it_was_typed() { + let cloud = Cloud::free(4); + *cloud.create.lock().expect("the create answer") = problem(409, "share_limit_reached"); + *cloud.after_create.lock().expect("the change") = Some(|cloud| cloud.live.store(5, Ordering::SeqCst)); + let harness = Harness::new(cloud, query(), true); + harness.wait_for(|page| *page == SheetPage::Form); + harness.entry("Title").set_text("Monthly orders"); + harness.entry("Note").set_text("For the review"); + + harness.chrome().create.emit_clicked(); + harness.wait_for(|page| *page == SheetPage::AtLimit); + harness.buttons("Revoke")[0].emit_clicked(); + harness.wait_for(|page| *page == SheetPage::Form); + + assert_eq!(harness.entry("Title").text(), "Monthly orders"); + assert_eq!(harness.entry("Note").text(), "For the review"); +} + +#[gtk4::test] +fn a_link_with_a_control_character_is_refused_rather_than_shown() { + let cloud = Cloud::free(0); + // JSON's escape for NUL, which no GTK label can hold. + *cloud.create.lock().expect("the create answer") = (201, created(r"https://s.tablepro.app/a\u0000b")); + let harness = Harness::new(cloud, query(), true); + harness.wait_for(|page| *page == SheetPage::Form); + + harness.chrome().create.emit_clicked(); + wait_until(WAIT, || harness.chrome().banner.is_revealed()).expect("the refusal shown"); + + assert_eq!(harness.page(), Some(SheetPage::Form)); + assert_eq!( + harness.chrome().banner.title(), + "The link couldn’t be created. Try again." + ); +} + +#[gtk4::test] +fn a_link_the_clipboard_did_not_take_is_shown_as_created_not_copied() { + let harness = Harness::new(Cloud::free(0), query(), true); + harness.wait_for(|page| *page == SheetPage::Form); + + harness.dialog.show(SheetPage::Created { + url: URL.to_owned(), + copied: false, + columns_truncated: false, + }); + + let status = harness + .content() + .downcast::() + .expect("the created page"); + assert_eq!(status.title(), "Link created"); + assert_eq!( + status.description().as_deref(), + Some("The link could not be copied to the clipboard. Copy it with the button below.") + ); + assert_eq!(harness.buttons("Copy").len(), 1); +} + +fn wide_result(columns: usize) -> ShareSubject { + let names: Arc<[ResultColumn]> = (0..columns) + .map(|index| ResultColumn::new(format!("c{index}"), ColumnType::untyped_text("text"))) + .collect(); + ShareSubject { + rows: Some(SharedRows { + columns: names, + rows: vec![RowSnapshot::new( + (0..columns) + .map(|index| Value::Text(index.to_string())) + .collect::>() + .into(), + Vec::new(), + )], + extent: tablepro_core::export::ResultExtent::complete(1), + }), + ..query() + } +} + +const TEAMS: &str = r#"[{"id":"team_01","name":"Data","live":3,"live_limit":1000,"public_links":true}, + {"id":"team_02","name":"Ops","live":0,"live_limit":1000,"public_links":false}]"#; + +#[gtk4::test] +fn share_as_lists_personal_then_each_team_and_a_team_choice_reads_that_teams_limits() { + let mut cloud = Cloud::free(12); + cloud.pro = true; + *cloud.teams.lock().expect("the teams") = TEAMS.to_owned(); + let harness = Harness::new(cloud, query(), true); + harness.wait_for(|page| *page == SheetPage::Form); + let rows: Vec = descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .filter(|row| { + row.activatable_widget() + .is_some_and(|widget| widget.is::()) + }) + .collect(); + + assert_eq!( + rows.iter().map(|row| row.title().to_string()).collect::>(), + ["Personal", "Data", "Ops"] + ); + assert!(!rows[2].is_sensitive()); + assert_eq!( + rows[2].subtitle().as_deref(), + Some("Public links are off for this team.") + ); + assert_eq!(harness.chrome().footer.label(), "Pro · 12 links"); + harness.audit(); + + assert!(WidgetExt::activate(&rows[1]), "the Data row did not activate"); + wait_until(WAIT, || harness.requested("GET /v2/share-limits") == 2).expect("the limits read again"); + harness.wait_for(|page| *page == SheetPage::Form); + + assert_eq!(harness.chrome().footer.label(), "Data · 3 of 1,000 links"); + let form = harness.dialog.imp().form.borrow(); + assert_eq!( + form.as_ref().map(|form| form.values().team), + Some(Some("team_01".to_owned())) + ); +} + +#[gtk4::test] +fn a_result_past_the_column_cap_says_so_before_and_after_the_link_is_made() { + let harness = Harness::new(Cloud::free(0), wide_result(101), true); + harness.wait_for(|page| *page == SheetPage::Form); + let preview = descendants(&harness.content()) + .into_iter() + .find_map(|widget| widget.downcast::().ok()) + .expect("the preview"); + let described = descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .any(|group| group.description().as_deref() == Some("Shares the first 100 columns.")); + + assert!(described, "the preview does not say the columns are cut"); + assert_eq!(preview.columns().n_items(), 100); + + harness.chrome().create.emit_clicked(); + harness.wait_for(|page| matches!(page, SheetPage::Created { .. })); + + assert!(matches!( + harness.page(), + Some(SheetPage::Created { + columns_truncated: true, + .. + }) + )); + let status = harness + .content() + .downcast::() + .expect("the created page"); + assert_eq!( + status.description().as_deref(), + Some("The link shares the first 100 columns.") + ); +} + +#[gtk4::test] +fn a_suspended_link_says_so_in_the_list_at_the_limit() { + let cloud = Cloud::free(5); + cloud.suspended.store(true, Ordering::SeqCst); + let harness = Harness::new(cloud, query(), true); + harness.wait_for(|page| *page == SheetPage::AtLimit); + + let newest = descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|row| row.title() == "Newest") + .expect("the newest link"); + + assert!( + newest + .subtitle() + .is_some_and(|subtitle| subtitle.starts_with("Suspended · ")), + "{:?}", + newest.subtitle() + ); +} + +#[gtk4::test] +fn a_table_view_is_read_up_to_the_plans_rows_before_the_form_shows() { + use tablepro_core::Truncation; + use tablepro_test_support::{ConnectionScript, FakeReply}; + + let runtime = test_runtime(); + let columns: Arc<[ResultColumn]> = vec![ResultColumn::new("name", ColumnType::untyped_text("text"))].into(); + let mut script = ConnectionScript::default(); + script.stream_read.always(FakeReply::ok(vec![ + tablepro_core::ResultEvent::ResultSetStarted { columns }, + tablepro_core::ResultEvent::Rows((0..7).map(|row| vec![Value::Text(format!("n{row}"))]).collect()), + tablepro_core::ResultEvent::ResultSetFinished { + retained: 7, + total_rows: Some(7), + truncation: Truncation::Complete, + }, + ])); + let fake = crate::test_support::FakeSession::start(script, [], runtime.tasks()); + let mut cloud = Cloud::free(0); + cloud.max_rows = 3; + let subject = ShareSubject { + table: Some(crate::services::share_table::TableShare { + session: fake.session.clone(), + table: tablepro_core::meta::TableRef::new(None, "people"), + columns: vec![crate::services::grid::test_columns::info("name", "text")].into(), + shown: vec![0], + filter: tablepro_core::FilterSet::default(), + sort: Vec::new(), + identity: tablepro_core::meta::RowIdentity::UniqueKey { + columns: vec!["name".to_owned()], + }, + total: Some(40), + }), + ..query() + }; + let harness = Harness::new(cloud, subject, true); + + harness.wait_for(|page| *page == SheetPage::Form); + + let read = harness + .dialog + .subject() + .and_then(|subject| subject.rows.clone()) + .expect("the rows read"); + assert_eq!(read.rows.len(), 3); + assert_eq!(read.total(), 40); + let described = descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .any(|group| group.description().as_deref() == Some("Shares the first 3 of 40 rows.")); + assert!(described, "the cap note is missing"); +} + +fn people() -> ShareSubject { + let columns: Arc<[ResultColumn]> = ["id", "email", "notes"] + .into_iter() + .map(|name| ResultColumn::new(name, ColumnType::untyped_text("text"))) + .collect(); + let text = |value: &str| Value::Text(value.to_owned()); + ShareSubject { + sql: "SELECT * FROM users WHERE email = 'ann@example.com'".to_owned(), + rows: Some(SharedRows { + columns, + rows: vec![RowSnapshot::new( + vec![text("1"), text("ann@example.com"), text("+1 555 0100")].into(), + Vec::new(), + )], + extent: tablepro_core::export::ResultExtent::complete(1), + }), + ..query() + } +} + +fn column_row(harness: &Harness, title: &str) -> adw::ComboRow { + descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|row| row.title() == title) + .unwrap_or_else(|| panic!("no {title} column")) +} + +fn offered(row: &adw::ComboRow) -> Vec { + let model = row.model().and_downcast::().expect("the choices"); + (0..model.n_items()) + .filter_map(|at| model.string(at)) + .map(|label| label.to_string()) + .collect() +} + +fn chosen(row: &adw::ComboRow) -> String { + offered(row)[row.selected() as usize].clone() +} + +fn choose(row: &adw::ComboRow, label: &str) { + let at = offered(row) + .iter() + .position(|offered| offered == label) + .unwrap_or_else(|| panic!("{label} is not offered")); + row.set_selected(at as u32); +} + +fn labels(harness: &Harness) -> Vec { + descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .map(|label| label.label().to_string()) + .collect() +} + +fn has_label(harness: &Harness, text: &str) -> bool { + labels(harness).iter().any(|label| label == text) +} + +#[gtk4::test] +fn the_columns_list_masks_detected_columns_and_the_preview_shows_what_is_sent() { + use tablepro_core::masking::{MaskingStyle, ShareChoice}; + + let harness = Harness::new(Cloud::free(0), people(), true); + harness.wait_for(|page| *page == SheetPage::Form); + + let email = column_row(&harness, "email"); + assert_eq!(chosen(&email), "Mask as Email"); + assert_eq!(email.subtitle().as_deref(), Some("The name looks like personal data")); + assert_eq!( + offered(&email), + [ + "Keep", + "Mask as Full", + "Mask as Last 4 Characters", + "Mask as Email", + "Mask as Stable Hash", + "Mask as NULL", + "Remove" + ] + ); + let notes = column_row(&harness, "notes"); + assert_eq!(notes.subtitle().as_deref(), Some("Values look like phone numbers")); + assert_eq!(chosen(¬es), "Mask as Last 4 Characters"); + assert!( + descendants(¬es) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .any(|label| label.label() == "Last 4 Characters"), + "the row does not show the short form of the choice" + ); + assert_eq!(chosen(&column_row(&harness, "id")), "Keep"); + assert!(has_label(&harness, "2 columns masked, 0 removed.")); + assert!(has_label(&harness, "a•••@example.com"), "{:?}", labels(&harness)); + assert!(has_label(&harness, "••••0100")); + assert!( + descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .any(|group| group.description().as_deref() + == Some("TablePro masked columns that look sensitive. Check them before sharing.")), + "the detection note is missing" + ); + + choose(¬es, "Keep"); + choose(&column_row(&harness, "id"), "Remove"); + harness.summarized(); + + assert!( + has_label(&harness, "1 column masked, 1 removed."), + "{:?}", + labels(&harness) + ); + assert!(has_label(&harness, "+1 555 0100")); + let chosen = harness + .dialog + .imp() + .form + .borrow() + .as_ref() + .map(|form| form.values().columns) + .expect("the form"); + assert_eq!( + chosen, + [ + ShareChoice::Remove, + ShareChoice::Mask(MaskingStyle::Email), + ShareChoice::Keep + ] + ); + harness.audit(); +} + +#[gtk4::test] +fn personal_data_in_the_sql_offers_hide_sql_in_a_notice() { + let harness = Harness::new(Cloud::free(0), people(), true); + harness.wait_for(|page| *page == SheetPage::Form); + let hide_sql = descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|row| row.title() == "Hide SQL") + .expect("the Hide SQL switch"); + let [button] = harness.buttons("Hide SQL").try_into().expect("one Hide SQL button"); + let notice = button + .ancestor(adw::PreferencesGroup::static_type()) + .expect("the notice's group"); + assert!(notice.is_visible()); + + button.emit_clicked(); + + assert!(hide_sql.is_active()); + assert!(!notice.is_visible(), "the notice stayed after Hide SQL went on"); +} + +#[gtk4::test] +fn a_result_whose_first_row_cannot_go_says_so_and_cannot_be_created() { + let columns: Arc<[ResultColumn]> = vec![ResultColumn::new("note", ColumnType::untyped_text("text"))].into(); + let subject = ShareSubject { + rows: Some(SharedRows { + columns, + rows: vec![RowSnapshot::new( + vec![Value::Text("x".repeat(300_000))].into(), + Vec::new(), + )], + extent: tablepro_core::export::ResultExtent::complete(1), + }), + ..query() + }; + let harness = Harness::new(Cloud::free(0), subject, true); + harness.wait_for(|page| *page == SheetPage::Form); + + assert!( + descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .any(|group| group.description().as_deref() == Some("This result is too large to share.")), + "the sheet does not say the result is too large" + ); + assert!(!harness.chrome().create.is_sensitive()); + + harness.dialog.create(); + harness.settle(); + + assert_eq!(harness.posts(), 0, "a share too large was sent"); + + choose(&column_row(&harness, "note"), "Mask as Full"); + harness.summarized(); + + assert!(harness.chrome().create.is_sensitive(), "a masked value fits the budget"); +} + +#[gtk4::test] +fn a_form_built_again_for_the_same_rows_reads_what_the_detectors_and_the_summary_found() { + let harness = Harness::new(Cloud::free(0), people(), true); + harness.wait_for(|page| *page == SheetPage::Form); + let sent = harness.dialog.imp().sent.borrow().clone().expect("a summary"); + + harness.dialog.load_limits(); + harness.wait_for(|page| *page == SheetPage::Form); + + let again = harness.dialog.imp().sent.borrow().clone().expect("a summary"); + assert!( + std::rc::Rc::ptr_eq(&sent, &again), + "the same rows were summarized again" + ); + assert_eq!(chosen(&column_row(&harness, "notes")), "Mask as Last 4 Characters"); +} + +#[gtk4::test] +fn the_columns_chosen_are_what_the_create_uploads() { + let harness = Harness::new(Cloud::free(0), people(), true); + harness.wait_for(|page| *page == SheetPage::Form); + + choose(&column_row(&harness, "id"), "Remove"); + choose(&column_row(&harness, "notes"), "Mask as Stable Hash"); + harness.summarized(); + harness.chrome().create.emit_clicked(); + harness.wait_for(|page| matches!(page, SheetPage::Created { .. })); + + let [body] = harness.stub.bodies("POST /v2/shares").try_into().expect("one create"); + let body: serde_json::Value = serde_json::from_str(&body).expect("a JSON body"); + let snapshot = &body["snapshot"]; + let column = |at: usize, key: &str| snapshot["columns"][at][key].as_str().map(str::to_owned); + assert_eq!(snapshot["columns"].as_array().map(Vec::len), Some(2)); + assert_eq!( + [ + column(0, "name"), + column(0, "masked"), + column(1, "name"), + column(1, "masked") + ], + [Some("email"), Some("email"), Some("notes"), Some("hash")].map(|text| text.map(str::to_owned)) + ); + assert_eq!( + snapshot["rows"], + serde_json::json!([["a•••@example.com", tablepro_core::masking::stable_hash(b"+1 555 0100")]]) + ); +} + +#[gtk4::test] +fn removing_every_column_says_so_and_cannot_be_created() { + let harness = Harness::new(Cloud::free(0), people(), true); + harness.wait_for(|page| *page == SheetPage::Form); + + for column in ["id", "email", "notes"] { + choose(&column_row(&harness, column), "Remove"); + } + harness.summarized(); + + assert!( + descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .any(|group| group.description().as_deref() == Some("Keep or mask at least one column to share.")), + "the sheet does not say every column is removed" + ); + assert!(!harness.chrome().create.is_sensitive()); + + harness.dialog.create(); + harness.settle(); + + assert_eq!(harness.posts(), 0, "a share with no column was sent"); +} + +const TEAM_AT_CAP: &str = r#"[{"id":"team_01","name":"R&D","live":1000,"live_limit":1000,"public_links":true}]"#; + +#[gtk4::test] +fn a_team_at_its_cap_names_the_team_as_written_and_offers_another_owner() { + let mut cloud = Cloud::free(12); + cloud.pro = true; + *cloud.teams.lock().expect("the teams") = TEAM_AT_CAP.to_owned(); + let harness = Harness::new(cloud, query(), true); + harness.wait_for(|page| *page == SheetPage::Form); + harness.dialog.choose_target(Some("team_01".to_owned())); + harness.wait_for(|page| *page == SheetPage::AtLimit); + + // As shown, past the markup the description is parsed as. + let shown: Vec = descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .map(|label| label.text().to_string()) + .collect(); + assert!( + shown + .iter() + .any(|text| text == "R&D has 1,000 live links. The team allows 1,000. Revoke one to share another."), + "{shown:?}" + ); + let personal = descendants(&harness.content()) + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|row| { + row.title() == "Personal" + && row + .activatable_widget() + .is_some_and(|widget| widget.is::()) + }) + .expect("Share As on the page at the cap"); + harness.audit(); + + assert!(WidgetExt::activate(&personal), "the Personal row did not activate"); + harness.wait_for(|page| *page == SheetPage::Form); + + assert_eq!(harness.chrome().footer.label(), "Pro · 12 links"); +} + +fn password_row(harness: &Harness) -> adw::PasswordEntryRow { + descendants(&harness.content()) + .into_iter() + .find_map(|widget| widget.downcast::().ok()) + .expect("the password field") +} + +#[gtk4::test] +fn a_password_of_only_spaces_keeps_create_off_and_says_why() { + let mut cloud = Cloud::free(12); + cloud.pro = true; + let harness = Harness::new(cloud, query(), true); + harness.wait_for(|page| *page == SheetPage::Form); + let password = password_row(&harness); + + password.set_text(" \t "); + + assert!(!harness.chrome().create.is_sensitive()); + assert!( + harness + .row_titles() + .contains(&"A password can’t be only spaces or tabs.".to_owned()), + "{:?}", + harness.row_titles() + ); + harness.dialog.create(); + harness.settle(); + assert_eq!(harness.posts(), 0, "a password of only spaces was sent"); + + password.set_text(" hunter2 "); + + assert!(harness.chrome().create.is_sensitive()); + assert!( + !harness + .row_titles() + .contains(&"A password can’t be only spaces or tabs.".to_owned()) + ); +} + +#[gtk4::test] +fn sql_past_256_kib_keeps_create_off_and_says_why() { + let subject = ShareSubject::query("Long".to_owned(), "é".repeat(131_073), None); + let harness = Harness::new(Cloud::free(0), subject, true); + harness.wait_for(|page| *page == SheetPage::Form); + + assert!(!harness.chrome().create.is_sensitive()); + assert!( + harness + .row_titles() + .contains(&"This query is too long to share. A link holds up to 256 KB of SQL.".to_owned()), + "{:?}", + harness.row_titles() + ); +} diff --git a/linux/crates/app/src/ui/workspace/mod.rs b/linux/crates/app/src/ui/workspace/mod.rs index 19eecb0954..2a189746bd 100644 --- a/linux/crates/app/src/ui/workspace/mod.rs +++ b/linux/crates/app/src/ui/workspace/mod.rs @@ -85,6 +85,7 @@ use crate::application::AppServices; use crate::runtime::{DeliverInput, InputSender}; use crate::services::change_tracker_registry::ChangeTrackerRegistry; use crate::services::session_context::SessionContext; +use crate::services::share_subject::ShareSubject; use crate::services::structure_tracker_registry::StructureTrackerRegistry; use crate::workspace::{ApplicationInhibit, CloseBlocker, CloseGuards, WindowInhibitor, WorkspaceHandle}; @@ -190,6 +191,8 @@ pub(crate) struct WorkspaceModel { saved_queries_dialog: Option, import_dialog: Option, driver_id: String, + account: crate::services::account_service::AccountHandle, + telemetry: crate::services::telemetry::Telemetry, /// The driver as the user knows it, for the header's subtitle. driver_name: String, /// Writes the tab list a moment after the last change. @@ -590,6 +593,11 @@ pub(crate) enum WorkspaceInput { tab: Uuid, offer: Box, }, + // The tab it came from names a share that has no name of its own. + Share { + tab: Option, + subject: Box, + }, /// An export a tab offered ended. ExportEnded { tab: Uuid, @@ -861,6 +869,8 @@ impl Workspace { assistant, driver_name: driver_display_name(&context, &session.metadata().driver_id), driver_id: session.metadata().driver_id.clone(), + account: services.account(), + telemetry: services.telemetry(), context, key, input, @@ -1368,6 +1378,28 @@ impl WorkspaceModel { } } + fn on_share(&self, tab: Option, mut subject: ShareSubject) { + let Some(window) = self.window() else { + return; + }; + // The tab's own title, without the connection a shared tab bar adds to it. + if subject.title.trim().is_empty() + && let Some(title) = tab.and_then(|tab| self.tab_title(tab)) + { + subject.title = title.label; + } + if subject.dialect.is_none() { + subject.dialect = Some(self.driver_id.clone()); + } + super::share_dialog::ShareDialog::new(super::share_dialog::ShareDialogInit { + subject, + account: self.account.clone(), + tasks: self.tasks.clone(), + telemetry: self.telemetry.clone(), + }) + .present(Some(&window)); + } + fn update(&mut self, msg: WorkspaceInput) { match msg { WorkspaceInput::HealthChanged(health) => self.refresh_health_banner(&health), @@ -1456,6 +1488,7 @@ impl WorkspaceModel { WorkspaceInput::ReplaceActiveTabQuery(text) => self.on_replace_active_tab_query(text), WorkspaceInput::RefreshPage(tab) => self.on_refresh_page(tab), WorkspaceInput::ExportResults { tab, offer } => self.on_export_results(tab, *offer), + WorkspaceInput::Share { tab, subject } => self.on_share(tab, *subject), WorkspaceInput::ExportEnded { tab, outcome } => self.on_export_ended(tab, outcome), WorkspaceInput::ReopenClosedTab(tab) => self.on_reopen_closed_tab(tab), WorkspaceInput::RefreshTab(id) => self.on_refresh_tab(id), diff --git a/linux/crates/app/src/ui/workspace/sidebar/favorites_pane.rs b/linux/crates/app/src/ui/workspace/sidebar/favorites_pane.rs index 723722ed8c..2d99a418fe 100644 --- a/linux/crates/app/src/ui/workspace/sidebar/favorites_pane.rs +++ b/linux/crates/app/src/ui/workspace/sidebar/favorites_pane.rs @@ -26,6 +26,7 @@ const KEYS: &str = "favorite-keys"; const RENAME: &str = "rename"; const DELETE: &str = "delete"; const MOVE: &str = "move"; +const SHARE: &str = "share"; const NEW_FOLDER: &str = "new-folder"; #[derive(Debug, Clone)] @@ -34,6 +35,7 @@ pub(crate) enum FavoriteAction { Rename(SavedQuery), Delete(SavedQuery), MoveTo(SavedQuery), + Share(SavedQuery), NewFolder(Option), RenameFolder(SavedQueryFolder), DeleteFolder(SavedQueryFolder), diff --git a/linux/crates/app/src/ui/workspace/sidebar/favorites_pane_tests.rs b/linux/crates/app/src/ui/workspace/sidebar/favorites_pane_tests.rs index 05956f44ed..7caaf0d966 100644 --- a/linux/crates/app/src/ui/workspace/sidebar/favorites_pane_tests.rs +++ b/linux/crates/app/src/ui/workspace/sidebar/favorites_pane_tests.rs @@ -122,7 +122,7 @@ fn a_favorite_has_a_named_menu_button_that_acts_on_its_row() { button.popup(); assert!(button.popover().expect("row popover").is_visible()); let menu = button.menu_model().expect("row menu"); - assert_eq!(menu.n_items(), 3); + assert_eq!(menu.n_items(), 4); crate::test_support::assert_access_keys(&menu); let action = menu .item_attribute_value(0, "action", None) @@ -435,3 +435,32 @@ fn reopening_an_expanded_subtree_keeps_a_selected_root_siblings_position() { Some(selected) ); } + +#[gtk4::test] +fn share_on_a_favorite_asks_to_share_its_query() { + let (pane, _window, actions) = shown(); + let menu = menu_of(Key::Query(2)); + let shares_at = |menu: &gio::Menu| { + (0..menu.n_items()).find(|position| { + menu.item_attribute_value(*position, "action", None) + .and_then(|value| value.get::()) + .as_deref() + == Some("favorite.share") + }) + }; + let share = shares_at(&menu).expect("Share… on a favorite"); + + list(&pane) + .activate_action("favorite.share", Some(&target(&menu, share))) + .expect("share from the menu"); + + assert!(matches!( + actions.borrow().last(), + Some(FavoriteAction::Share(query)) if query.id == 2 && query.name == "Two" + )); + assert_eq!( + shares_at(&menu_of(Key::Folder(1))), + None, + "a folder has nothing to share" + ); +} diff --git a/linux/crates/app/src/ui/workspace/sidebar/favorites_rows.rs b/linux/crates/app/src/ui/workspace/sidebar/favorites_rows.rs index b35e4df6d5..954a1deb49 100644 --- a/linux/crates/app/src/ui/workspace/sidebar/favorites_rows.rs +++ b/linux/crates/app/src/ui/workspace/sidebar/favorites_rows.rs @@ -167,7 +167,7 @@ pub(super) fn install_menu( asked: &Asked, ) -> gtk::PopoverMenu { let actions = gio::SimpleActionGroup::new(); - for name in [RENAME, DELETE, MOVE, NEW_FOLDER] { + for name in [RENAME, DELETE, MOVE, SHARE, NEW_FOLDER] { let action = gio::SimpleAction::new(name, Some(glib::VariantTy::STRING)); let (tree, index, asked) = (tree.clone(), index.clone(), asked.clone()); action.connect_activate(move |_, target| { @@ -220,6 +220,7 @@ fn request(asked: &Asked, name: &str, node: Node) { (RENAME, Node::Query(query)) => FavoriteAction::Rename(query), (DELETE, Node::Query(query)) => FavoriteAction::Delete(query), (MOVE, Node::Query(query)) => FavoriteAction::MoveTo(query), + (SHARE, Node::Query(query)) => FavoriteAction::Share(query), (RENAME, Node::Folder(folder)) => FavoriteAction::RenameFolder(folder), (DELETE, Node::Folder(folder)) => FavoriteAction::DeleteFolder(folder), (NEW_FOLDER, Node::Folder(folder)) => FavoriteAction::NewFolder(Some(folder)), @@ -290,12 +291,13 @@ fn install_keys( pub(super) fn menu_of(key: Key) -> gio::Menu { let menu = gio::Menu::new(); let entries = match key { - Key::Query(_) => [ + Key::Query(_) => vec![ (gettext("_Rename…"), RENAME), (gettext("_Move to Folder…"), MOVE), + (gettext("_Share…"), SHARE), (gettext("_Delete…"), DELETE), ], - Key::Folder(_) => [ + Key::Folder(_) => vec![ (gettext("New _Subfolder…"), NEW_FOLDER), (gettext("_Rename…"), RENAME), (gettext("_Delete…"), DELETE), diff --git a/linux/crates/app/src/ui/workspace/tab_factory.rs b/linux/crates/app/src/ui/workspace/tab_factory.rs index 4b423600cf..a7186704fc 100644 --- a/linux/crates/app/src/ui/workspace/tab_factory.rs +++ b/linux/crates/app/src/ui/workspace/tab_factory.rs @@ -501,6 +501,13 @@ fn connect_browse(browse: &BrowseTab, tab_id: Uuid, input: &WorkspaceSender) { offer: Box::new(offer), }); }); + let share = input.clone(); + browse.connect_share_requested(move |_, subject| { + share.deliver(WorkspaceInput::Share { + tab: Some(tab_id), + subject: Box::new(subject), + }); + }); let alert = input.clone(); browse.connect_alert(move |_, title, body| alert.deliver(WorkspaceInput::ShowAlert { title, body })); let toast = input.clone(); @@ -575,6 +582,13 @@ pub(super) fn connect_editor( offer: Box::new(offer), }); }); + let share = input.clone(); + editor.connect_share_requested(move |_, subject| { + share.deliver(WorkspaceInput::Share { + tab: Some(tab_id), + subject: Box::new(subject), + }); + }); // The overlay is an ancestor of the editor, so a strong capture // would keep both alive once the window lets go of them. let toasts = toasts.clone(); diff --git a/linux/crates/app/src/ui/workspace/tests/shell.rs b/linux/crates/app/src/ui/workspace/tests/shell.rs index a7e724aacb..41c081e037 100644 --- a/linux/crates/app/src/ui/workspace/tests/shell.rs +++ b/linux/crates/app/src/ui/workspace/tests/shell.rs @@ -459,7 +459,13 @@ fn primary_menu_has_no_quit() { } } - for expected in ["app.new-window", "app.preferences", "app.shortcuts", "app.about"] { + for expected in [ + "app.new-window", + "app.manage-shared-links", + "app.preferences", + "app.shortcuts", + "app.about", + ] { assert!(actions.iter().any(|action| action == expected), "{expected} is missing"); } assert!(!actions.iter().any(|action| action == "app.quit"), "the menu has Quit"); @@ -479,7 +485,7 @@ fn application_and_session_commands_have_separate_native_menus() { let primary = test.app.menu_by_id("primary_menu").expect("the primary menu"); let mut app_actions = Vec::new(); collect_actions(primary.upcast_ref(), &mut app_actions); - assert_eq!(app_actions.len(), 10); + assert_eq!(app_actions.len(), 11); let button = session_menu_button(&test); assert!(!button.is_primary(), "F10 belongs to Main Menu"); crate::test_support::assert_labelled(&button).expect("the menu's accessible name"); @@ -969,3 +975,38 @@ fn the_sidebar_takes_the_width_kept_in_settings_and_has_a_handle_to_set_it() { split.set_collapsed(false); assert!(handle.is_visible()); } + +#[gtk4::test] +fn share_query_opens_the_sheet_with_the_tabs_sql_and_name() { + let test = TestWindow::connected("ShareQuerySheet"); + wait_until(WAIT, || !test.window.settling()).expect("the saved tabs read"); + let before = editors(&test.window); + let input = test.workspace().sender().expect("the workspace's input"); + crate::runtime::DeliverInput::deliver(&input, crate::ui::workspace::WorkspaceInput::NewEditorTab); + wait_until(WAIT, || editors(&test.window).len() > before.len()).expect("a new editor tab"); + let editor = editors(&test.window) + .into_iter() + .find(|editor| !before.contains(editor)) + .expect("the editor"); + editor.buffer().set_text("SELECT * FROM orders"); + + editor.share_query(); + wait_until(WAIT, || test.window.visible_dialog().is_some()).expect("the share sheet"); + + let dialog = test + .window + .visible_dialog() + .and_downcast::() + .expect("the share sheet"); + let subject = dialog.subject().expect("what it shares"); + let page = shell_of(&test.workspace()) + .tab_view() + .selected_page() + .expect("the editor's page"); + assert_eq!(subject.sql, "SELECT * FROM orders"); + assert_eq!(subject.title, page.title()); + assert!(subject.rows.is_none()); + assert!(subject.dialect.is_some()); + assert_eq!(dialog.title(), "Share Query"); + dialog.force_close(); +} diff --git a/linux/crates/app/src/ui/workspace/workspace_shell.rs b/linux/crates/app/src/ui/workspace/workspace_shell.rs index def3ec0b5c..0f1ca5f6b3 100644 --- a/linux/crates/app/src/ui/workspace/workspace_shell.rs +++ b/linux/crates/app/src/ui/workspace/workspace_shell.rs @@ -852,6 +852,18 @@ impl WorkspaceShell { FavoriteAction::Rename(favorite) => self.ask_favorite_name(favorite), FavoriteAction::Delete(favorite) => self.ask_favorite_deletion(favorite), FavoriteAction::MoveTo(favorite) => self.ask_folder_for(favorite), + FavoriteAction::Share(favorite) => { + if let Some(sender) = self.front().and_then(|front| front.sender()) { + sender.deliver(super::WorkspaceInput::Share { + tab: None, + subject: Box::new(crate::services::share_subject::ShareSubject::query( + favorite.name, + favorite.query, + None, + )), + }); + } + } FavoriteAction::NewFolder(parent) => self.ask_folder_name(parent, None), FavoriteAction::RenameFolder(folder) => self.ask_folder_name(None, Some(folder)), FavoriteAction::DeleteFolder(folder) => self.ask_folder_deletion(folder), diff --git a/linux/crates/app/tests/desktop_entry.rs b/linux/crates/app/tests/desktop_entry.rs index 99326646fa..037d3d7314 100644 --- a/linux/crates/app/tests/desktop_entry.rs +++ b/linux/crates/app/tests/desktop_entry.rs @@ -45,9 +45,10 @@ fn sql_scripts_are_offered_to_tablepro() { ); } -// xdg-open and browsers hand a postgresql:// link to the app that claims x-scheme-handler/postgresql. +// xdg-open and browsers hand a postgresql:// link to the app that claims x-scheme-handler/postgresql, and a +// shared query's tablepro://share link to the one that claims x-scheme-handler/tablepro. #[test] -fn connection_links_are_offered_to_tablepro() { +fn connection_and_share_links_are_offered_to_tablepro() { let entry = entry().expect("the desktop entry parses"); let types = list(&entry, MAIN, "MimeType").expect("a MimeType list"); @@ -57,6 +58,7 @@ fn connection_links_are_offered_to_tablepro() { .collect(); claimed.sort_unstable(); let mut expected = tablepro_app::LINK_SCHEMES.to_vec(); + expected.push(tablepro_app::SHARE_LINK_SCHEME); expected.sort_unstable(); assert_eq!(claimed, expected); diff --git a/linux/data/app.tablepro.TablePro.desktop.in.in b/linux/data/app.tablepro.TablePro.desktop.in.in index f8c22c3e79..e90bb58446 100644 --- a/linux/data/app.tablepro.TablePro.desktop.in.in +++ b/linux/data/app.tablepro.TablePro.desktop.in.in @@ -9,7 +9,7 @@ Icon=@app-id@ Terminal=false Type=Application Categories=Development;Database; -MimeType=application/vnd.sqlite3;application/sql;x-scheme-handler/cassandra;x-scheme-handler/ch;x-scheme-handler/clickhouse;x-scheme-handler/cql;x-scheme-handler/duckdb;x-scheme-handler/mariadb;x-scheme-handler/mongodb;x-scheme-handler/mongodb+srv;x-scheme-handler/mssql;x-scheme-handler/mysql;x-scheme-handler/mysqlx;x-scheme-handler/postgres;x-scheme-handler/postgresql;x-scheme-handler/redis;x-scheme-handler/rediss;x-scheme-handler/scylla;x-scheme-handler/scylladb;x-scheme-handler/sqlite;x-scheme-handler/sqlite3;x-scheme-handler/sqlserver;x-scheme-handler/valkey;x-scheme-handler/valkeys; +MimeType=application/vnd.sqlite3;application/sql;x-scheme-handler/cassandra;x-scheme-handler/ch;x-scheme-handler/clickhouse;x-scheme-handler/cql;x-scheme-handler/duckdb;x-scheme-handler/mariadb;x-scheme-handler/mongodb;x-scheme-handler/mongodb+srv;x-scheme-handler/mssql;x-scheme-handler/mysql;x-scheme-handler/mysqlx;x-scheme-handler/postgres;x-scheme-handler/postgresql;x-scheme-handler/redis;x-scheme-handler/rediss;x-scheme-handler/scylla;x-scheme-handler/scylladb;x-scheme-handler/sqlite;x-scheme-handler/sqlite3;x-scheme-handler/sqlserver;x-scheme-handler/tablepro;x-scheme-handler/valkey;x-scheme-handler/valkeys; DBusActivatable=true StartupNotify=true X-GNOME-UsesNotifications=true diff --git a/linux/data/resources/gtk/menus.ui b/linux/data/resources/gtk/menus.ui index c4e9d30aba..e838950e80 100644 --- a/linux/data/resources/gtk/menus.ui +++ b/linux/data/resources/gtk/menus.ui @@ -36,6 +36,10 @@
+ + Manage Shared _Links… + app.manage-shared-links + _Preferences app.preferences diff --git a/linux/data/resources/ui/sql-editor.ui b/linux/data/resources/ui/sql-editor.ui index 1a5fb69551..ecfbceceb0 100644 --- a/linux/data/resources/ui/sql-editor.ui +++ b/linux/data/resources/ui/sql-editor.ui @@ -30,6 +30,14 @@ E_xport Results… win.export-results + + S_hare Query… + editor.share-query + + + Share Res_ult… + editor.share-result + Forma_t editor.format diff --git a/linux/data/tablepro.1 b/linux/data/tablepro.1 index e65ac49237..b1ab0f05b6 100644 --- a/linux/data/tablepro.1 +++ b/linux/data/tablepro.1 @@ -236,6 +236,11 @@ A link never connects without consent. For a saved connection, click Open; Enter and Escape cancel. For other links, review the connect dialog and click Connect. A successful connection from that dialog is saved. +.SH SHARE LINKS +The desktop also registers the tablepro scheme. +A link of the form tablepro://share?token=TOKEN, from a shared query's page, +opens the shared SQL in a new query tab of the connection in front. +The SQL never runs on its own, and the link names no connection. .SH EXIT STATUS .TP .B 0 diff --git a/linux/docs/decisions/0027-one-data-grid.md b/linux/docs/decisions/0027-one-data-grid.md index 617d40e2df..73fc2d52e0 100644 --- a/linux/docs/decisions/0027-one-data-grid.md +++ b/linux/docs/decisions/0027-one-data-grid.md @@ -1,6 +1,6 @@ # 0027: One data grid on GtkColumnView, with rows and a focused cell -- **Status**: Accepted; row numbers superseded by [0044](0044-pinned-row-numbers.md) +- **Status**: Accepted; row numbers superseded by [0044](0044-pinned-row-numbers.md); the share sheet's sample rows amended by [0046](0046-share-links-and-the-tablepro-scheme.md) - **Date**: 2026-10-25 ## Context diff --git a/linux/docs/decisions/0042-account-page-lists-this-platforms-features.md b/linux/docs/decisions/0042-account-page-lists-this-platforms-features.md index f294288de7..bece595298 100644 --- a/linux/docs/decisions/0042-account-page-lists-this-platforms-features.md +++ b/linux/docs/decisions/0042-account-page-lists-this-platforms-features.md @@ -1,6 +1,6 @@ # 0042: Preferences > Account lists only the features TablePro for Linux has -- **Status**: Accepted +- **Status**: Accepted; the empty Features group amended by [0046](0046-share-links-and-the-tablepro-scheme.md) - **Date**: 2026-11-07 ## Context diff --git a/linux/docs/decisions/0045-command-line-and-connection-urls.md b/linux/docs/decisions/0045-command-line-and-connection-urls.md index 1e144e1301..98685aff3f 100644 --- a/linux/docs/decisions/0045-command-line-and-connection-urls.md +++ b/linux/docs/decisions/0045-command-line-and-connection-urls.md @@ -1,6 +1,6 @@ # 0045: The tablepro command line and connection URLs -- **Status**: Accepted +- **Status**: Accepted; the link schemes amended by 0046 - **Date**: 2026-11-08 ## Context diff --git a/linux/docs/decisions/0046-share-links-and-the-tablepro-scheme.md b/linux/docs/decisions/0046-share-links-and-the-tablepro-scheme.md new file mode 100644 index 0000000000..ba60db987a --- /dev/null +++ b/linux/docs/decisions/0046-share-links-and-the-tablepro-scheme.md @@ -0,0 +1,41 @@ +# 0046: Share links from the editor, its results and favorites, and the tablepro scheme + +- **Status**: Accepted +- **Date**: 2026-11-13 + +## Context + +On 2026-11-13 the maintainer decided that every app shares a query or a result as a public link on the TablePro account, the same way on macOS, Linux and Windows: Free with 5 live links, 1,000 rows and an expiry of 1, 7 or 30 days, Pro without those limits. The calls, the snapshot of a result's rows, the secret scan and the deep link's parser are the core's ([core ADR 0027](../../../core/docs/decisions/0027-share-links.md)). A link's viewer page opens the app with `tablepro://share?token=`. The Linux app had no share feature and no handler for that scheme, and [ADR 0042](0042-account-page-lists-this-platforms-features.md) kept every paid feature off its account page. + +## Decision + +The SQL editor offers Share Query… and Share Result…, an editor result grid and a table tab's grid offer Share Result… after Export…, a favorite offers Share…, and the main menu offers Manage Shared Links…, which opens the account portal's list. Each one opens one share sheet, an `AdwDialog`. The desktop entry claims `x-scheme-handler/tablepro`, GIO's VFS keeps the link's text as it does a connection link's ([ADR 0045](0045-command-line-and-connection-urls.md)), and `open_files` hands a share link to its own route before any file or connection link. + +## How it works + +- **The sheet** (`crates/app/src/ui/share_dialog/`) reads `share_limits` when it opens and shows one page: signed out with Sign In…, the wait for the browser, an account that could not start, a failed read with Try Again, an unverified email with Open Account, sharing turned off, the live links at the limit with Revoke, the form, or the created link. `sheet_view.rs` derives each page and its wording as plain data, as `account_view.rs` does for Preferences > Account. +- **Share As.** An account with a seat in a team picks Personal or one of its teams; a team that turned public links off is listed but cannot be picked, and says so. A team link counts against the team's limit, so the footer and the list at the limit follow the team chosen, read with `list_shares` for that team. The list at the limit offers Share As too, so another owner with a free slot is one pick away. +- **The form.** Title starts from the tab, the favorite or the result's statement; Note; Expires as an `AdwToggleGroup` of the plan's expiries, where Free sees Never off with a Pro tag; Hide SQL for a result; Password and Allow viewers to download, which Free sees off with a Pro tag. The tag opens the pricing page in the browser and asks nothing. +- **What a result shares** is what an export of the shown rows writes: the grid's rows under the columns on screen in the user's order, pending edits included. The first 5 show in a plain `GtkColumnView` with the grid's display text, which amends [ADR 0027](0027-one-data-grid.md): a sample with no selection, menu or editing is not a grid. A note says when the plan's rows cut the result, and another when it has more columns than the server keeps (`max_columns`, 100 on every plan); the preview shows only those, the core cuts the snapshot to them, and the page after Create says so again when `columns_truncated` comes back. The rows are cut to the plan's `max_rows` and built into the snapshot on the runtime before upload. +- **A table tab** shares its view: once the limits are in, the sheet reads from the first row up to the plan's rows, with the tab's filter and sort, on a connection of the read's own as an export does, and keeps the columns on screen in their order. The SQL is `build_view_sql` for every column, so the filter and the sort find theirs; a view the engine cannot write as SQL is shared without it, and the sheet says why. The whole is the tab's exact count, never its estimate, which can be far off; without one, a read that stopped at the plan's rows says only that more rows exist. +- **Titles.** A query's title starts from its tab's title, without the connection a shared tab bar adds. A result's starts from its line in the results list, such as Result 1 (3), never from its statement, since Hide SQL keeps the statement from viewers. +- **Warnings.** The core's secret scan of the SQL and the column names shows inline and never blocks. Hide SQL takes the SQL's warnings away, since no viewer reads it then. +- **Create** runs once at a time; a second press while it runs does nothing, and the sheet cannot close until the answer is in, so a link is never made unseen. The link goes to the clipboard and shows with Copy, which takes the focus, and Open in Browser; when the clipboard refuses it, the page says the link was created rather than copied. A refusal shows its sentence from `error_text/account.rs` over the form. `share_limit_reached`, `email_unverified` and `sharing_disabled` read the limits again, which shows the page for what changed, and the form comes back as the user typed it once a revoke frees a slot. +- **Suspended links**, which a team or staff turned off, say Suspended in the list at the limit; they still count until revoked. +- **The deep link** waits for the account to start, since a link can launch the app, then reads the share with `fetch_shared`, which needs no sign-in. A word about a link that did not open goes to a window already open, and a picker opens only when there is none. A password-protected link asks in an `AdwAlertDialog` and asks again after a wrong one. The SQL takes the way a SQL file handed to the app takes: a new editor tab in the relational session in front, never run, or a wait behind the picker's banner until a connection joins the window. The link carries no connection. A result whose owner hid its SQL, or that was shared with blank SQL, says there is nothing to open. +- **Preferences > Account** lists `shared_links` as Pro Options for Shared Links, included or not by the entitlement, since every account shares and the plan lifts the Free limits. This amends [ADR 0042](0042-account-page-lists-this-platforms-features.md), under which no flag was on and the Features group never showed. + +## Consequences + +- An editor result is shared with the rows the run kept. When the run's row limit cut it, the count the viewer shows is the rows kept, since the true total is unknown. +- Team links are made from the sheet; editing and revoking links other than at the limit is the portal's. +- The public read goes through the core's `Account`, which needs this computer's machine ID. Where it cannot be read, a share link says why accounts are unavailable instead of opening, though the read itself needs no account. A core read of a share that takes no `Account` would lift this. +- The Features group of Preferences > Account now shows on Linux, with one row. +- A new scheme in the desktop entry is also registered with the VFS, and the desktop entry's test checks both lists. + +## Alternatives considered + +- **The DataGrid for the preview.** Its menu would offer hiding a column and exporting the sample, and neither would change what the link carries. +- **Sign In… opening Preferences > Account.** Two steps for one action; the sheet runs `Account::sign_in` itself and follows the account's status. +- **An `AdwComboRow` for Expires.** A combo row cannot show Never as present but unavailable, which the share plan asks of Free. +- **Opening the shared SQL in the active window's front session whatever its engine.** A key-value or document session runs no SQL; the script route already asks for a connection in that case. diff --git a/linux/docs/decisions/README.md b/linux/docs/decisions/README.md index 7299d5a144..8cc1835d63 100644 --- a/linux/docs/decisions/README.md +++ b/linux/docs/decisions/README.md @@ -74,7 +74,7 @@ A fact the repository keeps elsewhere, such as a workflow trigger, a branch, a v | [0024](0024-multi-cursor-on-text-marks.md) | Multiple cursors on text marks, in the app | Accepted | The SQL editor's view, a GtkSourceView subclass, keeps extra cursors as GtkTextMark pairs, runs GTK's own commands once per cursor and repeats committed text from `end-user-action`, so one undo takes back every cursor's edit. | | [0025](0025-bundled-duckdb.md) | DuckDB built from the duckdb crate's bundled sources | Accepted; the crate version superseded by 0031 | No PPA or COPR target but Ubuntu 26.10 ships libduckdb, so DuckDB 1.5.6 is compiled from the crate on every channel, with no extension fetched or loaded on its own. | | [0026](0026-documents-in-the-table-tab.md) | Document collections open in the table tab, and their statements are shell calls | Accepted | A document engine states `DataModel::Document`, lists collections as tables, opens them in the table tab, and every builder writes a mongosh call with bound values through a document arm chosen by the grammar. | -| [0027](0027-one-data-grid.md) | One data grid on GtkColumnView, with rows and a focused cell | Accepted; row numbers superseded by 0044 | Every surface shows rows in one `DataGrid`: row selection plus a focused cell, stable row slots, a row number column, values as text and a row detail pane. | +| [0027](0027-one-data-grid.md) | One data grid on GtkColumnView, with rows and a focused cell | Accepted; row numbers superseded by 0044; the share sheet's sample rows amended by 0046 | Every surface shows rows in one `DataGrid`: row selection plus a focused cell, stable row slots, a row number column, values as text and a row detail pane. | | [0028](0028-sessions-share-a-window.md) | A window holds several sessions in one tab view | Accepted | A `WorkspaceShell` per window shares one tab view among its sessions, each with its own workspace; the sidebar is a tree of the saved connections with each open session's schemas and tables. | | [0029](0029-images-decode-in-glycin.md) | Images from the database decode in glycin's sandbox | Accepted | Row Details decodes a value's picture with the glycin crate 3.x, in a sandboxed loader process, never with GTK's in-process loaders. | | [0030](0030-a-database-is-a-session-of-its-own.md) | A query tab's database, and another database as a session of its own | Accepted; dropping a sibling's database amended by 0034 | A query tab's own editor session moves to its database through the driver, or opens there where the engine binds it at connect; another database the window shows is a sibling session with its own workspace and sidebar row. | @@ -89,10 +89,11 @@ A fact the repository keeps elsewhere, such as a workflow trigger, a branch, a v | [0039](0039-usage-data.md) | Usage data through posthog-rs, on by default as on macOS | Accepted | posthog-rs's blocking client sends the clients.md events to the key `-Dposthog_key` gives; on by default, off from Preferences > General > Privacy; no key, no client. | | [0040](0040-copyright-file-from-the-source-tarballs.md) | The copyright file describes the source tarballs | Accepted | `debian/copyright` covers every crate `cargo vendor` ships and the code crates carry from other projects, from `cargo metadata` and each crate's license files; the binary inventory keeps the About dialog, the notices and the RPM `License` tag. | | [0041](0041-beta-repositories-and-release-packages.md) | Beta repositories, a Flatpak repository of our own, and packages on every GitHub release | Accepted; the run that builds a tag's packages amended by 0043 | A beta tag goes to a beta PPA, COPR project and Flatpak repository that testers add beside the stable ones; a signed Flatpak repository on R2 serves every other distribution with updates; every GitHub release carries the tested .deb and .rpm and a Flatpak bundle that updates from that repository, with SHA256SUMS. | -| [0042](0042-account-page-lists-this-platforms-features.md) | Preferences > Account lists only the features TablePro for Linux has | Accepted | Features lists only the codes whose platform flag is on and hides when none is; the licensing links move to a License group; the copy speaks of the plan and the license, never of a feature missing on Linux. | +| [0042](0042-account-page-lists-this-platforms-features.md) | Preferences > Account lists only the features TablePro for Linux has | Accepted; the empty Features group amended by 0046 | Features lists only the codes whose platform flag is on and hides when none is; the licensing links move to a License group; the copy speaks of the plan and the license, never of a feature missing on Linux. | | [0043](0043-a-tag-publishes-its-dry-run.md) | A tag publishes what its commit's dry run built | Accepted | A tag's run takes the tarballs, template, source packages, packages and unsigned Flatpak repositories from the green dry run of its commit, re-signs only the Flatpak, checks the rest against the dry run's SHA256SUMS, and fails before publishing when there is no such run. | | [0044](0044-pinned-row-numbers.md) | Row numbers share the grid’s scrolling and input | Accepted | A passive gutter shares the main grid’s selection and vertical adjustment inside one scroller; native input stays in the main view. | -| [0045](0045-command-line-and-connection-urls.md) | The tablepro command line and connection URLs | Accepted | One binary: `main()` runs a command word through `tablepro-cli` before the GUI starts, everything else reaches GApplication; the desktop entry claims the core parser's URL schemes, registered with the VFS so gvfs keeps the password; a link opens a saved connection after an alert or fills the connect dialog; the command line only reads the MCP token. | +| [0045](0045-command-line-and-connection-urls.md) | The tablepro command line and connection URLs | Accepted; the link schemes amended by 0046 | One binary: `main()` runs a command word through `tablepro-cli` before the GUI starts, everything else reaches GApplication; the desktop entry claims the core parser's URL schemes, registered with the VFS so gvfs keeps the password; a link opens a saved connection after an alert or fills the connect dialog; the command line only reads the MCP token. | +| [0046](0046-share-links-and-the-tablepro-scheme.md) | Share links from the editor, its results and favorites, and the tablepro scheme | Accepted | Share Query…, Share Result… and a favorite's Share… open one `AdwDialog` sheet over the core's share calls, with the plan's limits, a preview, secret warnings and Pro tags; the desktop entry and the VFS take `tablepro://share`, whose SQL opens in a new editor tab as a SQL file's does, never run. | 0011 is not used. It was reserved for the DDL decision, which was recorded as 0010, and docs cite ADRs by number, so the later ones keep theirs. diff --git a/linux/docs/testing.md b/linux/docs/testing.md index cc6a4e3cb4..f52bc2588e 100644 --- a/linux/docs/testing.md +++ b/linux/docs/testing.md @@ -345,8 +345,16 @@ It prints the tablepro-cloud commit, for the commit message. Then build and run - `remove-device`: removes the machine from the portal's Devices page. - `offline-file`: makes an offline file for `TABLEPRO_CLOUD_MACHINE_ID` through the portal's API, as its Devices page does, into `TABLEPRO_CLOUD_OUTPUT`. +The share cases also change the stack's database through `core/crates/account/tests/browser/seed.cjs`, which needs no browser and writes what tablepro-cloud's `web/e2e` seed writes. Each step takes `TABLEPRO_CLOUD_EMAIL`, which the test sets: + +- `unverify`: clears the account's email verification. +- `team`: makes a team the account owns, with the account and `TABLEPRO_CLOUD_MEMBER_EMAIL` seated on a Team license of 5 seats. +- `team-links-off`: turns public links off for the team the account owns, as `PUT /api/teams/{team_id}/sharing` does. + The cases cover a licensed sign-in with a restart, a refresh and a sign-out whose token the server then refuses; a free account without a keyring; a fourth machine told `device_limit_reached` with the three that hold the license; a machine over the limit that removes a holder in place and gets the license, while the holder with an offline file, which `device_limit_reached` names with its `offline_until`, is refused with `offline_file_active`; a second sign-in, which revokes the first one's token; a device removed in the portal, which signs the account out at its next refresh; and the profile and devices of an account, with an offline file the portal made unlocking a machine that never signed in, without opening its keyring. +The share link cases cover a Free account that holds five links and is refused a sixth and every Pro option; an account whose email is not verified, which is told so and shares nothing; a Pro link behind a password, which opens with it, keeps every digit of its numbers and takes a report, while a report without a Turnstile token is refused; and a seated team member's team link, which counts outside the member's own limit until the team turns public links off. + They read the stack from the environment: | Variable | Value | @@ -355,7 +363,8 @@ They read the stack from the environment: | `TABLEPRO_CLOUD_ENTITLEMENT_KEY` | The `x` of the stack's entitlement signing key, base64url | | `TABLEPRO_CLOUD_EMAIL_DOMAIN` | The domain of the accounts the tests make, so runs never share one | | `TABLEPRO_CLOUD_MAIL_URL` | The fake Resend that keeps the sign-in emails | -| `TABLEPRO_CLOUD_DATABASE_URL` | The stack's database, for the license grant and the seeded devices | +| `TABLEPRO_CLOUD_DATABASE_URL` | The stack's database, for the license grant, the seeded devices and `seed.cjs` | +| `TABLEPRO_CLOUD_REPORT_TOKEN` | A Turnstile token the stack's siteverify passes for the `share_report` action, for the report case | | `TABLEPRO_CLOUD_CHROME` | A Chrome or chrome-headless-shell binary | | `NODE_PATH` | Where `puppeteer` and `pg` are installed | diff --git a/linux/po/POTFILES.in b/linux/po/POTFILES.in index 79a85ae0aa..6ead8d5f5c 100644 --- a/linux/po/POTFILES.in +++ b/linux/po/POTFILES.in @@ -16,6 +16,7 @@ crates/app/src/application/metainfo_release.rs crates/app/src/application/mod.rs crates/app/src/application/open_files.rs crates/app/src/application/open_links.rs +crates/app/src/application/open_share_link.rs crates/app/src/application/quit_sequence.rs crates/app/src/application/runtime_versions.rs crates/app/src/application/session_signals.rs @@ -131,6 +132,9 @@ crates/app/src/services/secret_changes.rs crates/app/src/services/secret_labels.rs crates/app/src/services/secret_save_report.rs crates/app/src/services/session_context.rs +crates/app/src/services/share_link.rs +crates/app/src/services/share_subject.rs +crates/app/src/services/share_table.rs crates/app/src/services/snippet_library.rs crates/app/src/services/ssh_environment.rs crates/app/src/services/structure_tracker.rs @@ -574,6 +578,16 @@ crates/app/src/ui/session_window/tests/other_databases.rs crates/app/src/ui/session_window/tests/sessions.rs crates/app/src/ui/session_window/window_actions.rs crates/app/src/ui/session_window/work_notifier.rs +crates/app/src/ui/share_dialog/form.rs +crates/app/src/ui/share_dialog/imp.rs +crates/app/src/ui/share_dialog/masking_text.rs +crates/app/src/ui/share_dialog/mod.rs +crates/app/src/ui/share_dialog/pages.rs +crates/app/src/ui/share_dialog/preview.rs +crates/app/src/ui/share_dialog/share_columns.rs +crates/app/src/ui/share_dialog/sheet_view.rs +crates/app/src/ui/share_dialog/table_read.rs +crates/app/src/ui/share_dialog/tests.rs crates/app/src/ui/shell/mod.rs crates/app/src/ui/shell/primary_menu_button.rs crates/app/src/ui/source_dialog.rs diff --git a/linux/po/vi.po b/linux/po/vi.po index 5cfec4e775..051b18012d 100644 --- a/linux/po/vi.po +++ b/linux/po/vi.po @@ -12208,3 +12208,1547 @@ msgstr "Chưa liệt kê hết các khóa. Hãy tìm kiếm để thu hẹp danh #~ msgid "Filter tables…" #~ msgstr "Lọc bảng…" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "1 day" +msgstr "1 ngày" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "7 days" +msgstr "7 ngày" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "30 days" +msgstr "30 ngày" + +#: crates/app/src/ui/error_text/account.rs +msgid "A team link needs a seat on the team." +msgstr "Liên kết của nhóm cần một chỗ trong nhóm." + +#: crates/app/src/ui/share_dialog/form.rs +msgid "Allow viewers to download" +msgstr "Cho phép người xem tải xuống" + +#: crates/app/src/ui/session_window/mod.rs +msgid "Choose a connection to open the shared query" +msgstr "Chọn kết nối để mở truy vấn được chia sẻ" + +#: crates/app/src/ui/session_window/mod.rs +#, rust-format +msgid "Choose a connection to open {n} query" +msgid_plural "Choose a connection to open {n} queries" +msgstr[0] "Chọn kết nối để mở {n} truy vấn" + +#: crates/app/src/ui/share_dialog/mod.rs +msgid "Create Link" +msgstr "Tạo liên kết" + +#: crates/app/src/ui/share_dialog/form.rs +msgid "Expires" +msgstr "Hết hạn" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "Expires {date}" +msgstr "Hết hạn {date}" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "Free · {live} of {limit} link · first {max_rows} rows" +msgid_plural "Free · {live} of {limit} links · first {max_rows} rows" +msgstr[0] "Miễn phí · {live}/{limit} liên kết · {max_rows} dòng đầu" + +#: crates/app/src/ui/share_dialog/form.rs +msgid "Hide SQL" +msgstr "Ẩn SQL" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "Keep or mask at least one column to share." +msgstr "Giữ hoặc che ít nhất một cột để chia sẻ." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "This query is too long to share. A link holds up to 256 KB of SQL." +msgstr "Truy vấn này quá dài để chia sẻ. Một liên kết chứa tối đa 256 KB SQL." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "A password can’t be only spaces or tabs." +msgstr "Mật khẩu không thể chỉ gồm dấu cách hoặc tab." + +#: crates/app/src/ui/share_dialog/pages.rs +msgid "Link copied" +msgstr "Đã sao chép liên kết" + +#: crates/app/src/ui/share_dialog/pages.rs +msgid "Link created" +msgstr "Đã tạo liên kết" + +#: data/resources/gtk/menus.ui +msgid "Manage Shared _Links…" +msgstr "Quản lý _liên kết chia sẻ…" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "Never expires" +msgstr "Không hết hạn" + +#: crates/app/src/ui/share_dialog/form.rs +msgid "Note" +msgstr "Ghi chú" + +#: crates/app/src/ui/share_dialog/pages.rs +msgid "Open Account" +msgstr "Mở tài khoản" + +#: crates/app/src/application/open_share_link.rs +msgid "Open Shared Link" +msgstr "Mở liên kết chia sẻ" + +#: crates/app/src/ui/share_dialog/pages.rs +msgid "Open in Browser" +msgstr "Mở trong trình duyệt" + +#: crates/app/src/ui/preferences_dialog/account_view.rs +msgid "Pro Options for Shared Links" +msgstr "Tùy chọn Pro cho liên kết chia sẻ" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "Pro allows up to 1,000." +msgstr "Gói Pro cho phép tối đa 1.000 liên kết." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "Pro · {live} link" +msgid_plural "Pro · {live} links" +msgstr[0] "Pro · {live} liên kết" + +#: crates/app/src/ui/error_text/account.rs +msgid "Public links are turned off for this team." +msgstr "Nhóm này đã tắt liên kết công khai." + +#: crates/app/src/ui/share_dialog/pages.rs +msgid "Revoke" +msgstr "Thu hồi" + +#: crates/app/src/ui/share_dialog/pages.rs +#, rust-format +msgid "Revoke {title}" +msgstr "Thu hồi {title}" + +#: crates/app/src/ui/share_dialog/form.rs crates/app/src/ui/share_dialog/preview.rs +msgid "Rows that will be shared" +msgstr "Các dòng sẽ được chia sẻ" + +#: crates/app/src/ui/editor/mod.rs +msgid "Run a query that returns rows to share its result." +msgstr "Hãy chạy một truy vấn trả về dòng để chia sẻ kết quả của nó." + +#: data/resources/ui/sql-editor.ui +msgid "S_hare Query…" +msgstr "Chi_a sẻ truy vấn…" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "Share Query" +msgstr "Chia sẻ truy vấn" + +#: data/resources/ui/sql-editor.ui +msgid "Share Res_ult…" +msgstr "Chia sẻ _kết quả…" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "Share Result" +msgstr "Chia sẻ kết quả" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "Shared query" +msgstr "Truy vấn được chia sẻ" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "Shared result" +msgstr "Kết quả được chia sẻ" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "Shared {date}" +msgstr "Chia sẻ ngày {date}" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "Shares the first {shared} of {total} rows." +msgstr "Chia sẻ {shared} dòng đầu trong số {total} dòng." + +#: crates/app/src/ui/error_text/account.rs crates/app/src/ui/share_dialog/pages.rs +msgid "Sharing is turned off for this account." +msgstr "Tài khoản này đã tắt tính năng chia sẻ." + +#: crates/app/src/ui/share_dialog/form.rs +msgid "Show the Pro plan in your browser" +msgstr "Xem gói Pro trong trình duyệt" + +#: crates/app/src/ui/error_text/account.rs crates/app/src/ui/share_dialog/pages.rs +msgid "Sign in to your TablePro account to share links." +msgstr "Đăng nhập tài khoản TablePro để chia sẻ liên kết." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "Some columns may hold secrets: {names}." +msgstr "Một số cột có thể chứa thông tin bí mật: {names}." + +#: crates/app/src/ui/share_dialog/mod.rs +msgid "TablePro could not open the page in a web browser." +msgstr "TablePro không mở được trang trong trình duyệt web." + +#: crates/app/src/ui/error_text/account.rs +msgid "TablePro removed this link." +msgstr "TablePro đã gỡ liên kết này." + +#: crates/app/src/application/open_share_link.rs crates/app/src/ui/error_text/account.rs +msgid "That password is not correct." +msgstr "Mật khẩu không đúng." + +#: crates/app/src/ui/error_text/account.rs +msgid "The account service did not accept what was sent. Check the fields and try again." +msgstr "Dịch vụ tài khoản không chấp nhận dữ liệu đã gửi. Hãy kiểm tra các trường rồi thử lại." + +#: crates/app/src/ui/share_dialog/pages.rs +msgid "The link could not be copied to the clipboard. Copy it with the button below." +msgstr "Không sao chép được liên kết vào bảng nhớ tạm. Hãy sao chép bằng nút bên dưới." + +#: crates/app/src/ui/error_text/account.rs +msgid "The link couldn’t be created. Try again." +msgstr "Không tạo được liên kết. Hãy thử lại." + +#: crates/app/src/ui/share_dialog/mod.rs +msgid "The link is on its way. Wait for it before closing." +msgstr "Liên kết đang được tạo. Hãy chờ trước khi đóng." + +#: crates/app/src/ui/editor/mod.rs +msgid "There is nothing in the editor to share." +msgstr "Trình soạn thảo không có gì để chia sẻ." + +#: crates/app/src/application/open_share_link.rs crates/app/src/ui/error_text/account.rs +msgid "This link is password protected." +msgstr "Liên kết này được bảo vệ bằng mật khẩu." + +#: crates/app/src/ui/error_text/account.rs +msgid "This link was revoked." +msgstr "Liên kết này đã bị thu hồi." + +#: crates/app/src/ui/error_text/account.rs +msgid "This option needs TablePro Pro." +msgstr "Tùy chọn này cần TablePro Pro." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "This query may contain a secret ({kind}). Anyone with the link can read it." +msgstr "Truy vấn này có thể chứa thông tin bí mật ({kind}). Ai có liên kết cũng đọc được." + +#: crates/app/src/ui/error_text/account.rs +msgid "This result is too large to share." +msgstr "Kết quả này quá lớn để chia sẻ." + +#: crates/app/src/application/open_share_link.rs crates/app/src/ui/error_text/account.rs +msgid "This shared link is no longer available." +msgstr "Liên kết chia sẻ này không còn khả dụng." + +#: crates/app/src/application/open_share_link.rs +msgid "This shared result hides its SQL, so there is nothing to open." +msgstr "Kết quả được chia sẻ này ẩn SQL, nên không có gì để mở." + +#: crates/app/src/ui/share_dialog/form.rs +msgid "Title" +msgstr "Tiêu đề" + +#: crates/app/src/ui/error_text/account.rs +msgid "Too many links just now. Try again in a moment." +msgstr "Vừa tạo quá nhiều liên kết. Hãy thử lại sau giây lát." + +#: crates/app/src/ui/error_text/account.rs crates/app/src/ui/share_dialog/pages.rs +msgid "Verify your email address to share links." +msgstr "Hãy xác minh địa chỉ email để chia sẻ liên kết." + +#: crates/app/src/ui/error_text/account.rs +msgid "You appear to be offline. Try again once you’re connected." +msgstr "Có vẻ bạn đang ngoại tuyến. Hãy thử lại khi đã có kết nối." + +#: crates/app/src/ui/error_text/account.rs +msgid "You have reached your plan’s limit of live links. Revoke one to share another." +msgstr "Bạn đã đạt giới hạn liên kết đang hoạt động của gói. Hãy thu hồi một liên kết để chia sẻ liên kết khác." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "You have {live} live link. Free allows {limit}. Revoke one to share another." +msgid_plural "You have {live} live links. Free allows {limit}. Revoke one to share another." +msgstr[0] "Bạn có {live} liên kết đang hoạt động. Gói Miễn phí cho phép {limit}. Hãy thu hồi một liên kết để chia sẻ liên kết khác." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "You have {live} live link. Pro allows {limit}. Revoke one to share another." +msgid_plural "You have {live} live links. Pro allows {limit}. Revoke one to share another." +msgstr[0] "Bạn có {live} liên kết đang hoạt động. Gói Pro cho phép {limit}. Hãy thu hồi một liên kết để chia sẻ liên kết khác." + +#: crates/app/src/application/open_links.rs crates/app/src/application/open_share_link.rs +msgid "_Open" +msgstr "_Mở" + +#: crates/app/src/ui/data_grid/grid_menu.rs +msgid "_Share Result…" +msgstr "Chia sẻ kết _quả…" + +#: crates/app/src/ui/workspace/sidebar/favorites_rows.rs +msgid "_Share…" +msgstr "Chia _sẻ…" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "a GitHub token" +msgstr "token GitHub" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "a Google API key" +msgstr "khóa API của Google" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "a JSON Web Token" +msgstr "JSON Web Token" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "a Slack token" +msgstr "token Slack" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "a Stripe key" +msgstr "khóa Stripe" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "a password in a URL" +msgstr "mật khẩu trong URL" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "a password or token" +msgstr "mật khẩu hoặc token" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "a private key" +msgstr "khóa riêng tư" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "an AWS access key" +msgstr "khóa truy cập AWS" + +#: crates/app/src/ui/share_dialog/form.rs +#, rust-format +msgid "{option} needs TablePro Pro." +msgstr "{option} cần TablePro Pro." + +#: crates/app/src/application/imp.rs +msgid "[FILE or URL…]" +msgstr "[TỆP hoặc URL…]" + +#: crates/app/src/application/open_links.rs +#, rust-format +msgid "Open “{connection}”?" +msgstr "Mở “{connection}”?" + +#: crates/app/src/application/open_links.rs +msgid "A link asks TablePro to open this saved connection. Open it only if you trust where the link came from." +msgstr "Một liên kết yêu cầu TablePro mở kết nối đã lưu này. Chỉ mở nếu bạn tin cậy nguồn của liên kết." + +#: crates/app/src/ui/assistant/error_text.rs +msgid "The keyring is locked, so the API key cannot be read." +msgstr "Chùm khóa đang bị khóa, nên không đọc được khóa API." + +#: crates/app/src/ui/browse_tab/grid_handlers.rs +msgid "Nothing to share" +msgstr "Không có gì để chia sẻ" + +#: crates/app/src/ui/browse_tab/grid_handlers.rs +msgid "This view has no SQL of its own, so the link shares its rows without it." +msgstr "Chế độ xem này không có SQL riêng, nên liên kết chỉ chia sẻ các dòng." + +#: crates/app/src/ui/browse_tab/json_view.rs +msgid "Rows as JSON" +msgstr "Các dòng dạng JSON" + +#: crates/app/src/ui/browse_tab/json_view.rs +msgid "Can't Show Rows as JSON" +msgstr "Không hiện được các dòng dạng JSON" + +#: crates/app/src/ui/browse_tab/json_view.rs +msgid "The JSON preview could not be created. Try refreshing the rows." +msgstr "Không tạo được bản xem trước JSON. Hãy thử làm mới các dòng." + +#: crates/app/src/ui/browse_tab/json_view.rs +#, rust-format +msgid "The column “{column}” holds a value TablePro couldn't read, so these rows have no JSON to show." +msgstr "Cột “{column}” chứa một giá trị TablePro không đọc được, nên các dòng này không có JSON để hiển thị." + +#: crates/app/src/ui/browse_tab/json_view.rs +#, rust-format +msgid "{shown} of {total} rows shown. This is a limited preview. Export Rows includes the full page." +msgstr "Đang hiện {shown} trên {total} dòng. Đây là bản xem trước có giới hạn. Xuất các dòng sẽ gồm toàn bộ trang." + +#: crates/app/src/ui/browse_tab/json_view.rs +#, rust-format +msgid "{count} row marked for deletion is not shown." +msgid_plural "{count} rows marked for deletion are not shown." +msgstr[0] "Không hiện {count} dòng đã đánh dấu để xóa." + +#: crates/app/src/ui/browse_tab/layout.rs +msgid "_Highlight Rules…" +msgstr "_Quy tắc tô sáng…" + +#: crates/app/src/ui/browse_tab/layout.rs +msgid "_Delete Selected Rows" +msgstr "_Xóa các dòng đã chọn" + +#: crates/app/src/ui/browse_tab/layout.rs +msgid "First _Page" +msgstr "_Trang đầu" + +#: crates/app/src/ui/browse_tab/layout.rs +msgid "_Last Page" +msgstr "Trang _cuối" + +#: crates/app/src/ui/browse_tab/layout.rs +msgid "_Filter Rows…" +msgstr "_Lọc dòng…" + +#. Translators: the visible row range and elapsed page fetch time, including network time. +#: crates/app/src/ui/browse_tab/page_label.rs +#, rust-format +msgid "{range} · {time}" +msgstr "{range} · {time}" + +#: crates/app/src/ui/browse_tab/page_label.rs +msgid "<1 ms" +msgstr "<1 ms" + +#: crates/app/src/ui/browse_tab/page_label.rs +#, rust-format +msgid "{n} ms" +msgstr "{n} ms" + +#: crates/app/src/ui/browse_tab/page_label.rs +#, rust-format +msgid "{n} s" +msgstr "{n} giây" + +#: crates/app/src/ui/browse_tab/page_label.rs +#, rust-format +msgid "{minutes}m {seconds}s" +msgstr "{minutes} phút {seconds} giây" + +#: crates/app/src/ui/data_grid/edit/row_edits.rs +#, rust-format +msgid "{count} row can't take this value and was left as it was" +msgid_plural "{count} rows can't take this value and were left as they were" +msgstr[0] "{count} dòng không nhận được giá trị này nên được giữ nguyên" + +#: crates/app/src/ui/data_grid/grid_cell.rs +#, rust-format +msgid "{state}. {highlight}" +msgstr "{state}. {highlight}" + +#: crates/app/src/ui/data_grid/grid_cell.rs +msgid "Highlighted red" +msgstr "Tô sáng màu đỏ" + +#: crates/app/src/ui/data_grid/grid_cell.rs +msgid "Highlighted orange" +msgstr "Tô sáng màu cam" + +#: crates/app/src/ui/data_grid/grid_cell.rs +msgid "Highlighted yellow" +msgstr "Tô sáng màu vàng" + +#: crates/app/src/ui/data_grid/grid_cell.rs +msgid "Highlighted green" +msgstr "Tô sáng màu xanh lá" + +#: crates/app/src/ui/data_grid/grid_cell.rs +msgid "Highlighted blue" +msgstr "Tô sáng màu xanh dương" + +#: crates/app/src/ui/data_grid/grid_cell.rs +msgid "Highlighted purple" +msgstr "Tô sáng màu tím" + +#: crates/app/src/ui/data_grid/grid_cell.rs +msgid "Highlighted gray" +msgstr "Tô sáng màu xám" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "equals" +msgstr "bằng" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "doesn't equal" +msgstr "khác" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "greater than" +msgstr "lớn hơn" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "at least" +msgstr "tối thiểu" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "less than" +msgstr "nhỏ hơn" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "at most" +msgstr "tối đa" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "contains" +msgstr "chứa" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "starts with" +msgstr "bắt đầu bằng" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "ends with" +msgstr "kết thúc bằng" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "matches pattern" +msgstr "khớp mẫu" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "doesn't match pattern" +msgstr "không khớp mẫu" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "matches pattern, ignoring case" +msgstr "khớp mẫu, không phân biệt hoa thường" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "is NULL" +msgstr "là NULL" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "is not NULL" +msgstr "không phải NULL" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "is one of" +msgstr "là một trong" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "is none of" +msgstr "không là một trong" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "between" +msgstr "trong khoảng" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Gray" +msgstr "Xám" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +#, rust-format +msgid "{from} to {to}" +msgstr "{from} đến {to}" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +#: data/resources/ui/browse-tab.ui data/resources/ui/results-pane.ui +msgid "Highlight Rules" +msgstr "Quy tắc tô sáng" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "The first matching rule sets the colour. A cell rule takes priority over a row rule." +msgstr "Quy tắc khớp đầu tiên quyết định màu. Quy tắc cho ô được ưu tiên hơn quy tắc cho dòng." + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Column unavailable. Choose another column to use this rule." +msgstr "Cột không khả dụng. Hãy chọn cột khác để dùng quy tắc này." + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Enter a value to use this rule." +msgstr "Nhập giá trị để dùng quy tắc này." + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Row" +msgstr "Dòng" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Cell" +msgstr "Ô" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +#, rust-format +msgid "{column} {condition} {value}; {target}, {colour}" +msgstr "{column} {condition} {value}; {target}, {colour}" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "No Highlight Rules" +msgstr "Chưa có quy tắc tô sáng" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Add a rule to colour matching rows or cells." +msgstr "Thêm quy tắc để tô màu các dòng hoặc ô khớp điều kiện." + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +#, rust-format +msgid "Rule {number}" +msgstr "Quy tắc {number}" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Enabled" +msgstr "Bật" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Condition" +msgstr "Điều kiện" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Apply to" +msgstr "Áp dụng cho" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Match Case" +msgstr "Phân biệt hoa thường" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +#, rust-format +msgid "{column} ({number})" +msgstr "{column} ({number})" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +#, rust-format +msgid "{column} (unavailable)" +msgstr "{column} (không khả dụng)" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +#, rust-format +msgid "Value {number}" +msgstr "Giá trị {number}" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Remove Value" +msgstr "Gỡ giá trị" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Add Value" +msgstr "Thêm giá trị" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Move Up" +msgstr "Chuyển lên" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Move Down" +msgstr "Chuyển xuống" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Rule Actions" +msgstr "Thao tác quy tắc" + +#: crates/app/src/ui/data_grid/highlight_dialog.rs +msgid "Drag to Reorder" +msgstr "Kéo để sắp xếp lại" + +#: crates/app/src/ui/data_grid/row_detail/fields.rs +msgid "primary key" +msgstr "khóa chính" + +#: crates/app/src/ui/data_grid/row_detail/fields.rs +msgid "foreign key" +msgstr "khóa ngoại" + +#: crates/app/src/ui/data_grid/row_detail/fields.rs +msgid "Copy Value" +msgstr "Sao chép giá trị" + +#: crates/app/src/ui/data_grid/row_detail/fields.rs +msgid "Primary and foreign key" +msgstr "Khóa chính và khóa ngoại" + +#: crates/app/src/ui/data_grid/row_detail/fields.rs +msgid "Foreign key" +msgstr "Khóa ngoại" + +#: crates/app/src/ui/discard_alert.rs +msgid "The last save may have changed the database. Discarding this draft does not undo changes already saved." +msgstr "Lần lưu gần nhất có thể đã thay đổi cơ sở dữ liệu. Loại bỏ bản nháp này không hoàn tác các thay đổi đã lưu." + +#: crates/app/src/ui/preferences_dialog/mcp_page.rs +msgid "The keyring is locked, so the access token cannot be read." +msgstr "Chùm khóa đang bị khóa, nên không đọc được Access Token." + +#: crates/app/src/ui/quick_open/mod.rs data/resources/shortcuts-dialog.ui +msgid "Open Quickly" +msgstr "Mở nhanh" + +#: crates/app/src/ui/quick_open/mod.rs +msgid "Tables and views" +msgstr "Bảng và view" + +#: crates/app/src/ui/quick_open/mod.rs +msgid "Loading Tables and Views" +msgstr "Đang tải bảng và view" + +#: crates/app/src/ui/quick_open/mod.rs +msgid "Search tables and views" +msgstr "Tìm bảng và view" + +#: crates/app/src/ui/quick_open/mod.rs +#: crates/app/src/ui/quick_open/query_source.rs +msgid "Could not load tables and views." +msgstr "Không tải được bảng và view." + +#: crates/app/src/ui/quick_open/mod.rs +msgid "Could Not Load Tables and Views" +msgstr "Không tải được bảng và view" + +#: crates/app/src/ui/quick_open/mod.rs +msgid "Use Retry to try again." +msgstr "Bấm Thử lại để thử lần nữa." + +#: crates/app/src/ui/quick_open/mod.rs +msgid "Loading Results" +msgstr "Đang tải kết quả" + +#: crates/app/src/ui/quick_open/mod.rs +msgid "No results match what you typed." +msgstr "Không có kết quả nào khớp với nội dung bạn nhập." + +#: crates/app/src/ui/quick_open/mod.rs +msgid "View" +msgstr "View" + +#: crates/app/src/ui/quick_open/mod.rs +msgid "Table" +msgstr "Bảng" + +#: crates/app/src/ui/quick_open/mod.rs +msgid "Saved Query" +msgstr "Truy vấn đã lưu" + +#: crates/app/src/ui/quick_open/mod.rs +msgid "Past Query" +msgstr "Truy vấn đã chạy" + +#: crates/app/src/ui/quick_open/mod.rs +#, rust-format +msgid "{name}, {kind}, {scope}" +msgstr "{name}, {kind}, {scope}" + +#: crates/app/src/ui/quick_open/past_source.rs +msgid "Could not load past queries." +msgstr "Không tải được các truy vấn đã chạy." + +#: crates/app/src/ui/quick_open/query_source.rs +msgid "Search tables, views and queries" +msgstr "Tìm bảng, view và truy vấn" + +#: crates/app/src/ui/quick_open/query_source.rs +msgid "Tables, views and queries" +msgstr "Bảng, view và truy vấn" + +#: crates/app/src/ui/quick_open/query_source.rs +msgid "Could not load saved queries." +msgstr "Không tải được các truy vấn đã lưu." + +#: crates/app/src/ui/quick_open/query_source.rs +msgid "This saved query is no longer available." +msgstr "Truy vấn đã lưu này không còn khả dụng." + +#: crates/app/src/ui/quick_open/query_source.rs +msgid "Could not open this saved query." +msgstr "Không mở được truy vấn đã lưu này." + +#: crates/app/src/ui/quick_open/query_source.rs +msgid "This past query is no longer available." +msgstr "Truy vấn đã chạy này không còn khả dụng." + +#: crates/app/src/ui/quick_open/query_source.rs +msgid "Could not open this past query." +msgstr "Không mở được truy vấn đã chạy này." + +#: crates/app/src/ui/quick_open/query_source.rs +msgid "Saved queries and query history are unavailable." +msgstr "Truy vấn đã lưu và lịch sử truy vấn không khả dụng." + +#: crates/app/src/ui/result_pane/result_summary.rs +#, rust-format +msgid "No rows kept; a run stops keeping rows past {size}, and the server stopped the statement at the row limit, before its end" +msgstr "Không giữ dòng nào; mỗi lượt chạy ngừng giữ dòng khi vượt quá {size}, và máy chủ đã dừng câu lệnh ở giới hạn số dòng, trước khi chạy hết" + +#: crates/app/src/ui/result_pane/result_summary.rs +#, rust-format +msgid "No rows kept; a run stops keeping rows past {size}" +msgstr "Không giữ dòng nào; mỗi lượt chạy ngừng giữ dòng khi vượt quá {size}" + +#: crates/app/src/ui/result_pane/result_summary.rs +#, rust-format +msgid "Showing the first {shown} row; a run stops keeping rows past {size}, and the server stopped the statement at the row limit, before its end" +msgid_plural "Showing the first {shown} rows; a run stops keeping rows past {size}, and the server stopped the statement at the row limit, before its end" +msgstr[0] "Đang hiện {shown} dòng đầu tiên; mỗi lượt chạy ngừng giữ dòng khi vượt quá {size}, và máy chủ đã dừng câu lệnh ở giới hạn số dòng, trước khi chạy hết" + +#: crates/app/src/ui/result_pane/result_summary.rs +#, rust-format +msgid "Showing {shown} of {total} row; a run stops keeping rows past {size}" +msgid_plural "Showing {shown} of {total} rows; a run stops keeping rows past {size}" +msgstr[0] "Đang hiện {shown} trên {total} dòng; mỗi lượt chạy ngừng giữ dòng khi vượt quá {size}" + +#: crates/app/src/ui/result_pane/result_summary.rs +#, rust-format +msgid "Showing the first {shown} row; a run stops keeping rows past {size}" +msgid_plural "Showing the first {shown} rows; a run stops keeping rows past {size}" +msgstr[0] "Đang hiện {shown} dòng đầu tiên; mỗi lượt chạy ngừng giữ dòng khi vượt quá {size}" + +#: crates/app/src/ui/saved_queries_dialog/mod.rs +msgid "Loading Saved Queries" +msgstr "Đang tải truy vấn đã lưu" + +#: crates/app/src/ui/session_window/import_from_app.rs +msgid "Saved query import was interrupted because a connection was deleted." +msgstr "Việc nhập truy vấn đã lưu bị gián đoạn vì một kết nối đã bị xóa." + +#: crates/app/src/ui/session_window/import_from_app.rs +msgid "Saved query import could not finish. Some queries may have been saved." +msgstr "Không hoàn tất được việc nhập truy vấn đã lưu. Một số truy vấn có thể đã được lưu." + +#: crates/app/src/ui/session_window/state_file_status.rs +msgid "Column layouts could not be saved" +msgstr "Không lưu được bố cục cột" + +#: crates/app/src/ui/session_window/state_file_status.rs +msgid "Table filters could not be saved" +msgstr "Không lưu được bộ lọc bảng" + +#: crates/app/src/ui/session_window/state_file_status.rs +msgid "Highlight rules could not be saved" +msgstr "Không lưu được quy tắc tô sáng" + +#: crates/app/src/ui/session_window/state_file_status.rs +msgid "Saved column layouts are unavailable. Their file has been kept unchanged." +msgstr "Bố cục cột đã lưu không khả dụng. Tệp của chúng vẫn được giữ nguyên." + +#: crates/app/src/ui/session_window/state_file_status.rs +msgid "Saved table filters are unavailable. Their file has been kept unchanged." +msgstr "Bộ lọc bảng đã lưu không khả dụng. Tệp của chúng vẫn được giữ nguyên." + +#: crates/app/src/ui/session_window/state_file_status.rs +msgid "Saved highlight rules are unavailable. Their file has been kept unchanged." +msgstr "Quy tắc tô sáng đã lưu không khả dụng. Tệp của chúng vẫn được giữ nguyên." + +#: crates/app/src/ui/session_window/state_file_status.rs +msgid "Table Settings Could Not Be Saved" +msgstr "Không lưu được cài đặt bảng" + +#: crates/app/src/ui/session_window/state_file_status.rs +msgid "Closing now will lose changes to highlight rules, filters or column layouts." +msgstr "Đóng bây giờ sẽ mất các thay đổi về quy tắc tô sáng, bộ lọc hoặc bố cục cột." + +#: crates/app/src/ui/session_window/state_file_status.rs +msgid "Keep Open" +msgstr "Giữ mở" + +#: crates/app/src/ui/session_window/state_file_status.rs +msgid "Close Without Saving" +msgstr "Đóng mà không lưu" + +#: crates/app/src/ui/share_dialog/form.rs +msgid "Share As" +msgstr "Chia sẻ với tư cách" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "Public links are off for this team." +msgstr "Nhóm này đã tắt liên kết công khai." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "{live} of {limit} link" +msgid_plural "{live} of {limit} links" +msgstr[0] "{live}/{limit} liên kết" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "{team} · {links}" +msgstr "{team} · {links}" + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "{team} has {live} live link. The team allows {limit}. Revoke one to share another." +msgid_plural "{team} has {live} live links. The team allows {limit}. Revoke one to share another." +msgstr[0] "{team} có {live} liên kết đang hoạt động. Nhóm cho phép {limit}. Hãy thu hồi một liên kết để chia sẻ liên kết khác." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "Shares the first {count} column." +msgid_plural "Shares the first {count} columns." +msgstr[0] "Chia sẻ {count} cột đầu tiên." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +#, rust-format +msgid "The link shares the first {count} column." +msgid_plural "The link shares the first {count} columns." +msgstr[0] "Liên kết chia sẻ {count} cột đầu tiên." + +#: crates/app/src/ui/share_dialog/sheet_view.rs +msgid "Suspended" +msgstr "Đã tạm ngưng" + +#: crates/app/src/ui/structure_tab/save_handlers.rs +msgid "The last save may have changed the database. Reload to read its current structure and discard this draft." +msgstr "Lần lưu gần nhất có thể đã thay đổi cơ sở dữ liệu. Hãy tải lại để đọc cấu trúc hiện tại và loại bỏ bản nháp này." + +#: crates/app/src/ui/structure_tab/save_handlers.rs +msgid "Refreshing reloads the table structure from the database and discards its unsaved changes." +msgstr "Làm mới sẽ tải lại cấu trúc bảng từ cơ sở dữ liệu và loại bỏ các thay đổi chưa lưu." + +#: crates/app/src/ui/structure_tab/save_handlers.rs +msgid "Discard Structure Changes?" +msgstr "Loại bỏ thay đổi cấu trúc?" + +#: crates/app/src/ui/structure_tab/save_handlers.rs +msgid "Wait for the table structure to load, then make the change again." +msgstr "Hãy chờ cấu trúc bảng tải xong rồi thực hiện lại thay đổi." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "Could not move that saved query." +msgstr "Không chuyển được truy vấn đã lưu đó." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "Could not create that folder." +msgstr "Không tạo được thư mục đó." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "Could not rename that folder." +msgstr "Không đổi tên được thư mục đó." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "Could not delete that folder." +msgstr "Không xóa được thư mục đó." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "Rename Folder" +msgstr "Đổi tên thư mục" + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "New Subfolder" +msgstr "Thư mục con mới" + +#: crates/app/src/ui/workspace/favorite_folders.rs +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +msgid "New Folder" +msgstr "Thư mục mới" + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "This folder and its subfolders will be deleted. Their saved queries will move to the top level." +msgstr "Thư mục này và các thư mục con sẽ bị xóa. Các truy vấn đã lưu trong đó sẽ được chuyển lên cấp cao nhất." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "No Folder" +msgstr "Không có thư mục" + +#: crates/app/src/ui/workspace/favorite_folders.rs +#, rust-format +msgid "Move “{name}”" +msgstr "Chuyển “{name}”" + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "Move" +msgstr "Chuyển" + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "That name is already used by another folder in the same place." +msgstr "Tên đó đã được một thư mục khác ở cùng vị trí dùng." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "Folder names cannot contain control characters." +msgstr "Tên thư mục không được chứa ký tự điều khiển." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "That folder name is too long." +msgstr "Tên thư mục đó quá dài." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "Enter a name for the folder." +msgstr "Nhập tên cho thư mục." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "A folder cannot be moved inside itself or one of its subfolders." +msgstr "Không thể chuyển thư mục vào chính nó hoặc một thư mục con của nó." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "That folder was deleted elsewhere." +msgstr "Thư mục đó đã bị xóa ở nơi khác." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "Favorites are unavailable. Restart TablePro to try again." +msgstr "Mục yêu thích không khả dụng. Hãy khởi động lại TablePro để thử lại." + +#: crates/app/src/ui/workspace/favorite_folders.rs +msgid "The saved query or destination folder was deleted elsewhere." +msgstr "Truy vấn đã lưu hoặc thư mục đích đã bị xóa ở nơi khác." + +#: crates/app/src/ui/workspace/schema_chooser.rs +msgid "Showing all databases" +msgstr "Đang hiện tất cả cơ sở dữ liệu" + +#: crates/app/src/ui/workspace/schema_chooser.rs +msgid "Showing all schemas" +msgstr "Đang hiện tất cả schema" + +#: crates/app/src/ui/workspace/schema_chooser.rs +#, rust-format +msgid "Showing {shown} of {total} database" +msgid_plural "Showing {shown} of {total} databases" +msgstr[0] "Đang hiện {shown} trên {total} cơ sở dữ liệu" + +#: crates/app/src/ui/workspace/schema_chooser.rs +#, rust-format +msgid "Showing {shown} of {total} schema" +msgid_plural "Showing {shown} of {total} schemas" +msgstr[0] "Đang hiện {shown} trên {total} schema" + +#: crates/app/src/ui/workspace/schema_chooser.rs +msgid "Databases" +msgstr "Cơ sở dữ liệu" + +#. The front's own word replaces it; a template button needs a name before then. +#: crates/app/src/ui/workspace/schema_chooser.rs +#: data/resources/ui/workspace-shell.ui +msgid "Schemas" +msgstr "Schema" + +#: crates/app/src/ui/workspace/schema_chooser.rs +msgid "Show _All" +msgstr "Hiển thị _tất cả" + +#: crates/app/src/ui/workspace/schema_chooser.rs +msgid "Search databases" +msgstr "Tìm cơ sở dữ liệu" + +#: crates/app/src/ui/workspace/schema_chooser.rs +msgid "Search schemas" +msgstr "Tìm schema" + +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +#: data/resources/ui/workspace-shell.ui +msgid "Favorites" +msgstr "Yêu thích" + +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +msgid "The query history file could not be opened. Check the file and restart TablePro." +msgstr "Không mở được tệp lịch sử truy vấn. Hãy kiểm tra tệp rồi khởi động lại TablePro." + +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +msgid "Saved queries could not be read. Try again." +msgstr "Không đọc được các truy vấn đã lưu. Hãy thử lại." + +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +msgid "Favorites Unavailable" +msgstr "Mục yêu thích không khả dụng" + +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +msgid "Favorites could not be refreshed." +msgstr "Không làm mới được mục yêu thích." + +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +msgid "No Favorites" +msgstr "Chưa có mục yêu thích" + +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +msgid "Save a query from the SQL editor or create a folder to organize favorites." +msgstr "Lưu một truy vấn từ trình soạn thảo SQL hoặc tạo thư mục để sắp xếp mục yêu thích." + +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +msgid "Loading Favorites" +msgstr "Đang tải mục yêu thích" + +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +msgid "No Connection Selected" +msgstr "Chưa chọn kết nối" + +#: crates/app/src/ui/workspace/sidebar/favorites_pane.rs +msgid "Open a connection to see its saved queries." +msgstr "Mở một kết nối để xem các truy vấn đã lưu của kết nối đó." + +#: crates/app/src/ui/workspace/sidebar/favorites_rows.rs +#, rust-format +msgid "Options for “{name}”" +msgstr "Tùy chọn cho “{name}”" + +#: crates/app/src/ui/workspace/sidebar/favorites_rows.rs +#, rust-format +msgid "Folder “{name}”" +msgstr "Thư mục “{name}”" + +#: crates/app/src/ui/workspace/sidebar/favorites_rows.rs +#, rust-format +msgid "Saved query “{name}”" +msgstr "Truy vấn đã lưu “{name}”" + +#: crates/app/src/ui/workspace/sidebar/favorites_rows.rs +#, rust-format +msgid "{item} in {folder}" +msgstr "{item} trong {folder}" + +#: crates/app/src/ui/workspace/sidebar/favorites_rows.rs +msgid "_Move to Folder…" +msgstr "_Chuyển vào thư mục…" + +#: crates/app/src/ui/workspace/sidebar/favorites_rows.rs +msgid "_Delete…" +msgstr "_Xóa…" + +#: crates/app/src/ui/workspace/sidebar/favorites_rows.rs +msgid "New _Subfolder…" +msgstr "_Thư mục con mới…" + +#: crates/app/src/ui/workspace/sidebar/sidebar_index.rs +msgctxt "sidebar group" +msgid "Views" +msgstr "View" + +#: crates/app/src/ui/workspace/sidebar/sidebar_index.rs +msgctxt "sidebar group" +msgid "Materialized Views" +msgstr "Materialized View" + +#: crates/app/src/ui/workspace/sidebar/sidebar_index.rs +msgctxt "sidebar group" +msgid "Foreign Tables" +msgstr "Bảng ngoại" + +#: crates/app/src/ui/workspace/sidebar/sidebar_index.rs +msgctxt "sidebar group" +msgid "Sequences" +msgstr "Sequence" + +#: crates/app/src/ui/workspace/sidebar/sidebar_index.rs +msgctxt "sidebar group" +msgid "Procedures" +msgstr "Procedure" + +#: crates/app/src/ui/workspace/sidebar/sidebar_index.rs +msgctxt "sidebar group" +msgid "Functions" +msgstr "Hàm" + +#: crates/app/src/ui/workspace/sidebar/sidebar_index.rs +msgctxt "sidebar group" +msgid "Triggers" +msgstr "Trigger" + +#: crates/app/src/ui/workspace/sidebar/tree_menu.rs +msgid "New _Table…" +msgstr "_Bảng mới…" + +#: crates/app/src/ui/workspace/sidebar/tree_menu.rs +msgid "New _Database…" +msgstr "_Cơ sở dữ liệu mới…" + +#: crates/app/src/ui/workspace/sidebar/tree_menu.rs +msgid "New _Keyspace…" +msgstr "_Keyspace mới…" + +#: crates/app/src/ui/workspace/sidebar/tree_row.rs +#, rust-format +msgid "{count} object" +msgid_plural "{count} objects" +msgstr[0] "{count} đối tượng" + +#: crates/app/src/ui/workspace/status_pages.rs +#, rust-format +msgid "Replace “{name}”?" +msgstr "Thay thế “{name}”?" + +#: crates/app/src/ui/workspace/status_pages.rs +msgid "A saved query already uses this name. Replacing it will overwrite its SQL." +msgstr "Đã có một truy vấn đã lưu dùng tên này. Thay thế sẽ ghi đè SQL của truy vấn đó." + +#: crates/app/src/ui/workspace/workspace_shell.rs +#: data/resources/shortcuts-dialog.ui +msgid "Refresh Tab" +msgstr "Làm mới tab" + +#: crates/app/src/ui/workspace/workspace_shell.rs +msgid "Session Menu" +msgstr "Menu phiên làm việc" + +#: crates/app/src/ui/workspace/workspace_shell.rs +#, rust-format +msgid "Safe Mode: {level}" +msgstr "Chế độ an toàn: {level}" + +#: crates/app/src/ui/workspace/workspace_shell.rs +msgid "Rename Favorite" +msgstr "Đổi tên mục yêu thích" + +#: crates/app/src/ui/workspace/workspace_shell.rs +msgid "The saved query is deleted. This cannot be undone." +msgstr "Truy vấn đã lưu sẽ bị xóa. Không thể hoàn tác." + +#: crates/app/src/ui/workspace/workspace_shell.rs +msgid "Could not rename that saved query." +msgstr "Không đổi tên được truy vấn đã lưu đó." + +#: crates/app/src/ui/workspace/workspace_shell.rs +msgid "Enter a name for the saved query." +msgstr "Nhập tên cho truy vấn đã lưu." + +#: crates/app/src/ui/workspace/workspace_shell.rs +msgid "Saved queries are unavailable. Restart TablePro to try again." +msgstr "Truy vấn đã lưu không khả dụng. Hãy khởi động lại TablePro để thử lại." + +#: crates/app/src/ui/workspace/workspace_tabs.rs +msgid "The last save may have changed the database. Reload to read its current rows and discard these changes." +msgstr "Lần lưu gần nhất có thể đã thay đổi cơ sở dữ liệu. Hãy tải lại để đọc các dòng hiện tại và loại bỏ các thay đổi này." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Sidebar width" +msgstr "Độ rộng thanh bên" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "The most the sidebar takes, in scale-independent pixels; the content always keeps half the window." +msgstr "Độ rộng tối đa của thanh bên, tính bằng pixel không phụ thuộc tỷ lệ; phần nội dung luôn giữ một nửa cửa sổ." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Show row numbers" +msgstr "Hiện số thứ tự dòng" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Show each row's number in the first column of a data grid." +msgstr "Hiện số thứ tự của từng dòng ở cột đầu tiên của lưới dữ liệu." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Data grid row height" +msgstr "Chiều cao dòng của lưới dữ liệu" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "How much room a data grid row takes around its text." +msgstr "Khoảng trống quanh văn bản trong mỗi dòng của lưới dữ liệu." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Format of copied rows" +msgstr "Định dạng của dòng được sao chép" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "The format Copy writes when several rows are selected." +msgstr "Định dạng mà lệnh Sao chép ghi ra khi chọn nhiều dòng." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Open row details when a row is selected" +msgstr "Mở chi tiết dòng khi chọn một dòng" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Whether selecting a row in a data grid opens its row details pane." +msgstr "Chọn một dòng trong lưới dữ liệu có mở khung chi tiết dòng hay không." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Default sort of a table" +msgstr "Sắp xếp mặc định của bảng" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "The column a table tab sorts by when it opens, until the user picks another." +msgstr "Cột mà tab bảng dùng để sắp xếp khi mở, cho tới khi người dùng chọn cột khác." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Direction of the default sort" +msgstr "Chiều của sắp xếp mặc định" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Which way a table tab sorts by its default column." +msgstr "Chiều sắp xếp của tab bảng theo cột mặc định." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Show invisible characters" +msgstr "Hiện ký tự ẩn" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Whether cells and value fields mark zero-width, control and special space characters." +msgstr "Các ô và trường giá trị có đánh dấu ký tự độ rộng bằng không, ký tự điều khiển và ký tự khoảng trắng đặc biệt hay không." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Date format of cells" +msgstr "Định dạng ngày của ô" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "How the data grid spells dates and timestamps. A copy and an export keep the database's own spelling." +msgstr "Cách lưới dữ liệu hiển thị ngày và dấu thời gian. Bản sao chép và bản xuất giữ nguyên cách ghi của cơ sở dữ liệu." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Text for a NULL value" +msgstr "Văn bản cho giá trị NULL" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "What a data grid cell shows for a value that is NULL." +msgstr "Nội dung mà ô của lưới dữ liệu hiển thị cho giá trị NULL." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Use the system monospace font in the data grid" +msgstr "Dùng phông chữ đơn cách của hệ thống trong lưới dữ liệu" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Whether the data grid follows the desktop monospace font instead of a custom one." +msgstr "Lưới dữ liệu có dùng phông chữ đơn cách của màn hình nền thay vì một phông chữ tùy chọn hay không." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Custom data grid font" +msgstr "Phông chữ lưới dữ liệu tùy chọn" + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "Pango font description the data grid uses when the system font is turned off." +msgstr "Mô tả phông chữ Pango mà lưới dữ liệu dùng khi tắt phông chữ hệ thống." + +#: data/app.tablepro.TablePro.gschema.xml.in +msgid "GtkSourceView style scheme id for the SQL editor. Empty follows the system light or dark style." +msgstr "Mã bộ màu GtkSourceView cho trình soạn thảo SQL. Để trống thì theo kiểu sáng hoặc tối của hệ thống." + +#: data/resources/gtk/menus.ui +msgid "_Open Quickly…" +msgstr "_Mở nhanh…" + +#: data/resources/ui/browse-tab.ui +msgid "_Discard Changes…" +msgstr "_Loại bỏ thay đổi…" + +#: data/resources/ui/browse-tab.ui +msgid "Data" +msgstr "Dữ liệu" + +#: data/resources/ui/browse-tab.ui +msgid "Structure" +msgstr "Cấu trúc" + +#: data/resources/ui/browse-tab.ui +#: data/resources/ui/preferences-data-browser-group.ui +msgid "JSON" +msgstr "JSON" + +#: data/resources/ui/browse-tab.ui +msgid "Copy JSON Preview" +msgstr "Sao chép bản xem trước JSON" + +#: data/resources/ui/browse-tab.ui +msgid "More JSON Actions" +msgstr "Thao tác JSON khác" + +#: data/resources/ui/browse-tab.ui +msgid "More Structure Actions" +msgstr "Thao tác cấu trúc khác" + +#: data/resources/ui/browse-tab.ui data/resources/ui/results-pane.ui +msgid "Choose which columns the grid shows" +msgstr "Chọn các cột hiển thị trong lưới" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Show Row Numbers" +msgstr "Hiện số thứ tự dòng" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Row Height" +msgstr "Chiều cao dòng" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Compact" +msgstr "Gọn" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Normal" +msgstr "Bình thường" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Comfortable" +msgstr "Thoải mái" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Spacious" +msgstr "Rộng rãi" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Open Row Details on Selection" +msgstr "Mở chi tiết dòng khi chọn" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Selecting a row opens its details pane" +msgstr "Chọn một dòng sẽ mở khung chi tiết của dòng đó" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Show Invisible Characters" +msgstr "Hiện ký tự ẩn" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Mark zero-width, control and special space characters in cells and value fields" +msgstr "Đánh dấu ký tự độ rộng bằng không, ký tự điều khiển và ký tự khoảng trắng đặc biệt trong ô và trường giá trị" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Date Format" +msgstr "Định dạng ngày" + +#. No subtitle: its width would squeeze the chosen example. +#: data/resources/ui/preferences-data-browser-group.ui +msgid "How cells show dates and timestamps. Copy and export use the original values." +msgstr "Cách ô hiển thị ngày và dấu thời gian. Sao chép và xuất dùng giá trị gốc." + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Default Sort" +msgstr "Sắp xếp mặc định" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "How a table is ordered when it opens" +msgstr "Thứ tự của bảng khi mở" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "No sorting (server order)" +msgstr "Không sắp xếp (thứ tự của máy chủ)" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "First column" +msgstr "Cột đầu tiên" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Default Sort Direction" +msgstr "Chiều sắp xếp mặc định" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Ascending" +msgstr "Tăng dần" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Copy Rows As" +msgstr "Sao chép dòng dưới dạng" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "The format Copy writes when several rows are selected" +msgstr "Định dạng mà Sao chép ghi ra khi chọn nhiều dòng" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "TSV" +msgstr "TSV" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "TSV with Headers" +msgstr "TSV kèm tiêu đề" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "CSV" +msgstr "CSV" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "CSV with Headers" +msgstr "CSV kèm tiêu đề" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Markdown" +msgstr "Markdown" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Text for NULL" +msgstr "Văn bản cho NULL" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Up to 20 characters. Empty text uses NULL." +msgstr "Tối đa 20 ký tự. Để trống thì dùng NULL." + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Use the System Monospace Font for Cells" +msgstr "Dùng phông chữ đơn cách của hệ thống cho ô" + +#: data/resources/ui/preferences-data-browser-group.ui +msgid "Cell Font" +msgstr "Phông chữ của ô" + +#: data/resources/ui/preferences-editor-page.ui +msgid "Follow System Style" +msgstr "Theo kiểu của hệ thống" + +#: data/resources/ui/preferences-editor-page.ui +msgid "Use Adwaita in the desktop’s light or dark style" +msgstr "Dùng Adwaita theo kiểu sáng hoặc tối của màn hình nền" + +#: data/resources/ui/row-detail-pane.ui +msgid "Search fields" +msgstr "Tìm trường" + +#: data/resources/ui/row-detail-pane.ui +msgid "Show edited fields only" +msgstr "Chỉ hiện trường đã sửa" + +#: data/resources/ui/row-detail-pane.ui +msgid "No Matching Fields" +msgstr "Không có trường nào khớp" + +#: data/resources/ui/workspace-shell.ui +msgid "Sidebar Width" +msgstr "Độ rộng thanh bên" + +msgid "Full" +msgstr "Toàn bộ" + +msgid "Last 4 Characters" +msgstr "4 ký tự cuối" + +msgid "Email" +msgstr "Email" + +msgid "Stable Hash" +msgstr "Băm ổn định" + +msgid "Keep" +msgstr "Giữ" + +msgid "The name looks like personal data" +msgstr "Tên cột giống dữ liệu cá nhân" + +msgid "Values look like card numbers" +msgstr "Giá trị giống số thẻ" + +msgid "Values look like IBANs" +msgstr "Giá trị giống số IBAN" + +msgid "Values look like access tokens" +msgstr "Giá trị giống mã truy cập" + +msgid "Values look like API keys" +msgstr "Giá trị giống khóa API" + +msgid "Values look like email addresses" +msgstr "Giá trị giống địa chỉ email" + +msgid "Values look like phone numbers" +msgstr "Giá trị giống số điện thoại" + +msgid "Values look like IP addresses" +msgstr "Giá trị giống địa chỉ IP" + +msgid "TablePro masked columns that look sensitive. Check them before sharing." +msgstr "TablePro đã che các cột có vẻ nhạy cảm. Hãy kiểm tra trước khi chia sẻ." + +msgid "This query contains what looks like personal data ({kind}). Turn on Hide SQL to keep the query private." +msgstr "Truy vấn này chứa thứ có vẻ là dữ liệu cá nhân ({kind}). Bật Ẩn SQL để giữ truy vấn riêng tư." + +msgid "a card number" +msgstr "số thẻ" + +msgid "an IBAN" +msgstr "số IBAN" + +msgid "an access token" +msgstr "mã truy cập" + +msgid "an API key" +msgstr "khóa API" + +msgid "an email address" +msgstr "địa chỉ email" + +msgid "a phone number" +msgstr "số điện thoại" + +msgid "an IP address" +msgstr "địa chỉ IP" + +msgid "{n} column masked, {m} removed." +msgid_plural "{n} columns masked, {m} removed." +msgstr[0] "Đã che {n} cột, đã gỡ {m} cột." + +msgid "Mask as {style}" +msgstr "Che kiểu {style}" diff --git a/windows/AGENTS.md b/windows/AGENTS.md index d6e1004ef0..602bbbb48d 100644 --- a/windows/AGENTS.md +++ b/windows/AGENTS.md @@ -47,6 +47,8 @@ This is the guide for work under `windows/`. The root `AGENTS.md` holds the rule - `QueryEvent.Finished.Transaction` is the transaction the editor's connection is left in. A session's `Health` is waited on with `WaitForHealthChangeAsync`, which returns once it differs from the one passed in. - The app starts the core with `TableProCore.CreateWithSystemSecrets`, so the core keeps secrets in Credential Manager itself. `ISecretStore` is for tests and hosts with a store of their own; the core calls it on a thread of its own. - `TableProCore.Library` reads and writes the saved connections in the storage directory the configuration names. A list the app shows is rebuilt from `GetSnapshotAsync` after each change. +- A result share's columns start from `ResultSet.GetShareMaskingAsync` (what the detectors see), `GetShareSummaryAsync` says what a share with the sheet's choices sends and `GetSharePreviewAsync` shows it masked as sent; `CreateShareAsync` takes the same choices. Nothing else masks (`docs/decisions/0010-data-masking.md`). +- `TableProCore.OpenAccountAsync` opens the TablePro account once per app; `ReadStatusChangesAsync` gives its status on the UI thread, and its share calls (`GetShareLimitsAsync`, `CreateShareAsync` from a finished `ResultSet`, `ListSharesAsync`, `RevokeShareAsync`, `ExtendShareAsync`, `FetchSharedAsync`) throw `account.*` codes. `ShareLinks` holds the core's secret scan and deep link rule (`docs/decisions/0008-tablepro-account.md`, `docs/decisions/0009-share-links.md`). ## Commands diff --git a/windows/docs/decisions/0008-tablepro-account.md b/windows/docs/decisions/0008-tablepro-account.md new file mode 100644 index 0000000000..e57551f04f --- /dev/null +++ b/windows/docs/decisions/0008-tablepro-account.md @@ -0,0 +1,40 @@ +# 0008: Signing in to the TablePro account + +- **Status**: Accepted +- **Date**: 2026-11-13 + +## Context + +The Windows app had no TablePro account. On 2026-11-13 the maintainer decided that Windows gets account sign-in in the share-links round, since a share link needs a signed-in account with a verified email. The core builds the account from `tablepro-account` for Windows and gives it to the app through the FFI's `AccountService` ([core 0026](../../../core/docs/decisions/0026-the-windows-app-signs-in-through-the-ffi.md)); tablepro-cloud registers the public client `tablepro-windows` with a loopback redirect on any port. + +## Decision + +The app opens one account at launch and shows it on the Settings page, with the logic in `src/TablePro.App.Model` and the calls in `src/TablePro.Interop`. + +### Interop + +- `TableProCore.OpenAccountAsync(AccountConfiguration, IAccountBrowser)` returns a `TableProAccount`, which restores the last sign-in and keeps the entitlement fresh until it is disposed. Its calls run on the thread pool as every other call does, and throw `TableProException` with the core's `account.*` code. +- The core's status callback only signals. `AccountWake` holds one slot in a bounded channel, as `RunWake` does for a run, and `ReadStatusChangesAsync` reads `Status` again on the UI thread for every wake, so changes that come while the UI is busy are read as one. +- `IAccountBrowser.OpenAsync` opens the sign-in page. The core calls it on a thread it lets block; the app's `SystemBrowser` hands the URL to the UI thread's dispatcher and opens it with `Launcher.LaunchUriAsync`, which needs the thread its window lives on. +- The refresh token stays in the core's own store: `TablePro/account//refresh-token` in Credential Manager under `CreateWithSystemSecrets`, the key named for the account service and the account file, or `SecretItem.AccountRefreshToken` of a host's `ISecretStore` (core 0026). The account's device and entitlement are in `account.json` in the data folder. +- The core reads `MachineGuid` itself. `AccountConfiguration.MachineGuid` is for a host off Windows, as the interop tests. + +### App + +- `Workbench.StartAccount` opens the account once, in `App.OnLaunched`, and keeps its status for every window. `AccountChanged` is raised on the UI thread after the status or a sign-in's progress changes. One sign-in runs at a time; the Settings page and the share sheet both start it, and Cancel ends the wait for the browser. +- Settings opens with an Account section: a card that names the account (its name, else its email), its email and plan, with one action, Sign in..., Cancel while the browser is open, or Sign out. Signed in, Plan has Refresh and, expanded, Manage account and Manage shared links, which open the portal in the browser; Devices lists the account's devices when it opens, this computer first, each with Remove where the server allows it. +- An InfoBar above the card says what needs doing: an error a press met, an entitlement that expired or could not refresh (with Refresh or Try again), the device limit (with Remove a device..., which opens a dialog of the devices holding the license: a removed device leaves the list, the core asks the account again, and the dialog closes once the license is under its limit; a removal whose refresh failed says so apart from a removal that failed), or a sign-in Credential Manager did not keep. +- `AccountPanel` turns the status and the sign-in's progress into the stage, title, plan and notice the page shows. Pro is the entitlement's `shared_links` feature, as the server resolves it. +- Every `account.*` code, and the FFI's own account and share codes, has its sentence in `Strings/en-US/Resources.resw` as `Error_`. +- A Debug build signs in to a local tablepro-cloud when `TABLEPRO_ACCOUNT_URL` and `TABLEPRO_API_URL` are set, with `TABLEPRO_ENTITLEMENT_KEYS` for its signing keys. A Release build always uses tablepro.app. + +## Rationale + +- The core already runs the account for Linux, and its Windows seams (Credential Manager, `MachineGuid`, the loopback listener) are in the FFI, so the app only lays it out and words it. +- Stock controls: the Toolkit's SettingsExpander and SettingsCard, as the rest of Settings, InfoBar and ContentDialog. + +## Consequences + +- No offline file import, billing or license key entry yet; the portal has them. +- The UI tests run signed out: a data folder with no `account.json` starts signed out and the core never opens Credential Manager, so nothing reaches tablepro.app. +- Each data folder signs in on its own: the credential's key follows the account file, so a second data folder or a development stack never takes another's token. diff --git a/windows/docs/decisions/0009-share-links.md b/windows/docs/decisions/0009-share-links.md new file mode 100644 index 0000000000..3f89c752c0 --- /dev/null +++ b/windows/docs/decisions/0009-share-links.md @@ -0,0 +1,50 @@ +# 0009: Share links + +- **Status**: Accepted +- **Date**: 2026-11-13 + +## Context + +On 2026-11-13 the maintainer decided that every app shares a query or a result as a public link on tablepro-cloud, from a signed-in account with a verified email: Free with 5 live links, 1,000 rows and an expiry of 1, 7 or 30 days, Pro with 1,000 links, 10,000 rows, no expiry, a password and viewer downloads off. A link's deep link `tablepro://share?token=` opens its SQL in the app. The core holds the calls, the snapshot, the secret scan and the deep link rule ([core 0027](../../../core/docs/decisions/0027-share-links.md)), and the account they go through ([0008](0008-tablepro-account.md)). + +## Decision + +The sheet and the menus work as the macOS and Linux apps' do, in Windows sentence case and with three dots for an ellipsis, as the rest of the app words its commands. The plan's rules are in `SharePlan` and `SharedLinkOpen` (`src/TablePro.App.Model`), tested with no core; `ShareSheet` and `SharedLinkDialogs` lay out. + +### Entry points + +- The query results grid gets its first context menu: Copy, then Share result.... A table tab's grid menu adds Share..., which shares the table's whole view and is off while edits are pending, since the snapshot holds the server's values. +- A table share reads the view again from its first row, whichever page shows, stopped if the sheet closes first, with the filter and sort the rows shown were read with and the plan's rows as its limit (`TableTab.ReadForShareAsync`), counts what the filter picks, and sends the page's `ViewSql`: the query the view stands for, with its filter values written in and no row window ([core 0027](../../../core/docs/decisions/0027-share-links.md)). So "first N of M" holds, Hide SQL is offered and the link opens in TablePro. Where the engine cannot write that query, the sheet says so and shares the rows without SQL. +- The SQL editor's own menu gets Share query..., with the selection, else the whole text. `SqlEditor.ContextMenuOpening` lets the host add its items each time the menu opens, since the editor builds a new menu for each window it moves to. +- The File menu has Share result..., Share query... and Manage shared links..., which opens `https://account.tablepro.app/shared-links`. The Windows app has no saved queries or favorite queries yet, so none of them offer Share.... + +### The sheet + +- A `ContentDialog`, titled Share result or Share query, whose one section follows the account: signed out, Sign in..., which starts the account's sign-in and waits in the sheet; an account that could not start says why; signed in, the plan's limits are read (`GET /v2/share-limits`) with a spinner, and an offline or failed read offers Retry. +- An unverified email offers Open account; sharing turned off says so; at the cap, the live personal links, or the chosen team's, are listed oldest first, each with Revoke and a suspended one marked Suspended, with "Pro allows up to 1,000." on Free, and a freed slot shows the form again from limits read anew. +- Share as, shown when the account holds a seat in a team: Personal, then each team from the limits; a team that turned public links off is listed but not offered ("Public links are off for this team."). A team link sends its team, and the footer, the cap and the cap's list use the team's own count, limit and links. +- The form: Title, prefilled from the tab or the table; Note; Expires, every expiry listed with the ones the plan does not allow disabled, and Never on Free tagged Pro; Hide SQL for a result that has its SQL; Password and Allow viewers to download, disabled with a Pro tag on Free. A Pro tag is a `HyperlinkButton` to the plans page, with no dialog. +- A result shows its first 5 rows of the visible columns in the app's own grid, over the result set's cells, and "Shares the first 1,000 of 48,210 rows." when the plan cuts it. The core builds the snapshot from the same set and the visible column count, cut to the plan's rows, with a table view's count as its total, so no row crosses the FFI to come back. +- The server takes a result's first 100 columns (`MaxColumns` in the limits): the preview shows those and says "Shares the first 100 columns.", and the link's page says so again once the core reports it cut them. +- The core's secret scan warns inline about the SQL, while it would be shown, and about the result's column names; it never blocks a share. +- The footer reads "Free · 3 of 5 links · first 1,000 rows" or "Pro · 12 links". +- Share creates the link once: the button is off while it runs. Success copies the URL to the clipboard and shows it with Copy and Open in browser, and the dialog's close button reads Done. A refusal the limits explain (`share_limit_reached`, `email_unverified`, `sharing_disabled`, `signed_out`) reads them again; every other code has the sheet's sentence (`ShareErrors`), and anything else "The link couldn't be created. Try again." +- `SharePlan.Request` never sends an option the plan does not allow, so Free is never refused with `pro_required` for what the sheet offered. + +### Deep links + +- The package declares the `windows.protocol` extension for `tablepro`. The packaged app is activated with the link; the execution alias and an unpackaged build get it as an argument. A launch while the app runs on the same data folder hands its activation to the running app (`SingleInstance`), which reads the link from it. +- Links open one at a time, in the order they came, and one already waiting is not added twice (`PendingSharedLinks`). Their password prompt and messages wait until the window has loaded and no other dialog is open (`WindowDialogs.ShowWhenFreeAsync`), so a link that comes during another dialog or at a cold start is not dropped. +- `ShareLinks.TokenFromLink` takes only the core's format. The public share is read with no sign-in; `share_password_required` asks for the password, `share_password_wrong` asks again and says so, and `not_found` says the link is no longer available. +- The SQL opens in a new query tab of the connection in front, or the first connected one, and never runs; no connection detail is carried. With no connection open, a dialog shows the SQL with Copy SQL. A share that hides its SQL, or a result shared with none, says there is nothing to open. + +## Rationale + +- The core already builds the snapshot losslessly, scans for secrets and validates the token for Linux, so Windows lays out and words. +- Stock controls: ContentDialog, InfoBar, ComboBox, PasswordBox, CheckBox, HyperlinkButton, MenuFlyout, and the app's own data grid for the preview. + +## Consequences + +- A table share reads up to the plan's rows once more when the sheet opens, and counts the view, so a large table waits on both before the form shows. +- No editing of a link after it is made in the app: the portal has it. +- The UI tests show the sheet and the Settings section signed out; a signed-in sheet needs a test stack. diff --git a/windows/docs/decisions/0010-data-masking.md b/windows/docs/decisions/0010-data-masking.md new file mode 100644 index 0000000000..6c87faa696 --- /dev/null +++ b/windows/docs/decisions/0010-data-masking.md @@ -0,0 +1,25 @@ +# 0010: Masking a shared result + +- **Status**: Accepted +- **Date**: 2026-11-14 + +## Context + +On 2026-11-14 the maintainer decided that masking in this work is only for sharing: a share link hides sensitive columns before it leaves the machine, and nothing else in the Windows app masks (share-v2 PLAN-MASKING 8.0). The core computes the styles, detects what looks sensitive, previews and sums up the rows a share sends, and builds the masked snapshot ([core 0028](../../../core/docs/decisions/0028-data-masking.md)). + +## Decision + +The share sheet's result section works as the macOS app's does, in Windows sentence case (0009). Its rules are in `src/TablePro.App.Model` (`ShareColumns`, `ShareRounds`, `SharePlan`), tested with no core; `ShareSheet` lays out. + +- **Columns.** Below the preview, one row per column with Keep, Mask with a style (Full, Last 4 characters, Email, Stable hash, NULL) or Remove, from `ResultSet.GetShareMaskingAsync`. A column the detectors flag starts masked with the suggested style and says what it looks like; the user may keep it. Every row lays its controls on the same fixed columns. +- **Preview and summary.** Each choice starts a round: `ResultSet.GetShareSummaryAsync` and then `GetSharePreviewAsync` are read off the UI thread, and one from an older round is dropped. The preview is the core's own, so a Stable Hash shows as sent. As the macOS preview, its columns stop at 200 px with an ellipsis, a cell's tooltip shows the whole value, and a masked column's header carries the eye with a slash, named "Masked: {style}". The row note, the 100-column note and why a result too large cannot go come from the summary. Share, the dialog's accent button, stays off until this round's summary and preview have landed, while a value is too large, and when every column is removed. It sends only with the form's plan (`ShareRounds.Plan`): any other section clears it, so an owner picked at its cap never creates a link with the plan of the one picked before. +- **Notices.** "{n} columns masked, {m} removed." with a singular form, a note to check the columns after a detection, and an InfoBar with a Hide SQL button when the SQL holds what looks like personal data. + +## Consequences + +- The grid, copies and exports show stored values; only a share's snapshot is masked, and the server never receives the originals. +- The sheet runs on Windows only; its logic is covered by `tests/TablePro.App.Model.Tests` and the core's calls by `tests/TablePro.Interop.Tests/MaskingTests.cs`. + +## Alternatives considered + +- **Mask in the app.** The Stable Hash key is the core's, per process, so the app could not preview it. diff --git a/windows/docs/decisions/README.md b/windows/docs/decisions/README.md index 5f547dbf3e..d1f42919ad 100644 --- a/windows/docs/decisions/README.md +++ b/windows/docs/decisions/README.md @@ -15,3 +15,6 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0005](0005-distribution.md) | Shipping the app | Accepted | One self-contained Native AOT MSIX per architecture in an `.msixbundle` signed with Azure Artifact Signing, on GitHub Releases and winget; the core on the hybrid CRT; the 1809 floor checked in the package and on Windows Server 2022. | | [0006](0006-editing-table-rows.md) | Editing a table's rows | Accepted | A table tab edits as the macOS app does: F2, Enter or a double-click edits a cell, rows are added, duplicated and deleted, every change stays pending until Save, reloads and closes ask first, Safe Mode's Confirm writes shows the statements, and the core plans and runs the save (core 0019). | | [0007](0007-browsing-a-connection.md) | Filtering, structure, definitions, export and query history | Accepted | A table tab has Data and Structure and a filter bar over the core's bound page read; functions, procedures, triggers and sequences open their source read only; Export results writes through the core's encoders; Show query history lists the runs the core recorded. | +| [0008](0008-tablepro-account.md) | Signing in to the TablePro account | Accepted | One account opened at launch through the core's `AccountService` (core 0026); Settings shows it with sign in, sign out, refresh, devices and the device limit; every `account.*` code has its sentence. | +| [0009](0009-share-links.md) | Share links | Accepted | Share result, Share query and Share in the grids', editor's and File menus; a ContentDialog sheet over the plan's limits with preview, Hide SQL, Pro options, secret warnings and the cap's Revoke list; `tablepro://share` links open their SQL in a new query tab, never run (core 0027). | +| [0010](0010-data-masking.md) | Masking a shared result | Accepted | The share sheet's Keep, Mask or Remove per column, detected columns masked by default, the core's preview and summary of what a link sends, and the Hide SQL suggestion; nothing else masks (core 0028). | diff --git a/windows/src/TablePro.App.Model/AccountPanel.cs b/windows/src/TablePro.App.Model/AccountPanel.cs new file mode 100644 index 0000000000..a4813a5802 --- /dev/null +++ b/windows/src/TablePro.App.Model/AccountPanel.cs @@ -0,0 +1,125 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +public enum AccountStage +{ + // The account could not start, as when the machine has no ID; Settings says why. + Unavailable, + SignedOut, + + // Waiting for the browser; Cancel ends the wait. + SigningIn, + SignedIn, + + // An imported offline file on a machine that is not signed in. + Offline, +} + +public enum AccountNoticeKind +{ + Expired, + RefreshFailed, + DeviceLimitReached, + + // No secret store took the sign-in, so the next launch starts signed out. + NotRemembered, +} + +// Code is the error the last refresh met, for RefreshFailed. +public sealed record AccountNotice(AccountNoticeKind Kind, string? Code = null); + +// What Settings shows for the TablePro account. +public sealed record AccountPanel( + AccountStage Stage, + string? Title, + string? Email, + bool IsPro, + AccountNotice? Notice, + IReadOnlyList LimitDevices) +{ + // The feature the server resolves for Pro, a seated team member's included (share links PLAN, Decisions). + public const string ProFeature = "shared_links"; + + public static AccountPanel Unavailable { get; } = new(AccountStage.Unavailable, null, null, false, null, []); + + public static AccountPanel For(AccountStatus status, bool signingIn) + { + ArgumentNullException.ThrowIfNull(status); + var stage = status.State switch + { + _ when signingIn => AccountStage.SigningIn, + AccountState.SignedIn => AccountStage.SignedIn, + AccountState.Offline => AccountStage.Offline, + _ => AccountStage.SignedOut, + }; + var title = string.IsNullOrWhiteSpace(status.Name) ? status.Email : status.Name; + var devices = status.Problem is EntitlementProblem.DeviceLimitReached limit + ? AccountDevices.Ordered(limit.Devices) + : []; + return new AccountPanel( + stage, + title, + status.Email, + status.Features.Contains(ProFeature, StringComparer.Ordinal), + NoticeOf(status), + devices); + } + + private static AccountNotice? NoticeOf(AccountStatus status) => status switch + { + { State: not AccountState.SignedIn } => null, + { Problem: EntitlementProblem.Expired } => new AccountNotice(AccountNoticeKind.Expired), + { Problem: EntitlementProblem.RefreshFailed failed } => new AccountNotice(AccountNoticeKind.RefreshFailed, failed.Code), + { Problem: EntitlementProblem.DeviceLimitReached } => new AccountNotice(AccountNoticeKind.DeviceLimitReached), + { Remembered: false } => new AccountNotice(AccountNoticeKind.NotRemembered), + _ => null, + }; +} + +public enum DeviceRemoval +{ + Removed, + + // The device went, but the refresh the core runs after a removal failed, which the error says. + RemovedNotRefreshed, + NotRemoved, +} + +public static class AccountDevices +{ + // A removal that threw may still have removed the device, so the list read after it decides. + public static DeviceRemoval Removal(bool succeeded, IReadOnlyList? listedAfter, string deviceId) + { + ArgumentNullException.ThrowIfNull(deviceId); + if (succeeded) + { + return DeviceRemoval.Removed; + } + + return listedAfter is not null && listedAfter.All(device => device.Id != deviceId) + ? DeviceRemoval.RemovedNotRefreshed + : DeviceRemoval.NotRemoved; + } + + // The device-limit dialog stays open while the license is still past its limit. + public static bool PastLimit(AccountStatus status) + { + ArgumentNullException.ThrowIfNull(status); + return status.Problem is EntitlementProblem.DeviceLimitReached; + } + + // This machine first, then the most recently seen. + public static IReadOnlyList Ordered(IEnumerable devices) + { + ArgumentNullException.ThrowIfNull(devices); + return [.. devices.OrderByDescending(device => device.IsThisMachine).ThenByDescending(device => device.LastSeenAt)]; + } + + // The server refuses to remove a device while its offline file is good, and this machine signs out instead. + public static bool CanRemove(AccountDevice device, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(device); + return !device.IsThisMachine && (device.OfflineUntil is not { } until || until <= now); + } +} diff --git a/windows/src/TablePro.App.Model/QueryTab.cs b/windows/src/TablePro.App.Model/QueryTab.cs index 178cf4739f..7855b3fb24 100644 --- a/windows/src/TablePro.App.Model/QueryTab.cs +++ b/windows/src/TablePro.App.Model/QueryTab.cs @@ -101,6 +101,9 @@ public QueryTab( public bool HasUnsavedChanges => false; + // The typed SQL whose results the tab shows, which a result share sends; null after Commit or Roll back. + public string? LastStatement => _statement; + // A query tab's text is kept in the session, so closing loses nothing to ask about. public Task ConfirmCloseAsync(bool offerSave) => Task.FromResult(true); diff --git a/windows/src/TablePro.App.Model/ShareColumns.cs b/windows/src/TablePro.App.Model/ShareColumns.cs new file mode 100644 index 0000000000..2038b40629 --- /dev/null +++ b/windows/src/TablePro.App.Model/ShareColumns.cs @@ -0,0 +1,158 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +public enum ShareColumnAction +{ + Keep, + Mask, + Remove, +} + +// One shared column: a detected one starts masked with the suggested style and may be kept; any other starts kept +// (share-v2 PLAN-MASKING 8.0 and 8.4). +public sealed class ShareColumn +{ + public static IReadOnlyList Styles { get; } = + [MaskStyle.Full, MaskStyle.LastFour, MaskStyle.Email, MaskStyle.Hash, MaskStyle.Null]; + + internal ShareColumn(ShareColumnMasking masking) + { + Name = masking.Name; + Suggestion = masking.Suggestion; + (Action, Style) = Suggestion is { } suggestion + ? (ShareColumnAction.Mask, suggestion.Style) + : (ShareColumnAction.Keep, MaskStyle.Full); + } + + public string Name { get; } + + public MaskSuggestion? Suggestion { get; } + + public ShareColumnAction Action { get; private set; } + + // The style Mask uses; kept while another action is picked, so a return to Mask finds it. + public MaskStyle Style { get; private set; } + + public ShareColumnChoice Choice => Action switch + { + ShareColumnAction.Remove => ShareColumnChoice.Remove.Instance, + ShareColumnAction.Mask => new ShareColumnChoice.Mask(Style), + _ => ShareColumnChoice.Keep.Instance, + }; + + public void Choose(ShareColumnAction action) => Action = action; + + public void Choose(MaskStyle style) => Style = style; +} + +// The share sheet's Columns list, in the result's order. +public sealed class ShareColumns +{ + private ShareColumns(IReadOnlyList columns) + { + Columns = columns; + } + + public static ShareColumns None { get; } = new([]); + + public IReadOnlyList Columns { get; } + + public int Masked => Columns.Count(column => column.Action == ShareColumnAction.Mask); + + public int Removed => Columns.Count(column => column.Action == ShareColumnAction.Remove); + + public int Kept => Columns.Count - Removed; + + // "1 column masked, 2 removed." or "3 columns masked, 0 removed."; the removed count shares the noun. + public string SummaryKey => Masked == 1 ? "ShareColumnsSummaryOne" : "ShareColumnsSummaryMany"; + + // The sheet says so under the list, so the user checks the columns before sharing. + public bool HasDetections => Columns.Any(column => column.Suggestion is not null); + + // A share needs at least one column to send. + public bool RemovesEveryColumn => Columns.Count > 0 && Removed == Columns.Count; + + public IReadOnlyList Choices => [.. Columns.Select(column => column.Choice)]; + + // The style of each column the link sends, in its order; null for one sent as it is. The preview marks the rest. + public IReadOnlyList SentStyles => + [ + .. Columns + .Where(column => column.Action != ShareColumnAction.Remove) + .Select(column => column.Action == ShareColumnAction.Mask ? column.Style : (MaskStyle?)null), + ]; + + public static ShareColumns From(IReadOnlyList masking) + { + ArgumentNullException.ThrowIfNull(masking); + return new ShareColumns([.. masking.Select(column => new ShareColumn(column))]); + } +} + +// The resource key that names what a column or a literal looks like ("Looks like: email address"), as macOS words it. +public static class SensitiveWords +{ + private static readonly Dictionary NameKinds = new(StringComparer.Ordinal) + { + ["email"] = "Email", + ["mail"] = "Email", + ["phone"] = "Phone", + ["mobile"] = "Phone", + ["tel"] = "Phone", + ["telephone"] = "Phone", + ["fax"] = "Phone", + ["msisdn"] = "Phone", + ["password"] = "Secret", + ["passwd"] = "Secret", + ["pwd"] = "Secret", + ["secret"] = "Secret", + ["token"] = "Secret", + ["apikey"] = "Secret", + ["accesskey"] = "Secret", + ["privatekey"] = "Secret", + ["credential"] = "Secret", + ["ssn"] = "NationalId", + ["socialsecurity"] = "NationalId", + ["nationalid"] = "NationalId", + ["passport"] = "NationalId", + ["taxid"] = "NationalId", + ["tin"] = "NationalId", + ["creditcard"] = "CardOrAccount", + ["cardnumber"] = "CardOrAccount", + ["ccnumber"] = "CardOrAccount", + ["pan"] = "CardOrAccount", + ["iban"] = "CardOrAccount", + ["accountnumber"] = "CardOrAccount", + ["routingnumber"] = "CardOrAccount", + ["address"] = "Address", + ["street"] = "Address", + ["zip"] = "Address", + ["zipcode"] = "Address", + ["postcode"] = "Address", + ["postal"] = "Address", + ["dob"] = "BirthDate", + ["birthdate"] = "BirthDate", + ["dateofbirth"] = "BirthDate", + ["birthday"] = "BirthDate", + ["ip"] = "IpAddress", + ["ipaddress"] = "IpAddress", + ["ipv4"] = "IpAddress", + ["ipv6"] = "IpAddress", + ["firstname"] = "PersonName", + ["lastname"] = "PersonName", + ["fullname"] = "PersonName", + ["surname"] = "PersonName", + ["givenname"] = "PersonName", + }; + + // Null for a term the core added after this build; the sheet then shows the term itself. + public static string? KeyFor(MaskReason reason) => reason switch + { + MaskReason.ColumnName name => NameKinds.TryGetValue(name.Term, out var kind) ? "SensitiveName_" + kind : null, + MaskReason.Values values => KeyFor(values.Kind), + _ => null, + }; + + public static string KeyFor(SensitiveKind kind) => "SensitiveValue_" + kind; +} diff --git a/windows/src/TablePro.App.Model/SharePlan.cs b/windows/src/TablePro.App.Model/SharePlan.cs new file mode 100644 index 0000000000..9d09c24e43 --- /dev/null +++ b/windows/src/TablePro.App.Model/SharePlan.cs @@ -0,0 +1,278 @@ +using System.Globalization; +using System.Text; +using TablePro.Interop; + +namespace TablePro.App.Model; + +public enum ShareStage +{ + EmailUnverified, + SharingDisabled, + + // Every live slot is taken: the live links are listed with Revoke until one frees. + AtCap, + Form, +} + +// Whether a result can be shared now: its columns and the core's summary of what they send must be read first. +public enum ShareReadiness +{ + Reading, + Ready, + NoColumns, + TooLarge, +} + +// Every expiry is listed; one the plan does not allow is disabled, and Never on Free carries a Pro tag. +public sealed record ExpiryChoice(ShareExpiry Expiry, bool Enabled, bool ProTag); + +// The footer line: "Free · 3 of 5 links · first 1,000 rows", "Pro · 12 links", or a team's "Data · 4 of 1,000 links". +public sealed record ShareFooter(bool Pro, long Live, long Limit, long MaxRows, string? Team = null) +{ + // "Pro · 1 link" counts its links; the others count against a limit, which stays plural. + public string ProKey => Live == 1 ? "ShareFooterProOne" : "ShareFooterProMany"; +} + +// The at-cap line: "You have 7 live links. Free allows 5." and, on Free, "Pro allows up to 1,000."; or a team's. +public sealed record ShareCap(bool Pro, long Live, long Limit, string? Team = null); + +// Share as: Personal (no TeamId), then each seated team; one whose public links are off is listed, not offered. +public sealed record ShareOwner(string? TeamId, string? Name, bool Enabled); + +// What the sheet's fields hold when Share is pressed. +public sealed record ShareForm( + string Title, + string Note, + ShareExpiry Expiry, + bool HideSql, + string Password, + bool AllowDownload) +{ + // The record's own ToString would print the password into a log line or a debugger's summary. + private bool PrintMembers(StringBuilder builder) + { + builder.Append( + CultureInfo.InvariantCulture, + $"Title = {Title}, Expiry = {Expiry}, HideSql = {HideSql}, HasPassword = {Password.Length > 0}, "); + builder.Append(CultureInfo.InvariantCulture, $"AllowDownload = {AllowDownload}"); + return true; + } +} + +// What one share sheet offers, from the plan's limits (share links PLAN, Client UX). +public sealed class SharePlan +{ + public const string ProPlan = "pro"; + + // The preview shows this many rows of the visible columns. + public const int PreviewRows = 5; + + // The server takes this much SQL, counted in UTF-8 bytes; the core refuses more at create. + public const int MaxSqlBytes = 256 * 1024; + + private static readonly ShareExpiry[] AllExpiries = + [ShareExpiry.OneDay, ShareExpiry.SevenDays, ShareExpiry.ThirtyDays, ShareExpiry.Never]; + + private SharePlan(ShareLimits limits, ShareKind kind, long totalRows, bool hasSql, string? teamId) + { + Limits = limits; + Kind = kind; + HasSql = hasSql; + Owners = + [ + new ShareOwner(null, null, true), + .. limits.Teams.Select(team => new ShareOwner(team.Id, team.Name, team.PublicLinks)), + ]; + Team = limits.Teams.FirstOrDefault(team => team.Id == teamId && team.PublicLinks); + TotalRows = kind == ShareKind.Result ? Math.Max(0, totalRows) : 0; + IsPro = string.Equals(limits.Plan, ProPlan, StringComparison.Ordinal); + Expiries = [.. AllExpiries.Select(Choice)]; + DefaultExpiry = Expiries.FirstOrDefault(choice => choice.Enabled && choice.Expiry == limits.DefaultExpiry)?.Expiry + ?? Expiries.LastOrDefault(choice => choice.Enabled)?.Expiry + ?? ShareExpiry.ThirtyDays; + } + + public ShareLimits Limits { get; } + + public ShareKind Kind { get; } + + // A table page carries no statement the app can name, so it shares without one. + public bool HasSql { get; } + + public bool IsPro { get; } + + public IReadOnlyList Owners { get; } + + // The team the link is made for, null for a personal link; a team with public links off is never chosen. + public ShareTeam? Team { get; } + + public string? TeamId => Team?.Id; + + // A team link counts against the team's own limit, never the creator's. + public long Live => Team?.Live ?? Limits.Live; + + public long LiveLimit => Team?.LiveLimit ?? Limits.LiveLimit; + + public IReadOnlyList Expiries { get; } + + public ShareExpiry DefaultExpiry { get; } + + public long TotalRows { get; } + + // The client cuts the rows to the plan's limit before upload; the server derives truncated itself. + public long SharedRows => Math.Min(TotalRows, Math.Max(0, Limits.MaxRows)); + + public bool IsTruncated => Kind == ShareKind.Result && TotalRows > SharedRows; + + public long PreviewRowCount => Math.Min(SharedRows, PreviewRows); + + // A query share always shows its SQL. + public bool OffersHideSql => Kind == ShareKind.Result && HasSql; + + public bool PasswordAllowed => Limits.Password; + + public bool DownloadChoiceAllowed => Limits.DisableDownload; + + public bool AtCap => Live >= LiveLimit; + + public ShareStage Stage => Limits switch + { + { EmailVerified: false } => ShareStage.EmailUnverified, + { SharingDisabled: true } => ShareStage.SharingDisabled, + _ when AtCap => ShareStage.AtCap, + _ => ShareStage.Form, + }; + + public ShareFooter Footer => new(IsPro, Live, LiveLimit, Limits.MaxRows, Team?.Name); + + // Live, not the limit: after a downgrade an account can hold more live links than its plan allows. + public ShareCap Cap => new(IsPro, Live, LiveLimit, Team?.Name); + + public static SharePlan For( + ShareLimits limits, ShareKind kind, long totalRows = 0, bool hasSql = true, string? teamId = null) + { + ArgumentNullException.ThrowIfNull(limits); + return new SharePlan(limits, kind, totalRows, hasSql, teamId); + } + + // A summary read for older choices is never passed here: the sheet drops it as stale, so Share waits. + public ShareReadiness Readiness(ShareColumns? columns, ShareSummary? summary) => Kind switch + { + ShareKind.Query => ShareReadiness.Ready, + _ when columns is null => ShareReadiness.Reading, + _ when columns.RemovesEveryColumn => ShareReadiness.NoColumns, + _ when summary is null => ShareReadiness.Reading, + _ when summary.Refused is ShareRefusal.NoColumns => ShareReadiness.NoColumns, + _ when summary.Refused is not null => ShareReadiness.TooLarge, + _ => ShareReadiness.Ready, + }; + + // The body budget can cut a share below the plan's rows, so the row note follows what the core says it sends. + public bool CutsRows(ShareSummary summary) + { + ArgumentNullException.ThrowIfNull(summary); + return Kind == ShareKind.Result && summary.Refused is null && summary.RowsSent < TotalRows; + } + + public static int PreviewRowsOf(ShareSummary summary) + { + ArgumentNullException.ThrowIfNull(summary); + return (int)Math.Clamp(summary.RowsSent, 0, PreviewRows); + } + + // The server takes the first MaxColumns visible columns of a result, on every plan. + public bool CutsColumns(int visibleColumns) => + Kind == ShareKind.Result && Limits.MaxColumns > 0 && visibleColumns > Limits.MaxColumns; + + public int SharedColumns(int visibleColumns) => + CutsColumns(visibleColumns) ? (int)Limits.MaxColumns : Math.Max(0, visibleColumns); + + // Free never sends an option the server would refuse with pro_required. + public ShareRequest Request(ShareForm form, string sql, string? dialect) + { + ArgumentNullException.ThrowIfNull(form); + ArgumentNullException.ThrowIfNull(sql); + var allowed = Expiries.Any(choice => choice.Enabled && choice.Expiry == form.Expiry); + return new ShareRequest(Kind, sql) + { + Title = Trimmed(form.Title), + Note = Trimmed(form.Note), + Dialect = string.IsNullOrWhiteSpace(dialect) ? null : dialect, + Expiry = allowed ? form.Expiry : DefaultExpiry, + HideSql = OffersHideSql && form.HideSql, + // As typed: the core strips it and refuses one of only spaces, so a link never loses its password here. + Password = PasswordAllowed && form.Password.Length > 0 ? form.Password : null, + AllowDownload = DownloadChoiceAllowed && !form.AllowDownload ? false : null, + TeamId = TeamId, + }; + } + + // What a link keeps of a password: readers send it in a header, where HTTP drops outer spaces and tabs. + public static string SentPassword(string password) + { + ArgumentNullException.ThrowIfNull(password); + return password.Trim(' ', '\t'); + } + + // The sentences, as macOS words them, for what the form's own fields hold that the core refuses at create; Share + // stays off while there is one. + public IReadOnlyList FieldProblems(string password, string sql) + { + ArgumentNullException.ThrowIfNull(password); + ArgumentNullException.ThrowIfNull(sql); + var problems = new List(); + if (Encoding.UTF8.GetByteCount(sql) > MaxSqlBytes) + { + problems.Add("ShareSqlTooLong"); + } + + if (PasswordAllowed && password.Length > 0 && SentPassword(password).Length == 0) + { + problems.Add("SharePasswordBlank"); + } + + return problems; + } + + // The links a revoke would free a slot of, oldest first: the personal ones, or the chosen team's. + public static IReadOnlyList LiveOldestFirst(IEnumerable links, string? teamId = null) + { + ArgumentNullException.ThrowIfNull(links); + return [.. links + .Where(link => link.IsLive && (teamId is null ? link.Scope == "account" : link.TeamId == teamId)) + .DistinctBy(link => link.Id) + .OrderBy(link => link.CreatedAt)]; + } + + private ExpiryChoice Choice(ShareExpiry expiry) + { + var enabled = Limits.Expiries.Contains(expiry); + return new ExpiryChoice(expiry, enabled, !enabled && !IsPro && expiry == ShareExpiry.Never); + } + + private static string? Trimmed(string text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); +} + +// The share sheet's own sentence per problem code (PLAN, Wording); anything else is the general one. +public static class ShareErrors +{ + public const string Failed = "ShareErrorFailed"; + + public static string KeyFor(string code) => code switch + { + "account.signed_out" => "ShareErrorSignedOut", + "account.email_unverified" => "ShareErrorEmailUnverified", + "account.pro_required" => "ShareErrorProRequired", + "account.sharing_disabled" => "ShareErrorSharingDisabled", + "account.team_sharing_disabled" => "ShareErrorTeamSharingDisabled", + "account.snapshot_too_large" => "ShareErrorTooLarge", + "account.rate_limited" => "ShareErrorRateLimited", + "account.unreachable" => "ShareErrorOffline", + "ffi.share_no_columns" => "ShareNoColumns", + _ => Failed, + }; + + // A refusal the limits explain: reading them again shows the sheet the server's view. + public static bool ReloadsLimits(string code) => + code is "account.share_limit_reached" or "account.email_unverified" or "account.sharing_disabled"; +} diff --git a/windows/src/TablePro.App.Model/ShareRounds.cs b/windows/src/TablePro.App.Model/ShareRounds.cs new file mode 100644 index 0000000000..ff7d905332 --- /dev/null +++ b/windows/src/TablePro.App.Model/ShareRounds.cs @@ -0,0 +1,73 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +// The share sheet's reads for its current choices. Each choice starts a round; a summary or a preview of an older round +// is dropped when it lands, and a result is shared only once this round's summary and preview have both landed. +public sealed class ShareRounds +{ + public int Round { get; private set; } + + // Share sends with the form's plan only. Any other section clears it, so a team picked at its cap never leaves + // Share live with the plan of the owner picked before. + public SharePlan? Plan { get; private set; } + + // Null until this round's summary lands. + public ShareSummary? Summary { get; private set; } + + // This round's preview is on screen, so the rows shown are the ones the link sends. + public bool PreviewShown { get; private set; } + + public int Begin() + { + Round++; + Summary = null; + PreviewShown = false; + return Round; + } + + // A new plan starts a round, so a summary read for the old one is dropped. + public void Show(SharePlan? plan) + { + Plan = plan is { Stage: ShareStage.Form } ? plan : null; + Begin(); + } + + public bool CanShare(ShareColumns? columns) => + Plan is { } plan && Readiness(plan, columns) == ShareReadiness.Ready; + + public bool IsCurrent(int round) => round == Round; + + public bool TakeSummary(int round, ShareSummary summary) + { + ArgumentNullException.ThrowIfNull(summary); + if (round != Round) + { + return false; + } + + Summary = summary; + return true; + } + + // Only after this round's summary said the rows can go; a preview never stands for rows too large to send. + public bool TakePreview(int round) + { + if (round != Round || Summary is not { Refused: null }) + { + return false; + } + + PreviewShown = true; + return true; + } + + public ShareReadiness Readiness(SharePlan plan, ShareColumns? columns) + { + ArgumentNullException.ThrowIfNull(plan); + var readiness = plan.Readiness(columns, Summary); + return readiness == ShareReadiness.Ready && plan.Kind == ShareKind.Result && !PreviewShown + ? ShareReadiness.Reading + : readiness; + } +} diff --git a/windows/src/TablePro.App.Model/SharedLinkOpen.cs b/windows/src/TablePro.App.Model/SharedLinkOpen.cs new file mode 100644 index 0000000000..b115087df3 --- /dev/null +++ b/windows/src/TablePro.App.Model/SharedLinkOpen.cs @@ -0,0 +1,84 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +public enum SharedLinkStep +{ + AskPassword, + + // The password typed was wrong; the prompt asks again and says so. + AskPasswordAgain, + Unavailable, + + // The owner hid the SQL, so there is nothing to open. + HiddenSql, + Open, + Failed, +} + +// tablepro://share?token= opens the link's SQL in a new query tab, never runs it and carries no connection. +public static class SharedLinkOpen +{ + public const string Scheme = "tablepro"; + + // A launch through the execution alias passes the link as an argument rather than a protocol activation. + public static string? LinkIn(IEnumerable arguments) + { + ArgumentNullException.ThrowIfNull(arguments); + return arguments + .Select(argument => argument.Trim().Trim('"')) + .FirstOrDefault(argument => argument.StartsWith(Scheme + ":", StringComparison.OrdinalIgnoreCase)); + } + + public static SharedLinkStep After(PublicShare shared) + { + ArgumentNullException.ThrowIfNull(shared); + return string.IsNullOrWhiteSpace(shared.Sql) ? SharedLinkStep.HiddenSql : SharedLinkStep.Open; + } + + public static SharedLinkStep After(CoreError error) + { + ArgumentNullException.ThrowIfNull(error); + return error.Code switch + { + "account.share_password_required" => SharedLinkStep.AskPassword, + "account.share_password_wrong" => SharedLinkStep.AskPasswordAgain, + "account.not_found" => SharedLinkStep.Unavailable, + _ => SharedLinkStep.Failed, + }; + } + + // The tab is named after the link, or the general name when its owner gave none. + public static string TabTitle(PublicShare shared, string fallback) + { + ArgumentNullException.ThrowIfNull(shared); + return string.IsNullOrWhiteSpace(shared.Title) ? fallback : shared.Title.Trim(); + } +} + +// Links come from other launches at any time: one opens at a time, in order, and a link already waiting is kept once. +public sealed class PendingSharedLinks +{ + private readonly Queue _waiting = new(); + private string? _opening; + + // True when nothing is opening, so the caller starts taking links; otherwise the one opening takes it in turn. + public bool Offer(string link) + { + ArgumentNullException.ThrowIfNull(link); + if (link == _opening || _waiting.Contains(link)) + { + return false; + } + + _waiting.Enqueue(link); + return _opening is null; + } + + // The next link to open, null once none waits. + public string? TakeNext() + { + _opening = _waiting.TryDequeue(out var next) ? next : null; + return _opening; + } +} diff --git a/windows/src/TablePro.App.Model/TabSession.cs b/windows/src/TablePro.App.Model/TabSession.cs index 05587b0387..3cad780acc 100644 --- a/windows/src/TablePro.App.Model/TabSession.cs +++ b/windows/src/TablePro.App.Model/TabSession.cs @@ -47,7 +47,7 @@ Task ReadTablePageAsync( } // The run gives the page's rows as an editor run's events do; columns past VisibleColumns are the row's address. -public sealed record TablePageRead(ITabRun Run, int VisibleColumns, bool CanSeek); +public sealed record TablePageRead(ITabRun Run, int VisibleColumns, bool CanSeek, string? ViewSql = null); // A table's rows as a save sees them. `rows` is the set a page was read into, null when no set is shown. public interface ITableEditor : IDisposable @@ -133,7 +133,7 @@ public async Task ReadTablePageAsync( { var page = await _share.Session.ReadTablePageAsync(table, sort, filter, limit, offset, cancellationToken) .ConfigureAwait(true); - return new TablePageRead(new CoreTabRun(page.Run), page.VisibleColumns, page.CanSeek); + return new TablePageRead(new CoreTabRun(page.Run), page.VisibleColumns, page.CanSeek, page.ViewSql); } public Task CountRowsAsync(TableName table, TableFilter? filter, CancellationToken cancellationToken) => diff --git a/windows/src/TablePro.App.Model/TableShareRead.cs b/windows/src/TablePro.App.Model/TableShareRead.cs new file mode 100644 index 0000000000..023c483c3a --- /dev/null +++ b/windows/src/TablePro.App.Model/TableShareRead.cs @@ -0,0 +1,34 @@ +using TablePro.Interop; + +namespace TablePro.App.Model; + +// A table share: the view's first rows, its SQL (null where the engine cannot write it) and the filter's row count. +public sealed class TableShareRead : IDisposable +{ + private readonly ITabRun _run; + + public TableShareRead(ITabRun run, int visibleColumns, string? viewSql, long totalRows) + { + ArgumentNullException.ThrowIfNull(run); + _run = run; + Rows = run.GetResultSet(0); + VisibleColumns = visibleColumns; + ViewSql = viewSql; + TotalRows = totalRows; + } + + public ResultSet? Rows { get; } + + // The columns past it are the row's address, which a share never sends. + public int VisibleColumns { get; } + + public string? ViewSql { get; } + + public long TotalRows { get; } + + public void Dispose() + { + Rows?.Dispose(); + _run.Dispose(); + } +} diff --git a/windows/src/TablePro.App.Model/TableTab.cs b/windows/src/TablePro.App.Model/TableTab.cs index 11e836bde1..2587a0c034 100644 --- a/windows/src/TablePro.App.Model/TableTab.cs +++ b/windows/src/TablePro.App.Model/TableTab.cs @@ -636,6 +636,47 @@ public async Task ConfirmCloseAsync(bool offerSave) public void Stop() => _run?.Cancel(); + // From the view's first row with the shown filter and sort, whichever page shows, so "first N of M" holds. + public async Task ReadForShareAsync(long maxRows, CancellationToken cancellationToken) + { + ArgumentOutOfRangeException.ThrowIfNegative(maxRows); + var sort = _shownSort.Direction == SortDirection.None + ? null + : new ColumnSort(_shownSort.Column, _shownSort.Direction == SortDirection.Ascending); + var filter = _shownFilter; + var read = await _session.ReadTablePageAsync(Table, sort, filter, maxRows, 0, cancellationToken) + .ConfigureAwait(true); + try + { + QueryOutcome? outcome = null; + await foreach (var queryEvent in read.Run.ReadEventsAsync(cancellationToken).ConfigureAwait(true)) + { + if (queryEvent is QueryEvent.Finished finished) + { + outcome = finished.Outcome; + } + } + + switch (outcome) + { + case QueryOutcome.Completed: + break; + case QueryOutcome.Failed failed: + throw new TableProException(failed.Error); + default: + throw new OperationCanceledException(cancellationToken); + } + + var total = await _session.CountRowsAsync(Table, filter, cancellationToken).ConfigureAwait(true); + return new TableShareRead(read.Run, read.VisibleColumns, read.ViewSql, total); + } + catch + { + read.Run.Dispose(); + throw; + } + } + public Task CloseAsync() => _closing ??= CloseOnceAsync(); private Task Track(Task save) diff --git a/windows/src/TablePro.App/App.xaml.cs b/windows/src/TablePro.App/App.xaml.cs index 98b25a93a8..7d9650c6a3 100644 --- a/windows/src/TablePro.App/App.xaml.cs +++ b/windows/src/TablePro.App/App.xaml.cs @@ -1,4 +1,6 @@ +using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml; +using Microsoft.Windows.AppLifecycle; using TablePro.App.Services; using TablePro.DataGrid; using TablePro.Interop; @@ -29,15 +31,25 @@ protected override void OnLaunched(LaunchActivatedEventArgs args) var folder = AppStorage.DataFolder; Directory.CreateDirectory(folder); var core = TableProCore.CreateWithSystemSecrets(new HostConfiguration(AppStorage.Version, folder)); - _window = new MainWindow(new Workbench(core, folder)); + var workbench = new Workbench(core, folder); + workbench.StartAccount( + AccountSetup.Configuration(folder), + new SystemBrowser(DispatcherQueue.GetForCurrentThread()), + AccountSetup.Portal()); + _window = new MainWindow(workbench); _window.SessionSaved += (_, _) => ReleaseFolder(); _window.Closed += (_, _) => ReleaseFolder(); _window.ActivateRestored(); // Off the first grid's path: the fallback fonts for non-Latin cells load in the background. DataGridView.WarmUpFonts(); + if (LaunchLink() is { } link) + { + _window.OpenSharedLink(link); + } } - internal void BringToFront() + // Another launch handed over, with the tablepro:// link it was started for, if any. + internal void Activate(string? link) { if (_window is null || _closed) { @@ -52,6 +64,24 @@ internal void BringToFront() { CrashLog.Write(exception); } + + if (link is not null) + { + _window.OpenSharedLink(link); + } + } + + private static string? LaunchLink() + { + try + { + return ActivationLink.OfLaunch(AppInstance.GetCurrent().GetActivatedEventArgs()); + } + catch (Exception exception) + { + CrashLog.Write(exception); + return null; + } } // The session is saved by now, so a launch from here on starts its own window instead of handing over to this one. diff --git a/windows/src/TablePro.App/MainWindow.Share.cs b/windows/src/TablePro.App/MainWindow.Share.cs new file mode 100644 index 0000000000..17d1be2d8f --- /dev/null +++ b/windows/src/TablePro.App/MainWindow.Share.cs @@ -0,0 +1,81 @@ +using System.Runtime.InteropServices; +using Microsoft.UI.Xaml; +using TablePro.App.Model; +using TablePro.App.Services; +using TablePro.App.Views; +using TablePro.Interop; +using Windows.System; + +namespace TablePro.App; + +// Share links (docs/decisions/0009-share-links.md): the File menu's commands and tablepro://share links. +public sealed partial class MainWindow +{ + private readonly PendingSharedLinks _links = new(); + + // The primary opens links, one at a time; a tab window hands them over. Its SQL opens in a new tab, never run. + internal async void OpenSharedLink(string link) + { + if (!IsPrimary) + { + _primary.OpenSharedLink(link); + return; + } + + if (!_links.Offer(link)) + { + return; + } + + while (_links.TakeNext() is { } next) + { + try + { + await OpenOneSharedLinkAsync(next); + } + catch (Exception exception) when (exception is COMException or InvalidOperationException) + { + CrashLog.Write(exception); + } + } + } + + private async Task OpenOneSharedLinkAsync(string link) + { + if (await SharedLinkDialogs.FetchAsync(Root, _workbench, link) is not { } shared) + { + return; + } + + var open = _front is { View.IsConnected: true } front + ? front + : _open.FirstOrDefault(connection => connection.View.IsConnected); + if (open is null) + { + await SharedLinkDialogs.ShowWithoutConnectionAsync(Root, shared); + return; + } + + Select(open); + open.View.NewQueryTab(shared.Sql, SharedLinkOpen.TabTitle(shared, Strings.Get("SharedQueryTitle"))); + } + + private async void OnShareResult(object sender, RoutedEventArgs e) + { + if (Workspace is { } workspace) + { + await workspace.ShareAsync(ShareKind.Result); + } + } + + private async void OnShareQuery(object sender, RoutedEventArgs e) + { + if (Workspace is { } workspace) + { + await workspace.ShareAsync(ShareKind.Query); + } + } + + private async void OnManageSharedLinks(object sender, RoutedEventArgs e) => + await Launcher.LaunchUriAsync(AccountSetup.SharedLinksPage(_workbench.Portal)); +} diff --git a/windows/src/TablePro.App/MainWindow.xaml b/windows/src/TablePro.App/MainWindow.xaml index 42f65e274f..954de63c53 100644 --- a/windows/src/TablePro.App/MainWindow.xaml +++ b/windows/src/TablePro.App/MainWindow.xaml @@ -75,6 +75,14 @@ + + + + + + + + diff --git a/windows/src/TablePro.App/MainWindow.xaml.cs b/windows/src/TablePro.App/MainWindow.xaml.cs index e685cd1578..a68d556da1 100644 --- a/windows/src/TablePro.App/MainWindow.xaml.cs +++ b/windows/src/TablePro.App/MainWindow.xaml.cs @@ -1251,6 +1251,8 @@ private void UpdateCommands() MenuShowHistory.IsEnabled = workspace is not null; MenuShowHistory.IsChecked = workspace?.HistoryVisible ?? false; MenuExportResults.IsEnabled = workspace?.CanExport ?? false; + MenuShareResult.IsEnabled = workspace?.CanShareResult ?? false; + MenuShareQuery.IsEnabled = workspace?.CanShareQuery ?? false; MenuRefresh.IsEnabled = workspace is not null; MenuEditConnection.IsEnabled = front?.ConnectionId is not null; MenuReconnect.IsEnabled = front is { State: ConnectionState.Connected or ConnectionState.Failed }; diff --git a/windows/src/TablePro.App/Package.appxmanifest b/windows/src/TablePro.App/Package.appxmanifest index 47c43d8d7a..ccda2971fa 100644 --- a/windows/src/TablePro.App/Package.appxmanifest +++ b/windows/src/TablePro.App/Package.appxmanifest @@ -49,6 +49,12 @@ + + + + TablePro + + diff --git a/windows/src/TablePro.App/Program.cs b/windows/src/TablePro.App/Program.cs index e675444189..5790b5d06b 100644 --- a/windows/src/TablePro.App/Program.cs +++ b/windows/src/TablePro.App/Program.cs @@ -33,13 +33,17 @@ private static void Main() GC.KeepAlive(current); } - // Raised off the UI thread, when another launch on this data folder hands over. + // Raised off the UI thread, when another launch on this data folder hands over, a tablepro:// link with it. private static AppInstance? Listen(App app, DispatcherQueue queue) { try { var current = AppInstance.GetCurrent(); - current.Activated += (_, _) => queue.TryEnqueue(app.BringToFront); + current.Activated += (_, activation) => + { + var link = LinkOf(activation); + queue.TryEnqueue(() => app.Activate(link)); + }; return current; } catch (Exception exception) @@ -48,4 +52,17 @@ private static void Main() return null; } } + + private static string? LinkOf(AppActivationArguments activation) + { + try + { + return ActivationLink.Of(activation); + } + catch (Exception exception) + { + CrashLog.Write(exception); + return null; + } + } } diff --git a/windows/src/TablePro.App/Services/AccountSetup.cs b/windows/src/TablePro.App/Services/AccountSetup.cs new file mode 100644 index 0000000000..dce42d554b --- /dev/null +++ b/windows/src/TablePro.App/Services/AccountSetup.cs @@ -0,0 +1,91 @@ +using System.Runtime.InteropServices; +using TablePro.Interop; +using Windows.System; + +namespace TablePro.App.Services; + +// The TablePro account's settings (docs/decisions/0008-tablepro-account.md); a release build always uses tablepro.app. +internal static class AccountSetup +{ + public static readonly Uri ProductionPortal = new("https://account.tablepro.app"); + public static readonly Uri PricingUri = new("https://tablepro.app/#pricing"); + + public static AccountConfiguration Configuration(string folder) + { + var configuration = new AccountConfiguration( + Environment.MachineName, + AppStorage.Version, + RuntimeInformation.OSDescription, + Path.Combine(folder, "account.json"), + Strings.Get("AccountCallbackFinished"), + Strings.Get("AccountCallbackUnknown")); +#if DEBUG + // A development build may sign in to a local tablepro-cloud; both URLs go together, as the core requires. + if (Development() is { } stack) + { + return configuration with + { + AccountUrl = stack.Account, + ApiUrl = stack.Api, + EntitlementKeys = stack.Keys, + }; + } +#endif + return configuration; + } + + public static Uri Portal() + { +#if DEBUG + if (Development() is { } stack && Uri.TryCreate(stack.Account, UriKind.Absolute, out var local)) + { + return local; + } +#endif + return ProductionPortal; + } + + public static Uri SharedLinksPage(Uri portal) => new(portal, "shared-links"); + +#if DEBUG + private static (string Account, string Api, string[] Keys)? Development() + { + var account = Environment.GetEnvironmentVariable("TABLEPRO_ACCOUNT_URL"); + var api = Environment.GetEnvironmentVariable("TABLEPRO_API_URL"); + if (string.IsNullOrWhiteSpace(account) || string.IsNullOrWhiteSpace(api)) + { + return null; + } + + var keys = (Environment.GetEnvironmentVariable("TABLEPRO_ENTITLEMENT_KEYS") ?? string.Empty) + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + return (account.Trim(), api.Trim(), keys); + } +#endif +} + +// The core asks on a thread of its own; Launcher runs on the UI thread, where the window it opens over lives. +internal sealed class SystemBrowser(Microsoft.UI.Dispatching.DispatcherQueue queue) : IAccountBrowser +{ + public Task OpenAsync(Uri url) + { + var opened = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var queued = queue.TryEnqueue(async () => + { + try + { + opened.TrySetResult(await Launcher.LaunchUriAsync(url)); + } + catch (Exception exception) + { + opened.TrySetException(exception); + } + }); + if (!queued) + { + opened.TrySetResult(false); + } + + return opened.Task; + } +} diff --git a/windows/src/TablePro.App/Services/ActivationLink.cs b/windows/src/TablePro.App/Services/ActivationLink.cs new file mode 100644 index 0000000000..faa9c6e3c0 --- /dev/null +++ b/windows/src/TablePro.App/Services/ActivationLink.cs @@ -0,0 +1,30 @@ +using Microsoft.Windows.AppLifecycle; +using TablePro.App.Model; +using Windows.ApplicationModel.Activation; + +namespace TablePro.App.Services; + +// A packaged launch carries the tablepro:// link as a protocol activation, the execution alias as an argument. +internal static class ActivationLink +{ + // Read on the thread that raised the activation, before it is handed to the UI thread. + public static string? Of(AppActivationArguments activation) + { + ArgumentNullException.ThrowIfNull(activation); + return activation.Kind switch + { + ExtendedActivationKind.Protocol when activation.Data is IProtocolActivatedEventArgs protocol => + protocol.Uri?.OriginalString, + ExtendedActivationKind.Launch when activation.Data is ILaunchActivatedEventArgs launch => + InArguments(launch.Arguments), + _ => null, + }; + } + + // A first launch reads its own command line, which the activation's arguments may leave out. + public static string? OfLaunch(AppActivationArguments activation) => + Of(activation) ?? SharedLinkOpen.LinkIn(Environment.GetCommandLineArgs().Skip(1)); + + private static string? InArguments(string? arguments) => + SharedLinkOpen.LinkIn((arguments ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries)); +} diff --git a/windows/src/TablePro.App/Services/WindowDialogs.cs b/windows/src/TablePro.App/Services/WindowDialogs.cs index 0724a20cf5..cce88df929 100644 --- a/windows/src/TablePro.App/Services/WindowDialogs.cs +++ b/windows/src/TablePro.App/Services/WindowDialogs.cs @@ -8,9 +8,46 @@ namespace TablePro.App.Services; internal static class WindowDialogs { private static readonly HashSet OpenRoots = []; + private static TaskCompletionSource? _free; public static bool IsOpen(XamlRoot? root) => root is not null && OpenRoots.Contains(root); + // A dialog nobody asked for just then, as a link from another launch, waits for the window and any open dialog. + public static async Task ShowWhenFreeAsync(ContentDialog dialog, FrameworkElement owner) + { + ArgumentNullException.ThrowIfNull(dialog); + ArgumentNullException.ThrowIfNull(owner); + while (true) + { + if (owner.XamlRoot is null || !owner.IsLoaded) + { + await LoadedAsync(owner).ConfigureAwait(true); + } + else if (OpenRoots.Count > 0) + { + await (_free ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task + .ConfigureAwait(true); + } + else + { + return await ShowAsync(dialog, owner).ConfigureAwait(true); + } + } + } + + private static Task LoadedAsync(FrameworkElement owner) + { + var loaded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + void OnLoaded(object sender, RoutedEventArgs args) + { + owner.Loaded -= OnLoaded; + loaded.TrySetResult(); + } + + owner.Loaded += OnLoaded; + return loaded.Task; + } + public static async Task ShowAsync(ContentDialog dialog, FrameworkElement owner) { if (owner.XamlRoot is not { } root || OpenRoots.Count > 0) @@ -36,6 +73,11 @@ public static async Task ShowAsync(ContentDialog dialog, Fr { owner.Unloaded -= OnUnloaded; OpenRoots.Remove(root); + if (OpenRoots.Count == 0 && _free is { } free) + { + _free = null; + free.TrySetResult(); + } } } } diff --git a/windows/src/TablePro.App/Services/Workbench.cs b/windows/src/TablePro.App/Services/Workbench.cs index 02a227ba9b..f39ae995ea 100644 --- a/windows/src/TablePro.App/Services/Workbench.cs +++ b/windows/src/TablePro.App/Services/Workbench.cs @@ -6,8 +6,11 @@ namespace TablePro.App.Services; internal sealed class Workbench : IDisposable { private readonly SettingsStore _settings; + private readonly CancellationTokenSource _lifetime = new(); private bool _settingsUnsaved; private Task? _history; + private Task? _account; + private CancellationTokenSource? _signingIn; public Workbench(TableProCore core, string folder) { @@ -23,6 +26,9 @@ public Workbench(TableProCore core, string folder) // Raised after this app changed the saved connections, so every list rebuilds from a new snapshot. public event EventHandler? LibraryChanged; + // Raised on the UI thread after the account's status or a sign-in's progress changed. + public event EventHandler? AccountChanged; + public TableProCore Core { get; } public string Folder { get; } @@ -38,6 +44,19 @@ public Workbench(TableProCore core, string folder) // Shared by every workspace and kept in the session file. public double ObjectPaneWidth { get; set; } = ObjectPane.DefaultWidth; + public AccountStatus AccountStatus { get; private set; } = AccountStatus.SignedOut; + + // The error that kept the account from starting, as a machine with no ID does. + public CoreError? AccountFailure { get; private set; } + + public bool IsSigningIn => _signingIn is not null; + + public AccountPanel AccountPanel => + AccountFailure is null ? AccountPanel.For(AccountStatus, IsSigningIn) : AccountPanel.Unavailable; + + // account.tablepro.app, or a development build's local account service. + public Uri Portal { get; private set; } = AccountSetup.ProductionPortal; + public DatabaseEngine? Engine(string id) => Engines.FirstOrDefault(engine => engine.Id == id); public string EngineName(string id) => Engine(id)?.DisplayName ?? id; @@ -82,6 +101,87 @@ private void SaveSettings() public void NotifyLibraryChanged() => LibraryChanged?.Invoke(this, EventArgs.Empty); + // Once, at launch, on the UI thread: the account restores the last sign-in and keeps the entitlement fresh. + public void StartAccount(AccountConfiguration configuration, IAccountBrowser browser, Uri portal) + { + Portal = portal; + _account ??= OpenAccountAsync(configuration, browser); + } + + // Null before StartAccount and when the account could not start. + public Task GetAccountAsync() => _account ?? Task.FromResult(null); + + // One at a time. False when cancelled or another is waiting; a failure throws TableProException. + public async Task SignInAsync() + { + if (_signingIn is not null || await GetAccountAsync().ConfigureAwait(true) is not { } account + || _signingIn is not null) + { + return false; + } + + using var signingIn = new CancellationTokenSource(); + _signingIn = signingIn; + AccountChanged?.Invoke(this, EventArgs.Empty); + try + { + await account.SignInAsync(signingIn.Token).ConfigureAwait(true); + return true; + } + catch (OperationCanceledException) + { + return false; + } + finally + { + _signingIn = null; + ShowAccount(account.Status); + } + } + + public void CancelSignIn() => _signingIn?.Cancel(); + + // After a call that changes the account, so a list or a dialog reads the status it left. + public void ShowAccount(AccountStatus status) + { + AccountStatus = status; + AccountChanged?.Invoke(this, EventArgs.Empty); + } + + private async Task OpenAccountAsync(AccountConfiguration configuration, IAccountBrowser browser) + { + TableProAccount account; + try + { + account = await Core.OpenAccountAsync(configuration, browser).ConfigureAwait(true); + } + catch (TableProException exception) + { + AccountFailure = exception.Error; + AccountChanged?.Invoke(this, EventArgs.Empty); + return null; + } + + ShowAccount(account.Status); + _ = WatchAccountAsync(account); + return account; + } + + private async Task WatchAccountAsync(TableProAccount account) + { + try + { + await foreach (var status in account.ReadStatusChangesAsync(_lifetime.Token).ConfigureAwait(true)) + { + ShowAccount(status); + } + } + catch (OperationCanceledException) + { + // The app is closing. + } + } + // Opened once and shared by every window. Null when the store cannot open: queries still run, unrecorded. public Task GetHistoryAsync() => _history ??= OpenHistoryAsync(); @@ -125,11 +225,19 @@ public async Task InstallSampleAsync() public void Dispose() { + _lifetime.Cancel(); + _signingIn?.Cancel(); if (_history is { IsCompletedSuccessfully: true, Result: { } history }) { history.Dispose(); } + if (_account is { IsCompletedSuccessfully: true, Result: { } account }) + { + account.Dispose(); + } + + _lifetime.Dispose(); Core.Dispose(); } } diff --git a/windows/src/TablePro.App/Strings/en-US/Resources.resw b/windows/src/TablePro.App/Strings/en-US/Resources.resw index b95bdd1167..0c723caba4 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -663,6 +663,21 @@ Query timeout in seconds + + Full + + + Last 4 characters + + + Email + + + Stable hash + + + NULL + Appearance @@ -2595,4 +2610,586 @@ New fingerprint: {2} {0} · {1} + + You can close this tab and go back to TablePro. + + + TablePro is not waiting for this sign-in. Start it again from TablePro. + + + Account + + + TablePro account + + + Sign in to share links and use your plan on this computer. Everything else works without an account. + + + Finish signing in in the web browser that opened. + + + {0} · {1} + + + Pro + + + Free + + + Using an offline file. Sign in to share links. + + + Sign in... + + + Sign out + + + Refresh + + + Try again + + + Remove a device... + + + Account + + + Plan not verified lately + + + The last verification of your plan ran out. Connect to the internet and refresh. + + + Could not verify your plan + + + Your license is in use on as many devices as it allows. Remove one to use it on this computer. + + + Sign-in not saved + + + Credential Manager did not take the sign-in, so TablePro asks for it again the next time it starts. + + + Plan + + + TablePro checks your plan with the account service once a day. + + + Refresh + + + Manage account + + + Opens in your web browser + + + Manage shared links + + + See, extend and revoke your links in your web browser + + + Devices + + + The computers that use your plan + + + Device limit reached + + + Your license is in use on as many devices as it allows. Remove one to use it on this computer. + + + Remove + + + Remove {0} + + + This computer + + + {0} · last seen {1:d} + + + {0} · offline file until {1:d} + + + {0} was removed. {1} + + + Windows + + + macOS + + + Linux + + + iOS + + + Share result... + + + Share query... + + + Manage shared links... + + + Share result... + + + Share query... + + + Share... + + + Share result + + + Share query + + + Share + + + Done + + + Title + + + Note + + + Optional + + + Expires + + + Hide SQL + + + Password + + + Allow viewers to download + + + 1 day + + + 7 days + + + 30 days + + + Never + + + {0} · {1} + + + Pro + + + Pro: see the plans in your web browser + + + Rows that will be shared + + + A password can't be only spaces or tabs. + + + This query is too long to share. A link holds up to 256 KB of SQL. + + + Masked: {0} + + + Keep or mask at least one column to share. + + + This result is too large to share: a value in {0} is over 256 KB. Mask or remove that column to share the rest. + + + This result is too large to share: its first row alone is over 4.5 MB. Mask or remove columns to share it. + + + Columns + + + 1 column masked, {1} removed. + + + {0} columns masked, {1} removed. + + + TablePro masked columns that look sensitive. Check them before sharing. + + + Keep + + + Mask + + + Remove + + + Sharing for {0} + + + Mask style for {0} + + + Looks like: {0} + + + This query contains what looks like personal data ({0}). Turn on Hide SQL to keep the query private. + + + email address + + + phone number + + + password or secret + + + ID number + + + card or account number + + + postal address + + + date of birth + + + IP address + + + person's name + + + card number + + + IBAN + + + JSON Web Token + + + API key + + + email address + + + phone number + + + IP address + + + Shares the first {0:N0} of {1:N0} rows. + + + Free · {0:N0} of {1:N0} links · first {2:N0} rows + + + Pro · {0:N0} link + + + Pro · {0:N0} links + + + You have {0:N0} live links. Free allows {1:N0}. Revoke one to share another. + + + You have {0:N0} live links. Pro allows {1:N0}. Revoke one to share another. + + + Pro allows up to 1,000. + + + Untitled link + + + Created {0:d} + + + Created {0:d} · expires {1:d} + + + Revoke + + + Revoke {0} + + + Loading... + + + Creating the link... + + + Finish signing in in the web browser that opened. + + + Sign in... + + + Open account + + + Retry + + + Link copied + + + Copy + + + Open in browser + + + These rows are no longer held. Run the query again to share them. + + + This query may contain a secret ({0}). Anyone with the link can read it. + + + Some columns may hold secrets: {0}. + + + an AWS access key + + + a private key + + + a JSON web token + + + a GitHub token + + + a Slack token + + + a Stripe key + + + a Google API key + + + a password in a URL + + + a password or token + + + Sign in to your TablePro account to share links. + + + Verify your email address to share links. + + + This option needs TablePro Pro. + + + Sharing is turned off for this account. + + + Public links are turned off for this team. + + + This result is too large to share. + + + Too many links just now. Try again in a moment. + + + You appear to be offline. Try again once you're connected. + + + The link couldn't be created. Try again. + + + Reading the rows... + + + TablePro cannot write this table's query for its database, so the link shares the rows without SQL and opens nothing in TablePro. + + + Share as + + + Personal + + + {0} · Public links are off for this team. + + + {0} · {1:N0} of {2:N0} links + + + {0} has {1:N0} live links. The team allows {2:N0}. Revoke one to share another. + + + Suspended + + + Shares the first {0:N0} columns. + + + The link shares the first {0:N0} columns. + + + Shared link + + + Shared query + + + This shared link is no longer available. + + + This shared result hides its SQL, so there is nothing to open. + + + This link is password protected. + + + That password is not correct. + + + Open + + + Connect to a database to open this query in a new tab. It never runs on its own. + + + Copy SQL + + + Close + + + TablePro's account service could not be reached. Check the internet connection and try again. + + + The web browser did not open the sign-in page. + + + The sign-in was not finished in the web browser in time. Try again. + + + The sign-in was canceled. + + + The account service refused the sign-in. + + + Sign in to your TablePro account first. + + + This computer was removed from your account. Sign in again to use it. + + + Your license is in use on as many devices as it allows. Remove one to use it on this computer. + + + The offline file is for another account than the one signed in. + + + The account service refused the request. + + + The account service asked for fewer requests. Try again in a moment. + + + TablePro could not verify the plan the account service sent. + + + TablePro could not keep the account's state in its data folder. + + + The account service sent an answer TablePro does not understand. + + + This computer has no machine ID, which the TablePro account needs. + + + Verify your email address to share links. + + + This option needs TablePro Pro. + + + Sharing is turned off for this account. + + + Public links are turned off for this team. + + + A team link needs a seat in the team. + + + That link or team was not found. + + + Every live link is taken. Revoke one to share another. + + + This link was revoked. + + + This link was removed by TablePro. + + + The account service refused what was sent. + + + This result is too large to share. + + + This link is password protected. + + + That password is not correct. + + + The account settings of this build are not valid. + + + A result share needs its rows. + + + The rows are still arriving. Share them once the query finishes. + diff --git a/windows/src/TablePro.App/Views/DeviceLimitDialog.cs b/windows/src/TablePro.App/Views/DeviceLimitDialog.cs new file mode 100644 index 0000000000..68015eb9b9 --- /dev/null +++ b/windows/src/TablePro.App/Views/DeviceLimitDialog.cs @@ -0,0 +1,142 @@ +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Controls; +using TablePro.App.Model; +using TablePro.App.Services; +using TablePro.Interop; + +namespace TablePro.App.Views; + +// The license is in use on as many devices as it allows: one is removed here, which asks the account again. +internal static class DeviceLimitDialog +{ + public static async Task ShowAsync(FrameworkElement owner, Workbench workbench, IReadOnlyList devices) + { + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(workbench); + ArgumentNullException.ThrowIfNull(devices); + var error = new InfoBar { Severity = InfoBarSeverity.Error, IsClosable = false, Visibility = Visibility.Collapsed }; + var list = new StackPanel { Spacing = 8 }; + var content = new StackPanel { Spacing = 12 }; + content.Children.Add(new TextBlock { Text = Strings.Get("DeviceLimitMessage"), TextWrapping = TextWrapping.Wrap }); + content.Children.Add(error); + content.Children.Add(list); + var dialog = new ContentDialog + { + RequestedTheme = owner.ActualTheme, + Title = Strings.Get("DeviceLimitTitle"), + Content = new ScrollViewer { Content = content, MaxHeight = 480 }, + CloseButtonText = Strings.Get("Cancel"), + DefaultButton = ContentDialogButton.Close, + }; + AutomationProperties.SetAutomationId(list, "DeviceLimitList"); + void Show(InfoBarSeverity severity, string message) + { + error.Severity = severity; + error.Message = message; + error.Visibility = Visibility.Visible; + error.IsOpen = true; + } + + foreach (var device in AccountDevices.Ordered(devices)) + { + list.Children.Add(Row(device, async (row, button) => + { + if (await workbench.GetAccountAsync().ConfigureAwait(true) is not { } account) + { + return; + } + + button.IsEnabled = false; + error.Visibility = Visibility.Collapsed; + error.IsOpen = false; + TableProException? failure = null; + IReadOnlyList? listed = null; + try + { + // The core asks the account again after a removal, so no refresh is asked here. + await account.RemoveDeviceAsync(device.Id).ConfigureAwait(true); + } + catch (TableProException exception) + { + failure = exception; + try + { + listed = await account.GetDevicesAsync().ConfigureAwait(true); + } + catch (TableProException) + { + // Unknown, so the device counts as still there. + } + } + + var status = account.Status; + workbench.ShowAccount(status); + switch (AccountDevices.Removal(failure is null, listed, device.Id)) + { + case DeviceRemoval.NotRemoved: + button.IsEnabled = true; + Show(InfoBarSeverity.Error, Strings.Error(failure!.Error)); + break; + case DeviceRemoval.RemovedNotRefreshed: + list.Children.Remove(row); + var reason = Strings.Error(failure!.Error); + Show(InfoBarSeverity.Warning, Strings.Format("DeviceRemovedNotRefreshed", device.Name, reason)); + break; + default: + list.Children.Remove(row); + if (!AccountDevices.PastLimit(status)) + { + dialog.Hide(); + } + + break; + } + })); + } + + await WindowDialogs.ShowAsync(dialog, owner).ConfigureAwait(true); + } + + private static Grid Row(AccountDevice device, Func remove) + { + var row = new Grid { ColumnSpacing = 12 }; + row.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + var text = new StackPanel(); + text.Children.Add(new TextBlock { Text = device.Name, TextTrimming = TextTrimming.CharacterEllipsis }); + text.Children.Add(new TextBlock + { + Text = DeviceText(device), + Style = (Style)Application.Current.Resources["CaptionTextBlockStyle"], + TextWrapping = TextWrapping.Wrap, + }); + row.Children.Add(text); + var button = new Button + { + Content = Strings.Get("DeviceRemove"), + VerticalAlignment = VerticalAlignment.Center, + IsEnabled = AccountDevices.CanRemove(device, DateTimeOffset.Now), + }; + AutomationProperties.SetName(button, Strings.Format("DeviceRemoveName", device.Name)); + button.Click += async (_, _) => await remove(row, button).ConfigureAwait(true); + Grid.SetColumn(button, 1); + row.Children.Add(button); + return row; + } + + // "This computer", or the platform and when it was last seen; an offline file says until when it holds. + public static string DeviceText(AccountDevice device) + { + ArgumentNullException.ThrowIfNull(device); + if (device.IsThisMachine) + { + return Strings.Get("DeviceThisComputer"); + } + + var platform = Strings.Get("DevicePlatform_" + device.Platform) is { Length: > 0 } named ? named : device.Platform; + return device.OfflineUntil is { } until && until > DateTimeOffset.Now + ? Strings.Format("DeviceOfflineUntil", platform, until.LocalDateTime) + : Strings.Format("DeviceLastSeen", platform, device.LastSeenAt.LocalDateTime); + } +} diff --git a/windows/src/TablePro.App/Views/IShareSource.cs b/windows/src/TablePro.App/Views/IShareSource.cs new file mode 100644 index 0000000000..4e0982cea6 --- /dev/null +++ b/windows/src/TablePro.App/Views/IShareSource.cs @@ -0,0 +1,9 @@ +using TablePro.Interop; + +namespace TablePro.App.Views; + +// A tab whose menus offer a share; the workspace that holds it opens the sheet. +internal interface IShareSource +{ + event EventHandler? ShareRequested; +} diff --git a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs index 428e64fbdf..0a07f3cc24 100644 --- a/windows/src/TablePro.App/Views/QueryTabView.xaml.cs +++ b/windows/src/TablePro.App/Views/QueryTabView.xaml.cs @@ -1,6 +1,8 @@ using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Automation; using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Input; using Microsoft.UI.Xaml.Media; using TablePro.App.Model; using TablePro.App.Services; @@ -11,7 +13,7 @@ namespace TablePro.App.Views; // The editor over the run's results; the run, the close and the transaction are QueryTab's. -public sealed partial class QueryTabView : UserControl, ITabContent, IQueryTabView +public sealed partial class QueryTabView : UserControl, ITabContent, IQueryTabView, IShareSource { private readonly QueryTab _model; private EditTarget _target; @@ -49,10 +51,15 @@ internal QueryTabView( SqlText.GotFocus += (_, _) => _target = EditTarget.Editor; Results.GridView.GotFocus += (_, _) => _target = EditTarget.Grid; Results.MessagesBox.GotFocus += (_, _) => _target = EditTarget.Messages; + Results.GridView.ContextRequested += OnGridContextRequested; + SqlText.ContextMenuOpening += OnEditorMenuOpening; } public event EventHandler? StateChanged; + // Share result... on the grid's menu and Share query... on the editor's; the workspace opens the sheet. + public event EventHandler? ShareRequested; + // The history kept a run of this tab, so a history pane reads it again. public event EventHandler? HistoryRecorded; @@ -77,6 +84,13 @@ internal QueryTabView( internal ResultsPane ResultsView => Results; + // The SQL whose results the grid shows. + internal string? LastStatement => _model.LastStatement; + + // The selection, else the whole editor, as Run takes it. + internal string QueryToShare => + SqlText.Model.GetSelectedText() is var selected && !string.IsNullOrWhiteSpace(selected) ? selected : SqlText.Text; + string IQueryTabView.SelectedText => SqlText.Model.GetSelectedText(); string IQueryTabView.WholeText => SqlText.Text; @@ -195,6 +209,56 @@ async Task IQueryTabView.ConfirmRollBackAsync() private async void OnRollBack(object sender, RoutedEventArgs e) => await _model.RollBackAsync().ConfigureAwait(true); + // Built when asked for, since a menu keeps the window it first opened in and a tab can move to another. + private void OnGridContextRequested(UIElement sender, ContextRequestedEventArgs args) + { + args.Handled = true; + var grid = Results.GridView; + var menu = new MenuFlyout(); + var copy = new MenuFlyoutItem + { + Text = Strings.Get("GridMenuCopy"), + Icon = new SymbolIcon(Symbol.Copy), + IsEnabled = grid.RowCount > 0, + }; + copy.Click += async (_, _) => await grid.CopySelectionAsync().ConfigureAwait(true); + menu.Items.Add(copy); + menu.Items.Add(new MenuFlyoutSeparator()); + var share = new MenuFlyoutItem + { + Text = Strings.Get("ShareResultCommand"), + Icon = new SymbolIcon(Symbol.Share), + IsEnabled = !IsRunning && Results.ShownSet is { IsFinished: true }, + }; + share.Click += (_, _) => ShareRequested?.Invoke(this, ShareKind.Result); + menu.Items.Add(share); + if (args.TryGetPosition(grid, out var point)) + { + menu.ShowAt(grid, new FlyoutShowOptions { Position = point }); + } + else if (grid.FocusedCellMenuPoint() is { } cell) + { + // From the keyboard, the menu opens at the cell it acts on, not over the editor. + menu.ShowAt(grid, new FlyoutShowOptions { Position = cell }); + } + else + { + menu.ShowAt(grid); + } + } + + private void OnEditorMenuOpening(object? sender, IList items) + { + var share = new MenuFlyoutItem + { + Text = Strings.Get("ShareQueryCommand"), + IsEnabled = !string.IsNullOrWhiteSpace(QueryToShare), + }; + share.Click += (_, _) => ShareRequested?.Invoke(this, ShareKind.Query); + items.Add(new MenuFlyoutSeparator()); + items.Add(share); + } + private void OnRun(object sender, RoutedEventArgs e) => Run(); private void OnStop(object sender, RoutedEventArgs e) => Stop(); diff --git a/windows/src/TablePro.App/Views/SettingsView.xaml b/windows/src/TablePro.App/Views/SettingsView.xaml index 657ab6910d..fcc92d6e86 100644 --- a/windows/src/TablePro.App/Views/SettingsView.xaml +++ b/windows/src/TablePro.App/Views/SettingsView.xaml @@ -18,7 +18,33 @@ AutomationProperties.HeadingLevel="Level1" Style="{StaticResource TitleTextBlockStyle}" /> - + + + + + + +