From a7683843bec89c074c37f70a66449aee300aa12d Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 05:16:34 +0700 Subject: [PATCH 001/126] feat(macos): share a saved query as a public link and open share links --- .../openapi-generator-config.yaml | 6 + .../Sources/TableProCloudAPI/openapi.json | 1425 ++++++++++++++++- apple/TablePro/Core/Events/AppCommands.swift | 1 + .../Core/Services/Account/AccountAPI.swift | 14 + .../Services/Account/AccountServices.swift | 3 + .../Infrastructure/AppActivationPolicy.swift | 1 + .../Infrastructure/DeeplinkParser.swift | 12 + .../Infrastructure/LaunchIntent.swift | 2 + .../Infrastructure/LaunchIntentRouter.swift | 41 +- .../Services/Infrastructure/TabRouter.swift | 14 + .../Infrastructure/WelcomeRouter.swift | 21 + .../Core/Services/Shares/ShareClient.swift | 132 ++ .../TablePro/Models/Settings/ProFeature.swift | 7 + .../TablePro/Resources/Localizable.xcstrings | 48 + .../Main/MainContentCommandActions.swift | 13 + .../Sidebar/FavoritesOutlineCoordinator.swift | 1 + .../Views/Sidebar/FavoritesOutlineView.swift | 1 + .../Views/Sidebar/FavoritesTabView.swift | 40 + .../Sidebar/Menu/FavoritesMenuCommand.swift | 1 + .../Sidebar/Menu/FavoritesMenuSpec.swift | 6 + .../DeeplinkShareParsingTests.swift | 46 + .../Infrastructure/WelcomeRouterTests.swift | 11 + .../Sidebar/FavoritesMenuSpecTests.swift | 11 + 23 files changed, 1851 insertions(+), 6 deletions(-) create mode 100644 apple/TablePro/Core/Services/Shares/ShareClient.swift create mode 100644 apple/TableProTests/Core/Services/Infrastructure/DeeplinkShareParsingTests.swift diff --git a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml index fb565cf1e3..2a999d96fc 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml +++ b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml @@ -13,3 +13,9 @@ filter: - issue-entitlement - list-library-changes - push-library-changes + - create-share + - list-shares + - get-share + - update-share + - delete-share + - get-shared diff --git a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json index a3af459ea3..96f9936098 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json +++ b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json @@ -112,6 +112,90 @@ ], "type": "object" }, + "ColumnJSON": { + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "CreateShareBody": { + "additionalProperties": false, + "properties": { + "dialect": { + "description": "The SQL dialect, for display", + "maxLength": 40, + "type": "string" + }, + "expires_at": { + "description": "When the link stops working; omit for no expiry", + "format": "date-time", + "type": [ + "string", + "null" + ] + }, + "kind": { + "type": "string" + }, + "note": { + "maxLength": 2000, + "type": "string" + }, + "snapshot": { + "$ref": "#/components/schemas/SnapshotInput", + "description": "The frozen result set, for a result share" + }, + "sql": { + "type": "string" + }, + "team_id": { + "description": "Team TypeID; omit for a personal share", + "type": "string" + }, + "title": { + "maxLength": 200, + "type": "string" + } + }, + "required": [ + "kind", + "sql" + ], + "type": "object" + }, + "CreatedShare": { + "properties": { + "expires_at": { + "format": "date-time", + "type": "string" + }, + "id": { + "type": "string" + }, + "token": { + "description": "The raw link token, shown once", + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": [ + "id", + "token", + "url" + ], + "type": "object" + }, "Cycle": { "enum": [ "monthly", @@ -772,19 +856,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": { @@ -1046,7 +1134,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 +1148,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 +1163,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, @@ -1203,6 +1301,9 @@ ], "type": "string" }, + "education": { + "$ref": "#/components/schemas/PricingEducation" + }, "plans": { "items": { "$ref": "#/components/schemas/PlanPrice" @@ -1212,7 +1313,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" }, @@ -1267,6 +1381,83 @@ ], "type": "object" }, + "PublicShare": { + "properties": { + "created_at": { + "format": "date-time", + "type": "string" + }, + "dialect": { + "type": "string" + }, + "expires_at": { + "format": "date-time", + "type": "string" + }, + "kind": { + "type": "string" + }, + "made_with": { + "description": "Attribution the viewer page shows", + "type": "string" + }, + "note": { + "type": "string" + }, + "snapshot": { + "$ref": "#/components/schemas/PublicSnapshot" + }, + "sql": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "kind", + "title", + "sql", + "created_at", + "made_with" + ], + "type": "object" + }, + "PublicSnapshot": { + "properties": { + "columns": { + "items": { + "$ref": "#/components/schemas/ShareColumn" + }, + "type": "array" + }, + "row_count": { + "description": "Rows the query returned, which may exceed those shown", + "format": "int64", + "type": "integer" + }, + "rows": { + "items": { + "items": {}, + "type": [ + "array", + "null" + ] + }, + "type": "array" + }, + "truncated": { + "type": "boolean" + } + }, + "required": [ + "columns", + "rows", + "row_count", + "truncated" + ], + "type": "object" + }, "Seats": { "properties": { "available": { @@ -1301,6 +1492,143 @@ ], "type": "object" }, + "ShareColumn": { + "properties": { + "name": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "ShareList": { + "properties": { + "data": { + "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" + }, + "ShareView": { + "properties": { + "created_at": { + "format": "date-time", + "type": "string" + }, + "dialect": { + "type": "string" + }, + "expires_at": { + "format": "date-time", + "type": "string" + }, + "has_result": { + "description": "true for a result share", + "type": "boolean" + }, + "id": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "note": { + "type": "string" + }, + "revoked_at": { + "format": "date-time", + "type": "string" + }, + "scope": { + "description": "account or team", + "type": "string" + }, + "sql": { + "type": "string" + }, + "team_id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "updated_at": { + "format": "date-time", + "type": "string" + }, + "url": { + "description": "The link, present when the server can rebuild it", + "type": "string" + }, + "view_count": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "id", + "kind", + "scope", + "title", + "sql", + "has_result", + "view_count", + "created_at", + "updated_at" + ], + "type": "object" + }, + "SnapshotInput": { + "additionalProperties": false, + "properties": { + "columns": { + "items": { + "$ref": "#/components/schemas/ColumnJSON" + }, + "minItems": 1, + "type": "array" + }, + "row_count": { + "description": "Rows the query returned, if more than those sent", + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "rows": { + "items": { + "items": {}, + "type": [ + "array", + "null" + ] + }, + "type": "array" + }, + "truncated": { + "type": "boolean" + } + }, + "required": [ + "columns", + "rows" + ], + "type": "object" + }, "Team": { "properties": { "has_seat": { @@ -1426,6 +1754,32 @@ "name" ], "type": "object" + }, + "UpdateShareBody": { + "additionalProperties": false, + "properties": { + "clear_expiry": { + "description": "Remove the expiry", + "type": "boolean" + }, + "expires_at": { + "description": "Set a new expiry; omit to leave it unchanged", + "format": "date-time", + "type": [ + "string", + "null" + ] + }, + "note": { + "maxLength": 2000, + "type": "string" + }, + "title": { + "maxLength": 200, + "type": "string" + } + }, + "type": "object" } }, "securitySchemes": { @@ -2953,6 +3307,1067 @@ ] } }, + "/shared/{token}": { + "get": { + "description": "No authentication. A missing, revoked or expired link answers 404 alike.", + "operationId": "get-shared", + "parameters": [ + { + "description": "The share's link token", + "in": "path", + "name": "token", + "required": true, + "schema": { + "description": "The share's link token", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicShare" + } + } + }, + "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" + } + } + }, + "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, or it is not visible to you." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "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" + } + }, + "summary": "Read a shared link", + "tags": [ + "Shares" + ] + } + }, + "/shares": { + "get": { + "operationId": "list-shares", + "parameters": [ + { + "description": "Team TypeID to list a team's shares; omit for the caller's own", + "explode": false, + "in": "query", + "name": "team", + "schema": { + "description": "Team TypeID to list a team's shares; omit for the caller's own", + "type": "string" + } + }, + { + "description": "The last share's ID from the previous page", + "explode": false, + "in": "query", + "name": "cursor", + "schema": { + "description": "The last share's ID from the previous page", + "type": "string" + } + }, + { + "explode": false, + "in": "query", + "name": "limit", + "schema": { + "default": 50, + "format": "int64", + "maximum": 200, + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareList" + } + } + }, + "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": "No such share, or it is not visible to you." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "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": "List the caller's shares", + "tags": [ + "Shares" + ] + }, + "post": { + "description": "Needs the shared_links feature. A team share needs a seat in the team.", + "operationId": "create-share", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateShareBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatedShare" + } + } + }, + "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": { + "feature_required": { + "summary": "Feature required", + "value": { + "type": "https://api.tablepro.app/problems/feature-required", + "title": "Feature required", + "status": 403, + "code": "feature_required", + "detail": "Your plan does not include shared_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." + } + }, + "forbidden_2": { + "summary": "Forbidden", + "value": { + "type": "https://api.tablepro.app/problems/forbidden", + "title": "Forbidden", + "status": 403, + "code": "forbidden", + "detail": "A team share needs a seat in the team." + } + } + }, + "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": "No such share, or it is not visible to you." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "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 live share limit." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Conflict" + }, + "422": { + "content": { + "application/problem+json": { + "examples": { + "snapshot_too_large": { + "summary": "Snapshot too large", + "value": { + "type": "https://api.tablepro.app/problems/snapshot-too-large", + "title": "Snapshot too large", + "status": 422, + "code": "snapshot_too_large", + "detail": "The result snapshot is over the hard limit." + } + } + }, + "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": "Create a share link", + "tags": [ + "Shares" + ] + } + }, + "/shares/{id}": { + "delete": { + "description": "The link stops working at once.", + "operationId": "delete-share", + "parameters": [ + { + "description": "Share TypeID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "description": "Share 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": "No such share, or it is not visible to you." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "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": "Revoke a share", + "tags": [ + "Shares" + ] + }, + "get": { + "operationId": "get-share", + "parameters": [ + { + "description": "Share TypeID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "description": "Share TypeID", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareView" + } + } + }, + "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": "No such share, or it is not visible to you." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "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": "Get one share, with its link", + "tags": [ + "Shares" + ] + }, + "patch": { + "operationId": "update-share", + "parameters": [ + { + "description": "Share TypeID", + "in": "path", + "name": "id", + "required": true, + "schema": { + "description": "Share TypeID", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateShareBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareView" + } + } + }, + "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": "No such share, or it is not visible to you." + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Not Found" + }, + "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": "Change a share's title, note or expiry", + "tags": [ + "Shares" + ] + } + }, "/teams": { "get": { "description": "With the caller's role and seat in each, in the order the account joined them. App sign-ins only.", diff --git a/apple/TablePro/Core/Events/AppCommands.swift b/apple/TablePro/Core/Events/AppCommands.swift index e7fc785a16..762e164293 100644 --- a/apple/TablePro/Core/Events/AppCommands.swift +++ b/apple/TablePro/Core/Events/AppCommands.swift @@ -102,6 +102,7 @@ final class AppCommands { // MARK: - File / Connection Import-Export let openSQLFiles = PassthroughSubject<[URL], Never>() + let openSharedSQL = PassthroughSubject<[String], Never>() private init() {} } diff --git a/apple/TablePro/Core/Services/Account/AccountAPI.swift b/apple/TablePro/Core/Services/Account/AccountAPI.swift index d228807de4..2ce3944d3b 100644 --- a/apple/TablePro/Core/Services/Account/AccountAPI.swift +++ b/apple/TablePro/Core/Services/Account/AccountAPI.swift @@ -20,6 +20,20 @@ internal enum AccountAPI { ) } + // A client with no bearer token, for the public read (GET /v2/shared/{token}): a share a recipient opens may be + // viewed while signed out. + static func publicClient( + configuration: AccountConfiguration, + transport: any ClientTransport + ) -> Client { + Client( + serverURL: configuration.apiServerURL, + configuration: Configuration(dateTranscoder: RFC3339DateTranscoder()), + transport: transport, + middlewares: [] + ) + } + static func transport(session: URLSession) -> any ClientTransport { URLSessionTransport(configuration: .init(session: session)) } diff --git a/apple/TablePro/Core/Services/Account/AccountServices.swift b/apple/TablePro/Core/Services/Account/AccountServices.swift index 298881d777..a05b4579e8 100644 --- a/apple/TablePro/Core/Services/Account/AccountServices.swift +++ b/apple/TablePro/Core/Services/Account/AccountServices.swift @@ -51,6 +51,8 @@ internal final class AccountServices { let devices: DeviceRegistry let access: FeatureAccess let api: any APIProtocol + // No bearer token, for the public share read. + let publicAPI: any APIProtocol let events = PassthroughSubject() private let entitlements: EntitlementStore private let legacy: LegacyLicenseStore @@ -92,6 +94,7 @@ internal final class AccountServices { onRefused: { Task { @MainActor in refusals.services?.sessionWasRefused() } } ) self.api = AccountAPI.client(configuration: configuration, transport: transport, session: session) + self.publicAPI = AccountAPI.publicClient(configuration: configuration, transport: transport) 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..87cf0a240b 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, + .openShare, .pairIntegration, .openDatabaseURL, .installPlugin, diff --git a/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift b/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift index 236defed2d..c7f4ddf9bb 100644 --- a/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift +++ b/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift @@ -65,11 +65,23 @@ internal enum DeeplinkParser { return parseIntegrations(url) case "settings": return parseSettings(url) + case "share": + return parseShare(url) default: return .failure(.unknownHost(host)) } } + private static func parseShare(_ url: URL) -> Result { + guard let token = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems? + .first(where: { $0.name == "token" })?.value, + !token.isEmpty + else { + return .failure(.missingRequiredParam("token")) + } + return .success(.openShare(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/LaunchIntent.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift index c7cb643940..3d48ae6fda 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 openShare(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, + .openShare, .pairIntegration, .startMCPServer, .openSettings, diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift index a67a39c49b..5e43f3c4a6 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift @@ -1,6 +1,7 @@ import AppKit import Foundation import os +import TableProCloudAPI @MainActor internal final class LaunchIntentRouter { @@ -44,6 +45,9 @@ internal final class LaunchIntentRouter { case .installPlugin(let url): try await installPlugin(url) + + case .openShare(let token): + try await openShare(token: token) } } catch let error where error.isUserCancellation { Self.logger.info("Intent cancelled: \(error.publicLogShape, privacy: .public)") @@ -53,6 +57,41 @@ internal final class LaunchIntentRouter { } } + private func openShare(token: String) async throws { + let client = ShareClient(api: AccountServices.shared.publicAPI) + let share: Components.Schemas.PublicShare + do throws(ShareFailure) { + share = try await client.view(token: token) + } catch { + presentShareUnavailable(error) + return + } + let opened = try await TabRouter.shared.openSharedQuery(sql: share.sql) + if !opened { + // No connected database to open against. Queue the SQL the way openSQLFile does, so it + // opens once the user connects one, and show where to do that. + WelcomeRouter.shared.enqueueSharedSQL(share.sql) + } + } + + private func presentShareUnavailable(_ failure: ShareFailure) { + let message: String + switch failure { + case .canceled: + return + case .notFound: + message = String(localized: "This shared link is no longer available.") + case .offline: + message = String(localized: "You appear to be offline. Try again once you're connected.") + case .rateLimited: + message = String(localized: "Too many requests just now. Try again in a moment.") + case .signedOut, .featureRequired, .forbidden, .limitReached, .refused, .server: + message = String(localized: "The shared query couldn't be opened.") + } + AppActivationPolicyController.shared.activate(ignoringOtherApps: true) + AlertHelper.showInfoSheet(title: String(localized: "Open Shared Query"), message: message, window: nil) + } + private func openDataFileDocument(at url: URL) async throws { Self.logger.debug("LaunchIntentRouter.openDataFileDocument - calling NSDocumentController.shared (\(String(describing: Swift.type(of: NSDocumentController.shared)), privacy: .public)).openDocument for \(url.lastPathComponent, privacy: .private(mask: .hash))") try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in @@ -160,7 +199,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, .openShare, .startMCPServer, .openSettings: title = String(localized: "Action Failed") } if presentRecoverableError(error, for: intent, title: title) { return } diff --git a/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift b/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift index 4c917cc3e1..352b10da8f 100644 --- a/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift @@ -475,6 +475,20 @@ internal final class TabRouter { // MARK: - SQL File + /// Opens a shared query's SQL in the connection the user is looking at, like a SQL file but seeded from text. + /// Returns false when no connection is open, so the caller can tell the user to connect first. + @discardableResult + internal func openSharedQuery(sql: String) async throws -> 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 } + try await openQuery(connectionId: target, sql: sql) + return true + } + private func openSQLFile(_ url: URL) async throws { if HostedTabRouting.live.revealTab(editing: url) { AppActivationPolicyController.shared.activate(ignoringOtherApps: true) diff --git a/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift b/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift index bc6e9d7ee3..0b5b3520ed 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift @@ -43,6 +43,7 @@ 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 pendingSharedSQL: [String] = [] @Published private(set) var pendingError: PendingConnectionError? @Published private(set) var pendingPluginInstall: DatabaseConnection? @@ -53,6 +54,7 @@ internal final class WelcomeRouter: ObservableObject { .receive(on: RunLoop.main) .sink { [weak self] _ in self?.drainPendingSQLFiles() + self?.drainPendingSharedSQL() } } @@ -62,6 +64,12 @@ internal final class WelcomeRouter: ObservableObject { AppCommands.shared.openSQLFiles.send(urls) } + private func drainPendingSharedSQL() { + let statements = consumePendingSharedSQL() + guard !statements.isEmpty else { return } + AppCommands.shared.openSharedSQL.send(statements) + } + internal func route(_ request: WelcomeRequest) { pendingRequest = request showWelcomeWindow() @@ -97,6 +105,19 @@ internal final class WelcomeRouter: ObservableObject { pendingSQLFiles.append(url) } + // A shared query arriving with no connected database: hold its SQL and show where to connect, the + // way routeShare does for a connection share. It opens on the next databaseDidConnect. + internal func enqueueSharedSQL(_ sql: String) { + pendingSharedSQL.append(sql) + showWelcomeWindow() + } + + internal func consumePendingSharedSQL() -> [String] { + let value = pendingSharedSQL + pendingSharedSQL.removeAll() + return value + } + internal func consumePendingImport() -> ConnectionBundle? { let value = pendingImport pendingImport = nil diff --git a/apple/TablePro/Core/Services/Shares/ShareClient.swift b/apple/TablePro/Core/Services/Shares/ShareClient.swift new file mode 100644 index 0000000000..735cb555ae --- /dev/null +++ b/apple/TablePro/Core/Services/Shares/ShareClient.swift @@ -0,0 +1,132 @@ +// +// ShareClient.swift +// TablePro +// + +import Foundation +import TableProCloudAPI + +internal enum ShareFailure: Error, Equatable, Sendable { + case offline + // The request was cancelled (torn down, superseded). Nothing to tell the user. + case canceled + // The 429's Retry-After, when it carried one. + case rateLimited(retryAfter: Duration?) + case server + case signedOut + // The account's plan does not include shared_links. + case featureRequired + // A team share without a seat, or a share not the caller's to manage. + case forbidden + // Unknown, revoked, or expired. + case notFound + // The account holds its live-share cap. + case limitReached + // The server refused the request as sent (422); sending it again changes nothing. + case refused + + var isRetryable: Bool { + switch self { + case .offline, .rateLimited, .server: + return true + case .canceled, .signedOut, .featureRequired, .forbidden, .notFound, .limitReached, .refused: + return false + } + } + + static func from(_ error: AccountError) -> ShareFailure { + switch error { + case .canceled: + return .canceled + case .signedOut: + return .signedOut + case .server(let status, _) where status == 401: + return .signedOut + case .server(let status, _) where status == 429: + return .rateLimited(retryAfter: nil) + case .server(let status, _) where status >= 500: + return .server + case .server: + return .refused + default: + return .offline + } + } +} + +internal struct CreatedShareLink: Sendable { + let id: String + let token: String + let url: String +} + +// The /v2 share calls go through the generated client, which carries the session's access token. The public read +// needs no token, but sending one is harmless. +internal struct ShareClient: Sendable { + let api: any APIProtocol + + func createQuery(title: String, sql: String, note: String?, dialect: String?) async throws(ShareFailure) -> CreatedShareLink { + do { + switch try await api.createShare(body: .json(.init(dialect: dialect, kind: "query", note: note, sql: sql, title: title))) { + case .ok(let answer): + let body = try answer.body.json + return CreatedShareLink(id: body.id, token: body.token, url: body.url) + case .unauthorized: + throw ShareFailure.signedOut + case .forbidden(let answer): + let problem = try answer.body.applicationProblemJson + throw problem.code == "feature_required" ? ShareFailure.featureRequired : .forbidden + case .notFound: + throw ShareFailure.notFound + case .conflict: + throw ShareFailure.limitReached + case .unprocessableContent: + throw ShareFailure.refused + case .tooManyRequests(let answer): + throw ShareFailure.rateLimited(retryAfter: Self.delay(seconds: answer.headers.retryAfter)) + case .internalServerError: + throw ShareFailure.server + case .undocumented(let status, _): + throw Self.undocumented(status) + } + } catch let failure as ShareFailure { + throw failure + } catch { + throw ShareFailure.from(AccountError.from(error)) + } + } + + func view(token: String) async throws(ShareFailure) -> Components.Schemas.PublicShare { + do { + switch try await api.getShared(path: .init(token: token)) { + case .ok(let answer): + return try answer.body.json + case .notFound, .unprocessableContent: + throw ShareFailure.notFound + case .tooManyRequests(let answer): + throw ShareFailure.rateLimited(retryAfter: Self.delay(seconds: answer.headers.retryAfter)) + case .internalServerError: + throw ShareFailure.server + case .undocumented(let status, _): + throw Self.undocumented(status) + } + } catch let failure as ShareFailure { + throw failure + } catch { + throw ShareFailure.from(AccountError.from(error)) + } + } + + private static func delay(seconds: Int?) -> Duration? { + guard let seconds, seconds > 0 else { return nil } + return .seconds(seconds) + } + + private static func undocumented(_ status: Int) -> ShareFailure { + switch status { + case 429: .rateLimited(retryAfter: nil) + case 500...: .server + default: .refused + } + } +} diff --git a/apple/TablePro/Models/Settings/ProFeature.swift b/apple/TablePro/Models/Settings/ProFeature.swift index 741fb45c3c..0b21c0f340 100644 --- a/apple/TablePro/Models/Settings/ProFeature.swift +++ b/apple/TablePro/Models/Settings/ProFeature.swift @@ -17,6 +17,7 @@ internal enum ProFeature: String, CaseIterable { case teamLibrary = "team_library" case compareSync = "compare_sync" case dataRewind = "data_rewind" + case sharedLinks = "shared_links" var displayName: String { switch self { @@ -40,6 +41,8 @@ internal enum ProFeature: String, CaseIterable { return String(localized: "Compare & Sync") case .dataRewind: return String(localized: "Data Rewind") + case .sharedLinks: + return String(localized: "Share Links") } } @@ -65,6 +68,8 @@ internal enum ProFeature: String, CaseIterable { return "arrow.left.arrow.right.square" case .dataRewind: return "clock.arrow.circlepath" + case .sharedLinks: + return "link" } } @@ -90,6 +95,8 @@ internal enum ProFeature: String, CaseIterable { return String(localized: "Compare structure or data between two connections and generate the sync script.") case .dataRewind: return String(localized: "Restore the previous values of rows you already saved.") + case .sharedLinks: + return String(localized: "Share a query, or a query and its results, as a public link anyone can open in a browser.") } } diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 93949bd22a..0893b65f71 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -16679,6 +16679,9 @@ "A point's id cannot change. Insert a new row with the new id instead." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "A public link to this query is on your clipboard." : { + }, "A publish to the team library is still running. Try again when it finishes." : { @@ -128275,6 +128278,9 @@ } } } + }, + "Open a database connection, then open the link again." : { + }, "Open a database to browse its tables." : { "localizations" : { @@ -129703,6 +129709,9 @@ } } } + }, + "Open Shared Query" : { + }, "Open Source Libraries" : { "localizations" : { @@ -166014,6 +166023,9 @@ } } } + }, + "Share a query, or a query and its results, as a public link anyone can open in a browser." : { + }, "Share anonymous usage data" : { "extractionState" : "stale", @@ -166095,6 +166107,15 @@ } } } + }, + "Share Link" : { + + }, + "Share Link…" : { + + }, + "Share Links" : { + }, "Share usage data" : { "localizations" : { @@ -166138,6 +166159,9 @@ }, "Share Used" : { + }, + "Sharing links needs a paid plan." : { + }, "Sheet" : { "localizations" : { @@ -169251,6 +169275,9 @@ }, "Sign in to Vault with your browser?" : { + }, + "Sign in to your account to share links." : { + }, "Sign In With" : { @@ -190653,6 +190680,9 @@ } } } + }, + "The link couldn't be created. Try again." : { + }, "The list of allowed values is not carried over." : { "localizations" : { @@ -194276,6 +194306,9 @@ }, "The settings it was created with could not be read, so it gets the target's own." : { + }, + "The shared query couldn't be opened." : { + }, "The shell drops a field named __proto__ from a new document. Remove the field, then set it on the saved document." : { "extractionState" : "manual", @@ -203034,6 +203067,9 @@ } } } + }, + "This shared link is no longer available." : { + }, "This shortcut is reserved by macOS and cannot be assigned." : { "localizations" : { @@ -205719,9 +205755,15 @@ } } } + }, + "Too many requests just now. Try again in a moment." : { + }, "Too many rows. Add up to %lld rows at a time." : { + }, + "Too many shares just now. Try again in a moment." : { + }, "Tool" : { "localizations" : { @@ -219424,6 +219466,9 @@ } } } + }, + "You appear to be offline. Try again once you're connected." : { + }, "You have no saved queries to publish." : { "localizations" : { @@ -219554,6 +219599,9 @@ }, "You're signed in" : { + }, + "You've reached your share limit. Revoke a link and try again." : { + }, "You've used TablePro on %lld days" : { "localizations" : { diff --git a/apple/TablePro/Views/Main/MainContentCommandActions.swift b/apple/TablePro/Views/Main/MainContentCommandActions.swift index c7c1904a51..174389b6da 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions.swift @@ -1404,8 +1404,13 @@ final class MainContentCommandActions: ObservableObject { observeKeyWindowOnly(AppCommands.shared.openSQLFiles) { [weak self] urls in self?.handleOpenSQLFiles(urls) } + observeKeyWindowOnly(AppCommands.shared.openSharedSQL) { [weak self] statements in + self?.handleOpenSharedSQL(statements) + } } +} +extension MainContentCommandActions { private func handleOpenSQLFiles(_ urls: [URL]) { Task { for url in urls { @@ -1421,6 +1426,14 @@ final class MainContentCommandActions: ObservableObject { } } } + + private func handleOpenSharedSQL(_ statements: [String]) { + Task { + for sql in statements { + _ = try? await TabRouter.shared.openSharedQuery(sql: sql) + } + } + } } extension MainContentCommandActions { diff --git a/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift index ea9a7aec47..5d103f2c7b 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift @@ -329,6 +329,7 @@ internal final class FavoritesOutlineCoordinator: NSObject, NSOutline allFolders: owner.input.allFolders, teamLibraryTeams: owner.input.teamLibraryTeams, hasTeamLibraryConflicts: owner.input.hasTeamLibraryConflicts, + canShare: owner.input.canShare, databaseEntityName: owner.input.databaseEntityName, activeDatabase: owner.input.activeDatabase, linkedFileGitStates: owner.input.linkedFileGitStates, diff --git a/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift b/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift index 791943c252..6d6e412fb6 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift @@ -22,6 +22,7 @@ internal struct FavoritesOutlineInput { internal let allFolders: [SQLFavoriteFolder] internal let teamLibraryTeams: [TeamLibraryTeam] internal let hasTeamLibraryConflicts: Bool + internal var canShare: Bool = false internal var linkedFileGitStates: [UUID: LinkedFileGitState] = [:] internal var linkedFolderGitStates: [UUID: LinkedFolderGitMenuState] = [:] } diff --git a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift index 1c56a97245..38faff4014 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift @@ -321,6 +321,43 @@ internal struct FavoritesTabView: View { ) } + private func shareFavorite(_ favorite: SQLFavorite) { + Task { @MainActor in + let client = ShareClient(api: AccountServices.shared.api) + do throws(ShareFailure) { + let link = try await client.createQuery(title: favorite.name, sql: favorite.query, note: nil, dialect: nil) + ClipboardService.shared.writeText(link.url) + AlertHelper.showInfoSheet( + title: String(localized: "Share Link"), + message: String(localized: "A public link to this query is on your clipboard."), + window: nil + ) + } catch { + guard let message = Self.shareFailureMessage(error) else { return } + AlertHelper.showInfoSheet(title: String(localized: "Share Link"), message: message, window: nil) + } + } + } + + private static func shareFailureMessage(_ failure: ShareFailure) -> String? { + switch failure { + case .canceled: + return nil + case .featureRequired: + return String(localized: "Sharing links needs a paid plan.") + case .signedOut: + return String(localized: "Sign in to your account to share links.") + case .limitReached: + return String(localized: "You've reached your share limit. Revoke a link and try again.") + case .offline: + return String(localized: "You appear to be offline. Try again once you're connected.") + case .rateLimited: + return String(localized: "Too many shares just now. Try again in a moment.") + case .forbidden, .notFound, .refused, .server: + return String(localized: "The link couldn't be created. Try again.") + } + } + private func presentTeamLibraryInfo(_ message: String) { AlertHelper.showInfoSheet( title: String(localized: "Team Library"), @@ -350,6 +387,7 @@ internal struct FavoritesTabView: View { allFolders: viewModel.nodes.collectFolders(), teamLibraryTeams: featureAccess.isAvailable(.teamLibrary) ? teamLibrarySync.writableTeams : [], hasTeamLibraryConflicts: !teamLibrarySync.conflicts.isEmpty, + canShare: featureAccess.isAvailable(.sharedLinks), linkedFileGitStates: gitStatusStore.states(for: Self.linkedFavorites(in: items)), linkedFolderGitStates: linkedFolderGitStates ), @@ -635,6 +673,8 @@ internal struct FavoritesTabView: View { viewModel.deleteFavorite(favorite) case .showFavoriteHistory(let favorite): coordinator?.showVersionHistory(of: favorite) + case .shareFavorite(let favorite): + shareFavorite(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..65b66136fb 100644 --- a/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuCommand.swift +++ b/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuCommand.swift @@ -26,6 +26,7 @@ internal enum FavoritesMenuCommand: Equatable { case moveFavorite(id: UUID, toFolder: UUID?) case deleteFavorite(SQLFavorite) case showFavoriteHistory(SQLFavorite) + case shareFavorite(SQLFavorite) 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..82b69673cb 100644 --- a/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift +++ b/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift @@ -16,6 +16,7 @@ internal struct FavoritesMenuContext { internal let allFolders: [SQLFavoriteFolder] internal let teamLibraryTeams: [TeamLibraryTeam] internal let hasTeamLibraryConflicts: Bool + internal let canShare: Bool internal let databaseEntityName: String internal let activeDatabase: String? internal let linkedFileGitStates: [UUID: LinkedFileGitState] @@ -26,6 +27,7 @@ internal struct FavoritesMenuContext { allFolders: [SQLFavoriteFolder] = [], teamLibraryTeams: [TeamLibraryTeam] = [], hasTeamLibraryConflicts: Bool = false, + canShare: Bool = false, databaseEntityName: String = "Database", activeDatabase: String? = nil, linkedFileGitStates: [UUID: LinkedFileGitState] = [:], @@ -35,6 +37,7 @@ internal struct FavoritesMenuContext { self.allFolders = allFolders self.teamLibraryTeams = teamLibraryTeams self.hasTeamLibraryConflicts = hasTeamLibraryConflicts + self.canShare = canShare self.databaseEntityName = databaseEntityName self.activeDatabase = activeDatabase self.linkedFileGitStates = linkedFileGitStates @@ -156,6 +159,9 @@ internal enum FavoritesMenuSpec { .command(String(localized: "Edit…"), .editFavorite(favorite)), .command(String(localized: "Show History"), .showFavoriteHistory(favorite)) ] + if context.canShare { + edits.append(.command(String(localized: "Share Link…"), .shareFavorite(favorite))) + } if let moveTo = moveToSubmenu(favorite, folders: context.allFolders) { edits.append(moveTo) } diff --git a/apple/TableProTests/Core/Services/Infrastructure/DeeplinkShareParsingTests.swift b/apple/TableProTests/Core/Services/Infrastructure/DeeplinkShareParsingTests.swift new file mode 100644 index 0000000000..bbf48eeeed --- /dev/null +++ b/apple/TableProTests/Core/Services/Infrastructure/DeeplinkShareParsingTests.swift @@ -0,0 +1,46 @@ +// +// DeeplinkShareParsingTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct DeeplinkShareParsingTests { + private func token(for link: String) throws -> String? { + let url = try #require(URL(string: link)) + guard case .success(.openShare(let token)) = DeeplinkParser.parse(url) else { + return nil + } + return token + } + + @Test("A share link carries its token") + func shareLinkCarriesToken() throws { + #expect(try token(for: "tablepro://share?token=abc123") == "abc123") + } + + @Test("A percent-encoded token is decoded") + func percentEncodedTokenIsDecoded() throws { + #expect(try token(for: "tablepro://share?token=a%2Fb") == "a/b") + } + + @Test("Other query items are ignored") + func otherQueryItemsAreIgnored() throws { + #expect(try token(for: "tablepro://share?from=web&token=abc123") == "abc123") + } + + @Test( + "A link without a usable token fails", + arguments: ["tablepro://share", "tablepro://share?token=", "tablepro://share?t=abc123"] + ) + func missingTokenFails(link: String) throws { + let url = try #require(URL(string: link)) + guard case .failure(.missingRequiredParam("token")) = DeeplinkParser.parse(url) else { + Issue.record("Expected .missingRequiredParam(\"token\") for \(link)") + return + } + } +} diff --git a/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift b/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift index 56ee100c6c..19f3b7227d 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift @@ -72,6 +72,17 @@ final class WelcomeRouterTests { #expect(selected == .mysql) } + @Test + func sharedSQLEnqueuesInOrderAndDrainsOnce() { + router.enqueueSharedSQL("SELECT 1") + router.enqueueSharedSQL("SELECT 2") + + #expect(router.pendingSharedSQL == ["SELECT 1", "SELECT 2"]) + #expect(router.consumePendingSharedSQL() == ["SELECT 1", "SELECT 2"]) + #expect(router.pendingSharedSQL.isEmpty) + #expect(router.consumePendingSharedSQL().isEmpty) + } + @Test func requestSlotIsIndependentOfTheOtherPendingSlots() { let connection = DatabaseConnection(name: "Test", type: .mysql) diff --git a/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift b/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift index 4f8fff68a5..81c8c84d35 100644 --- a/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift +++ b/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift @@ -15,6 +15,7 @@ struct FavoritesMenuSpecTests { allFolders: [SQLFavoriteFolder] = [], teamLibraryTeams: [TeamLibraryTeam] = [], hasTeamLibraryConflicts: Bool = false, + canShare: Bool = false, activeDatabase: String? = "shop" ) -> FavoritesMenuContext { FavoritesMenuContext( @@ -22,6 +23,7 @@ struct FavoritesMenuSpecTests { allFolders: allFolders, teamLibraryTeams: teamLibraryTeams, hasTeamLibraryConflicts: hasTeamLibraryConflicts, + canShare: canShare, activeDatabase: activeDatabase ) } @@ -376,6 +378,15 @@ struct FavoritesMenuSpecTests { #expect(issued.contains(.showFavoriteHistory(query))) } + @Test("Share Link appears on a saved query only when sharing is available") + func shareLinkGatedBySharing() { + let query = favorite() + let shared = commands(FavoritesMenuSpec.sections(for: context(clicked: .query(.favorite(query)), canShare: true))) + #expect(shared.contains(.shareFavorite(query))) + let withheld = commands(FavoritesMenuSpec.sections(for: context(clicked: .query(.favorite(query)), canShare: false))) + #expect(!withheld.contains(.shareFavorite(query))) + } + private func linkedFile() -> LinkedSQLFavorite { LinkedSQLFavorite( folderId: UUID(), From a359926215764fd5b1c30aef910f4502bad41210 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 05:17:02 +0700 Subject: [PATCH 002/126] docs(changelog): add share-links fragments --- apple/changelog.d/4253.added.1.md | 1 + apple/changelog.d/4253.added.md | 1 + 2 files changed, 2 insertions(+) create mode 100644 apple/changelog.d/4253.added.1.md create mode 100644 apple/changelog.d/4253.added.md diff --git a/apple/changelog.d/4253.added.1.md b/apple/changelog.d/4253.added.1.md new file mode 100644 index 0000000000..22cebdc45e --- /dev/null +++ b/apple/changelog.d/4253.added.1.md @@ -0,0 +1 @@ +Open a shared query link from the browser, straight into TablePro. diff --git a/apple/changelog.d/4253.added.md b/apple/changelog.d/4253.added.md new file mode 100644 index 0000000000..ede0748571 --- /dev/null +++ b/apple/changelog.d/4253.added.md @@ -0,0 +1 @@ +Share a saved query as a public link from the Favorites menu, on a paid plan. From e79305ae36a2d96b9f402a556ef92897501b6975 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 08:55:50 +0700 Subject: [PATCH 003/126] feat(macos): share a query result as a public link from the grid --- .../DataGrid/DataGridOwnerProtocols.swift | 3 + .../Core/Services/Shares/ShareClient.swift | 40 ++++- .../Utilities/SQL/ResultSnapshotBuilder.swift | 166 ++++++++++++++++++ .../TablePro/Resources/Localizable.xcstrings | 9 + .../DataGridViewController+RowMenu.swift | 8 + .../Views/Main/Child/DataTabGridAdapter.swift | 5 + .../MainContentCoordinator+GridModels.swift | 2 +- .../MainContentCoordinator+ShareResult.swift | 62 +++++++ .../Views/Sidebar/FavoritesTabView.swift | 21 +-- .../ResultSnapshotBuilderTests.swift | 100 +++++++++++ apple/changelog.d/4253.added.2.md | 1 + 11 files changed, 393 insertions(+), 24 deletions(-) create mode 100644 apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift create mode 100644 apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift create mode 100644 apple/TableProTests/Core/Utilities/ResultSnapshotBuilderTests.swift create mode 100644 apple/changelog.d/4253.added.2.md 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/Services/Shares/ShareClient.swift b/apple/TablePro/Core/Services/Shares/ShareClient.swift index 735cb555ae..eaa48c2d5b 100644 --- a/apple/TablePro/Core/Services/Shares/ShareClient.swift +++ b/apple/TablePro/Core/Services/Shares/ShareClient.swift @@ -34,6 +34,26 @@ internal enum ShareFailure: Error, Equatable, Sendable { } } + // The message a create flow (a favorite, a result) shows, or nil when there is nothing to say. + var createMessage: String? { + switch self { + case .canceled: + return nil + case .featureRequired: + return String(localized: "Sharing links needs a paid plan.") + case .signedOut: + return String(localized: "Sign in to your account to share links.") + case .limitReached: + return String(localized: "You've reached your share limit. Revoke a link and try again.") + case .offline: + return String(localized: "You appear to be offline. Try again once you're connected.") + case .rateLimited: + return String(localized: "Too many shares just now. Try again in a moment.") + case .forbidden, .notFound, .refused, .server: + return String(localized: "The link couldn't be created. Try again.") + } + } + static func from(_ error: AccountError) -> ShareFailure { switch error { case .canceled: @@ -66,11 +86,25 @@ internal struct ShareClient: Sendable { let api: any APIProtocol func createQuery(title: String, sql: String, note: String?, dialect: String?) async throws(ShareFailure) -> CreatedShareLink { + try await create(body: .init(dialect: dialect, kind: "query", note: note, sql: sql, title: title)) + } + + func createResult( + title: String, + sql: String, + note: String?, + dialect: String?, + snapshot: Components.Schemas.SnapshotInput + ) async throws(ShareFailure) -> CreatedShareLink { + try await create(body: .init(dialect: dialect, kind: "result", note: note, snapshot: snapshot, sql: sql, title: title)) + } + + private func create(body: Components.Schemas.CreateShareBody) async throws(ShareFailure) -> CreatedShareLink { do { - switch try await api.createShare(body: .json(.init(dialect: dialect, kind: "query", note: note, sql: sql, title: title))) { + switch try await api.createShare(body: .json(body)) { case .ok(let answer): - let body = try answer.body.json - return CreatedShareLink(id: body.id, token: body.token, url: body.url) + let created = try answer.body.json + return CreatedShareLink(id: created.id, token: created.token, url: created.url) case .unauthorized: throw ShareFailure.signedOut case .forbidden(let answer): diff --git a/apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift b/apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift new file mode 100644 index 0000000000..c13e1d674f --- /dev/null +++ b/apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift @@ -0,0 +1,166 @@ +// +// ResultSnapshotBuilder.swift +// TablePro +// + +import Foundation +import TableProCloudAPI +import TableProPluginKit + +// Turns a displayed result into a share snapshot. Lossless on the web viewer: a value wider than a +// JS safe integer, or a high-precision decimal, goes as a string so no digit is rounded away; safe +// numbers go as JSON numbers so the viewer right-aligns them. +enum ResultSnapshotBuilder { + static let maxRows = 10_000 + static let maxColumns = 100 + // Per cell and for the whole snapshot, under the server's 256 KB/cell and 5 MB (compressed) caps. + static let maxCellBytes = 64 * 1_024 + static let maxSnapshotBytes = 8 * 1_024 * 1_024 + + struct Built { + let snapshot: Components.Schemas.SnapshotInput + let rowsSent: Int + } + + // totalRowCount: the result's true total when known; nil when the result was cut short with no count. + // moreRowsAvailable: the result had rows beyond those loaded. + static func build( + from read: DisplayedResultReader.Output, + totalRowCount: Int?, + moreRowsAvailable: Bool + ) -> Built { + var truncated = false + + var columnNames = read.columns + var columnTypes = read.columnTypes + if columnNames.count > maxColumns { + columnNames = Array(columnNames.prefix(maxColumns)) + columnTypes = Array(columnTypes.prefix(maxColumns)) + truncated = true + } + let columns = columnNames.enumerated().map { index, name in + Components.Schemas.ColumnJSON(name: name, _type: columnTypeLabel(columnTypes, at: index)) + } + + var rows: [[OpenAPIValueContainer]?] = [] + var bytes = 0 + for row in read.rows { + if rows.count >= maxRows { truncated = true; break } + var cells: [OpenAPIValueContainer] = [] + var rowBytes = 0 + for index in 0 ..< columnNames.count { + let type = columnTypes.indices.contains(index) ? columnTypes[index] : .text(rawType: nil) + let cell = row.indices.contains(index) ? row[index] : .null + let encoded = SnapshotCellEncoder.encode(cell, type: type) + rowBytes += encoded.byteCount + cells.append(encoded.value) + } + if !rows.isEmpty, bytes + rowBytes > maxSnapshotBytes { truncated = true; break } + bytes += rowBytes + rows.append(cells) + } + + if moreRowsAvailable { truncated = true } + if let total = totalRowCount, total > rows.count { truncated = true } + + let rowCount: Int64? + if let total = totalRowCount, total > rows.count { + rowCount = Int64(total) + } else { + rowCount = nil + } + + let snapshot = Components.Schemas.SnapshotInput( + columns: columns, + rowCount: rowCount, + rows: rows, + truncated: truncated + ) + return Built(snapshot: snapshot, rowsSent: rows.count) + } + + private static func columnTypeLabel(_ types: [ColumnType], at index: Int) -> String? { + guard types.indices.contains(index) else { return nil } + return types[index].rawType ?? types[index].displayName + } +} + +// The cell mapping, factored out so it can be tested without a result set. +enum SnapshotCellEncoder { + struct Encoded { + let value: OpenAPIValueContainer + let byteCount: Int + } + + // 2^53 - 1: the largest integer a JS number holds exactly, so the viewer's JSON.parse keeps it. + static let safeIntegerMagnitude: Int64 = 9_007_199_254_740_991 + + static func encode(_ cell: PluginCellValue, type: ColumnType) -> Encoded { + switch cell { + case .null: + return Encoded(value: OpenAPIValueContainer(nilLiteral: ()), byteCount: 4) + case .bytes(let data): + return string("(binary, \(data.count) bytes)") + case .text(let value): + return encodeText(value, type: type) + } + } + + private static func encodeText(_ value: String, type: ColumnType) -> Encoded { + switch type { + case .boolean: + return encodeBoolean(value) + case .integer: + return encodeInteger(value) + case .decimal: + return encodeDecimal(value) + case .text, .date, .timestamp, .datetime, .json, .blob, + .enumType, .set, .spatial, .vector, .array: + return string(value) + } + } + + private static func encodeBoolean(_ value: String) -> Encoded { + switch value.lowercased() { + case "true", "1", "yes", "on": + return Encoded(value: OpenAPIValueContainer(booleanLiteral: true), byteCount: 4) + case "false", "0", "no", "off": + return Encoded(value: OpenAPIValueContainer(booleanLiteral: false), byteCount: 5) + default: + // MySQL's BOOLEAN is TINYINT(1), which also stores 2 or -1. + return encodeInteger(value) + } + } + + private static func encodeInteger(_ value: String) -> Encoded { + guard let literal = JsonNumberNormalizer.integerLiteral(from: value) else { + return string(value) + } + if let number = Int64(literal), (-safeIntegerMagnitude ... safeIntegerMagnitude).contains(number) { + return Encoded(value: OpenAPIValueContainer(integerLiteral: Int(number)), byteCount: literal.utf8.count) + } + return string(literal) + } + + private static func encodeDecimal(_ value: String) -> Encoded { + guard let literal = JsonNumberNormalizer.numberLiteral(from: value) else { + return string(value) + } + if let double = Double(literal), double.isFinite, + JsonNumberNormalizer.numberLiteral(from: String(double)) == literal { + return Encoded(value: OpenAPIValueContainer(floatLiteral: double), byteCount: literal.utf8.count) + } + return string(literal) + } + + private static func string(_ value: String) -> Encoded { + let capped = capped(value) + return Encoded(value: OpenAPIValueContainer(stringLiteral: capped), byteCount: capped.utf8.count) + } + + private static func capped(_ value: String) -> String { + guard value.utf8.count > ResultSnapshotBuilder.maxCellBytes else { return value } + let prefix = String(value.prefix(ResultSnapshotBuilder.maxCellBytes / 4)) + return prefix + "…" + } +} diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 0893b65f71..b871d3e8e7 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -16682,6 +16682,9 @@ }, "A public link to this query is on your clipboard." : { + }, + "A public link to this result is on your clipboard." : { + }, "A publish to the team library is still running. Try again when it finishes." : { @@ -166116,6 +166119,12 @@ }, "Share Links" : { + }, + "Share Result" : { + + }, + "Share Result…" : { + }, "Share usage data" : { "localizations" : { diff --git a/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowMenu.swift b/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowMenu.swift index 5b754272d6..1c237e2da6 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), FeatureAccess.shared.isAvailable(.sharedLinks) { + 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/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/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+ShareResult.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift new file mode 100644 index 0000000000..2246a8190f --- /dev/null +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift @@ -0,0 +1,62 @@ +// +// MainContentCoordinator+ShareResult.swift +// TablePro +// + +import Foundation + +extension MainContentCoordinator { + // Shares the active result as a public link: the selected rows, or the whole loaded result when + // nothing is selected, capped and sent to the share service, then the URL is put on the clipboard. + func shareActiveResult() { + guard let tab = tabManager.selectedTab else { return } + let tableRows = tabSessionRegistry.tableRows(for: tab.id) + guard !tableRows.rows.isEmpty else { return } + + let model = gridModel(forTab: tab.id) + let selectedDisplayIndices = Set(model.selectedRowIDs.compactMap { model.displayIndex(of: $0) }) + let hasSelection = !selectedDisplayIndices.isEmpty + let projection = VisibleColumnProjection(indices: model.columns.columns.map(\.dataIndex)) + let read = DisplayedResultReader.read( + tableRows: tableRows, + displayIDs: model.order.filteredIDs, + selectedDisplayIndices: selectedDisplayIndices, + defaultedCells: model.changeState?.defaultedCells(in: tableRows) ?? [:], + columns: projection + ) + guard !read.rows.isEmpty else { return } + + let sql = (tab.pagination.baseQueryForMore ?? tab.content.query) + .trimmingCharacters(in: .whitespacesAndNewlines) + guard !sql.isEmpty else { return } + + let built = ResultSnapshotBuilder.build( + from: read, + totalRowCount: hasSelection ? nil : (tab.pagination.hasExactRowCount ? tab.pagination.totalRowCount : nil), + moreRowsAvailable: hasSelection ? false : tab.pagination.hasMoreRows + ) + + let window = contentWindow + Task { @MainActor in + let client = ShareClient(api: AccountServices.shared.api) + do throws(ShareFailure) { + let link = try await client.createResult( + title: tab.title, + sql: sql, + note: nil, + dialect: connection.type.rawValue, + snapshot: built.snapshot + ) + ClipboardService.shared.writeText(link.url) + AlertHelper.showInfoSheet( + title: String(localized: "Share Result"), + message: String(localized: "A public link to this result is on your clipboard."), + window: window + ) + } catch { + guard let message = error.createMessage else { return } + AlertHelper.showInfoSheet(title: String(localized: "Share Result"), message: message, window: window) + } + } + } +} diff --git a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift index 38faff4014..541b8f05e2 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift @@ -333,31 +333,12 @@ internal struct FavoritesTabView: View { window: nil ) } catch { - guard let message = Self.shareFailureMessage(error) else { return } + guard let message = error.createMessage else { return } AlertHelper.showInfoSheet(title: String(localized: "Share Link"), message: message, window: nil) } } } - private static func shareFailureMessage(_ failure: ShareFailure) -> String? { - switch failure { - case .canceled: - return nil - case .featureRequired: - return String(localized: "Sharing links needs a paid plan.") - case .signedOut: - return String(localized: "Sign in to your account to share links.") - case .limitReached: - return String(localized: "You've reached your share limit. Revoke a link and try again.") - case .offline: - return String(localized: "You appear to be offline. Try again once you're connected.") - case .rateLimited: - return String(localized: "Too many shares just now. Try again in a moment.") - case .forbidden, .notFound, .refused, .server: - return String(localized: "The link couldn't be created. Try again.") - } - } - private func presentTeamLibraryInfo(_ message: String) { AlertHelper.showInfoSheet( title: String(localized: "Team Library"), diff --git a/apple/TableProTests/Core/Utilities/ResultSnapshotBuilderTests.swift b/apple/TableProTests/Core/Utilities/ResultSnapshotBuilderTests.swift new file mode 100644 index 0000000000..5acfb5e7fe --- /dev/null +++ b/apple/TableProTests/Core/Utilities/ResultSnapshotBuilderTests.swift @@ -0,0 +1,100 @@ +// +// ResultSnapshotBuilderTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProCloudAPI +import TableProPluginKit +import Testing + +struct ResultSnapshotBuilderTests { + private func cell(_ value: PluginCellValue, _ type: ColumnType) -> OpenAPIValueContainer { + SnapshotCellEncoder.encode(value, type: type).value + } + + @Test("A safe integer stays a JSON number") + func safeIntegerIsNumber() { + #expect(cell(.text("42"), .integer(rawType: "int")) == OpenAPIValueContainer(integerLiteral: 42)) + #expect(cell(.text("42.0"), .integer(rawType: "int")) == OpenAPIValueContainer(integerLiteral: 42)) + #expect(cell(.text("9007199254740991"), .integer(rawType: "bigint")) == OpenAPIValueContainer(integerLiteral: 9_007_199_254_740_991)) + } + + @Test("An integer past 2^53 is a string, lossless") + func bigIntegerIsString() { + #expect(cell(.text("9007199254740993"), .integer(rawType: "bigint")) == OpenAPIValueContainer(stringLiteral: "9007199254740993")) + #expect(cell(.text("-12345678901234567890"), .integer(rawType: "numeric")) == OpenAPIValueContainer(stringLiteral: "-12345678901234567890")) + } + + @Test("A decimal that round-trips is a number; high precision is a string") + func decimalPrecision() { + #expect(cell(.text("3.14"), .decimal(rawType: "double")) == OpenAPIValueContainer(floatLiteral: 3.14)) + #expect(cell(.text("0.12345678901234567890123"), .decimal(rawType: "numeric")) == OpenAPIValueContainer(stringLiteral: "0.12345678901234567890123")) + } + + @Test("Booleans normalize, including TINYINT(1) values") + func booleans() { + #expect(cell(.text("1"), .boolean(rawType: "bool")) == OpenAPIValueContainer(booleanLiteral: true)) + #expect(cell(.text("false"), .boolean(rawType: "bool")) == OpenAPIValueContainer(booleanLiteral: false)) + #expect(cell(.text("2"), .boolean(rawType: "tinyint")) == OpenAPIValueContainer(integerLiteral: 2)) + } + + @Test("Null, bytes and text") + func otherTypes() { + #expect(cell(.null, .text(rawType: nil)) == OpenAPIValueContainer(nilLiteral: ())) + #expect(cell(.bytes(Data(count: 1_024)), .blob(rawType: "blob")) == OpenAPIValueContainer(stringLiteral: "(binary, 1024 bytes)")) + #expect(cell(.text("hello"), .text(rawType: "text")) == OpenAPIValueContainer(stringLiteral: "hello")) + #expect(cell(.text("{\"a\":1}"), .json(rawType: "json")) == OpenAPIValueContainer(stringLiteral: "{\"a\":1}")) + } + + @Test("A huge text cell is capped") + func longTextCapped() { + let huge = String(repeating: "x", count: 200_000) + let encoded = SnapshotCellEncoder.encode(.text(huge), type: .text(rawType: "text")) + #expect(encoded.byteCount < huge.utf8.count) + #expect(encoded.value == OpenAPIValueContainer(stringLiteral: String(huge.prefix(ResultSnapshotBuilder.maxCellBytes / 4)) + "…")) + } + + private func output(columns: [String], types: [ColumnType], rows: [[PluginCellValue]]) -> DisplayedResultReader.Output { + DisplayedResultReader.Output(columns: columns, columnTypes: types, rows: rows, skippedDeletedCount: 0) + } + + @Test("row_count and truncated reflect a result cut short") + func truncationFlags() { + let read = output(columns: ["n"], types: [.integer(rawType: "int")], rows: [[.text("1")], [.text("2")]]) + let built = ResultSnapshotBuilder.build(from: read, totalRowCount: 500, moreRowsAvailable: true) + #expect(built.rowsSent == 2) + #expect(built.snapshot.rowCount == 500) + #expect(built.snapshot.truncated == true) + } + + @Test("A fully loaded result is not truncated and omits row_count") + func notTruncated() { + let read = output(columns: ["n"], types: [.integer(rawType: "int")], rows: [[.text("1")], [.text("2")]]) + let built = ResultSnapshotBuilder.build(from: read, totalRowCount: 2, moreRowsAvailable: false) + #expect(built.snapshot.truncated == false) + #expect(built.snapshot.rowCount == nil) + } + + @Test("Rows past the cap are dropped and marked truncated") + func rowCap() { + let rows = Array(repeating: [PluginCellValue.text("1")], count: ResultSnapshotBuilder.maxRows + 50) + let read = output(columns: ["n"], types: [.integer(rawType: "int")], rows: rows) + let built = ResultSnapshotBuilder.build(from: read, totalRowCount: nil, moreRowsAvailable: false) + #expect(built.rowsSent == ResultSnapshotBuilder.maxRows) + #expect(built.snapshot.truncated == true) + } + + @Test("Columns past the cap are dropped and marked truncated") + func columnCap() { + let count = ResultSnapshotBuilder.maxColumns + 5 + let columns = (0 ..< count).map { "c\($0)" } + let types = Array(repeating: ColumnType.text(rawType: "text"), count: count) + let row = Array(repeating: PluginCellValue.text("x"), count: count) + let built = ResultSnapshotBuilder.build(from: output(columns: columns, types: types, rows: [row]), totalRowCount: nil, moreRowsAvailable: false) + #expect(built.snapshot.columns.count == ResultSnapshotBuilder.maxColumns) + #expect(built.snapshot.rows.first??.count == ResultSnapshotBuilder.maxColumns) + #expect(built.snapshot.truncated == true) + } +} diff --git a/apple/changelog.d/4253.added.2.md b/apple/changelog.d/4253.added.2.md new file mode 100644 index 0000000000..e60e7078c9 --- /dev/null +++ b/apple/changelog.d/4253.added.2.md @@ -0,0 +1 @@ +Share a query's result as a public link from the grid, on a paid plan. From 7654979d4a5557057130f9a817e13da376081ae8 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 09:20:28 +0700 Subject: [PATCH 004/126] fix(macos): harden result sharing from review - Exclude rows pending deletion from a published snapshot. - Gate Share Result on the shared_links entitlement. - Guard both share paths against a double-click minting two links. - Cap the snapshot under the server's 5 MB compressed limit (4.5 MB uncompressed). - Map an unexpected AccountError to .server, not .offline. --- .../Core/Services/Shares/ShareClient.swift | 21 ++++++++----------- .../Utilities/SQL/ResultSnapshotBuilder.swift | 6 ++++-- .../MainContentCoordinator+ShareResult.swift | 7 ++++++- .../Views/Main/MainContentCoordinator.swift | 2 ++ .../Views/Sidebar/FavoritesTabView.swift | 5 +++++ 5 files changed, 26 insertions(+), 15 deletions(-) diff --git a/apple/TablePro/Core/Services/Shares/ShareClient.swift b/apple/TablePro/Core/Services/Shares/ShareClient.swift index eaa48c2d5b..6949b14179 100644 --- a/apple/TablePro/Core/Services/Shares/ShareClient.swift +++ b/apple/TablePro/Core/Services/Shares/ShareClient.swift @@ -10,8 +10,7 @@ internal enum ShareFailure: Error, Equatable, Sendable { case offline // The request was cancelled (torn down, superseded). Nothing to tell the user. case canceled - // The 429's Retry-After, when it carried one. - case rateLimited(retryAfter: Duration?) + case rateLimited case server case signedOut // The account's plan does not include shared_links. @@ -63,13 +62,16 @@ internal enum ShareFailure: Error, Equatable, Sendable { case .server(let status, _) where status == 401: return .signedOut case .server(let status, _) where status == 429: - return .rateLimited(retryAfter: nil) + return .rateLimited case .server(let status, _) where status >= 500: return .server case .server: return .refused - default: + case .network: return .offline + default: + // An OAuth, decode, or state error is not "offline"; treat it as a server-side problem. + return .server } } } @@ -117,7 +119,7 @@ internal struct ShareClient: Sendable { case .unprocessableContent: throw ShareFailure.refused case .tooManyRequests(let answer): - throw ShareFailure.rateLimited(retryAfter: Self.delay(seconds: answer.headers.retryAfter)) + throw ShareFailure.rateLimited case .internalServerError: throw ShareFailure.server case .undocumented(let status, _): @@ -138,7 +140,7 @@ internal struct ShareClient: Sendable { case .notFound, .unprocessableContent: throw ShareFailure.notFound case .tooManyRequests(let answer): - throw ShareFailure.rateLimited(retryAfter: Self.delay(seconds: answer.headers.retryAfter)) + throw ShareFailure.rateLimited case .internalServerError: throw ShareFailure.server case .undocumented(let status, _): @@ -151,14 +153,9 @@ internal struct ShareClient: Sendable { } } - private static func delay(seconds: Int?) -> Duration? { - guard let seconds, seconds > 0 else { return nil } - return .seconds(seconds) - } - private static func undocumented(_ status: Int) -> ShareFailure { switch status { - case 429: .rateLimited(retryAfter: nil) + case 429: .rateLimited case 500...: .server default: .refused } diff --git a/apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift b/apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift index c13e1d674f..d9362506ac 100644 --- a/apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift +++ b/apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift @@ -13,9 +13,11 @@ import TableProPluginKit enum ResultSnapshotBuilder { static let maxRows = 10_000 static let maxColumns = 100 - // Per cell and for the whole snapshot, under the server's 256 KB/cell and 5 MB (compressed) caps. + // Per cell, under the server's 256 KB/cell cap. The snapshot budget is counted on the uncompressed + // bytes and kept under the server's 5 MB compressed cap: gzip never expands, so staying under 4.5 MB + // uncompressed stays under 5 MB compressed, and a deterministic 422 never surprises the user. static let maxCellBytes = 64 * 1_024 - static let maxSnapshotBytes = 8 * 1_024 * 1_024 + static let maxSnapshotBytes = 4_500_000 struct Built { let snapshot: Components.Schemas.SnapshotInput diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift index 2246a8190f..697d95af34 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift @@ -9,7 +9,8 @@ extension MainContentCoordinator { // Shares the active result as a public link: the selected rows, or the whole loaded result when // nothing is selected, capped and sent to the share service, then the URL is put on the clipboard. func shareActiveResult() { - guard let tab = tabManager.selectedTab else { return } + guard FeatureAccess.shared.isAvailable(.sharedLinks) else { return } + guard !isSharingInFlight, let tab = tabManager.selectedTab else { return } let tableRows = tabSessionRegistry.tableRows(for: tab.id) guard !tableRows.rows.isEmpty else { return } @@ -21,6 +22,8 @@ extension MainContentCoordinator { tableRows: tableRows, displayIDs: model.order.filteredIDs, selectedDisplayIndices: selectedDisplayIndices, + // A row marked for deletion must not land in a public snapshot, as the JSON view already excludes it. + deletedRowIDs: model.changeState?.deletedRowIDs ?? [], defaultedCells: model.changeState?.defaultedCells(in: tableRows) ?? [:], columns: projection ) @@ -37,7 +40,9 @@ extension MainContentCoordinator { ) let window = contentWindow + isSharingInFlight = true Task { @MainActor in + defer { isSharingInFlight = false } let client = ShareClient(api: AccountServices.shared.api) do throws(ShareFailure) { let link = try await client.createResult( diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index 95198bade6..f952333816 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -129,6 +129,8 @@ enum ActiveSheet: Identifiable { @MainActor final class MainContentCoordinator: ObservableObject { + // Set while a Share Result request is in flight, so a second click does not mint a duplicate link. + var isSharingInFlight = false nonisolated static let logger = Logger(subsystem: "com.TablePro", category: "MainContentCoordinator") nonisolated static let lifecycleLogger = Logger(subsystem: "com.TablePro", category: "NativeTabLifecycle") diff --git a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift index 541b8f05e2..244de2129b 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift @@ -18,6 +18,8 @@ internal struct FavoritesTabView: View { @State private var favoriteDatabases: Set = [] @State private var folderToDelete: SQLFavoriteFolder? @State private var showDeleteFolderAlert = false + // Set while a Share Link request is in flight, so a second click does not mint a duplicate link. + @State private var isSharing = false @State private var linkedFileToTrash: LinkedSQLFavorite? @State private var showTrashLinkedFileAlert = false @State private var linkedMetadataTarget: LinkedSQLFavorite? @@ -322,7 +324,10 @@ internal struct FavoritesTabView: View { } private func shareFavorite(_ favorite: SQLFavorite) { + guard !isSharing else { return } + isSharing = true Task { @MainActor in + defer { isSharing = false } let client = ShareClient(api: AccountServices.shared.api) do throws(ShareFailure) { let link = try await client.createQuery(title: favorite.name, sql: favorite.query, note: nil, dialect: nil) From 7615f0c452af638d7a77e0c9e6dbb0bb38d7843e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 14:09:02 +0700 Subject: [PATCH 005/126] refactor(macos): remove the first share links implementation --- .../openapi-generator-config.yaml | 6 - .../Sources/TableProCloudAPI/openapi.json | 1425 +---------------- .../DataGrid/DataGridOwnerProtocols.swift | 3 - apple/TablePro/Core/Events/AppCommands.swift | 1 - .../Core/Services/Account/AccountAPI.swift | 14 - .../Services/Account/AccountServices.swift | 3 - .../Infrastructure/AppActivationPolicy.swift | 1 - .../Infrastructure/DeeplinkParser.swift | 12 - .../Infrastructure/LaunchIntent.swift | 2 - .../Infrastructure/LaunchIntentRouter.swift | 41 +- .../Services/Infrastructure/TabRouter.swift | 14 - .../Infrastructure/WelcomeRouter.swift | 21 - .../Core/Services/Shares/ShareClient.swift | 163 -- .../Utilities/SQL/ResultSnapshotBuilder.swift | 168 -- .../TablePro/Models/Settings/ProFeature.swift | 7 - .../TablePro/Resources/Localizable.xcstrings | 57 - .../DataGridViewController+RowMenu.swift | 8 - .../Views/Main/Child/DataTabGridAdapter.swift | 5 - .../MainContentCoordinator+GridModels.swift | 2 +- .../MainContentCoordinator+ShareResult.swift | 67 - .../Main/MainContentCommandActions.swift | 13 - .../Views/Main/MainContentCoordinator.swift | 2 - .../Sidebar/FavoritesOutlineCoordinator.swift | 1 - .../Views/Sidebar/FavoritesOutlineView.swift | 1 - .../Views/Sidebar/FavoritesTabView.swift | 26 - .../Sidebar/Menu/FavoritesMenuCommand.swift | 1 - .../Sidebar/Menu/FavoritesMenuSpec.swift | 6 - .../DeeplinkShareParsingTests.swift | 46 - .../Infrastructure/WelcomeRouterTests.swift | 11 - .../ResultSnapshotBuilderTests.swift | 100 -- .../Sidebar/FavoritesMenuSpecTests.swift | 11 - apple/changelog.d/4253.added.1.md | 1 - apple/changelog.d/4253.added.2.md | 1 - apple/changelog.d/4253.added.md | 1 - 34 files changed, 7 insertions(+), 2234 deletions(-) delete mode 100644 apple/TablePro/Core/Services/Shares/ShareClient.swift delete mode 100644 apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift delete mode 100644 apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift delete mode 100644 apple/TableProTests/Core/Services/Infrastructure/DeeplinkShareParsingTests.swift delete mode 100644 apple/TableProTests/Core/Utilities/ResultSnapshotBuilderTests.swift delete mode 100644 apple/changelog.d/4253.added.1.md delete mode 100644 apple/changelog.d/4253.added.2.md delete mode 100644 apple/changelog.d/4253.added.md diff --git a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml index 2a999d96fc..fb565cf1e3 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml +++ b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi-generator-config.yaml @@ -13,9 +13,3 @@ filter: - issue-entitlement - list-library-changes - push-library-changes - - create-share - - list-shares - - get-share - - update-share - - delete-share - - get-shared diff --git a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json index 96f9936098..a3af459ea3 100644 --- a/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json +++ b/apple/Packages/TableProMacCore/Sources/TableProCloudAPI/openapi.json @@ -112,90 +112,6 @@ ], "type": "object" }, - "ColumnJSON": { - "additionalProperties": false, - "properties": { - "name": { - "type": "string" - }, - "type": { - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "CreateShareBody": { - "additionalProperties": false, - "properties": { - "dialect": { - "description": "The SQL dialect, for display", - "maxLength": 40, - "type": "string" - }, - "expires_at": { - "description": "When the link stops working; omit for no expiry", - "format": "date-time", - "type": [ - "string", - "null" - ] - }, - "kind": { - "type": "string" - }, - "note": { - "maxLength": 2000, - "type": "string" - }, - "snapshot": { - "$ref": "#/components/schemas/SnapshotInput", - "description": "The frozen result set, for a result share" - }, - "sql": { - "type": "string" - }, - "team_id": { - "description": "Team TypeID; omit for a personal share", - "type": "string" - }, - "title": { - "maxLength": 200, - "type": "string" - } - }, - "required": [ - "kind", - "sql" - ], - "type": "object" - }, - "CreatedShare": { - "properties": { - "expires_at": { - "format": "date-time", - "type": "string" - }, - "id": { - "type": "string" - }, - "token": { - "description": "The raw link token, shown once", - "type": "string" - }, - "url": { - "type": "string" - } - }, - "required": [ - "id", - "token", - "url" - ], - "type": "object" - }, "Cycle": { "enum": [ "monthly", @@ -856,23 +772,19 @@ "type": "string" }, "source": { - "description": "Extensible enum: subscription, order, manual, legacy, redeem_code, education", + "description": "Extensible enum: subscription, order, manual, legacy", "examples": [ "subscription", "order", "manual", - "legacy", - "redeem_code", - "education" + "legacy" ], "type": "string", "x-extensible-enum": [ "subscription", "order", "manual", - "legacy", - "redeem_code", - "education" + "legacy" ] }, "status": { @@ -1134,7 +1046,7 @@ "NewsletterStats": { "properties": { "subscribers": { - "description": "Subscribers no suppression holds back, counted at most once an hour", + "description": "Contacts in the newsletter segment who have not unsubscribed, counted at most once an hour", "format": "int64", "minimum": 0, "type": "integer" @@ -1148,11 +1060,6 @@ "NewsletterSubscriptionRequest": { "additionalProperties": false, "properties": { - "consent_version": { - "description": "Names the consent text the form showed", - "maxLength": 32, - "type": "string" - }, "email": { "format": "email", "maxLength": 254, @@ -1163,11 +1070,6 @@ "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, @@ -1301,9 +1203,6 @@ ], "type": "string" }, - "education": { - "$ref": "#/components/schemas/PricingEducation" - }, "plans": { "items": { "$ref": "#/components/schemas/PlanPrice" @@ -1313,20 +1212,7 @@ }, "required": [ "country", - "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" + "plans" ], "type": "object" }, @@ -1381,83 +1267,6 @@ ], "type": "object" }, - "PublicShare": { - "properties": { - "created_at": { - "format": "date-time", - "type": "string" - }, - "dialect": { - "type": "string" - }, - "expires_at": { - "format": "date-time", - "type": "string" - }, - "kind": { - "type": "string" - }, - "made_with": { - "description": "Attribution the viewer page shows", - "type": "string" - }, - "note": { - "type": "string" - }, - "snapshot": { - "$ref": "#/components/schemas/PublicSnapshot" - }, - "sql": { - "type": "string" - }, - "title": { - "type": "string" - } - }, - "required": [ - "kind", - "title", - "sql", - "created_at", - "made_with" - ], - "type": "object" - }, - "PublicSnapshot": { - "properties": { - "columns": { - "items": { - "$ref": "#/components/schemas/ShareColumn" - }, - "type": "array" - }, - "row_count": { - "description": "Rows the query returned, which may exceed those shown", - "format": "int64", - "type": "integer" - }, - "rows": { - "items": { - "items": {}, - "type": [ - "array", - "null" - ] - }, - "type": "array" - }, - "truncated": { - "type": "boolean" - } - }, - "required": [ - "columns", - "rows", - "row_count", - "truncated" - ], - "type": "object" - }, "Seats": { "properties": { "available": { @@ -1492,143 +1301,6 @@ ], "type": "object" }, - "ShareColumn": { - "properties": { - "name": { - "type": "string" - }, - "type": { - "type": "string" - } - }, - "required": [ - "name" - ], - "type": "object" - }, - "ShareList": { - "properties": { - "data": { - "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" - }, - "ShareView": { - "properties": { - "created_at": { - "format": "date-time", - "type": "string" - }, - "dialect": { - "type": "string" - }, - "expires_at": { - "format": "date-time", - "type": "string" - }, - "has_result": { - "description": "true for a result share", - "type": "boolean" - }, - "id": { - "type": "string" - }, - "kind": { - "type": "string" - }, - "note": { - "type": "string" - }, - "revoked_at": { - "format": "date-time", - "type": "string" - }, - "scope": { - "description": "account or team", - "type": "string" - }, - "sql": { - "type": "string" - }, - "team_id": { - "type": "string" - }, - "title": { - "type": "string" - }, - "updated_at": { - "format": "date-time", - "type": "string" - }, - "url": { - "description": "The link, present when the server can rebuild it", - "type": "string" - }, - "view_count": { - "format": "int64", - "type": "integer" - } - }, - "required": [ - "id", - "kind", - "scope", - "title", - "sql", - "has_result", - "view_count", - "created_at", - "updated_at" - ], - "type": "object" - }, - "SnapshotInput": { - "additionalProperties": false, - "properties": { - "columns": { - "items": { - "$ref": "#/components/schemas/ColumnJSON" - }, - "minItems": 1, - "type": "array" - }, - "row_count": { - "description": "Rows the query returned, if more than those sent", - "format": "int64", - "minimum": 0, - "type": "integer" - }, - "rows": { - "items": { - "items": {}, - "type": [ - "array", - "null" - ] - }, - "type": "array" - }, - "truncated": { - "type": "boolean" - } - }, - "required": [ - "columns", - "rows" - ], - "type": "object" - }, "Team": { "properties": { "has_seat": { @@ -1754,32 +1426,6 @@ "name" ], "type": "object" - }, - "UpdateShareBody": { - "additionalProperties": false, - "properties": { - "clear_expiry": { - "description": "Remove the expiry", - "type": "boolean" - }, - "expires_at": { - "description": "Set a new expiry; omit to leave it unchanged", - "format": "date-time", - "type": [ - "string", - "null" - ] - }, - "note": { - "maxLength": 2000, - "type": "string" - }, - "title": { - "maxLength": 200, - "type": "string" - } - }, - "type": "object" } }, "securitySchemes": { @@ -3307,1067 +2953,6 @@ ] } }, - "/shared/{token}": { - "get": { - "description": "No authentication. A missing, revoked or expired link answers 404 alike.", - "operationId": "get-shared", - "parameters": [ - { - "description": "The share's link token", - "in": "path", - "name": "token", - "required": true, - "schema": { - "description": "The share's link token", - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PublicShare" - } - } - }, - "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" - } - } - }, - "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, or it is not visible to you." - } - } - }, - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Not Found" - }, - "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" - } - }, - "summary": "Read a shared link", - "tags": [ - "Shares" - ] - } - }, - "/shares": { - "get": { - "operationId": "list-shares", - "parameters": [ - { - "description": "Team TypeID to list a team's shares; omit for the caller's own", - "explode": false, - "in": "query", - "name": "team", - "schema": { - "description": "Team TypeID to list a team's shares; omit for the caller's own", - "type": "string" - } - }, - { - "description": "The last share's ID from the previous page", - "explode": false, - "in": "query", - "name": "cursor", - "schema": { - "description": "The last share's ID from the previous page", - "type": "string" - } - }, - { - "explode": false, - "in": "query", - "name": "limit", - "schema": { - "default": 50, - "format": "int64", - "maximum": 200, - "minimum": 1, - "type": "integer" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ShareList" - } - } - }, - "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": "No such share, or it is not visible to you." - } - } - }, - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Not Found" - }, - "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": "List the caller's shares", - "tags": [ - "Shares" - ] - }, - "post": { - "description": "Needs the shared_links feature. A team share needs a seat in the team.", - "operationId": "create-share", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateShareBody" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreatedShare" - } - } - }, - "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": { - "feature_required": { - "summary": "Feature required", - "value": { - "type": "https://api.tablepro.app/problems/feature-required", - "title": "Feature required", - "status": 403, - "code": "feature_required", - "detail": "Your plan does not include shared_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." - } - }, - "forbidden_2": { - "summary": "Forbidden", - "value": { - "type": "https://api.tablepro.app/problems/forbidden", - "title": "Forbidden", - "status": 403, - "code": "forbidden", - "detail": "A team share needs a seat in the team." - } - } - }, - "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": "No such share, or it is not visible to you." - } - } - }, - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "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 live share limit." - } - } - }, - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Conflict" - }, - "422": { - "content": { - "application/problem+json": { - "examples": { - "snapshot_too_large": { - "summary": "Snapshot too large", - "value": { - "type": "https://api.tablepro.app/problems/snapshot-too-large", - "title": "Snapshot too large", - "status": 422, - "code": "snapshot_too_large", - "detail": "The result snapshot is over the hard limit." - } - } - }, - "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": "Create a share link", - "tags": [ - "Shares" - ] - } - }, - "/shares/{id}": { - "delete": { - "description": "The link stops working at once.", - "operationId": "delete-share", - "parameters": [ - { - "description": "Share TypeID", - "in": "path", - "name": "id", - "required": true, - "schema": { - "description": "Share 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": "No such share, or it is not visible to you." - } - } - }, - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Not Found" - }, - "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": "Revoke a share", - "tags": [ - "Shares" - ] - }, - "get": { - "operationId": "get-share", - "parameters": [ - { - "description": "Share TypeID", - "in": "path", - "name": "id", - "required": true, - "schema": { - "description": "Share TypeID", - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ShareView" - } - } - }, - "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": "No such share, or it is not visible to you." - } - } - }, - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Not Found" - }, - "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": "Get one share, with its link", - "tags": [ - "Shares" - ] - }, - "patch": { - "operationId": "update-share", - "parameters": [ - { - "description": "Share TypeID", - "in": "path", - "name": "id", - "required": true, - "schema": { - "description": "Share TypeID", - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateShareBody" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ShareView" - } - } - }, - "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": "No such share, or it is not visible to you." - } - } - }, - "schema": { - "$ref": "#/components/schemas/Problem" - } - } - }, - "description": "Not Found" - }, - "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": "Change a share's title, note or expiry", - "tags": [ - "Shares" - ] - } - }, "/teams": { "get": { "description": "With the caller's role and seat in each, in the order the account joined them. App sign-ins only.", diff --git a/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift b/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift index 0cecfd6ad8..7844ea8b62 100644 --- a/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift +++ b/apple/TablePro/Core/DataGrid/DataGridOwnerProtocols.swift @@ -12,7 +12,6 @@ enum DataGridCommand: Hashable, CaseIterable { case hideColumns case showRowsAsJSON case exportResults - case shareResult case clearResults case searchAllRows case navigateForeignKey @@ -96,7 +95,6 @@ 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) @@ -129,7 +127,6 @@ 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/Events/AppCommands.swift b/apple/TablePro/Core/Events/AppCommands.swift index 762e164293..e7fc785a16 100644 --- a/apple/TablePro/Core/Events/AppCommands.swift +++ b/apple/TablePro/Core/Events/AppCommands.swift @@ -102,7 +102,6 @@ final class AppCommands { // MARK: - File / Connection Import-Export let openSQLFiles = PassthroughSubject<[URL], Never>() - let openSharedSQL = PassthroughSubject<[String], Never>() private init() {} } diff --git a/apple/TablePro/Core/Services/Account/AccountAPI.swift b/apple/TablePro/Core/Services/Account/AccountAPI.swift index 2ce3944d3b..d228807de4 100644 --- a/apple/TablePro/Core/Services/Account/AccountAPI.swift +++ b/apple/TablePro/Core/Services/Account/AccountAPI.swift @@ -20,20 +20,6 @@ internal enum AccountAPI { ) } - // A client with no bearer token, for the public read (GET /v2/shared/{token}): a share a recipient opens may be - // viewed while signed out. - static func publicClient( - configuration: AccountConfiguration, - transport: any ClientTransport - ) -> Client { - Client( - serverURL: configuration.apiServerURL, - configuration: Configuration(dateTranscoder: RFC3339DateTranscoder()), - transport: transport, - middlewares: [] - ) - } - static func transport(session: URLSession) -> any ClientTransport { URLSessionTransport(configuration: .init(session: session)) } diff --git a/apple/TablePro/Core/Services/Account/AccountServices.swift b/apple/TablePro/Core/Services/Account/AccountServices.swift index a05b4579e8..298881d777 100644 --- a/apple/TablePro/Core/Services/Account/AccountServices.swift +++ b/apple/TablePro/Core/Services/Account/AccountServices.swift @@ -51,8 +51,6 @@ internal final class AccountServices { let devices: DeviceRegistry let access: FeatureAccess let api: any APIProtocol - // No bearer token, for the public share read. - let publicAPI: any APIProtocol let events = PassthroughSubject() private let entitlements: EntitlementStore private let legacy: LegacyLicenseStore @@ -94,7 +92,6 @@ internal final class AccountServices { onRefused: { Task { @MainActor in refusals.services?.sessionWasRefused() } } ) self.api = AccountAPI.client(configuration: configuration, transport: transport, session: session) - self.publicAPI = AccountAPI.publicClient(configuration: configuration, transport: transport) 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 87cf0a240b..323be30207 100644 --- a/apple/TablePro/Core/Services/Infrastructure/AppActivationPolicy.swift +++ b/apple/TablePro/Core/Services/Infrastructure/AppActivationPolicy.swift @@ -80,7 +80,6 @@ internal extension LaunchIntent { .openDatabaseFile, .openDataFile, .openConnectionShare, - .openShare, .pairIntegration, .openDatabaseURL, .installPlugin, diff --git a/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift b/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift index c7f4ddf9bb..236defed2d 100644 --- a/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift +++ b/apple/TablePro/Core/Services/Infrastructure/DeeplinkParser.swift @@ -65,23 +65,11 @@ internal enum DeeplinkParser { return parseIntegrations(url) case "settings": return parseSettings(url) - case "share": - return parseShare(url) default: return .failure(.unknownHost(host)) } } - private static func parseShare(_ url: URL) -> Result { - guard let token = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems? - .first(where: { $0.name == "token" })?.value, - !token.isEmpty - else { - return .failure(.missingRequiredParam("token")) - } - return .success(.openShare(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/LaunchIntent.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift index 3d48ae6fda..c7cb643940 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntent.swift @@ -23,7 +23,6 @@ internal enum LaunchIntent: @unchecked Sendable { case openDatabaseFile(URL, DatabaseType) case openDataFile(URL) case openConnectionShare(URL) - case openShare(token: String) case pairIntegration(PairingRequest) case startMCPServer /// nil opens the last-used pane. @@ -47,7 +46,6 @@ internal enum LaunchIntent: @unchecked Sendable { .openSQLFile, .importConnection, .openConnectionShare, - .openShare, .pairIntegration, .startMCPServer, .openSettings, diff --git a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift index 397164c7b1..5842ab53a5 100644 --- a/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/LaunchIntentRouter.swift @@ -1,7 +1,6 @@ import AppKit import Foundation import os -import TableProCloudAPI @MainActor internal final class LaunchIntentRouter { @@ -45,9 +44,6 @@ internal final class LaunchIntentRouter { case .installPlugin(let url): try await installPlugin(url) - - case .openShare(let token): - try await openShare(token: token) } } catch let error where error.isUserCancellation { Self.logger.info("Intent cancelled: \(error.publicLogShape, privacy: .public)") @@ -57,41 +53,6 @@ internal final class LaunchIntentRouter { } } - private func openShare(token: String) async throws { - let client = ShareClient(api: AccountServices.shared.publicAPI) - let share: Components.Schemas.PublicShare - do throws(ShareFailure) { - share = try await client.view(token: token) - } catch { - presentShareUnavailable(error) - return - } - let opened = try await TabRouter.shared.openSharedQuery(sql: share.sql) - if !opened { - // No connected database to open against. Queue the SQL the way openSQLFile does, so it - // opens once the user connects one, and show where to do that. - WelcomeRouter.shared.enqueueSharedSQL(share.sql) - } - } - - private func presentShareUnavailable(_ failure: ShareFailure) { - let message: String - switch failure { - case .canceled: - return - case .notFound: - message = String(localized: "This shared link is no longer available.") - case .offline: - message = String(localized: "You appear to be offline. Try again once you're connected.") - case .rateLimited: - message = String(localized: "Too many requests just now. Try again in a moment.") - case .signedOut, .featureRequired, .forbidden, .limitReached, .refused, .server: - message = String(localized: "The shared query couldn't be opened.") - } - AppActivationPolicyController.shared.activate(ignoringOtherApps: true) - AlertHelper.showInfoSheet(title: String(localized: "Open Shared Query"), message: message, window: nil) - } - private func openDataFileDocument(at url: URL) async throws { Self.logger.debug("LaunchIntentRouter.openDataFileDocument - calling NSDocumentController.shared (\(String(describing: Swift.type(of: NSDocumentController.shared)), privacy: .public)).openDocument for \(url.lastPathComponent, privacy: .private(mask: .hash))") try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in @@ -202,7 +163,7 @@ internal final class LaunchIntentRouter { title = String(localized: "Connection Failed") case .openSQLFile, .openDataFile: title = String(localized: "Could Not Open File") - case .importConnection, .openConnectionShare, .openShare, .startMCPServer, .openSettings: + case .importConnection, .openConnectionShare, .startMCPServer, .openSettings: title = String(localized: "Action Failed") } if presentRecoverableError(error, for: intent, title: title) { return } diff --git a/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift b/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift index 352b10da8f..4c917cc3e1 100644 --- a/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/TabRouter.swift @@ -475,20 +475,6 @@ internal final class TabRouter { // MARK: - SQL File - /// Opens a shared query's SQL in the connection the user is looking at, like a SQL file but seeded from text. - /// Returns false when no connection is open, so the caller can tell the user to connect first. - @discardableResult - internal func openSharedQuery(sql: String) async throws -> 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 } - try await openQuery(connectionId: target, sql: sql) - return true - } - private func openSQLFile(_ url: URL) async throws { if HostedTabRouting.live.revealTab(editing: url) { AppActivationPolicyController.shared.activate(ignoringOtherApps: true) diff --git a/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift b/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift index 0b5b3520ed..bc6e9d7ee3 100644 --- a/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift +++ b/apple/TablePro/Core/Services/Infrastructure/WelcomeRouter.swift @@ -43,7 +43,6 @@ 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 pendingSharedSQL: [String] = [] @Published private(set) var pendingError: PendingConnectionError? @Published private(set) var pendingPluginInstall: DatabaseConnection? @@ -54,7 +53,6 @@ internal final class WelcomeRouter: ObservableObject { .receive(on: RunLoop.main) .sink { [weak self] _ in self?.drainPendingSQLFiles() - self?.drainPendingSharedSQL() } } @@ -64,12 +62,6 @@ internal final class WelcomeRouter: ObservableObject { AppCommands.shared.openSQLFiles.send(urls) } - private func drainPendingSharedSQL() { - let statements = consumePendingSharedSQL() - guard !statements.isEmpty else { return } - AppCommands.shared.openSharedSQL.send(statements) - } - internal func route(_ request: WelcomeRequest) { pendingRequest = request showWelcomeWindow() @@ -105,19 +97,6 @@ internal final class WelcomeRouter: ObservableObject { pendingSQLFiles.append(url) } - // A shared query arriving with no connected database: hold its SQL and show where to connect, the - // way routeShare does for a connection share. It opens on the next databaseDidConnect. - internal func enqueueSharedSQL(_ sql: String) { - pendingSharedSQL.append(sql) - showWelcomeWindow() - } - - internal func consumePendingSharedSQL() -> [String] { - let value = pendingSharedSQL - pendingSharedSQL.removeAll() - return value - } - internal func consumePendingImport() -> ConnectionBundle? { let value = pendingImport pendingImport = nil diff --git a/apple/TablePro/Core/Services/Shares/ShareClient.swift b/apple/TablePro/Core/Services/Shares/ShareClient.swift deleted file mode 100644 index 6949b14179..0000000000 --- a/apple/TablePro/Core/Services/Shares/ShareClient.swift +++ /dev/null @@ -1,163 +0,0 @@ -// -// ShareClient.swift -// TablePro -// - -import Foundation -import TableProCloudAPI - -internal enum ShareFailure: Error, Equatable, Sendable { - case offline - // The request was cancelled (torn down, superseded). Nothing to tell the user. - case canceled - case rateLimited - case server - case signedOut - // The account's plan does not include shared_links. - case featureRequired - // A team share without a seat, or a share not the caller's to manage. - case forbidden - // Unknown, revoked, or expired. - case notFound - // The account holds its live-share cap. - case limitReached - // The server refused the request as sent (422); sending it again changes nothing. - case refused - - var isRetryable: Bool { - switch self { - case .offline, .rateLimited, .server: - return true - case .canceled, .signedOut, .featureRequired, .forbidden, .notFound, .limitReached, .refused: - return false - } - } - - // The message a create flow (a favorite, a result) shows, or nil when there is nothing to say. - var createMessage: String? { - switch self { - case .canceled: - return nil - case .featureRequired: - return String(localized: "Sharing links needs a paid plan.") - case .signedOut: - return String(localized: "Sign in to your account to share links.") - case .limitReached: - return String(localized: "You've reached your share limit. Revoke a link and try again.") - case .offline: - return String(localized: "You appear to be offline. Try again once you're connected.") - case .rateLimited: - return String(localized: "Too many shares just now. Try again in a moment.") - case .forbidden, .notFound, .refused, .server: - return String(localized: "The link couldn't be created. Try again.") - } - } - - static func from(_ error: AccountError) -> ShareFailure { - switch error { - case .canceled: - return .canceled - case .signedOut: - return .signedOut - case .server(let status, _) where status == 401: - return .signedOut - case .server(let status, _) where status == 429: - return .rateLimited - case .server(let status, _) where status >= 500: - return .server - case .server: - return .refused - case .network: - return .offline - default: - // An OAuth, decode, or state error is not "offline"; treat it as a server-side problem. - return .server - } - } -} - -internal struct CreatedShareLink: Sendable { - let id: String - let token: String - let url: String -} - -// The /v2 share calls go through the generated client, which carries the session's access token. The public read -// needs no token, but sending one is harmless. -internal struct ShareClient: Sendable { - let api: any APIProtocol - - func createQuery(title: String, sql: String, note: String?, dialect: String?) async throws(ShareFailure) -> CreatedShareLink { - try await create(body: .init(dialect: dialect, kind: "query", note: note, sql: sql, title: title)) - } - - func createResult( - title: String, - sql: String, - note: String?, - dialect: String?, - snapshot: Components.Schemas.SnapshotInput - ) async throws(ShareFailure) -> CreatedShareLink { - try await create(body: .init(dialect: dialect, kind: "result", note: note, snapshot: snapshot, sql: sql, title: title)) - } - - private func create(body: Components.Schemas.CreateShareBody) async throws(ShareFailure) -> CreatedShareLink { - do { - switch try await api.createShare(body: .json(body)) { - case .ok(let answer): - let created = try answer.body.json - return CreatedShareLink(id: created.id, token: created.token, url: created.url) - case .unauthorized: - throw ShareFailure.signedOut - case .forbidden(let answer): - let problem = try answer.body.applicationProblemJson - throw problem.code == "feature_required" ? ShareFailure.featureRequired : .forbidden - case .notFound: - throw ShareFailure.notFound - case .conflict: - throw ShareFailure.limitReached - case .unprocessableContent: - throw ShareFailure.refused - case .tooManyRequests(let answer): - throw ShareFailure.rateLimited - case .internalServerError: - throw ShareFailure.server - case .undocumented(let status, _): - throw Self.undocumented(status) - } - } catch let failure as ShareFailure { - throw failure - } catch { - throw ShareFailure.from(AccountError.from(error)) - } - } - - func view(token: String) async throws(ShareFailure) -> Components.Schemas.PublicShare { - do { - switch try await api.getShared(path: .init(token: token)) { - case .ok(let answer): - return try answer.body.json - case .notFound, .unprocessableContent: - throw ShareFailure.notFound - case .tooManyRequests(let answer): - throw ShareFailure.rateLimited - case .internalServerError: - throw ShareFailure.server - case .undocumented(let status, _): - throw Self.undocumented(status) - } - } catch let failure as ShareFailure { - throw failure - } catch { - throw ShareFailure.from(AccountError.from(error)) - } - } - - private static func undocumented(_ status: Int) -> ShareFailure { - switch status { - case 429: .rateLimited - case 500...: .server - default: .refused - } - } -} diff --git a/apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift b/apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift deleted file mode 100644 index d9362506ac..0000000000 --- a/apple/TablePro/Core/Utilities/SQL/ResultSnapshotBuilder.swift +++ /dev/null @@ -1,168 +0,0 @@ -// -// ResultSnapshotBuilder.swift -// TablePro -// - -import Foundation -import TableProCloudAPI -import TableProPluginKit - -// Turns a displayed result into a share snapshot. Lossless on the web viewer: a value wider than a -// JS safe integer, or a high-precision decimal, goes as a string so no digit is rounded away; safe -// numbers go as JSON numbers so the viewer right-aligns them. -enum ResultSnapshotBuilder { - static let maxRows = 10_000 - static let maxColumns = 100 - // Per cell, under the server's 256 KB/cell cap. The snapshot budget is counted on the uncompressed - // bytes and kept under the server's 5 MB compressed cap: gzip never expands, so staying under 4.5 MB - // uncompressed stays under 5 MB compressed, and a deterministic 422 never surprises the user. - static let maxCellBytes = 64 * 1_024 - static let maxSnapshotBytes = 4_500_000 - - struct Built { - let snapshot: Components.Schemas.SnapshotInput - let rowsSent: Int - } - - // totalRowCount: the result's true total when known; nil when the result was cut short with no count. - // moreRowsAvailable: the result had rows beyond those loaded. - static func build( - from read: DisplayedResultReader.Output, - totalRowCount: Int?, - moreRowsAvailable: Bool - ) -> Built { - var truncated = false - - var columnNames = read.columns - var columnTypes = read.columnTypes - if columnNames.count > maxColumns { - columnNames = Array(columnNames.prefix(maxColumns)) - columnTypes = Array(columnTypes.prefix(maxColumns)) - truncated = true - } - let columns = columnNames.enumerated().map { index, name in - Components.Schemas.ColumnJSON(name: name, _type: columnTypeLabel(columnTypes, at: index)) - } - - var rows: [[OpenAPIValueContainer]?] = [] - var bytes = 0 - for row in read.rows { - if rows.count >= maxRows { truncated = true; break } - var cells: [OpenAPIValueContainer] = [] - var rowBytes = 0 - for index in 0 ..< columnNames.count { - let type = columnTypes.indices.contains(index) ? columnTypes[index] : .text(rawType: nil) - let cell = row.indices.contains(index) ? row[index] : .null - let encoded = SnapshotCellEncoder.encode(cell, type: type) - rowBytes += encoded.byteCount - cells.append(encoded.value) - } - if !rows.isEmpty, bytes + rowBytes > maxSnapshotBytes { truncated = true; break } - bytes += rowBytes - rows.append(cells) - } - - if moreRowsAvailable { truncated = true } - if let total = totalRowCount, total > rows.count { truncated = true } - - let rowCount: Int64? - if let total = totalRowCount, total > rows.count { - rowCount = Int64(total) - } else { - rowCount = nil - } - - let snapshot = Components.Schemas.SnapshotInput( - columns: columns, - rowCount: rowCount, - rows: rows, - truncated: truncated - ) - return Built(snapshot: snapshot, rowsSent: rows.count) - } - - private static func columnTypeLabel(_ types: [ColumnType], at index: Int) -> String? { - guard types.indices.contains(index) else { return nil } - return types[index].rawType ?? types[index].displayName - } -} - -// The cell mapping, factored out so it can be tested without a result set. -enum SnapshotCellEncoder { - struct Encoded { - let value: OpenAPIValueContainer - let byteCount: Int - } - - // 2^53 - 1: the largest integer a JS number holds exactly, so the viewer's JSON.parse keeps it. - static let safeIntegerMagnitude: Int64 = 9_007_199_254_740_991 - - static func encode(_ cell: PluginCellValue, type: ColumnType) -> Encoded { - switch cell { - case .null: - return Encoded(value: OpenAPIValueContainer(nilLiteral: ()), byteCount: 4) - case .bytes(let data): - return string("(binary, \(data.count) bytes)") - case .text(let value): - return encodeText(value, type: type) - } - } - - private static func encodeText(_ value: String, type: ColumnType) -> Encoded { - switch type { - case .boolean: - return encodeBoolean(value) - case .integer: - return encodeInteger(value) - case .decimal: - return encodeDecimal(value) - case .text, .date, .timestamp, .datetime, .json, .blob, - .enumType, .set, .spatial, .vector, .array: - return string(value) - } - } - - private static func encodeBoolean(_ value: String) -> Encoded { - switch value.lowercased() { - case "true", "1", "yes", "on": - return Encoded(value: OpenAPIValueContainer(booleanLiteral: true), byteCount: 4) - case "false", "0", "no", "off": - return Encoded(value: OpenAPIValueContainer(booleanLiteral: false), byteCount: 5) - default: - // MySQL's BOOLEAN is TINYINT(1), which also stores 2 or -1. - return encodeInteger(value) - } - } - - private static func encodeInteger(_ value: String) -> Encoded { - guard let literal = JsonNumberNormalizer.integerLiteral(from: value) else { - return string(value) - } - if let number = Int64(literal), (-safeIntegerMagnitude ... safeIntegerMagnitude).contains(number) { - return Encoded(value: OpenAPIValueContainer(integerLiteral: Int(number)), byteCount: literal.utf8.count) - } - return string(literal) - } - - private static func encodeDecimal(_ value: String) -> Encoded { - guard let literal = JsonNumberNormalizer.numberLiteral(from: value) else { - return string(value) - } - if let double = Double(literal), double.isFinite, - JsonNumberNormalizer.numberLiteral(from: String(double)) == literal { - return Encoded(value: OpenAPIValueContainer(floatLiteral: double), byteCount: literal.utf8.count) - } - return string(literal) - } - - private static func string(_ value: String) -> Encoded { - let capped = capped(value) - return Encoded(value: OpenAPIValueContainer(stringLiteral: capped), byteCount: capped.utf8.count) - } - - private static func capped(_ value: String) -> String { - guard value.utf8.count > ResultSnapshotBuilder.maxCellBytes else { return value } - let prefix = String(value.prefix(ResultSnapshotBuilder.maxCellBytes / 4)) - return prefix + "…" - } -} diff --git a/apple/TablePro/Models/Settings/ProFeature.swift b/apple/TablePro/Models/Settings/ProFeature.swift index 0b21c0f340..741fb45c3c 100644 --- a/apple/TablePro/Models/Settings/ProFeature.swift +++ b/apple/TablePro/Models/Settings/ProFeature.swift @@ -17,7 +17,6 @@ internal enum ProFeature: String, CaseIterable { case teamLibrary = "team_library" case compareSync = "compare_sync" case dataRewind = "data_rewind" - case sharedLinks = "shared_links" var displayName: String { switch self { @@ -41,8 +40,6 @@ internal enum ProFeature: String, CaseIterable { return String(localized: "Compare & Sync") case .dataRewind: return String(localized: "Data Rewind") - case .sharedLinks: - return String(localized: "Share Links") } } @@ -68,8 +65,6 @@ internal enum ProFeature: String, CaseIterable { return "arrow.left.arrow.right.square" case .dataRewind: return "clock.arrow.circlepath" - case .sharedLinks: - return "link" } } @@ -95,8 +90,6 @@ internal enum ProFeature: String, CaseIterable { return String(localized: "Compare structure or data between two connections and generate the sync script.") case .dataRewind: return String(localized: "Restore the previous values of rows you already saved.") - case .sharedLinks: - return String(localized: "Share a query, or a query and its results, as a public link anyone can open in a browser.") } } diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 97384044b1..aa4f93e18d 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -16685,12 +16685,6 @@ "A point's id cannot change. Insert a new row with the new id instead." : { "extractionState" : "manual", "generatesSymbol" : false - }, - "A public link to this query is on your clipboard." : { - - }, - "A public link to this result is on your clipboard." : { - }, "A publish to the team library is still running. Try again when it finishes." : { @@ -128371,9 +128365,6 @@ } } } - }, - "Open a database connection, then open the link again." : { - }, "Open a database to browse its tables." : { "localizations" : { @@ -129802,9 +129793,6 @@ } } } - }, - "Open Shared Query" : { - }, "Open Source Libraries" : { "localizations" : { @@ -166122,9 +166110,6 @@ } } } - }, - "Share a query, or a query and its results, as a public link anyone can open in a browser." : { - }, "Share anonymous usage data" : { "extractionState" : "stale", @@ -166206,21 +166191,6 @@ } } } - }, - "Share Link" : { - - }, - "Share Link…" : { - - }, - "Share Links" : { - - }, - "Share Result" : { - - }, - "Share Result…" : { - }, "Share usage data" : { "localizations" : { @@ -166264,9 +166234,6 @@ }, "Share Used" : { - }, - "Sharing links needs a paid plan." : { - }, "Sheet" : { "localizations" : { @@ -169380,9 +169347,6 @@ }, "Sign in to Vault with your browser?" : { - }, - "Sign in to your account to share links." : { - }, "Sign In With" : { @@ -190818,9 +190782,6 @@ } } } - }, - "The link couldn't be created. Try again." : { - }, "The list of allowed values is not carried over." : { "localizations" : { @@ -194444,9 +194405,6 @@ }, "The settings it was created with could not be read, so it gets the target's own." : { - }, - "The shared query couldn't be opened." : { - }, "The shell drops a field named __proto__ from a new document. Remove the field, then set it on the saved document." : { "extractionState" : "manual", @@ -203228,9 +203186,6 @@ } } } - }, - "This shared link is no longer available." : { - }, "This shortcut is reserved by macOS and cannot be assigned." : { "localizations" : { @@ -205920,15 +205875,9 @@ } } } - }, - "Too many requests just now. Try again in a moment." : { - }, "Too many rows. Add up to %lld rows at a time." : { - }, - "Too many shares just now. Try again in a moment." : { - }, "Tool" : { "localizations" : { @@ -219640,9 +219589,6 @@ } } } - }, - "You appear to be offline. Try again once you're connected." : { - }, "You have no saved queries to publish." : { "localizations" : { @@ -219773,9 +219719,6 @@ }, "You're signed in" : { - }, - "You've reached your share limit. Revoke a link and try again." : { - }, "You've used TablePro on %lld days" : { "localizations" : { diff --git a/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowMenu.swift b/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowMenu.swift index 1c237e2da6..5b754272d6 100644 --- a/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowMenu.swift +++ b/apple/TablePro/Views/DataGrid/Commands/DataGridViewController+RowMenu.swift @@ -209,9 +209,6 @@ extension DataGridViewController { if gridCommands.offers(.exportResults) { items.append(menuItem(String(localized: "Export Results…"), #selector(exportResultsFromMenu(_:)), context)) } - if gridCommands.offers(.shareResult), FeatureAccess.shared.isAvailable(.sharedLinks) { - items.append(menuItem(String(localized: "Share Result…"), #selector(shareResultFromMenu(_:)), context)) - } if gridCommands.offers(.clearResults) { items.append(menuItem(String(localized: "Clear Results"), #selector(clearResultsFromMenu(_:)), context)) } @@ -241,7 +238,6 @@ extension DataGridViewController { #selector(DataGridViewController.applySetValueFromMenu(_:)), #selector(DataGridViewController.removeFieldFromMenu(_:)), #selector(DataGridViewController.exportResultsFromMenu(_:)), - #selector(DataGridViewController.shareResultFromMenu(_:)), #selector(DataGridViewController.clearResultsFromMenu(_:)), #selector(DataGridViewController.duplicateRowsFromMenu(_:)), #selector(DataGridViewController.copySummaryFigureFromMenu(_:)), @@ -269,10 +265,6 @@ 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/Main/Child/DataTabGridAdapter.swift b/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift index a463a7077b..0b608aae63 100644 --- a/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift +++ b/apple/TablePro/Views/Main/Child/DataTabGridAdapter.swift @@ -184,11 +184,6 @@ 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/Extensions/MainContentCoordinator+GridModels.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+GridModels.swift index e257f4de58..7dbdd9665a 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, .shareResult, .navigateForeignKey, + .hideColumns, .showRowsAsJSON, .exportResults, .navigateForeignKey, .highlightValues, .displayAs, .freezeColumns, .valueFilter ] let operations = isEditable ? (activeViewWriteTarget?.operations ?? .all) : [] diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift deleted file mode 100644 index 697d95af34..0000000000 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ShareResult.swift +++ /dev/null @@ -1,67 +0,0 @@ -// -// MainContentCoordinator+ShareResult.swift -// TablePro -// - -import Foundation - -extension MainContentCoordinator { - // Shares the active result as a public link: the selected rows, or the whole loaded result when - // nothing is selected, capped and sent to the share service, then the URL is put on the clipboard. - func shareActiveResult() { - guard FeatureAccess.shared.isAvailable(.sharedLinks) else { return } - guard !isSharingInFlight, let tab = tabManager.selectedTab else { return } - let tableRows = tabSessionRegistry.tableRows(for: tab.id) - guard !tableRows.rows.isEmpty else { return } - - let model = gridModel(forTab: tab.id) - let selectedDisplayIndices = Set(model.selectedRowIDs.compactMap { model.displayIndex(of: $0) }) - let hasSelection = !selectedDisplayIndices.isEmpty - let projection = VisibleColumnProjection(indices: model.columns.columns.map(\.dataIndex)) - let read = DisplayedResultReader.read( - tableRows: tableRows, - displayIDs: model.order.filteredIDs, - selectedDisplayIndices: selectedDisplayIndices, - // A row marked for deletion must not land in a public snapshot, as the JSON view already excludes it. - deletedRowIDs: model.changeState?.deletedRowIDs ?? [], - defaultedCells: model.changeState?.defaultedCells(in: tableRows) ?? [:], - columns: projection - ) - guard !read.rows.isEmpty else { return } - - let sql = (tab.pagination.baseQueryForMore ?? tab.content.query) - .trimmingCharacters(in: .whitespacesAndNewlines) - guard !sql.isEmpty else { return } - - let built = ResultSnapshotBuilder.build( - from: read, - totalRowCount: hasSelection ? nil : (tab.pagination.hasExactRowCount ? tab.pagination.totalRowCount : nil), - moreRowsAvailable: hasSelection ? false : tab.pagination.hasMoreRows - ) - - let window = contentWindow - isSharingInFlight = true - Task { @MainActor in - defer { isSharingInFlight = false } - let client = ShareClient(api: AccountServices.shared.api) - do throws(ShareFailure) { - let link = try await client.createResult( - title: tab.title, - sql: sql, - note: nil, - dialect: connection.type.rawValue, - snapshot: built.snapshot - ) - ClipboardService.shared.writeText(link.url) - AlertHelper.showInfoSheet( - title: String(localized: "Share Result"), - message: String(localized: "A public link to this result is on your clipboard."), - window: window - ) - } catch { - guard let message = error.createMessage else { return } - AlertHelper.showInfoSheet(title: String(localized: "Share Result"), message: message, window: window) - } - } - } -} diff --git a/apple/TablePro/Views/Main/MainContentCommandActions.swift b/apple/TablePro/Views/Main/MainContentCommandActions.swift index 174389b6da..c7c1904a51 100644 --- a/apple/TablePro/Views/Main/MainContentCommandActions.swift +++ b/apple/TablePro/Views/Main/MainContentCommandActions.swift @@ -1404,13 +1404,8 @@ final class MainContentCommandActions: ObservableObject { observeKeyWindowOnly(AppCommands.shared.openSQLFiles) { [weak self] urls in self?.handleOpenSQLFiles(urls) } - observeKeyWindowOnly(AppCommands.shared.openSharedSQL) { [weak self] statements in - self?.handleOpenSharedSQL(statements) - } } -} -extension MainContentCommandActions { private func handleOpenSQLFiles(_ urls: [URL]) { Task { for url in urls { @@ -1426,14 +1421,6 @@ extension MainContentCommandActions { } } } - - private func handleOpenSharedSQL(_ statements: [String]) { - Task { - for sql in statements { - _ = try? await TabRouter.shared.openSharedQuery(sql: sql) - } - } - } } extension MainContentCommandActions { diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index 3be7b9ed0d..465beded46 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -129,8 +129,6 @@ enum ActiveSheet: Identifiable { @MainActor final class MainContentCoordinator: ObservableObject { - // Set while a Share Result request is in flight, so a second click does not mint a duplicate link. - var isSharingInFlight = false nonisolated static let logger = Logger(subsystem: "com.TablePro", category: "MainContentCoordinator") nonisolated static let lifecycleLogger = Logger(subsystem: "com.TablePro", category: "NativeTabLifecycle") diff --git a/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift b/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift index 5d103f2c7b..ea9a7aec47 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesOutlineCoordinator.swift @@ -329,7 +329,6 @@ internal final class FavoritesOutlineCoordinator: NSObject, NSOutline allFolders: owner.input.allFolders, teamLibraryTeams: owner.input.teamLibraryTeams, hasTeamLibraryConflicts: owner.input.hasTeamLibraryConflicts, - canShare: owner.input.canShare, databaseEntityName: owner.input.databaseEntityName, activeDatabase: owner.input.activeDatabase, linkedFileGitStates: owner.input.linkedFileGitStates, diff --git a/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift b/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift index 6d6e412fb6..791943c252 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesOutlineView.swift @@ -22,7 +22,6 @@ internal struct FavoritesOutlineInput { internal let allFolders: [SQLFavoriteFolder] internal let teamLibraryTeams: [TeamLibraryTeam] internal let hasTeamLibraryConflicts: Bool - internal var canShare: Bool = false internal var linkedFileGitStates: [UUID: LinkedFileGitState] = [:] internal var linkedFolderGitStates: [UUID: LinkedFolderGitMenuState] = [:] } diff --git a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift index 244de2129b..1c56a97245 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift @@ -18,8 +18,6 @@ internal struct FavoritesTabView: View { @State private var favoriteDatabases: Set = [] @State private var folderToDelete: SQLFavoriteFolder? @State private var showDeleteFolderAlert = false - // Set while a Share Link request is in flight, so a second click does not mint a duplicate link. - @State private var isSharing = false @State private var linkedFileToTrash: LinkedSQLFavorite? @State private var showTrashLinkedFileAlert = false @State private var linkedMetadataTarget: LinkedSQLFavorite? @@ -323,27 +321,6 @@ internal struct FavoritesTabView: View { ) } - private func shareFavorite(_ favorite: SQLFavorite) { - guard !isSharing else { return } - isSharing = true - Task { @MainActor in - defer { isSharing = false } - let client = ShareClient(api: AccountServices.shared.api) - do throws(ShareFailure) { - let link = try await client.createQuery(title: favorite.name, sql: favorite.query, note: nil, dialect: nil) - ClipboardService.shared.writeText(link.url) - AlertHelper.showInfoSheet( - title: String(localized: "Share Link"), - message: String(localized: "A public link to this query is on your clipboard."), - window: nil - ) - } catch { - guard let message = error.createMessage else { return } - AlertHelper.showInfoSheet(title: String(localized: "Share Link"), message: message, window: nil) - } - } - } - private func presentTeamLibraryInfo(_ message: String) { AlertHelper.showInfoSheet( title: String(localized: "Team Library"), @@ -373,7 +350,6 @@ internal struct FavoritesTabView: View { allFolders: viewModel.nodes.collectFolders(), teamLibraryTeams: featureAccess.isAvailable(.teamLibrary) ? teamLibrarySync.writableTeams : [], hasTeamLibraryConflicts: !teamLibrarySync.conflicts.isEmpty, - canShare: featureAccess.isAvailable(.sharedLinks), linkedFileGitStates: gitStatusStore.states(for: Self.linkedFavorites(in: items)), linkedFolderGitStates: linkedFolderGitStates ), @@ -659,8 +635,6 @@ internal struct FavoritesTabView: View { viewModel.deleteFavorite(favorite) case .showFavoriteHistory(let favorite): coordinator?.showVersionHistory(of: favorite) - case .shareFavorite(let favorite): - shareFavorite(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 65b66136fb..a34512a5ea 100644 --- a/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuCommand.swift +++ b/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuCommand.swift @@ -26,7 +26,6 @@ internal enum FavoritesMenuCommand: Equatable { case moveFavorite(id: UUID, toFolder: UUID?) case deleteFavorite(SQLFavorite) case showFavoriteHistory(SQLFavorite) - case shareFavorite(SQLFavorite) 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 82b69673cb..c183ecf603 100644 --- a/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift +++ b/apple/TablePro/Views/Sidebar/Menu/FavoritesMenuSpec.swift @@ -16,7 +16,6 @@ internal struct FavoritesMenuContext { internal let allFolders: [SQLFavoriteFolder] internal let teamLibraryTeams: [TeamLibraryTeam] internal let hasTeamLibraryConflicts: Bool - internal let canShare: Bool internal let databaseEntityName: String internal let activeDatabase: String? internal let linkedFileGitStates: [UUID: LinkedFileGitState] @@ -27,7 +26,6 @@ internal struct FavoritesMenuContext { allFolders: [SQLFavoriteFolder] = [], teamLibraryTeams: [TeamLibraryTeam] = [], hasTeamLibraryConflicts: Bool = false, - canShare: Bool = false, databaseEntityName: String = "Database", activeDatabase: String? = nil, linkedFileGitStates: [UUID: LinkedFileGitState] = [:], @@ -37,7 +35,6 @@ internal struct FavoritesMenuContext { self.allFolders = allFolders self.teamLibraryTeams = teamLibraryTeams self.hasTeamLibraryConflicts = hasTeamLibraryConflicts - self.canShare = canShare self.databaseEntityName = databaseEntityName self.activeDatabase = activeDatabase self.linkedFileGitStates = linkedFileGitStates @@ -159,9 +156,6 @@ internal enum FavoritesMenuSpec { .command(String(localized: "Edit…"), .editFavorite(favorite)), .command(String(localized: "Show History"), .showFavoriteHistory(favorite)) ] - if context.canShare { - edits.append(.command(String(localized: "Share Link…"), .shareFavorite(favorite))) - } if let moveTo = moveToSubmenu(favorite, folders: context.allFolders) { edits.append(moveTo) } diff --git a/apple/TableProTests/Core/Services/Infrastructure/DeeplinkShareParsingTests.swift b/apple/TableProTests/Core/Services/Infrastructure/DeeplinkShareParsingTests.swift deleted file mode 100644 index bbf48eeeed..0000000000 --- a/apple/TableProTests/Core/Services/Infrastructure/DeeplinkShareParsingTests.swift +++ /dev/null @@ -1,46 +0,0 @@ -// -// DeeplinkShareParsingTests.swift -// TableProTests -// - -import Foundation -@testable import TablePro -import Testing - -@MainActor -struct DeeplinkShareParsingTests { - private func token(for link: String) throws -> String? { - let url = try #require(URL(string: link)) - guard case .success(.openShare(let token)) = DeeplinkParser.parse(url) else { - return nil - } - return token - } - - @Test("A share link carries its token") - func shareLinkCarriesToken() throws { - #expect(try token(for: "tablepro://share?token=abc123") == "abc123") - } - - @Test("A percent-encoded token is decoded") - func percentEncodedTokenIsDecoded() throws { - #expect(try token(for: "tablepro://share?token=a%2Fb") == "a/b") - } - - @Test("Other query items are ignored") - func otherQueryItemsAreIgnored() throws { - #expect(try token(for: "tablepro://share?from=web&token=abc123") == "abc123") - } - - @Test( - "A link without a usable token fails", - arguments: ["tablepro://share", "tablepro://share?token=", "tablepro://share?t=abc123"] - ) - func missingTokenFails(link: String) throws { - let url = try #require(URL(string: link)) - guard case .failure(.missingRequiredParam("token")) = DeeplinkParser.parse(url) else { - Issue.record("Expected .missingRequiredParam(\"token\") for \(link)") - return - } - } -} diff --git a/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift b/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift index 19f3b7227d..56ee100c6c 100644 --- a/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift +++ b/apple/TableProTests/Core/Services/Infrastructure/WelcomeRouterTests.swift @@ -72,17 +72,6 @@ final class WelcomeRouterTests { #expect(selected == .mysql) } - @Test - func sharedSQLEnqueuesInOrderAndDrainsOnce() { - router.enqueueSharedSQL("SELECT 1") - router.enqueueSharedSQL("SELECT 2") - - #expect(router.pendingSharedSQL == ["SELECT 1", "SELECT 2"]) - #expect(router.consumePendingSharedSQL() == ["SELECT 1", "SELECT 2"]) - #expect(router.pendingSharedSQL.isEmpty) - #expect(router.consumePendingSharedSQL().isEmpty) - } - @Test func requestSlotIsIndependentOfTheOtherPendingSlots() { let connection = DatabaseConnection(name: "Test", type: .mysql) diff --git a/apple/TableProTests/Core/Utilities/ResultSnapshotBuilderTests.swift b/apple/TableProTests/Core/Utilities/ResultSnapshotBuilderTests.swift deleted file mode 100644 index 5acfb5e7fe..0000000000 --- a/apple/TableProTests/Core/Utilities/ResultSnapshotBuilderTests.swift +++ /dev/null @@ -1,100 +0,0 @@ -// -// ResultSnapshotBuilderTests.swift -// TableProTests -// - -import Foundation -@testable import TablePro -import TableProCloudAPI -import TableProPluginKit -import Testing - -struct ResultSnapshotBuilderTests { - private func cell(_ value: PluginCellValue, _ type: ColumnType) -> OpenAPIValueContainer { - SnapshotCellEncoder.encode(value, type: type).value - } - - @Test("A safe integer stays a JSON number") - func safeIntegerIsNumber() { - #expect(cell(.text("42"), .integer(rawType: "int")) == OpenAPIValueContainer(integerLiteral: 42)) - #expect(cell(.text("42.0"), .integer(rawType: "int")) == OpenAPIValueContainer(integerLiteral: 42)) - #expect(cell(.text("9007199254740991"), .integer(rawType: "bigint")) == OpenAPIValueContainer(integerLiteral: 9_007_199_254_740_991)) - } - - @Test("An integer past 2^53 is a string, lossless") - func bigIntegerIsString() { - #expect(cell(.text("9007199254740993"), .integer(rawType: "bigint")) == OpenAPIValueContainer(stringLiteral: "9007199254740993")) - #expect(cell(.text("-12345678901234567890"), .integer(rawType: "numeric")) == OpenAPIValueContainer(stringLiteral: "-12345678901234567890")) - } - - @Test("A decimal that round-trips is a number; high precision is a string") - func decimalPrecision() { - #expect(cell(.text("3.14"), .decimal(rawType: "double")) == OpenAPIValueContainer(floatLiteral: 3.14)) - #expect(cell(.text("0.12345678901234567890123"), .decimal(rawType: "numeric")) == OpenAPIValueContainer(stringLiteral: "0.12345678901234567890123")) - } - - @Test("Booleans normalize, including TINYINT(1) values") - func booleans() { - #expect(cell(.text("1"), .boolean(rawType: "bool")) == OpenAPIValueContainer(booleanLiteral: true)) - #expect(cell(.text("false"), .boolean(rawType: "bool")) == OpenAPIValueContainer(booleanLiteral: false)) - #expect(cell(.text("2"), .boolean(rawType: "tinyint")) == OpenAPIValueContainer(integerLiteral: 2)) - } - - @Test("Null, bytes and text") - func otherTypes() { - #expect(cell(.null, .text(rawType: nil)) == OpenAPIValueContainer(nilLiteral: ())) - #expect(cell(.bytes(Data(count: 1_024)), .blob(rawType: "blob")) == OpenAPIValueContainer(stringLiteral: "(binary, 1024 bytes)")) - #expect(cell(.text("hello"), .text(rawType: "text")) == OpenAPIValueContainer(stringLiteral: "hello")) - #expect(cell(.text("{\"a\":1}"), .json(rawType: "json")) == OpenAPIValueContainer(stringLiteral: "{\"a\":1}")) - } - - @Test("A huge text cell is capped") - func longTextCapped() { - let huge = String(repeating: "x", count: 200_000) - let encoded = SnapshotCellEncoder.encode(.text(huge), type: .text(rawType: "text")) - #expect(encoded.byteCount < huge.utf8.count) - #expect(encoded.value == OpenAPIValueContainer(stringLiteral: String(huge.prefix(ResultSnapshotBuilder.maxCellBytes / 4)) + "…")) - } - - private func output(columns: [String], types: [ColumnType], rows: [[PluginCellValue]]) -> DisplayedResultReader.Output { - DisplayedResultReader.Output(columns: columns, columnTypes: types, rows: rows, skippedDeletedCount: 0) - } - - @Test("row_count and truncated reflect a result cut short") - func truncationFlags() { - let read = output(columns: ["n"], types: [.integer(rawType: "int")], rows: [[.text("1")], [.text("2")]]) - let built = ResultSnapshotBuilder.build(from: read, totalRowCount: 500, moreRowsAvailable: true) - #expect(built.rowsSent == 2) - #expect(built.snapshot.rowCount == 500) - #expect(built.snapshot.truncated == true) - } - - @Test("A fully loaded result is not truncated and omits row_count") - func notTruncated() { - let read = output(columns: ["n"], types: [.integer(rawType: "int")], rows: [[.text("1")], [.text("2")]]) - let built = ResultSnapshotBuilder.build(from: read, totalRowCount: 2, moreRowsAvailable: false) - #expect(built.snapshot.truncated == false) - #expect(built.snapshot.rowCount == nil) - } - - @Test("Rows past the cap are dropped and marked truncated") - func rowCap() { - let rows = Array(repeating: [PluginCellValue.text("1")], count: ResultSnapshotBuilder.maxRows + 50) - let read = output(columns: ["n"], types: [.integer(rawType: "int")], rows: rows) - let built = ResultSnapshotBuilder.build(from: read, totalRowCount: nil, moreRowsAvailable: false) - #expect(built.rowsSent == ResultSnapshotBuilder.maxRows) - #expect(built.snapshot.truncated == true) - } - - @Test("Columns past the cap are dropped and marked truncated") - func columnCap() { - let count = ResultSnapshotBuilder.maxColumns + 5 - let columns = (0 ..< count).map { "c\($0)" } - let types = Array(repeating: ColumnType.text(rawType: "text"), count: count) - let row = Array(repeating: PluginCellValue.text("x"), count: count) - let built = ResultSnapshotBuilder.build(from: output(columns: columns, types: types, rows: [row]), totalRowCount: nil, moreRowsAvailable: false) - #expect(built.snapshot.columns.count == ResultSnapshotBuilder.maxColumns) - #expect(built.snapshot.rows.first??.count == ResultSnapshotBuilder.maxColumns) - #expect(built.snapshot.truncated == true) - } -} diff --git a/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift b/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift index 81c8c84d35..4f8fff68a5 100644 --- a/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift +++ b/apple/TableProTests/Views/Sidebar/FavoritesMenuSpecTests.swift @@ -15,7 +15,6 @@ struct FavoritesMenuSpecTests { allFolders: [SQLFavoriteFolder] = [], teamLibraryTeams: [TeamLibraryTeam] = [], hasTeamLibraryConflicts: Bool = false, - canShare: Bool = false, activeDatabase: String? = "shop" ) -> FavoritesMenuContext { FavoritesMenuContext( @@ -23,7 +22,6 @@ struct FavoritesMenuSpecTests { allFolders: allFolders, teamLibraryTeams: teamLibraryTeams, hasTeamLibraryConflicts: hasTeamLibraryConflicts, - canShare: canShare, activeDatabase: activeDatabase ) } @@ -378,15 +376,6 @@ struct FavoritesMenuSpecTests { #expect(issued.contains(.showFavoriteHistory(query))) } - @Test("Share Link appears on a saved query only when sharing is available") - func shareLinkGatedBySharing() { - let query = favorite() - let shared = commands(FavoritesMenuSpec.sections(for: context(clicked: .query(.favorite(query)), canShare: true))) - #expect(shared.contains(.shareFavorite(query))) - let withheld = commands(FavoritesMenuSpec.sections(for: context(clicked: .query(.favorite(query)), canShare: false))) - #expect(!withheld.contains(.shareFavorite(query))) - } - private func linkedFile() -> LinkedSQLFavorite { LinkedSQLFavorite( folderId: UUID(), diff --git a/apple/changelog.d/4253.added.1.md b/apple/changelog.d/4253.added.1.md deleted file mode 100644 index 22cebdc45e..0000000000 --- a/apple/changelog.d/4253.added.1.md +++ /dev/null @@ -1 +0,0 @@ -Open a shared query link from the browser, straight into TablePro. diff --git a/apple/changelog.d/4253.added.2.md b/apple/changelog.d/4253.added.2.md deleted file mode 100644 index e60e7078c9..0000000000 --- a/apple/changelog.d/4253.added.2.md +++ /dev/null @@ -1 +0,0 @@ -Share a query's result as a public link from the grid, on a paid plan. diff --git a/apple/changelog.d/4253.added.md b/apple/changelog.d/4253.added.md deleted file mode 100644 index ede0748571..0000000000 --- a/apple/changelog.d/4253.added.md +++ /dev/null @@ -1 +0,0 @@ -Share a saved query as a public link from the Favorites menu, on a paid plan. From ae90d1870ec97437232898111edd399e007404c9 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 14:33:38 +0700 Subject: [PATCH 006/126] feat(core): build share snapshots from result rows and scan SQL and column names for secrets --- Cargo.lock | 1 + Cargo.toml | 1 + core/crates/core/Cargo.toml | 1 + core/crates/core/src/export/mod.rs | 2 + core/crates/core/src/export/snapshot.rs | 327 ++++++++++++++++++++++++ core/crates/core/src/lib.rs | 1 + core/crates/core/src/secret_scan.rs | 306 ++++++++++++++++++++++ 7 files changed, 639 insertions(+) create mode 100644 core/crates/core/src/export/snapshot.rs create mode 100644 core/crates/core/src/secret_scan.rs diff --git a/Cargo.lock b/Cargo.lock index 1c42a9049f..02f4a0bde1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7730,6 +7730,7 @@ dependencies = [ "num-bigint 0.4.8", "percent-encoding", "proptest", + "regex", "rust_xlsxwriter", "rustix", "rustls-pki-types", diff --git a/Cargo.toml b/Cargo.toml index 93589a4a14..b41a41ed38 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"] } diff --git a/core/crates/core/Cargo.toml b/core/crates/core/Cargo.toml index f85d042be6..864659a32b 100644 --- a/core/crates/core/Cargo.toml +++ b/core/crates/core/Cargo.toml @@ -14,6 +14,7 @@ flate2.workspace = true futures.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 diff --git a/core/crates/core/src/export/mod.rs b/core/crates/core/src/export/mod.rs index d4f28a061a..da599a9f9f 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,7 @@ 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::{Snapshot, SnapshotColumn, build_snapshot}; 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..2fee654db9 --- /dev/null +++ b/core/crates/core/src/export/snapshot.rs @@ -0,0 +1,327 @@ +use serde::ser::{Serialize, SerializeSeq, Serializer}; +use serde_json::value::RawValue; + +use crate::column::{ColumnKind, ResultColumn}; +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. + pub row_count: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SnapshotColumn { + pub name: String, + pub type_name: String, +} + +impl Snapshot { + pub fn truncated(&self) -> bool { + self.row_count > self.rows.len() as u64 + } +} + +// Takes at most `max_rows` rows; `row_count` is the result's true total, which a caller that holds every row gives +// as their count. +pub fn build_snapshot>( + columns: &[ResultColumn], + rows: impl IntoIterator, + row_count: u64, + max_rows: usize, +) -> Snapshot { + let rows: Vec>> = rows + .into_iter() + .take(max_rows) + .map(|row| snapshot_row(columns, row.as_ref())) + .collect(); + Snapshot { + columns: columns + .iter() + .map(|column| SnapshotColumn { + name: column.name.clone(), + type_name: column.column_type.name.clone(), + }) + .collect(), + row_count: row_count.max(rows.len() as u64), + rows, + } +} + +// One cell per column: a short row's missing cells are null, and a cell past the last column has nowhere to go. +fn snapshot_row(columns: &[ResultColumn], row: &[Value]) -> Vec> { + columns + .iter() + .enumerate() + .map(|(index, column)| { + 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, + }; + serde_json::value::to_raw_value(&cell).unwrap_or_else(|_| RawValue::NULL.to_owned()) + }) + .collect() +} + +// 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 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 = build_snapshot(&columns, &rows, rows.len() as u64, 3); + + assert_eq!(texts(&snapshot), [["0"], ["1"], ["2"]]); + assert_eq!(snapshot.row_count, 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 = build_snapshot(&columns, &rows, 2, 1_000); + + assert_eq!(snapshot.rows.len(), 2); + assert_eq!(snapshot.row_count, 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 = build_snapshot(&columns, &rows, 0, 10); + + assert_eq!(snapshot.row_count, 2); + } + + #[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 = build_snapshot(&columns, std::iter::empty::>(), 0, 10); + + assert_eq!( + snapshot.columns, + [ + SnapshotColumn { + name: "id".to_owned(), + type_name: "bigint".to_owned() + }, + SnapshotColumn { + name: "body".to_owned(), + type_name: "text".to_owned() + } + ] + ); + } + + #[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 = build_snapshot(&columns, &rows, 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 = build_snapshot(&columns, &rows, 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 = build_snapshot(&columns, &rows, 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 = build_snapshot(&columns, &rows, 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 = build_snapshot(&columns, &rows, 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 = build_snapshot(&columns, &rows, 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 = build_snapshot(&columns, &rows, 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")] + ); + } +} diff --git a/core/crates/core/src/lib.rs b/core/crates/core/src/lib.rs index 3307e8280a..17f5a20e05 100644 --- a/core/crates/core/src/lib.rs +++ b/core/crates/core/src/lib.rs @@ -65,6 +65,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/secret_scan.rs b/core/crates/core/src/secret_scan.rs new file mode 100644 index 0000000000..e139bfd874 --- /dev/null +++ b/core/crates/core/src/secret_scan.rs @@ -0,0 +1,306 @@ +use std::sync::LazyLock; + +use regex::Regex; + +// 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", + } + } + + 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[\w-]+\.eyJ[\w-]+\.[\w-]+", + 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 close its own quote or bracket before the operator, as in JSON or T-SQL. + Self::AssignedSecret => { + r#"(?i)\w*(?:password|passwd|pwd|secret|token|api_key)\w*["'`\]]?\s*(?:=>|:=|=|:)\s*(?:'[^'\n]+'|"[^"\n]+")"# + } + } + } +} + +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. +pub fn scan_sql(sql: &str) -> Vec { + let line_starts: Vec = std::iter::once(0) + .chain(sql.match_indices('\n').map(|(at, _)| at + 1)) + .collect(); + 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 +} + +// 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 +} + +// Separators and case go, so api_key, apiKey and API-KEY read alike. "ssn" must be a word of its own, or +// "class_name" would match. +fn column_may_hold_secret(name: &str) -> bool { + const PARTS: [&str; 7] = [ + "password", + "passwd", + "secret", + "token", + "apikey", + "creditcard", + "cardnumber", + ]; + let joined: String = name + .chars() + .filter(|character| character.is_alphanumeric()) + .flat_map(char::to_lowercase) + .collect(); + PARTS.iter().any(|part| joined.contains(part)) || words(name).any(|word| word == "ssn") +} + +// Split at anything not a letter or digit and where a lower-case letter meets an upper-case one. +fn words(name: &str) -> impl Iterator + '_ { + let mut words = Vec::new(); + let mut word = String::new(); + let mut previous_lower = false; + for character in name.chars() { + if !character.is_alphanumeric() { + if !word.is_empty() { + words.push(std::mem::take(&mut word)); + } + previous_lower = false; + continue; + } + if character.is_uppercase() && previous_lower && !word.is_empty() { + words.push(std::mem::take(&mut word)); + } + previous_lower = character.is_lowercase() || character.is_ascii_digit(); + word.extend(character.to_lowercase()); + } + if !word.is_empty() { + words.push(word); + } + words.into_iter() +} + +#[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()); + } +} From b5cb37fe9da8f13e49b3de4a8f6beff382bec849 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 14:33:39 +0700 Subject: [PATCH 007/126] feat(core-account): derive the Windows machine ID from MachineGuid --- core/crates/account/src/machine_id.rs | 70 ++++++++++++++++++++++++--- 1 file changed, 62 insertions(+), 8 deletions(-) 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:?}"); + } + } } From 22e1a26deb49aa5a4df1a5ad8ee975396535168e Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 14:49:52 +0700 Subject: [PATCH 008/126] chore(core-account): refresh the /v2 document from tablepro-cloud ccc35d13 --- .../account/openapi/v2.openapi-3.0.json | 2252 ++++++++++++++++- 1 file changed, 2175 insertions(+), 77 deletions(-) diff --git a/core/crates/account/openapi/v2.openapi-3.0.json b/core/crates/account/openapi/v2.openapi-3.0.json index e400b16478..490454a8df 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", + "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,139 @@ ], "type": "object" }, + "PublicColumn": { + "properties": { + "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", + "format": "int64", + "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", + "maxLength": 2048, + "type": "string" + } + }, + "required": [ + "reason", + "turnstile_token" + ], + "type": "object" + }, "Seats": { "properties": { "available": { @@ -1183,81 +1419,116 @@ ], "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" } }, "required": [ - "id", - "name", - "seats" + "plan", + "live", + "live_limit", + "max_rows", + "expiries", + "default_expiry", + "password", + "disable_download", + "team", + "email_verified", + "sharing_disabled" ], "type": "object" }, - "TeamList": { + "ShareList": { "properties": { "data": { + "description": "Newest first", "items": { - "$ref": "#/components/schemas/Team" + "$ref": "#/components/schemas/ShareView" }, "type": "array" }, @@ -1271,25 +1542,347 @@ ], "type": "object" }, - "TeamRef": { + "ShareListState": { + "enum": [ + "live", + "all" + ], + "type": "string" + }, + "ShareReportReason": { + "enum": [ + "illegal", + "malware_phishing", + "personal_data", + "spam", + "copyright", + "other" + ], + "type": "string" + }, + "ShareView": { "properties": { - "id": { - "description": "Team TypeID", - "example": "team_01jbvh7pn9e3sv4bzq4rqk4kzh", + "allow_download": { + "description": "The viewer offers CSV and JSON downloads", + "type": "boolean" + }, + "created_at": { + "format": "date-time", "type": "string" }, - "name": { - "example": "Acme", + "dialect": { + "description": "The SQL dialect, for display", "type": "string" - } - }, - "required": [ - "id", - "name" - ], - "type": "object" - } - }, + }, + "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", + "format": "int64", + "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" + ] + }, + "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", + "view_count", + "created_at", + "updated_at" + ], + "type": "object" + }, + "SnapshotBody": { + "additionalProperties": false, + "properties": { + "columns": { + "items": { + "$ref": "#/components/schemas/SnapshotColumnBody" + }, + "maxItems": 100, + "minItems": 1, + "type": "array" + }, + "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": { + "name": { + "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" + } + }, + "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.", @@ -2815,6 +3408,1511 @@ ] } }, + "/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": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareLimits" + } + } + }, + "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 caller's plan limits for shared links", + "tags": [ + "Shares" + ] + } + }, + "/shared/{token}": { + "get": { + "description": "No authentication. An unknown, revoked, removed or expired 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": "The link token", + "in": "path", + "name": "token", + "required": true, + "schema": { + "description": "The link token", + "type": "string" + } + }, + { + "description": "The link password, for a password-protected link", + "in": "header", + "name": "X-Share-Password", + "schema": { + "description": "The link password, for a password-protected link", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicShare" + } + } + }, + "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": { + "share_password_required": { + "summary": "Share password required", + "value": { + "code": "share_password_required", + "detail": "This link is password protected.", + "status": 401, + "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" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "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": "Not Found" + }, + "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" + } + }, + "summary": "Read a shared link", + "tags": [ + "Shares" + ] + } + }, + "/shared/{token}/report": { + "post": { + "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/ReportShareBody" + } + } + }, + "required": true + }, + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReportAccepted" + } + } + }, + "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" + } + } + }, + "403": { + "content": { + "application/json": { + "examples": { + "human_check_failed": { + "summary": "Human check failed", + "value": { + "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": "Human check failed", + "type": "https://api.tablepro.app/problems/human-check-failed" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "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" + } + }, + "summary": "Report a shared link", + "tags": [ + "Shares" + ] + } + }, + "/shares": { + "get": { + "description": "The caller's personal links, or with team a team's links for its owner and admins. Newest first, without sql.", + "operationId": "list-shares", + "parameters": [ + { + "description": "Team TypeID: that team's links, for its owner and admins; omit for the caller's personal links", + "explode": false, + "in": "query", + "name": "team", + "schema": { + "description": "Team TypeID: that team's links, for its owner and admins; 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": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareList" + } + } + }, + "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" + } + }, + "forbidden_2": { + "summary": "Forbidden", + "value": { + "code": "forbidden", + "detail": "Only the team's owner and admins can do this.", + "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": "No such share.", + "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": "query.cursor", + "message": "expected the next_cursor of the previous page" + } + ], + "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": "List shared links", + "tags": [ + "Shares" + ] + }, + "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/CreateShareBody" + } + } + }, + "required": true + }, + "responses": { + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreatedShare" + } + } + }, + "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": { + "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": "Forbidden" + }, + "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": "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": { + "snapshot_too_large": { + "summary": "Snapshot too large", + "value": { + "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" + } + } + }, + "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" + } + }, + "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": { + "$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": "Create a shared link", + "tags": [ + "Shares" + ] + } + }, + "/shares/{share_id}": { + "delete": { + "description": "The link stops working at once. Revoking a revoked link changes nothing.", + "operationId": "delete-share", + "parameters": [ + { + "description": "Share TypeID", + "in": "path", + "name": "share_id", + "required": true, + "schema": { + "description": "Share TypeID", + "maxLength": 64, + "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": "No such share.", + "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": { + "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": "Revoke a shared link", + "tags": [ + "Shares" + ] + }, + "get": { + "operationId": "get-share", + "parameters": [ + { + "description": "Share TypeID", + "in": "path", + "name": "share_id", + "required": true, + "schema": { + "description": "Share TypeID", + "maxLength": 64, + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareView" + } + } + }, + "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": "No such share.", + "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": { + "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": "Get one shared link, with its SQL", + "tags": [ + "Shares" + ] + }, + "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" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateShareBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShareView" + } + } + }, + "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" + } + }, + "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" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Forbidden" + }, + "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": "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/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": "Change a shared link", + "tags": [ + "Shares" + ] + } + }, "/teams": { "get": { "description": "With the caller's role and seat in each, in the order the account joined them. App sign-ins only.", From 38f8de0c44cd0e13eec470df734db0ca13373cfe Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 14:49:52 +0700 Subject: [PATCH 009/126] feat(core-account): add the Windows OAuth client and device platform --- core/crates/account/src/account_settings.rs | 22 +++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/core/crates/account/src/account_settings.rs b/core/crates/account/src/account_settings.rs index daba15b66d..04c99ca544 100644 --- a/core/crates/account/src/account_settings.rs +++ b/core/crates/account/src/account_settings.rs @@ -6,8 +6,8 @@ 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 +22,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)] @@ -95,6 +101,18 @@ 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()) + ); + } + #[test] fn production_is_tablepro_app_over_https() { let endpoints = Endpoints::production(); From b85ac3c8350c83d47c1eb58288de030e8daba3fd Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 14:49:58 +0700 Subject: [PATCH 010/126] feat(core-account): share links: limits, create, list, revoke, extend and the public read --- core/crates/account/build.rs | 5 +- .../src/{account.rs => account/mod.rs} | 9 +- .../crates/account/src/account/share_calls.rs | 622 ++++++++++++++++++ core/crates/account/src/account_error.rs | 58 +- core/crates/account/src/cloud_api.rs | 21 +- core/crates/account/src/lib.rs | 7 + core/crates/account/src/share.rs | 291 ++++++++ core/crates/account/src/share_link.rs | 70 ++ 8 files changed, 1077 insertions(+), 6 deletions(-) rename core/crates/account/src/{account.rs => account/mod.rs} (99%) create mode 100644 core/crates/account/src/account/share_calls.rs create mode 100644 core/crates/account/src/share.rs create mode 100644 core/crates/account/src/share_link.rs 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/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..07518b8e2c 100644 --- a/core/crates/account/src/account.rs +++ b/core/crates/account/src/account/mod.rs @@ -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 { @@ -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(Some(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(Some(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..b664bd5c3c --- /dev/null +++ b/core/crates/account/src/account/share_calls.rs @@ -0,0 +1,622 @@ +use std::num::NonZeroU64; + +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, Share, ShareExpiry, ShareLimits, SharePage, ShareRequest, SharedLink, SnapshotBody}; +use crate::share_link::is_share_token; + +const SHARE_PAGE: NonZeroU64 = NonZeroU64::MIN.saturating_add(99); +// 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`. + pub async fn create_share(&self, request: ShareRequest) -> Result { + let body = create_body(request)?; + let created = self + .share_call(Call::ShareCreate, async |api| { + answer(api.create_share(&body).await).await.map(CreatedShare::from) + }) + .await?; + tracing::info!(kind = %created.share.kind, "created a shared link"); + Ok(created) + } + + // The account's own links, newest first, without their SQL. `live_only` leaves out expired, revoked and removed. + pub async fn list_shares(&self, live_only: bool, cursor: Option<&str>) -> Result { + let state = list_state(live_only)?; + let cursor: Option = cursor + .map(|cursor| limited(cursor.to_owned(), "not a cursor the server gave")) + .transpose()?; + self.share_call(Call::Share, async |api| { + answer( + api.list_shares(cursor.as_ref(), Some(SHARE_PAGE), Some(state), None) + .await, + ) + .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(None)); + let password = password.map(|password| password.expose_secret()); + 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 { + 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 + .map(|password| limited(password.expose_secret().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 the server holds. +fn known>(share_id: &str) -> Result { + T::try_from(share_id.to_owned()).map_err(|_| not_found("not a share ID")) +} + +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","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; + + fn cloud(answer: impl Fn(&Sent) -> (u16, &'static str, String) + Send + '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(); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + 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}"# + .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::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, 48_210, 1)), + ..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).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()); + } +} diff --git a/core/crates/account/src/account_error.rs b/core/crates/account/src/account_error.rs index 32f79dbc56..eb196a8c01 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", @@ -68,3 +89,38 @@ impl AccountError { Self::Unreachable(detail) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn refused(code: &str) -> AccountError { + AccountError::Refused { + status: 403, + code: code.to_owned(), + detail: String::new(), + } + } + + #[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/cloud_api.rs b/core/crates/account/src/cloud_api.rs index b39c8de332..631d48bcb0 100644 --- a/core/crates/account/src/cloud_api.rs +++ b/core/crates/account/src/cloud_api.rs @@ -15,13 +15,17 @@ pub mod v2 { include!(concat!(env!("OUT_DIR"), "/v2.rs")); } +// None for a public call, such as reading a shared link, which sends no token at all. #[derive(Clone, Debug)] -pub struct Bearer(pub(crate) SecretString); +pub struct Bearer(pub(crate) Option); 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())) + let Some(token) = &self.inner().0 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,6 +41,9 @@ 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) => { @@ -57,6 +64,16 @@ pub(crate) async fn answer_error(error: Error) -> AccountErr } } +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!( diff --git a/core/crates/account/src/lib.rs b/core/crates/account/src/lib.rs index 3dc8dd24c1..b096067aec 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, Share, ShareExpiry, ShareKind, ShareLimits, SharePage, ShareRequest, SharedLink, SnapshotBody, + SnapshotColumnBody, +}; +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/share.rs b/core/crates/account/src/share.rs new file mode 100644 index 0000000000..c6e84651b6 --- /dev/null +++ b/core/crates/account/src/share.rs @@ -0,0 +1,291 @@ +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; + +#[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, + // 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, +} + +impl ShareLimits { + 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, + 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, +} + +#[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. + 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, +} + +#[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 maxLength for a column's type. +const COLUMN_TYPE_CHARACTERS: usize = 256; + +impl From for SnapshotBody { + fn from(snapshot: Snapshot) -> Self { + Self { + columns: snapshot + .columns + .into_iter() + .map(|column| SnapshotColumnBody { + name: column.name, + type_name: Some(column.type_name.chars().take(COLUMN_TYPE_CHARACTERS).collect()) + .filter(|type_name: &String| !type_name.is_empty()), + }) + .collect(), + rows: snapshot.rows, + row_count: Some(i64::try_from(snapshot.row_count).unwrap_or(i64::MAX)), + } + } +} + +// 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 { + pub row_count: i64, + 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), + 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, + } + } +} + +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()), + 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, + } + } +} + +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, + created_at: shared.created_at, + expires_at: shared.expires_at, + allow_download: shared.allow_download, + row_count: shared.snapshot.map(|snapshot| count(snapshot.row_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) +} 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}"); + } + } +} From fd7b00eace2e05f13f558d44d8b46cfc9ca5af79 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 14:51:00 +0700 Subject: [PATCH 011/126] feat(ffi): sign in to the TablePro account from the Windows app --- Cargo.lock | 1 + Cargo.toml | 6 +- core/crates/ffi/Cargo.toml | 2 + core/crates/ffi/src/account/account_info.rs | 304 ++++++++++++++++ .../crates/ffi/src/account/account_service.rs | 325 ++++++++++++++++++ core/crates/ffi/src/account/host_browser.rs | 116 +++++++ core/crates/ffi/src/account/machine_guid.rs | 49 +++ core/crates/ffi/src/account/mod.rs | 12 + core/crates/ffi/src/core_handle.rs | 62 +++- core/crates/ffi/src/credential_manager.rs | 66 +++- core/crates/ffi/src/error.rs | 42 +++ core/crates/ffi/src/host.rs | 45 +++ core/crates/ffi/src/lib.rs | 6 + core/crates/ffi/tests/account.rs | 313 +++++++++++++++++ 14 files changed, 1331 insertions(+), 18 deletions(-) create mode 100644 core/crates/ffi/src/account/account_info.rs create mode 100644 core/crates/ffi/src/account/account_service.rs create mode 100644 core/crates/ffi/src/account/host_browser.rs create mode 100644 core/crates/ffi/src/account/machine_guid.rs create mode 100644 core/crates/ffi/src/account/mod.rs create mode 100644 core/crates/ffi/tests/account.rs diff --git a/Cargo.lock b/Cargo.lock index 02f4a0bde1..bbcd49460e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7959,6 +7959,7 @@ dependencies = [ "futures", "russh", "secrecy", + "tablepro-account", "tablepro-core", "tablepro-driver-cassandra", "tablepro-driver-clickhouse", diff --git a/Cargo.toml b/Cargo.toml index b41a41ed38..ac73cf2926 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -169,13 +169,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. diff --git a/core/crates/ffi/Cargo.toml b/core/crates/ffi/Cargo.toml index 86cfc395d6..adb95bf69c 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 } @@ -54,6 +55,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..f573b78e20 --- /dev/null +++ b/core/crates/ffi/src/account/account_service.rs @@ -0,0 +1,325 @@ +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 vault = 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 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..a77101eaa5 --- /dev/null +++ b/core/crates/ffi/src/account/host_browser.rs @@ -0,0 +1,116 @@ +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. +#[uniffi::export(callback_interface)] +pub trait HostBrowser: Send + Sync { + fn open(&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)).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(&self, url: String) -> Result<(), HostBrowserError> { + self.0.lock().unwrap().push(url); + Ok(()) + } + } + + struct Refusing; + + impl HostBrowser for Refusing { + fn open(&self, _: String) -> Result<(), HostBrowserError> { + Err(HostBrowserError::Failed { + detail: "no default browser".to_owned(), + }) + } + } + + struct Throwing; + + impl HostBrowser for Throwing { + fn open(&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..89ad1c7335 --- /dev/null +++ b/core/crates/ffi/src/account/mod.rs @@ -0,0 +1,12 @@ +mod account_info; +mod account_service; +mod host_browser; +#[cfg(windows)] +mod machine_guid; + +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}; diff --git a/core/crates/ffi/src/core_handle.rs b/core/crates/ffi/src/core_handle.rs index 3395c4acfe..b6cd11cef0 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::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: Arc, paths: Option, store: Option, writes: LibraryWrites, @@ -66,15 +69,23 @@ 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(), + refresh_tokens: host, + }, + 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 +302,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 +320,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 +343,10 @@ impl Core { pub fn secret_items(&self) -> Arc { self.items.clone() } + + pub(crate) fn refresh_tokens(&self) -> Arc { + self.refresh_tokens.clone() + } } impl std::fmt::Debug for Core { @@ -356,7 +372,11 @@ fn no_storage() -> CoreError { CoreError::failed("ffi.no_storage", "the core was started without a storage folder") } -type SystemSecrets = (Arc, Arc); +struct SystemSecrets { + vault: Arc, + items: Arc, + refresh_tokens: Arc, +} #[cfg(windows)] fn system_secrets(tasks: &Tasks) -> Result { @@ -364,7 +384,11 @@ fn system_secrets(tasks: &Tasks) -> Result { "TablePro", tasks.clone(), )); - Ok((manager.clone(), manager)) + Ok(SystemSecrets { + vault: manager.clone(), + items: manager.clone(), + refresh_tokens: manager, + }) } #[cfg(not(windows))] @@ -564,6 +588,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 +626,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(NoItems), + }, 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..e50d576ab8 100644 --- a/core/crates/ffi/src/credential_manager.rs +++ b/core/crates/ffi/src/credential_manager.rs @@ -1,6 +1,7 @@ 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 +26,10 @@ 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"; +const 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 +52,10 @@ impl CredentialManager { format!("{}/{}", self.prefix, item_name(item)) } + fn refresh_token_target(&self) -> String { + format!("{}/{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 +116,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 +331,26 @@ impl SecretItems for CredentialManager { } } +#[async_trait] +impl RefreshTokenVault for CredentialManager { + async fn load_refresh_token(&self) -> Result, SecretError> { + let target = self.refresh_token_target(); + self.blocking(move || read(&target)).await + } + + async fn store_refresh_token(&self, token: &SecretString) -> Result<(), SecretError> { + let target = self.refresh_token_target(); + let token = token.clone(); + self.blocking(move || write(&target, token.expose_secret(), REFRESH_TOKEN_LABEL)) + .await + } + + async fn delete_refresh_token(&self) -> Result<(), SecretError> { + let target = self.refresh_token_target(); + self.blocking(move || delete(&target)).await + } +} + #[cfg(test)] mod tests { use super::*; @@ -496,6 +522,34 @@ mod tests { assert!(gone.is_none()); } + #[tokio::test] + async fn the_refresh_token_is_kept_apart_from_the_items_and_removed_whole() { + let manager = manager(); + let token = format!("{}tail", "r".repeat(PART_SIZE)); + manager + .store_item(SecretItem::McpToken, &SecretString::from("mcp")) + .await + .unwrap(); + + manager + .store_refresh_token(&SecretString::from(token.clone())) + .await + .unwrap(); + let found = manager.load_refresh_token().await.unwrap(); + manager.delete_refresh_token().await.unwrap(); + let gone = manager.load_refresh_token().await.unwrap(); + let continued = Credentials + .read(&format!("{}/1", manager.refresh_token_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 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/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..09fe40ea2f 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; @@ -31,6 +32,11 @@ mod structure; mod syntax; pub mod window_abi; +pub use account::{ + AccountConfig, AccountListener, AccountService, AccountStateTag, AccountStatusInfo, DeviceInfo, + EntitlementProblemTag, FeatureAccessTag, HostBrowser, HostBrowserError, LicenseInfo, MembershipInfo, ProfileInfo, + TeamInfo, +}; pub use cancel_token::CancelToken; pub use catalog::{ColumnEntry, ObjectEntry, ObjectKindTag, ObjectScopeArg, SchemaEntry, TableName}; pub use cloud::{CloudConnectionFields, CloudGroupFields, CloudLibraryPull, CloudLibraryRecords}; diff --git a/core/crates/ffi/tests/account.rs b/core/crates/ffi/tests/account.rs new file mode 100644 index 0000000000..8db3e0e38f --- /dev/null +++ b/core/crates/ffi/tests/account.rs @@ -0,0 +1,313 @@ +#![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 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(&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); +} From 5a7528bfe00a00b8c6a128eb485e21863be54d75 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 14:51:06 +0700 Subject: [PATCH 012/126] feat(ffi): share links, the secret scan and the deep link token for the Windows app --- core/crates/ffi/src/account/mod.rs | 9 + core/crates/ffi/src/account/secret_scan.rs | 108 +++++++ core/crates/ffi/src/account/share.rs | 358 +++++++++++++++++++++ core/crates/ffi/src/export.rs | 2 +- core/crates/ffi/src/lib.rs | 5 +- core/crates/ffi/tests/account.rs | 152 +++++++++ 6 files changed, 631 insertions(+), 3 deletions(-) create mode 100644 core/crates/ffi/src/account/secret_scan.rs create mode 100644 core/crates/ffi/src/account/share.rs diff --git a/core/crates/ffi/src/account/mod.rs b/core/crates/ffi/src/account/mod.rs index 89ad1c7335..f24e3f1db0 100644 --- a/core/crates/ffi/src/account/mod.rs +++ b/core/crates/ffi/src/account/mod.rs @@ -3,6 +3,8 @@ mod account_service; mod host_browser; #[cfg(windows)] mod machine_guid; +mod secret_scan; +mod share; pub use account_info::{ AccountStateTag, AccountStatusInfo, DeviceInfo, EntitlementProblemTag, FeatureAccessTag, LicenseInfo, @@ -10,3 +12,10 @@ pub use account_info::{ }; 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, + 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..887ab71e1b --- /dev/null +++ b/core/crates/ffi/src/account/share.rs @@ -0,0 +1,358 @@ +use std::sync::Arc; + +use chrono::{DateTime, Utc}; +use secrecy::SecretString; +use tablepro_account::{CreatedShare, Share, ShareExpiry, ShareKind, ShareLimits, SharePage, ShareRequest, SharedLink}; +use tablepro_core::column::ResultColumn; +use tablepro_core::export::{Snapshot, build_snapshot}; + +use super::account_service::AccountService; +use crate::error::CoreError; +use crate::export::held_row; +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, + 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, +} + +#[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, + 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, +} + +#[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. + pub async fn create_share( + &self, + request: ShareRequestArg, + result: Option>, + visible_columns: u32, + max_rows: u32, + ) -> Result { + let account = self.account.clone(); + let tasks = self.tasks.clone(); + on_runtime(&self.tasks, async move { + let snapshot = match (request.kind, result) { + (ShareKindTag::Query, _) => None, + (ShareKindTag::Result, None) => { + return Err(CoreError::failed( + "ffi.share_needs_result", + "a result share needs its result set", + )); + } + (ShareKindTag::Result, Some(set)) => { + let built = tasks + .spawn_blocking_task(move || snapshot_of(&set, visible_columns, max_rows)) + .await + .map_err(|failure| CoreError::failed("ffi.panicked", failure.to_string()))??; + Some(built) + } + }; + let created = account.create_share(share_request(request, snapshot)).await?; + Ok(created.into()) + }) + .await + } + + // The account's own links, newest first, without their SQL. + pub async fn list_shares(&self, live_only: bool, cursor: Option) -> Result { + let account = self.account.clone(); + on_runtime(&self.tasks, async move { + Ok(account.list_shares(live_only, cursor.as_deref()).await?.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 + } +} + +fn snapshot_of(set: &ResultSet, visible_columns: u32, max_rows: u32) -> Result { + // 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 held = set.result_columns(); + let visible = usize::try_from(visible_columns).unwrap_or(usize::MAX).min(held.len()); + let columns: Vec = held.iter().take(visible).cloned().collect(); + let total = set.row_count(); + let taken = total.min(u64::from(max_rows)); + let rows = (0..taken).map(|row| held_row(set, row, &columns)); + Ok(build_snapshot( + &columns, + rows, + total, + usize::try_from(max_rows).unwrap_or(usize::MAX), + )) +} + +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, + 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, + } + } +} + +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, + 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, + } + } +} + +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() + } +} diff --git a/core/crates/ffi/src/export.rs b/core/crates/ffi/src/export.rs index c07ad3ec92..28f7adb2ce 100644 --- a/core/crates/ffi/src/export.rs +++ b/core/crates/ffi/src/export.rs @@ -473,7 +473,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() diff --git a/core/crates/ffi/src/lib.rs b/core/crates/ffi/src/lib.rs index 09fe40ea2f..701c862976 100644 --- a/core/crates/ffi/src/lib.rs +++ b/core/crates/ffi/src/lib.rs @@ -33,9 +33,10 @@ mod syntax; pub mod window_abi; pub use account::{ - AccountConfig, AccountListener, AccountService, AccountStateTag, AccountStatusInfo, DeviceInfo, + AccountConfig, AccountListener, AccountService, AccountStateTag, AccountStatusInfo, CreatedShareInfo, DeviceInfo, EntitlementProblemTag, FeatureAccessTag, HostBrowser, HostBrowserError, LicenseInfo, MembershipInfo, ProfileInfo, - TeamInfo, + SecretHitInfo, SecretHitKindTag, ShareExpiryTag, ShareInfo, ShareKindTag, ShareLimitsInfo, SharePageInfo, + ShareRequestArg, 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}; diff --git a/core/crates/ffi/tests/account.rs b/core/crates/ffi/tests/account.rs index 8db3e0e38f..ecccbc1824 100644 --- a/core/crates/ffi/tests/account.rs +++ b/core/crates/ffi/tests/account.rs @@ -19,6 +19,7 @@ use tablepro_ffi::{ }; 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"}"#; @@ -311,3 +312,154 @@ async fn a_cancel_ends_the_wait_for_the_browser() { 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 tablepro_ffi::{ + DatabaseSession, FileOpenRequest, ResultSet, RunListener, RunOutcome, RunSettings, ShareKindTag, + ShareRequestArg, + }; + + use super::*; + + struct Quiet; + + impl RunListener for Quiet { + fn events_pending(&self) {} + } + + async fn run(session: &DatabaseSession, sql: &str) -> Arc { + 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).unwrap(); + editor.close().await.unwrap(); + set + } + + 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","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 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(); + let dir = tempfile::tempdir().unwrap(); + let file = FileOpenRequest { + path: dir.path().join("shop.sqlite").display().to_string(), + driver_id: None, + read_only: false, + create: true, + }; + let core = Core::new( + HostConfig { + client_version: "test".to_owned(), + storage_dir: None, + }, + Box::new(MemorySecrets::default()), + ) + .unwrap(); + let session = core.open_file(file, None).await.unwrap(); + let set = run( + &session, + "SELECT 9007199254740993 AS big, 'a' AS name, x'cafe' AS hidden UNION ALL SELECT 2, 'b', NULL", + ) + .await; + + let shared = opened + .service + .create_share(request(ShareKindTag::Result), Some(set), 2, 1) + .await + .unwrap(); + let query = opened + .service + .create_share(request(ShareKindTag::Query), None, 0, 0) + .await + .unwrap(); + let needs_set = opened + .service + .create_share(request(ShareKindTag::Result), None, 0, 1_000) + .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]); + } +} From 40e68b03a51b2f62ba1a58775c8f13bd87bd8eaf Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 14:51:06 +0700 Subject: [PATCH 013/126] docs(core): record the Windows account and share links decisions --- core/ARCHITECTURE.md | 8 +++-- core/docs/decisions/0016-tablepro-accounts.md | 2 +- ...he-windows-app-signs-in-through-the-ffi.md | 36 +++++++++++++++++++ core/docs/decisions/0025-share-links.md | 29 +++++++++++++++ core/docs/decisions/README.md | 4 ++- 5 files changed, 74 insertions(+), 5 deletions(-) create mode 100644 core/docs/decisions/0024-the-windows-app-signs-in-through-the-ffi.md create mode 100644 core/docs/decisions/0025-share-links.md diff --git a/core/ARCHITECTURE.md b/core/ARCHITECTURE.md index c4770bb521..8cb5ec0ea7 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 0024](docs/decisions/0024-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 ([ADR 0025](docs/decisions/0025-share-links.md)). `scan_sql_for_secrets`, `scan_columns_for_secrets` 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/docs/decisions/0016-tablepro-accounts.md b/core/docs/decisions/0016-tablepro-accounts.md index f0e5927546..1869305dfb 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 [0024](0024-the-windows-app-signs-in-through-the-ffi.md), share links amended by [0025](0025-share-links.md) - **Date**: 2026-11-05 ## Context diff --git a/core/docs/decisions/0024-the-windows-app-signs-in-through-the-ffi.md b/core/docs/decisions/0024-the-windows-app-signs-in-through-the-ffi.md new file mode 100644 index 0000000000..c471641216 --- /dev/null +++ b/core/docs/decisions/0024-the-windows-app-signs-in-through-the-ffi.md @@ -0,0 +1,36 @@ +# 0024: 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: the generic credential `TablePro/account-refresh-token` in Credential Manager under `Core::with_system_secrets`, or the host's `SecretItemTag::AccountRefreshToken` under `Core::new` | +| `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. +- **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/0025-share-links.md b/core/docs/decisions/0025-share-links.md new file mode 100644 index 0000000000..444b326218 --- /dev/null +++ b/core/docs/decisions/0025-share-links.md @@ -0,0 +1,29 @@ +# 0025: Share links go through the account, with the snapshot and the secret scan in the core + +- **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, 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. `fetch_shared` is public: the same HTTP client, no bearer, no session, and the password in `X-Share-Password`. +- **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. +- **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. + +## 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/README.md b/core/docs/decisions/README.md index 153e454636..e20fd77db5 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 0024, share links amended by 0025 | `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. | @@ -31,3 +31,5 @@ The format, the statuses and how a later ADR changes an earlier one follow [the | [0021](0021-an-int32-keeps-its-width.md) | An int32 keeps its width, and an edited number keeps its type | Accepted | `Value::Int32` holds MongoDB's int32, equal to the `Int` of the same number; a save carries each edited cell's read value, and a number binds in the read's BSON type when it is exactly one, else the column's. | | [0022](0022-browsing-through-the-ffi.md) | A table page is read on the session with its filter bound, and structure, definitions, export and history cross the FFI | Accepted | `read_table_page` builds the page with the filter, binds its values and reads it with `read_page` on a pooled connection as run events; `table_structure`, `object_definition`, `export_rows`, `export_table` and `Core::history` give the Linux app's reads to an app on the FFI. | | [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-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. | +| [0025](0025-share-links.md) | Share links go through the account, with the snapshot and the secret scan in the core | Accepted | `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; `secret_scan` warns; the deep link takes one 43-character base62 token. | From a16551f7beb57c31362091ec991f4f269c0cf48b Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 15:03:53 +0700 Subject: [PATCH 014/126] fix(ffi): name the browser callback's method open_url so the Swift header compiles --- core/crates/ffi/src/account/host_browser.rs | 13 +++++++------ core/crates/ffi/tests/account.rs | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/core/crates/ffi/src/account/host_browser.rs b/core/crates/ffi/src/account/host_browser.rs index a77101eaa5..b43b31cceb 100644 --- a/core/crates/ffi/src/account/host_browser.rs +++ b/core/crates/ffi/src/account/host_browser.rs @@ -4,10 +4,11 @@ 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. +// 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(&self, url: String) -> Result<(), HostBrowserError>; + fn open_url(&self, url: String) -> Result<(), HostBrowserError>; } #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)] @@ -47,7 +48,7 @@ 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)).await { + 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()), } @@ -65,7 +66,7 @@ mod tests { struct Recording(Arc>>); impl HostBrowser for Recording { - fn open(&self, url: String) -> Result<(), HostBrowserError> { + fn open_url(&self, url: String) -> Result<(), HostBrowserError> { self.0.lock().unwrap().push(url); Ok(()) } @@ -74,7 +75,7 @@ mod tests { struct Refusing; impl HostBrowser for Refusing { - fn open(&self, _: String) -> Result<(), HostBrowserError> { + fn open_url(&self, _: String) -> Result<(), HostBrowserError> { Err(HostBrowserError::Failed { detail: "no default browser".to_owned(), }) @@ -84,7 +85,7 @@ mod tests { struct Throwing; impl HostBrowser for Throwing { - fn open(&self, _: String) -> Result<(), HostBrowserError> { + fn open_url(&self, _: String) -> Result<(), HostBrowserError> { panic!("the app's callback threw"); } } diff --git a/core/crates/ffi/tests/account.rs b/core/crates/ffi/tests/account.rs index ecccbc1824..ba15d7b68b 100644 --- a/core/crates/ffi/tests/account.rs +++ b/core/crates/ffi/tests/account.rs @@ -79,7 +79,7 @@ impl AccountListener for Counting { struct Browser(Arc>>); impl HostBrowser for Browser { - fn open(&self, url: String) -> Result<(), HostBrowserError> { + fn open_url(&self, url: String) -> Result<(), HostBrowserError> { *self.0.lock().unwrap() = Some(url); Ok(()) } From b1746371f175f940a5286a07f7e8e55f796942a4 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 16:09:55 +0700 Subject: [PATCH 015/126] feat(windows-interop): the TablePro account and share links through the FFI, with the regenerated bindings --- windows/src/TablePro.Interop/Account.cs | 282 ++ .../Generated/tablepro_ffi.cs | 3368 +++++++++++++++-- .../src/TablePro.Interop/Mapping.Account.cs | 184 + windows/src/TablePro.Interop/Mapping.cs | 7 +- windows/src/TablePro.Interop/SecretStore.cs | 3 + windows/src/TablePro.Interop/ShareLinks.cs | 143 + windows/src/TablePro.Interop/TableProCore.cs | 13 + .../TablePro.Interop.Tests/AccountTests.cs | 349 ++ 8 files changed, 4093 insertions(+), 256 deletions(-) create mode 100644 windows/src/TablePro.Interop/Account.cs create mode 100644 windows/src/TablePro.Interop/Mapping.Account.cs create mode 100644 windows/src/TablePro.Interop/ShareLinks.cs create mode 100644 windows/tests/TablePro.Interop.Tests/AccountTests.cs diff --git a/windows/src/TablePro.Interop/Account.cs b/windows/src/TablePro.Interop/Account.cs new file mode 100644 index 0000000000..e915908f17 --- /dev/null +++ b/windows/src/TablePro.Interop/Account.cs @@ -0,0 +1,282 @@ +using System.Runtime.CompilerServices; +using System.Threading.Channels; +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +// The callback texts are the browser's page once the sign-in comes back, in the app's language (core ADR 0024). +public sealed record AccountConfiguration( + string DeviceName, + string AppVersion, + string OsVersion, + string AccountFile, + string CallbackFinished, + string CallbackUnknown) +{ + // Both null for tablepro.app; a development build names its local stack's two. + public string? AccountUrl { get; init; } + + public string? ApiUrl { get; init; } + + // The x of each Ed25519 key a development stack signs with; empty for the release keys. + public IReadOnlyList EntitlementKeys { get; init; } = []; + + // Null reads MachineGuid from the registry, the only source on Windows; elsewhere a test gives one. + public string? MachineGuid { get; init; } +} + +// Opens the sign-in page in the user's browser. The core calls it on a thread it lets block; false or a throw ends +// the sign-in with account.browser. +public interface IAccountBrowser +{ + Task OpenAsync(Uri url); +} + +public enum AccountState +{ + SignedOut, + SignedIn, + + // An imported offline file on a machine that is not signed in. + Offline, +} + +public enum FeatureAccess +{ + Available, + SignedOut, + NotIncluded, + Expired, + RefreshFailed, + DeviceLimitReached, +} + +// Codes stay strings, as the core keeps them: a plan, status or role this build does not know still shows. +public sealed record AccountStatus( + AccountState State, + string? AccountId, + string? Email, + string? Name, + IReadOnlyList Features, + IReadOnlyList Licenses, + DateTimeOffset? EntitlementExpiresAt, + EntitlementProblem? Problem, + bool Remembered) +{ + public static AccountStatus SignedOut { get; } = + new(AccountState.SignedOut, null, null, null, [], [], null, null, false); +} + +public abstract record EntitlementProblem +{ + private EntitlementProblem() + { + } + + public sealed record Expired : EntitlementProblem + { + public static Expired Instance { get; } = new(); + } + + // Code is the error the last refresh met, which the app words. + public sealed record RefreshFailed(string Code) : EntitlementProblem; + + public sealed record DeviceLimitReached(IReadOnlyList Devices) : EntitlementProblem; +} + +public sealed record AccountTeam(string Id, string Name); + +public sealed record AccountLicense( + string Id, + string Plan, + string Cycle, + string Source, + string Status, + DateTimeOffset? RenewsAt, + DateTimeOffset? EndsAt, + AccountTeam? Team); + +public sealed record AccountMembership(AccountTeam Team, string Role, bool HasSeat); + +public sealed record AccountProfile( + string Id, + string Email, + string? Name, + IReadOnlyList Licenses, + IReadOnlyList Teams); + +// Until OfflineUntil, removing the device is refused with the server's offline_file_active. +public sealed record AccountDevice( + string Id, + string Platform, + string Name, + string AppVersion, + string OsVersion, + DateTimeOffset LastSeenAt, + DateTimeOffset? LicensedAt, + DateTimeOffset? OfflineUntil, + bool IsThisMachine); + +// One per app; disposing it stops the refresh schedule. Every call throws TableProException with an account.* code. +public sealed class TableProAccount : IDisposable +{ + private readonly Native.AccountService _service; + private readonly AccountWake _wake; + private int _reading; + private volatile bool _disposed; + + internal TableProAccount(Native.AccountService service, AccountWake wake) + { + _service = service; + _wake = wake; + } + + // A snapshot; cheap enough to read on the UI thread. + public AccountStatus Status => Mapping.Status(_service.Status()); + + // From the entitlement's feature codes only: the app knows no plan or tier. + public FeatureAccess Access(string feature) + { + ArgumentNullException.ThrowIfNull(feature); + return Mapping.Access(_service.FeatureAccess(feature)); + } + + // Resumes on the caller's context; changes that come while it is busy are read as one. Read once. + public async IAsyncEnumerable ReadStatusChangesAsync( + [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + if (Interlocked.Exchange(ref _reading, 1) == 1) + { + throw new InvalidOperationException("The account's changes are already being read."); + } + + while (await _wake.WaitAsync(cancellationToken) && !_disposed) + { + _wake.Take(); + yield return Status; + } + } + + // The cancel ends only the wait for the browser: once it has come back, the sign-in is kept. + public Task SignInAsync(CancellationToken cancellationToken = default) => + CoreCall.RunAsync(token => _service.SignIn(token), cancellationToken); + + // Signs out here even when the server could not be told, which the error then says. + public Task SignOutAsync() => CoreCall.RunAsync(() => _service.SignOut()); + + public Task RefreshAsync() => CoreCall.RunAsync(() => _service.Refresh()); + + // False when the account was not past the device limit, so nothing was asked. + public Task RefreshPastDeviceLimitAsync() => CoreCall.RunAsync(() => _service.RefreshPastDeviceLimit()); + + public async Task GetProfileAsync() => + Mapping.Profile(await CoreCall.RunAsync(() => _service.Profile()).ConfigureAwait(false)); + + public async Task> GetDevicesAsync() => + [.. (await CoreCall.RunAsync(() => _service.Devices()).ConfigureAwait(false)).Select(Mapping.Device)]; + + public Task RemoveDeviceAsync(string deviceId) + { + ArgumentException.ThrowIfNullOrEmpty(deviceId); + return CoreCall.RunAsync(() => _service.RemoveDevice(deviceId)); + } + + public async Task GetShareLimitsAsync() => + Mapping.Limits(await CoreCall.RunAsync(() => _service.ShareLimits()).ConfigureAwait(false)); + + // A result share takes the set's first visibleColumns columns and its first maxRows rows, the plan's limit; the + // set must have all its rows. A query share takes no set. + public async Task CreateShareAsync( + ShareRequest request, + ResultSet? rows = null, + int visibleColumns = 0, + long maxRows = 0) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentOutOfRangeException.ThrowIfNegative(visibleColumns); + ArgumentOutOfRangeException.ThrowIfNegative(maxRows); + var native = Mapping.Request(request); + var set = rows?.Handle; + var limit = (uint)Math.Min(maxRows, uint.MaxValue); + var created = await CoreCall.RunAsync( + () => _service.CreateShare(native, set, checked((uint)visibleColumns), limit)) + .ConfigureAwait(false); + return Mapping.Created(created); + } + + // The account's own links, newest first, without their SQL. + public async Task ListSharesAsync(bool liveOnly, string? cursor = null) => + Mapping.Page(await CoreCall.RunAsync(() => _service.ListShares(liveOnly, cursor)).ConfigureAwait(false)); + + public Task RevokeShareAsync(string shareId) + { + ArgumentException.ThrowIfNullOrEmpty(shareId); + return CoreCall.RunAsync(() => _service.RevokeShare(shareId)); + } + + // A new expiry from now; Free extends a link this way. + public async Task ExtendShareAsync(string shareId, ShareExpiry expiry) + { + ArgumentException.ThrowIfNullOrEmpty(shareId); + var native = Mapping.Expiry(expiry); + return Mapping.Link(await CoreCall.RunAsync(() => _service.ExtendShare(shareId, native)).ConfigureAwait(false)); + } + + // Works signed out. account.share_password_required asks for the password, account.share_password_wrong again. + public async Task FetchSharedAsync(string token, string? password = null) + { + ArgumentNullException.ThrowIfNull(token); + var shared = await CoreCall.RunAsync(() => _service.FetchShared(token, password)).ConfigureAwait(false); + return Mapping.Public(shared); + } + + public void Dispose() + { + _disposed = true; + _wake.Close(); + _service.Dispose(); + } +} + +// The core calls it on a runtime thread; one slot holds every change not yet read. +internal sealed class AccountWake : Native.AccountListener +{ + private readonly Channel _signal = Channel.CreateBounded( + new BoundedChannelOptions(1) + { + FullMode = BoundedChannelFullMode.DropWrite, + SingleReader = true, + }); + + public void StatusChanged() => _signal.Writer.TryWrite(true); + + // False once the account is disposed and no change is left. + public ValueTask WaitAsync(CancellationToken cancellationToken) => + _signal.Reader.WaitToReadAsync(cancellationToken); + + public void Take() => _signal.Reader.TryRead(out _); + + public void Close() => _signal.Writer.TryComplete(); +} + +internal sealed class AccountBrowserAdapter(IAccountBrowser browser) : Native.HostBrowser +{ + // An exception other than the declared one would end the call as a panic in the core. + public void OpenUrl(string url) + { + bool opened; + try + { + opened = browser.OpenAsync(new Uri(url)).GetAwaiter().GetResult(); + } + catch (Exception exception) + { + throw new Native.HostBrowserException.Failed(exception.Message); + } + + if (!opened) + { + throw new Native.HostBrowserException.Failed("the system did not open the page"); + } + } +} diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 7953220314..a132ea94fc 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -750,6 +750,14 @@ public delegate void UniffiForeignFutureCompleteVoid( ulong @callbackData,_UniFFILib.UniffiForeignFutureResultVoid @result ); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceAccountListenerMethod0( + ulong @uniffiHandle,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void UniffiCallbackInterfaceHostBrowserMethod0( + ulong @uniffiHandle,RustBuffer @url,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err + ); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void UniffiCallbackInterfaceHostSecretsMethod0( ulong @uniffiHandle,RustBuffer @connectionId,RustBuffer @kind,IntPtr /*RustBuffer*/ @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err ); @@ -790,6 +798,20 @@ public delegate void UniffiCallbackInterfaceRunListenerMethod0( ulong @uniffiHandle,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err ); [StructLayout(LayoutKind.Sequential)] + public struct UniffiVTableCallbackInterfaceAccountListener + { + public IntPtr @uniffiFree; + public IntPtr @uniffiClone; + public IntPtr @statusChanged; + } + [StructLayout(LayoutKind.Sequential)] + public struct UniffiVTableCallbackInterfaceHostBrowser + { + public IntPtr @uniffiFree; + public IntPtr @uniffiClone; + public IntPtr @openUrl; + } + [StructLayout(LayoutKind.Sequential)] public struct UniffiVTableCallbackInterfaceHostSecrets { public IntPtr @uniffiFree; @@ -1067,6 +1089,50 @@ public struct UniffiVTableCallbackInterfaceRunListener + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1092,11 +1158,200 @@ static _UniFFILib() { _UniFFILib.uniffiCheckContractApiVersion(); _UniFFILib.uniffiCheckApiChecksums(); + UniffiCallbackInterfaceAccountListener.Register(); + UniffiCallbackInterfaceHostBrowser.Register(); UniffiCallbackInterfaceHostPrompter.Register(); UniffiCallbackInterfaceHostSecrets.Register(); UniffiCallbackInterfaceRunListener.Register(); } + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_clone_accountservice(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + void uniffi_tablepro_ffi_fn_free_accountservice(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_devices(ulong @ptr + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + RustBuffer uniffi_tablepro_ffi_fn_method_accountservice_feature_access(ulong @ptr,RustBuffer @feature,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_profile(ulong @ptr + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_refresh(ulong @ptr + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_refresh_past_device_limit(ulong @ptr + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_remove_device(ulong @ptr,RustBuffer @deviceId + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_sign_in(ulong @ptr,RustBuffer @cancel + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_sign_out(ulong @ptr + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + RustBuffer uniffi_tablepro_ffi_fn_method_accountservice_status(ulong @ptr,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_create_share(ulong @ptr,RustBuffer @request,RustBuffer @result,uint @visibleColumns,uint @maxRows + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_extend_share(ulong @ptr,RustBuffer @shareId,RustBuffer @expiry + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_fetch_shared(ulong @ptr,RustBuffer @token,RustBuffer @password + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_list_shares(ulong @ptr,sbyte @liveOnly,RustBuffer @cursor + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_revoke_share(ulong @ptr,RustBuffer @shareId + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_accountservice_share_limits(ulong @ptr + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -1196,6 +1451,17 @@ public static extern ulong uniffi_tablepro_ffi_fn_constructor_core_with_system_secrets(RustBuffer @config,ref UniffiRustCallStatus _uniffi_out_err ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ulong uniffi_tablepro_ffi_fn_method_core_open_account(ulong @ptr,RustBuffer @config,ulong @browser,ulong @listener + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -2337,7 +2603,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_hostsecrets(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostSecrets*/ @vtable + void uniffi_tablepro_ffi_fn_init_callback_vtable_accountlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceAccountListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -2348,7 +2614,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_hostprompter(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostPrompter*/ @vtable + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostbrowser(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostBrowser*/ @vtable ); #if NET8_0_OR_GREATER @@ -2359,7 +2625,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void uniffi_tablepro_ffi_fn_init_callback_vtable_runlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceRunListener*/ @vtable + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostsecrets(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostSecrets*/ @vtable ); #if NET8_0_OR_GREATER @@ -2370,7 +2636,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer uniffi_tablepro_ffi_fn_func_parse_connection_url(RustBuffer @url,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_init_callback_vtable_hostprompter(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceHostPrompter*/ @vtable ); #if NET8_0_OR_GREATER @@ -2381,7 +2647,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rustbuffer_alloc(ulong @size,ref UniffiRustCallStatus _uniffi_out_err + void uniffi_tablepro_ffi_fn_init_callback_vtable_runlistener(IntPtr /*_UniFFILib.UniffiVTableCallbackInterfaceRunListener*/ @vtable ); #if NET8_0_OR_GREATER @@ -2392,7 +2658,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rustbuffer_from_bytes(ForeignBytes @bytes,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_func_scan_columns_for_secrets(RustBuffer @names,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2403,7 +2669,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rustbuffer_free(RustBuffer @buf,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_func_scan_sql_for_secrets(RustBuffer @sql,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2414,7 +2680,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - RustBuffer ffi_tablepro_ffi_rustbuffer_reserve(RustBuffer @buf,ulong @additional,ref UniffiRustCallStatus _uniffi_out_err + RustBuffer uniffi_tablepro_ffi_fn_func_share_token_from_link(RustBuffer @link,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2425,7 +2691,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_poll_u8(ulong @handle,IntPtr @callback,ulong @callbackData + RustBuffer uniffi_tablepro_ffi_fn_func_parse_connection_url(RustBuffer @url,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2436,7 +2702,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_cancel_u8(ulong @handle + RustBuffer ffi_tablepro_ffi_rustbuffer_alloc(ulong @size,ref UniffiRustCallStatus _uniffi_out_err ); #if NET8_0_OR_GREATER @@ -2447,7 +2713,62 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - void ffi_tablepro_ffi_rust_future_free_u8(ulong @handle + RustBuffer ffi_tablepro_ffi_rustbuffer_from_bytes(ForeignBytes @bytes,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + void ffi_tablepro_ffi_rustbuffer_free(RustBuffer @buf,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + RustBuffer ffi_tablepro_ffi_rustbuffer_reserve(RustBuffer @buf,ulong @additional,ref UniffiRustCallStatus _uniffi_out_err + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + void ffi_tablepro_ffi_rust_future_poll_u8(ulong @handle,IntPtr @callback,ulong @callbackData + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + void ffi_tablepro_ffi_rust_future_cancel_u8(ulong @handle + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + void ffi_tablepro_ffi_rust_future_free_u8(ulong @handle ); #if NET8_0_OR_GREATER @@ -2945,6 +3266,39 @@ public static extern void ffi_tablepro_ffi_rust_future_complete_void(ulong @handle,ref UniffiRustCallStatus _uniffi_out_err ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_func_share_token_from_link( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -2956,6 +3310,171 @@ public static extern ushort uniffi_tablepro_ffi_checksum_func_parse_connection_url( ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_devices( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_feature_access( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_profile( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_refresh( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_remove_device( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_in( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_sign_out( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_status( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_create_share( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_extend_share( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_fetch_shared( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_list_shares( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_revoke_share( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_accountservice_share_limits( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -2978,6 +3497,17 @@ public static extern ushort uniffi_tablepro_ffi_checksum_method_canceltoken_is_cancelled( ); + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_core_open_account( + ); + #if NET8_0_OR_GREATER [LibraryImport("tablepro_ffi")] [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] @@ -3954,7 +4484,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load( + ushort uniffi_tablepro_ffi_checksum_method_accountlistener_status_changed( ); #if NET8_0_OR_GREATER @@ -3965,7 +4495,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store( + ushort uniffi_tablepro_ffi_checksum_method_hostbrowser_open_url( ); #if NET8_0_OR_GREATER @@ -3976,7 +4506,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_relabel( + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load( ); #if NET8_0_OR_GREATER @@ -3987,7 +4517,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete( + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store( ); #if NET8_0_OR_GREATER @@ -3998,7 +4528,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_connection( + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_relabel( ); #if NET8_0_OR_GREATER @@ -4009,7 +4539,7 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load_item( + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete( ); #if NET8_0_OR_GREATER @@ -4020,7 +4550,29 @@ public static partial [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] public static extern #endif - ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store_item( + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_delete_connection( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_load_item( + ); + + #if NET8_0_OR_GREATER + [LibraryImport("tablepro_ffi")] + [UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })] + public static partial +#else + [DllImport("tablepro_ffi", CallingConvention = CallingConvention.Cdecl)] + public static extern +#endif + ushort uniffi_tablepro_ffi_checksum_method_hostsecrets_store_item( ); #if NET8_0_OR_GREATER @@ -4076,12 +4628,120 @@ static void uniffiCheckContractApiVersion() { } } static void uniffiCheckApiChecksums() { + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets(); + if (checksum != 2030) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_columns_for_secrets` checksum `2030`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets(); + if (checksum != 6288) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_scan_sql_for_secrets` checksum `6288`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_share_token_from_link(); + if (checksum != 49369) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_share_token_from_link` checksum `49369`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_func_parse_connection_url(); if (checksum != 48047) { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_func_parse_connection_url` checksum `48047`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_devices(); + if (checksum != 18213) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_devices` checksum `18213`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_feature_access(); + if (checksum != 31576) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_feature_access` checksum `31576`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_profile(); + if (checksum != 61215) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_profile` checksum `61215`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_refresh(); + if (checksum != 5597) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_refresh` checksum `5597`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit(); + if (checksum != 6648) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_refresh_past_device_limit` checksum `6648`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_remove_device(); + if (checksum != 12305) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_remove_device` checksum `12305`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_sign_in(); + if (checksum != 18871) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_sign_in` checksum `18871`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_sign_out(); + if (checksum != 10320) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_sign_out` checksum `10320`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_status(); + if (checksum != 7584) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_status` checksum `7584`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_create_share(); + if (checksum != 41975) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_create_share` checksum `41975`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_extend_share(); + if (checksum != 63736) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_extend_share` checksum `63736`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_fetch_shared(); + if (checksum != 32477) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_fetch_shared` checksum `32477`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_list_shares(); + if (checksum != 5547) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_list_shares` checksum `5547`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_revoke_share(); + if (checksum != 62749) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_revoke_share` checksum `62749`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountservice_share_limits(); + if (checksum != 32202) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountservice_share_limits` checksum `32202`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_canceltoken_cancel(); if (checksum != 52249) { @@ -4094,6 +4754,12 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_canceltoken_is_cancelled` checksum `24287`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_core_open_account(); + if (checksum != 36884) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_core_open_account` checksum `36884`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_core_connect_saved(); if (checksum != 5649) { @@ -4622,6 +5288,18 @@ static void uniffiCheckApiChecksums() { throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_constructor_core_with_system_secrets` checksum `43052`, library returned `{checksum}`"); } } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_accountlistener_status_changed(); + if (checksum != 24504) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_accountlistener_status_changed` checksum `24504`, library returned `{checksum}`"); + } + } + { + var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostbrowser_open_url(); + if (checksum != 39709) { + throw new UniffiContractChecksumException($"TablePro.Interop.Native: uniffi bindings expected function `uniffi_tablepro_ffi_checksum_method_hostbrowser_open_url` checksum `39709`, library returned `{checksum}`"); + } + } { var checksum = _UniFFILib.uniffi_tablepro_ffi_checksum_method_hostsecrets_load(); if (checksum != 39136) { @@ -4877,47 +5555,58 @@ public override void Write(string value, BigEndianStream stream) { -/// -/// A cancel the foreign side passes into an async call, since UniFFI -/// itself never cancels a call. C# fires it from a `CancellationToken`, -/// Swift from a task's cancellation handler. -/// -internal interface ICancelToken { - void Cancel(); - bool IsCancelled(); +internal interface IAccountService { + /// + Task Devices(); + FeatureAccessTag FeatureAccess(string @feature); + /// + Task Profile(); + /// + Task Refresh(); + /// + Task RefreshPastDeviceLimit(); + /// + Task RemoveDevice(string @deviceId); + /// + Task SignIn(CancelToken? @cancel); + /// + Task SignOut(); + AccountStatusInfo Status(); + /// + Task CreateShare(ShareRequestArg @request, ResultSet? @result, uint @visibleColumns, uint @maxRows); + /// + Task ExtendShare(string @shareId, ShareExpiryTag @expiry); + /// + Task FetchShared(string @token, SecretString? @password); + /// + Task ListShares(bool @liveOnly, string? @cursor); + /// + Task RevokeShare(string @shareId); + /// + Task ShareLimits(); } -/// -/// A cancel the foreign side passes into an async call, since UniFFI -/// itself never cancels a call. C# fires it from a `CancellationToken`, -/// Swift from a task's cancellation handler. -/// -internal class CancelToken : ICancelToken, IDisposable { +internal class AccountService : IAccountService, IDisposable { protected ulong pointer; private int _wasDestroyed = 0; private long _callCounter = 1; - public CancelToken(ulong pointer) { + public AccountService(ulong pointer) { this.pointer = pointer; } - ~CancelToken() { + ~AccountService() { Destroy(); } - public CancelToken() : - this( - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_constructor_canceltoken_new( ref _status) -)) {} protected void FreeRustArcPtr() { _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - _UniFFILib.uniffi_tablepro_ffi_fn_free_canceltoken(this.pointer, ref status); + _UniFFILib.uniffi_tablepro_ffi_fn_free_accountservice(this.pointer, ref status); }); } protected ulong CloneRustArcPtr() { return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { - return _UniFFILib.uniffi_tablepro_ffi_fn_clone_canceltoken(this.pointer, ref status); + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_accountservice(this.pointer, ref status); }); } @@ -4985,58 +5674,478 @@ internal T CallWithPointer(Func func) } - public void Cancel() { - CallWithPointer(thisPtr => - _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_canceltoken_cancel(thisPtr, ref _status) -)); + /// + public async Task Devices() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_devices(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterSequenceTypeDeviceInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - - public bool IsCancelled() { - return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + public FeatureAccessTag FeatureAccess(string @feature) { + return CallWithPointer(thisPtr => FfiConverterTypeFeatureAccessTag.INSTANCE.Lift( _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => - _UniFFILib.uniffi_tablepro_ffi_fn_method_canceltoken_is_cancelled(thisPtr, ref _status) + _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_feature_access(thisPtr, FfiConverterString.INSTANCE.Lower(@feature), ref _status) ))); } - - -} -class FfiConverterTypeCancelToken: FfiConverter { - public static FfiConverterTypeCancelToken INSTANCE = new FfiConverterTypeCancelToken(); - - - public override ulong Lower(CancelToken value) { - return value.CallWithPointer(thisPtr => thisPtr); - } - - public override CancelToken Lift(ulong value) { - return new CancelToken(value); + /// + public async Task Profile() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_profile(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeProfileInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - public override CancelToken Read(BigEndianStream stream) { - return Lift(stream.ReadULong()); + + /// + public async Task Refresh() {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_refresh(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - public override int AllocationSize(CancelToken value) { - return 8; + + /// + public async Task RefreshPastDeviceLimit() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_refresh_past_device_limit(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_i8(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_i8(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_i8(future), + // Lift + (result) => FfiConverterBoolean.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } - - public override void Write(CancelToken value, BigEndianStream stream) { - stream.WriteULong(Lower(value)); + + /// + public async Task RemoveDevice(string @deviceId) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_remove_device(thisPtr, FfiConverterString.INSTANCE.Lower(@deviceId)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); } -} - - - -internal interface IConnectionLibrary { + /// - Task ApplyCloudPull(CloudLibraryPull @pull); + public async Task SignIn(CancelToken? @cancel) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_sign_in(thisPtr, FfiConverterOptionalTypeCancelToken.INSTANCE.Lower(@cancel)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + /// - Task CloudEdits(CloudLibraryRecords @base); + public async Task SignOut() {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_sign_out(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + public AccountStatusInfo Status() { + return CallWithPointer(thisPtr => FfiConverterTypeAccountStatusInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_status(thisPtr, ref _status) +))); + } + + + /// + public async Task CreateShare(ShareRequestArg @request, ResultSet? @result, uint @visibleColumns, uint @maxRows) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_create_share(thisPtr, FfiConverterTypeShareRequestArg.INSTANCE.Lower(@request), FfiConverterOptionalTypeResultSet.INSTANCE.Lower(@result), FfiConverterUInt32.INSTANCE.Lower(@visibleColumns), FfiConverterUInt32.INSTANCE.Lower(@maxRows)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeCreatedShareInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ExtendShare(string @shareId, ShareExpiryTag @expiry) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_extend_share(thisPtr, FfiConverterString.INSTANCE.Lower(@shareId), FfiConverterTypeShareExpiryTag.INSTANCE.Lower(@expiry)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeShareInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task FetchShared(string @token, SecretString? @password) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_fetch_shared(thisPtr, FfiConverterString.INSTANCE.Lower(@token), FfiConverterOptionalTypeSecretString.INSTANCE.Lower(@password)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeSharedLinkInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ListShares(bool @liveOnly, string? @cursor) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_list_shares(thisPtr, FfiConverterBoolean.INSTANCE.Lower(@liveOnly), FfiConverterOptionalString.INSTANCE.Lower(@cursor)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeSharePageInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task RevokeShare(string @shareId) {await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_revoke_share(thisPtr, FfiConverterString.INSTANCE.Lower(@shareId)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_void(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => {_UniFFILib.ffi_tablepro_ffi_rust_future_complete_void(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_void(future), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + /// + public async Task ShareLimits() { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_accountservice_share_limits(thisPtr); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_rust_buffer(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_rust_buffer(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_rust_buffer(future), + // Lift + (result) => FfiConverterTypeShareLimitsInfo.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } + + + +} +class FfiConverterTypeAccountService: FfiConverter { + public static FfiConverterTypeAccountService INSTANCE = new FfiConverterTypeAccountService(); + + + public override ulong Lower(AccountService value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override AccountService Lift(ulong value) { + return new AccountService(value); + } + + public override AccountService Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(AccountService value) { + return 8; + } + + public override void Write(AccountService value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +/// +/// A cancel the foreign side passes into an async call, since UniFFI +/// itself never cancels a call. C# fires it from a `CancellationToken`, +/// Swift from a task's cancellation handler. +/// +internal interface ICancelToken { + void Cancel(); + bool IsCancelled(); +} +/// +/// A cancel the foreign side passes into an async call, since UniFFI +/// itself never cancels a call. C# fires it from a `CancellationToken`, +/// Swift from a task's cancellation handler. +/// +internal class CancelToken : ICancelToken, IDisposable { + protected ulong pointer; + private int _wasDestroyed = 0; + private long _callCounter = 1; + + public CancelToken(ulong pointer) { + this.pointer = pointer; + } + + ~CancelToken() { + Destroy(); + } + public CancelToken() : + this( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_constructor_canceltoken_new( ref _status) +)) {} + + protected void FreeRustArcPtr() { + _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + _UniFFILib.uniffi_tablepro_ffi_fn_free_canceltoken(this.pointer, ref status); + }); + } + + protected ulong CloneRustArcPtr() { + return _UniffiHelpers.RustCall((ref UniffiRustCallStatus status) => { + return _UniFFILib.uniffi_tablepro_ffi_fn_clone_canceltoken(this.pointer, ref status); + }); + } + + public void Destroy() + { + // Only allow a single call to this method. + if (Interlocked.CompareExchange(ref _wasDestroyed, 1, 0) == 0) + { + // This decrement always matches the initial count of 1 given at creation time. + if (Interlocked.Decrement(ref _callCounter) == 0) + { + FreeRustArcPtr(); + } + } + } + + public void Dispose() + { + Destroy(); + GC.SuppressFinalize(this); // Suppress finalization to avoid unnecessary GC overhead. + } + + private void IncrementCallCounter() + { + // Check and increment the call counter, to keep the object alive. + // This needs a compare-and-set retry loop in case of concurrent updates. + long count; + do + { + count = Interlocked.Read(ref _callCounter); + if (count == 0L) throw new System.ObjectDisposedException(String.Format("'{0}' object has already been destroyed", this.GetType().Name)); + if (count == long.MaxValue) throw new System.OverflowException(String.Format("'{0}' call counter would overflow", this.GetType().Name)); + + } while (Interlocked.CompareExchange(ref _callCounter, count + 1, count) != count); + } + + private void DecrementCallCounter() + { + // This decrement always matches the increment we performed above. + if (Interlocked.Decrement(ref _callCounter) == 0) { + FreeRustArcPtr(); + } + } + + internal void CallWithPointer(Action action) + { + IncrementCallCounter(); + try { + action(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + internal T CallWithPointer(Func func) + { + IncrementCallCounter(); + try { + return func(CloneRustArcPtr()); + } + finally { + DecrementCallCounter(); + } + } + + + public void Cancel() { + CallWithPointer(thisPtr => + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_canceltoken_cancel(thisPtr, ref _status) +)); + } + + + + public bool IsCancelled() { + return CallWithPointer(thisPtr => FfiConverterBoolean.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_method_canceltoken_is_cancelled(thisPtr, ref _status) +))); + } + + + + +} +class FfiConverterTypeCancelToken: FfiConverter { + public static FfiConverterTypeCancelToken INSTANCE = new FfiConverterTypeCancelToken(); + + + public override ulong Lower(CancelToken value) { + return value.CallWithPointer(thisPtr => thisPtr); + } + + public override CancelToken Lift(ulong value) { + return new CancelToken(value); + } + + public override CancelToken Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(CancelToken value) { + return 8; + } + + public override void Write(CancelToken value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface IConnectionLibrary { + /// + Task ApplyCloudPull(CloudLibraryPull @pull); + /// + Task CloudEdits(CloudLibraryRecords @base); /// Task AddFavorites(string[] @ids, string? @before); /// @@ -5558,6 +6667,8 @@ public override void Write(ConnectionLibrary value, BigEndianStream stream) { internal interface ICore { + /// + Task OpenAccount(AccountConfig @config, HostBrowser @browser, AccountListener @listener); /// Task ConnectSaved(string @id, ConnectionSecrets @secrets, ConnectionSecrets @keep, HostPrompter? @prompter, CancelToken? @cancel); DriverInfo[] Drivers(); @@ -5664,7 +6775,29 @@ internal T CallWithPointer(Func func) DecrementCallCounter(); } } - + + + /// + public async Task OpenAccount(AccountConfig @config, HostBrowser @browser, AccountListener @listener) { + return await _UniFFIAsync.UniffiRustCallAsync( + // Get rust future + CallWithPointer(thisPtr => { + return _UniFFILib.uniffi_tablepro_ffi_fn_method_core_open_account(thisPtr, FfiConverterTypeAccountConfig.INSTANCE.Lower(@config), FfiConverterTypeHostBrowser.INSTANCE.Lower(@browser), FfiConverterTypeAccountListener.INSTANCE.Lower(@listener)); + }), + // Poll + (ulong future, IntPtr continuation, ulong data) => _UniFFILib.ffi_tablepro_ffi_rust_future_poll_u64(future, continuation, data), + // Complete + (ulong future, ref UniffiRustCallStatus status) => { + return _UniFFILib.ffi_tablepro_ffi_rust_future_complete_u64(future, ref status); + }, + // Free + (ulong future) => _UniFFILib.ffi_tablepro_ffi_rust_future_free_u64(future), + // Lift + (result) => FfiConverterTypeAccountService.INSTANCE.Lift(result), + // Error + FfiConverterTypeCoreError.INSTANCE + ); + } /// public async Task ConnectSaved(string @id, ConnectionSecrets @secrets, ConnectionSecrets @keep, HostPrompter? @prompter, CancelToken? @cancel) { @@ -7747,6 +8880,126 @@ public override void Write(TablePageRead value, BigEndianStream stream) { +internal record AccountConfig ( + string? AccountUrl, + string? ApiUrl, + string[] EntitlementKeys, + string DeviceName, + string AppVersion, + string OsVersion, + string AccountFile, + string CallbackFinished, + string CallbackUnknown, + string? MachineGuid +) { +} + +class FfiConverterTypeAccountConfig: FfiConverterRustBuffer { + public static FfiConverterTypeAccountConfig INSTANCE = new FfiConverterTypeAccountConfig(); + + public override AccountConfig Read(BigEndianStream stream) { + return new AccountConfig( + AccountUrl: FfiConverterOptionalString.INSTANCE.Read(stream), + ApiUrl: FfiConverterOptionalString.INSTANCE.Read(stream), + EntitlementKeys: FfiConverterSequenceString.INSTANCE.Read(stream), + DeviceName: FfiConverterString.INSTANCE.Read(stream), + AppVersion: FfiConverterString.INSTANCE.Read(stream), + OsVersion: FfiConverterString.INSTANCE.Read(stream), + AccountFile: FfiConverterString.INSTANCE.Read(stream), + CallbackFinished: FfiConverterString.INSTANCE.Read(stream), + CallbackUnknown: FfiConverterString.INSTANCE.Read(stream), + MachineGuid: FfiConverterOptionalString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(AccountConfig value) { + return 0 + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.AccountUrl) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.ApiUrl) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.EntitlementKeys) + + FfiConverterString.INSTANCE.AllocationSize(value.DeviceName) + + FfiConverterString.INSTANCE.AllocationSize(value.AppVersion) + + FfiConverterString.INSTANCE.AllocationSize(value.OsVersion) + + FfiConverterString.INSTANCE.AllocationSize(value.AccountFile) + + FfiConverterString.INSTANCE.AllocationSize(value.CallbackFinished) + + FfiConverterString.INSTANCE.AllocationSize(value.CallbackUnknown) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.MachineGuid); + } + + public override void Write(AccountConfig value, BigEndianStream stream) { + FfiConverterOptionalString.INSTANCE.Write(value.AccountUrl, stream); + FfiConverterOptionalString.INSTANCE.Write(value.ApiUrl, stream); + FfiConverterSequenceString.INSTANCE.Write(value.EntitlementKeys, stream); + FfiConverterString.INSTANCE.Write(value.DeviceName, stream); + FfiConverterString.INSTANCE.Write(value.AppVersion, stream); + FfiConverterString.INSTANCE.Write(value.OsVersion, stream); + FfiConverterString.INSTANCE.Write(value.AccountFile, stream); + FfiConverterString.INSTANCE.Write(value.CallbackFinished, stream); + FfiConverterString.INSTANCE.Write(value.CallbackUnknown, stream); + FfiConverterOptionalString.INSTANCE.Write(value.MachineGuid, stream); + } +} + + + +internal record AccountStatusInfo ( + AccountStateTag State, + string? AccountId, + string? Email, + string? Name, + string[] Features, + LicenseInfo[] Licenses, + long? EntitlementExpiresAtSecs, + EntitlementProblemTag? Problem, + bool Remembered +) { +} + +class FfiConverterTypeAccountStatusInfo: FfiConverterRustBuffer { + public static FfiConverterTypeAccountStatusInfo INSTANCE = new FfiConverterTypeAccountStatusInfo(); + + public override AccountStatusInfo Read(BigEndianStream stream) { + return new AccountStatusInfo( + State: FfiConverterTypeAccountStateTag.INSTANCE.Read(stream), + AccountId: FfiConverterOptionalString.INSTANCE.Read(stream), + Email: FfiConverterOptionalString.INSTANCE.Read(stream), + Name: FfiConverterOptionalString.INSTANCE.Read(stream), + Features: FfiConverterSequenceString.INSTANCE.Read(stream), + Licenses: FfiConverterSequenceTypeLicenseInfo.INSTANCE.Read(stream), + EntitlementExpiresAtSecs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + Problem: FfiConverterOptionalTypeEntitlementProblemTag.INSTANCE.Read(stream), + Remembered: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(AccountStatusInfo value) { + return 0 + + FfiConverterTypeAccountStateTag.INSTANCE.AllocationSize(value.State) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.AccountId) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Email) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Name) + + FfiConverterSequenceString.INSTANCE.AllocationSize(value.Features) + + FfiConverterSequenceTypeLicenseInfo.INSTANCE.AllocationSize(value.Licenses) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.EntitlementExpiresAtSecs) + + FfiConverterOptionalTypeEntitlementProblemTag.INSTANCE.AllocationSize(value.Problem) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Remembered); + } + + public override void Write(AccountStatusInfo value, BigEndianStream stream) { + FfiConverterTypeAccountStateTag.INSTANCE.Write(value.State, stream); + FfiConverterOptionalString.INSTANCE.Write(value.AccountId, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Email, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Name, stream); + FfiConverterSequenceString.INSTANCE.Write(value.Features, stream); + FfiConverterSequenceTypeLicenseInfo.INSTANCE.Write(value.Licenses, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.EntitlementExpiresAtSecs, stream); + FfiConverterOptionalTypeEntitlementProblemTag.INSTANCE.Write(value.Problem, stream); + FfiConverterBoolean.INSTANCE.Write(value.Remembered, stream); + } +} + + + internal record CellChange ( uint Column, CellEdit Edit @@ -8155,6 +9408,94 @@ public override void Write(ConnectionSecrets value, BigEndianStream stream) { +internal record CreatedShareInfo ( + ShareInfo Share, + string Url +) { +} + +class FfiConverterTypeCreatedShareInfo: FfiConverterRustBuffer { + public static FfiConverterTypeCreatedShareInfo INSTANCE = new FfiConverterTypeCreatedShareInfo(); + + public override CreatedShareInfo Read(BigEndianStream stream) { + return new CreatedShareInfo( + Share: FfiConverterTypeShareInfo.INSTANCE.Read(stream), + Url: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(CreatedShareInfo value) { + return 0 + + FfiConverterTypeShareInfo.INSTANCE.AllocationSize(value.Share) + + FfiConverterString.INSTANCE.AllocationSize(value.Url); + } + + public override void Write(CreatedShareInfo value, BigEndianStream stream) { + FfiConverterTypeShareInfo.INSTANCE.Write(value.Share, stream); + FfiConverterString.INSTANCE.Write(value.Url, stream); + } +} + + + +internal record DeviceInfo ( + string Id, + string Platform, + string Name, + string AppVersion, + string OsVersion, + long LastSeenAtSecs, + long? LicensedAtSecs, + long? OfflineUntilSecs, + bool IsThisMachine +) { +} + +class FfiConverterTypeDeviceInfo: FfiConverterRustBuffer { + public static FfiConverterTypeDeviceInfo INSTANCE = new FfiConverterTypeDeviceInfo(); + + public override DeviceInfo Read(BigEndianStream stream) { + return new DeviceInfo( + Id: FfiConverterString.INSTANCE.Read(stream), + Platform: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream), + AppVersion: FfiConverterString.INSTANCE.Read(stream), + OsVersion: FfiConverterString.INSTANCE.Read(stream), + LastSeenAtSecs: FfiConverterInt64.INSTANCE.Read(stream), + LicensedAtSecs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + OfflineUntilSecs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + IsThisMachine: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(DeviceInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Platform) + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterString.INSTANCE.AllocationSize(value.AppVersion) + + FfiConverterString.INSTANCE.AllocationSize(value.OsVersion) + + FfiConverterInt64.INSTANCE.AllocationSize(value.LastSeenAtSecs) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.LicensedAtSecs) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.OfflineUntilSecs) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.IsThisMachine); + } + + public override void Write(DeviceInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Platform, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterString.INSTANCE.Write(value.AppVersion, stream); + FfiConverterString.INSTANCE.Write(value.OsVersion, stream); + FfiConverterInt64.INSTANCE.Write(value.LastSeenAtSecs, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.LicensedAtSecs, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.OfflineUntilSecs, stream); + FfiConverterBoolean.INSTANCE.Write(value.IsThisMachine, stream); + } +} + + + /// /// An engine, as the connect dialog lists it. /// @@ -8860,6 +10201,94 @@ public override void Write(LibrarySnapshot value, BigEndianStream stream) { +internal record LicenseInfo ( + string Id, + string Plan, + string Cycle, + string Source, + string Status, + long? RenewsAtSecs, + long? EndsAtSecs, + TeamInfo? Team +) { +} + +class FfiConverterTypeLicenseInfo: FfiConverterRustBuffer { + public static FfiConverterTypeLicenseInfo INSTANCE = new FfiConverterTypeLicenseInfo(); + + public override LicenseInfo Read(BigEndianStream stream) { + return new LicenseInfo( + Id: FfiConverterString.INSTANCE.Read(stream), + Plan: FfiConverterString.INSTANCE.Read(stream), + Cycle: FfiConverterString.INSTANCE.Read(stream), + Source: FfiConverterString.INSTANCE.Read(stream), + Status: FfiConverterString.INSTANCE.Read(stream), + RenewsAtSecs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + EndsAtSecs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + Team: FfiConverterOptionalTypeTeamInfo.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(LicenseInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Plan) + + FfiConverterString.INSTANCE.AllocationSize(value.Cycle) + + FfiConverterString.INSTANCE.AllocationSize(value.Source) + + FfiConverterString.INSTANCE.AllocationSize(value.Status) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.RenewsAtSecs) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.EndsAtSecs) + + FfiConverterOptionalTypeTeamInfo.INSTANCE.AllocationSize(value.Team); + } + + public override void Write(LicenseInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Plan, stream); + FfiConverterString.INSTANCE.Write(value.Cycle, stream); + FfiConverterString.INSTANCE.Write(value.Source, stream); + FfiConverterString.INSTANCE.Write(value.Status, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.RenewsAtSecs, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.EndsAtSecs, stream); + FfiConverterOptionalTypeTeamInfo.INSTANCE.Write(value.Team, stream); + } +} + + + +internal record MembershipInfo ( + TeamInfo Team, + string Role, + bool HasSeat +) { +} + +class FfiConverterTypeMembershipInfo: FfiConverterRustBuffer { + public static FfiConverterTypeMembershipInfo INSTANCE = new FfiConverterTypeMembershipInfo(); + + public override MembershipInfo Read(BigEndianStream stream) { + return new MembershipInfo( + Team: FfiConverterTypeTeamInfo.INSTANCE.Read(stream), + Role: FfiConverterString.INSTANCE.Read(stream), + HasSeat: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(MembershipInfo value) { + return 0 + + FfiConverterTypeTeamInfo.INSTANCE.AllocationSize(value.Team) + + FfiConverterString.INSTANCE.AllocationSize(value.Role) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.HasSeat); + } + + public override void Write(MembershipInfo value, BigEndianStream stream) { + FfiConverterTypeTeamInfo.INSTANCE.Write(value.Team, stream); + FfiConverterString.INSTANCE.Write(value.Role, stream); + FfiConverterBoolean.INSTANCE.Write(value.HasSeat, stream); + } +} + + + /// /// The table a trigger fires on. /// @@ -9034,6 +10463,48 @@ public override void Write(PlannedStatement value, BigEndianStream stream) { +internal record ProfileInfo ( + string Id, + string Email, + string? Name, + LicenseInfo[] Licenses, + MembershipInfo[] Teams +) { +} + +class FfiConverterTypeProfileInfo: FfiConverterRustBuffer { + public static FfiConverterTypeProfileInfo INSTANCE = new FfiConverterTypeProfileInfo(); + + public override ProfileInfo Read(BigEndianStream stream) { + return new ProfileInfo( + Id: FfiConverterString.INSTANCE.Read(stream), + Email: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterOptionalString.INSTANCE.Read(stream), + Licenses: FfiConverterSequenceTypeLicenseInfo.INSTANCE.Read(stream), + Teams: FfiConverterSequenceTypeMembershipInfo.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ProfileInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Email) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Name) + + FfiConverterSequenceTypeLicenseInfo.INSTANCE.AllocationSize(value.Licenses) + + FfiConverterSequenceTypeMembershipInfo.INSTANCE.AllocationSize(value.Teams); + } + + public override void Write(ProfileInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Email, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Name, stream); + FfiConverterSequenceTypeLicenseInfo.INSTANCE.Write(value.Licenses, stream); + FfiConverterSequenceTypeMembershipInfo.INSTANCE.Write(value.Teams, stream); + } +} + + + internal record PromptFieldInfo ( string Label, bool Secret @@ -9216,74 +10687,438 @@ bool IsSystem ) { } -class FfiConverterTypeSchemaEntry: FfiConverterRustBuffer { - public static FfiConverterTypeSchemaEntry INSTANCE = new FfiConverterTypeSchemaEntry(); +class FfiConverterTypeSchemaEntry: FfiConverterRustBuffer { + public static FfiConverterTypeSchemaEntry INSTANCE = new FfiConverterTypeSchemaEntry(); + + public override SchemaEntry Read(BigEndianStream stream) { + return new SchemaEntry( + Name: FfiConverterString.INSTANCE.Read(stream), + IsDefault: FfiConverterBoolean.INSTANCE.Read(stream), + IsSystem: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SchemaEntry value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Name) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.IsDefault) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.IsSystem); + } + + public override void Write(SchemaEntry value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Name, stream); + FfiConverterBoolean.INSTANCE.Write(value.IsDefault, stream); + FfiConverterBoolean.INSTANCE.Write(value.IsSystem, stream); + } +} + + + +internal record SecretHitInfo ( + SecretHitKindTag Kind, + uint Line +) { +} + +class FfiConverterTypeSecretHitInfo: FfiConverterRustBuffer { + public static FfiConverterTypeSecretHitInfo INSTANCE = new FfiConverterTypeSecretHitInfo(); + + public override SecretHitInfo Read(BigEndianStream stream) { + return new SecretHitInfo( + Kind: FfiConverterTypeSecretHitKindTag.INSTANCE.Read(stream), + Line: FfiConverterUInt32.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SecretHitInfo value) { + return 0 + + FfiConverterTypeSecretHitKindTag.INSTANCE.AllocationSize(value.Kind) + + FfiConverterUInt32.INSTANCE.AllocationSize(value.Line); + } + + public override void Write(SecretHitInfo value, BigEndianStream stream) { + FfiConverterTypeSecretHitKindTag.INSTANCE.Write(value.Kind, stream); + FfiConverterUInt32.INSTANCE.Write(value.Line, stream); + } +} + + + +internal record ServerMessage ( + string Message, + string? Code, + string? Sqlstate, + string? Detail, + string? Hint, + uint? Position +) { +} + +class FfiConverterTypeServerMessage: FfiConverterRustBuffer { + public static FfiConverterTypeServerMessage INSTANCE = new FfiConverterTypeServerMessage(); + + public override ServerMessage Read(BigEndianStream stream) { + return new ServerMessage( + Message: FfiConverterString.INSTANCE.Read(stream), + Code: FfiConverterOptionalString.INSTANCE.Read(stream), + Sqlstate: FfiConverterOptionalString.INSTANCE.Read(stream), + Detail: FfiConverterOptionalString.INSTANCE.Read(stream), + Hint: FfiConverterOptionalString.INSTANCE.Read(stream), + Position: FfiConverterOptionalUInt32.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ServerMessage value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Message) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Code) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Sqlstate) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Detail) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Hint) + + FfiConverterOptionalUInt32.INSTANCE.AllocationSize(value.Position); + } + + public override void Write(ServerMessage value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Message, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Code, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Sqlstate, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Detail, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Hint, stream); + FfiConverterOptionalUInt32.INSTANCE.Write(value.Position, stream); + } +} + + + +internal record ShareInfo ( + string Id, + string Kind, + string Scope, + string? TeamId, + string Title, + string Note, + string Dialect, + string? Sql, + bool HasSnapshot, + ulong? RowCount, + bool? Truncated, + bool HideSql, + bool AllowDownload, + bool HasPassword, + string State, + string? RemovedReason, + ulong ViewCount, + long CreatedAtSecs, + long UpdatedAtSecs, + long? ExpiresAtSecs, + long? RevokedAtSecs, + long? RemovedAtSecs, + string? Url +) { +} + +class FfiConverterTypeShareInfo: FfiConverterRustBuffer { + public static FfiConverterTypeShareInfo INSTANCE = new FfiConverterTypeShareInfo(); + + public override ShareInfo Read(BigEndianStream stream) { + return new ShareInfo( + Id: FfiConverterString.INSTANCE.Read(stream), + Kind: FfiConverterString.INSTANCE.Read(stream), + Scope: FfiConverterString.INSTANCE.Read(stream), + TeamId: FfiConverterOptionalString.INSTANCE.Read(stream), + Title: FfiConverterString.INSTANCE.Read(stream), + Note: FfiConverterString.INSTANCE.Read(stream), + Dialect: FfiConverterString.INSTANCE.Read(stream), + Sql: FfiConverterOptionalString.INSTANCE.Read(stream), + HasSnapshot: FfiConverterBoolean.INSTANCE.Read(stream), + RowCount: FfiConverterOptionalUInt64.INSTANCE.Read(stream), + Truncated: FfiConverterOptionalBoolean.INSTANCE.Read(stream), + HideSql: FfiConverterBoolean.INSTANCE.Read(stream), + AllowDownload: FfiConverterBoolean.INSTANCE.Read(stream), + HasPassword: FfiConverterBoolean.INSTANCE.Read(stream), + State: FfiConverterString.INSTANCE.Read(stream), + RemovedReason: FfiConverterOptionalString.INSTANCE.Read(stream), + ViewCount: FfiConverterUInt64.INSTANCE.Read(stream), + CreatedAtSecs: FfiConverterInt64.INSTANCE.Read(stream), + UpdatedAtSecs: FfiConverterInt64.INSTANCE.Read(stream), + ExpiresAtSecs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + RevokedAtSecs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + RemovedAtSecs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + Url: FfiConverterOptionalString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ShareInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Kind) + + FfiConverterString.INSTANCE.AllocationSize(value.Scope) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.TeamId) + + FfiConverterString.INSTANCE.AllocationSize(value.Title) + + FfiConverterString.INSTANCE.AllocationSize(value.Note) + + FfiConverterString.INSTANCE.AllocationSize(value.Dialect) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Sql) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.HasSnapshot) + + FfiConverterOptionalUInt64.INSTANCE.AllocationSize(value.RowCount) + + FfiConverterOptionalBoolean.INSTANCE.AllocationSize(value.Truncated) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.HideSql) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.AllowDownload) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.HasPassword) + + FfiConverterString.INSTANCE.AllocationSize(value.State) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.RemovedReason) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.ViewCount) + + FfiConverterInt64.INSTANCE.AllocationSize(value.CreatedAtSecs) + + FfiConverterInt64.INSTANCE.AllocationSize(value.UpdatedAtSecs) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.ExpiresAtSecs) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.RevokedAtSecs) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.RemovedAtSecs) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Url); + } + + public override void Write(ShareInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Kind, stream); + FfiConverterString.INSTANCE.Write(value.Scope, stream); + FfiConverterOptionalString.INSTANCE.Write(value.TeamId, stream); + FfiConverterString.INSTANCE.Write(value.Title, stream); + FfiConverterString.INSTANCE.Write(value.Note, stream); + FfiConverterString.INSTANCE.Write(value.Dialect, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Sql, stream); + FfiConverterBoolean.INSTANCE.Write(value.HasSnapshot, stream); + FfiConverterOptionalUInt64.INSTANCE.Write(value.RowCount, stream); + FfiConverterOptionalBoolean.INSTANCE.Write(value.Truncated, stream); + FfiConverterBoolean.INSTANCE.Write(value.HideSql, stream); + FfiConverterBoolean.INSTANCE.Write(value.AllowDownload, stream); + FfiConverterBoolean.INSTANCE.Write(value.HasPassword, stream); + FfiConverterString.INSTANCE.Write(value.State, stream); + FfiConverterOptionalString.INSTANCE.Write(value.RemovedReason, stream); + FfiConverterUInt64.INSTANCE.Write(value.ViewCount, stream); + FfiConverterInt64.INSTANCE.Write(value.CreatedAtSecs, stream); + FfiConverterInt64.INSTANCE.Write(value.UpdatedAtSecs, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.ExpiresAtSecs, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.RevokedAtSecs, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.RemovedAtSecs, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Url, stream); + } +} + + + +internal record ShareLimitsInfo ( + string Plan, + ulong Live, + ulong LiveLimit, + ulong MaxRows, + ShareExpiryTag[] Expiries, + ShareExpiryTag? DefaultExpiry, + bool Password, + bool DisableDownload, + bool Team, + bool EmailVerified, + bool SharingDisabled +) { +} + +class FfiConverterTypeShareLimitsInfo: FfiConverterRustBuffer { + public static FfiConverterTypeShareLimitsInfo INSTANCE = new FfiConverterTypeShareLimitsInfo(); + + public override ShareLimitsInfo Read(BigEndianStream stream) { + return new ShareLimitsInfo( + Plan: FfiConverterString.INSTANCE.Read(stream), + Live: FfiConverterUInt64.INSTANCE.Read(stream), + LiveLimit: FfiConverterUInt64.INSTANCE.Read(stream), + MaxRows: FfiConverterUInt64.INSTANCE.Read(stream), + Expiries: FfiConverterSequenceTypeShareExpiryTag.INSTANCE.Read(stream), + DefaultExpiry: FfiConverterOptionalTypeShareExpiryTag.INSTANCE.Read(stream), + Password: FfiConverterBoolean.INSTANCE.Read(stream), + DisableDownload: FfiConverterBoolean.INSTANCE.Read(stream), + Team: FfiConverterBoolean.INSTANCE.Read(stream), + EmailVerified: FfiConverterBoolean.INSTANCE.Read(stream), + SharingDisabled: FfiConverterBoolean.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(ShareLimitsInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Plan) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.Live) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.LiveLimit) + + FfiConverterUInt64.INSTANCE.AllocationSize(value.MaxRows) + + FfiConverterSequenceTypeShareExpiryTag.INSTANCE.AllocationSize(value.Expiries) + + FfiConverterOptionalTypeShareExpiryTag.INSTANCE.AllocationSize(value.DefaultExpiry) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Password) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.DisableDownload) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.Team) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.EmailVerified) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.SharingDisabled); + } + + public override void Write(ShareLimitsInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Plan, stream); + FfiConverterUInt64.INSTANCE.Write(value.Live, stream); + FfiConverterUInt64.INSTANCE.Write(value.LiveLimit, stream); + FfiConverterUInt64.INSTANCE.Write(value.MaxRows, stream); + FfiConverterSequenceTypeShareExpiryTag.INSTANCE.Write(value.Expiries, stream); + FfiConverterOptionalTypeShareExpiryTag.INSTANCE.Write(value.DefaultExpiry, stream); + FfiConverterBoolean.INSTANCE.Write(value.Password, stream); + FfiConverterBoolean.INSTANCE.Write(value.DisableDownload, stream); + FfiConverterBoolean.INSTANCE.Write(value.Team, stream); + FfiConverterBoolean.INSTANCE.Write(value.EmailVerified, stream); + FfiConverterBoolean.INSTANCE.Write(value.SharingDisabled, stream); + } +} + + + +internal record SharePageInfo ( + ShareInfo[] Shares, + string? NextCursor +) { +} + +class FfiConverterTypeSharePageInfo: FfiConverterRustBuffer { + public static FfiConverterTypeSharePageInfo INSTANCE = new FfiConverterTypeSharePageInfo(); + + public override SharePageInfo Read(BigEndianStream stream) { + return new SharePageInfo( + Shares: FfiConverterSequenceTypeShareInfo.INSTANCE.Read(stream), + NextCursor: FfiConverterOptionalString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(SharePageInfo value) { + return 0 + + FfiConverterSequenceTypeShareInfo.INSTANCE.AllocationSize(value.Shares) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.NextCursor); + } + + public override void Write(SharePageInfo value, BigEndianStream stream) { + FfiConverterSequenceTypeShareInfo.INSTANCE.Write(value.Shares, stream); + FfiConverterOptionalString.INSTANCE.Write(value.NextCursor, stream); + } +} + + + +internal record ShareRequestArg ( + ShareKindTag Kind, + string Sql, + string? Title, + string? Note, + string? Dialect, + ShareExpiryTag? Expiry, + bool HideSql, + bool? AllowDownload, + SecretString? Password, + string? TeamId +) { +} + +class FfiConverterTypeShareRequestArg: FfiConverterRustBuffer { + public static FfiConverterTypeShareRequestArg INSTANCE = new FfiConverterTypeShareRequestArg(); - public override SchemaEntry Read(BigEndianStream stream) { - return new SchemaEntry( - Name: FfiConverterString.INSTANCE.Read(stream), - IsDefault: FfiConverterBoolean.INSTANCE.Read(stream), - IsSystem: FfiConverterBoolean.INSTANCE.Read(stream) + public override ShareRequestArg Read(BigEndianStream stream) { + return new ShareRequestArg( + Kind: FfiConverterTypeShareKindTag.INSTANCE.Read(stream), + Sql: FfiConverterString.INSTANCE.Read(stream), + Title: FfiConverterOptionalString.INSTANCE.Read(stream), + Note: FfiConverterOptionalString.INSTANCE.Read(stream), + Dialect: FfiConverterOptionalString.INSTANCE.Read(stream), + Expiry: FfiConverterOptionalTypeShareExpiryTag.INSTANCE.Read(stream), + HideSql: FfiConverterBoolean.INSTANCE.Read(stream), + AllowDownload: FfiConverterOptionalBoolean.INSTANCE.Read(stream), + Password: FfiConverterOptionalTypeSecretString.INSTANCE.Read(stream), + TeamId: FfiConverterOptionalString.INSTANCE.Read(stream) ); } - public override int AllocationSize(SchemaEntry value) { + public override int AllocationSize(ShareRequestArg value) { return 0 - + FfiConverterString.INSTANCE.AllocationSize(value.Name) - + FfiConverterBoolean.INSTANCE.AllocationSize(value.IsDefault) - + FfiConverterBoolean.INSTANCE.AllocationSize(value.IsSystem); + + FfiConverterTypeShareKindTag.INSTANCE.AllocationSize(value.Kind) + + FfiConverterString.INSTANCE.AllocationSize(value.Sql) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Title) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Note) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Dialect) + + FfiConverterOptionalTypeShareExpiryTag.INSTANCE.AllocationSize(value.Expiry) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.HideSql) + + FfiConverterOptionalBoolean.INSTANCE.AllocationSize(value.AllowDownload) + + FfiConverterOptionalTypeSecretString.INSTANCE.AllocationSize(value.Password) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.TeamId); } - public override void Write(SchemaEntry value, BigEndianStream stream) { - FfiConverterString.INSTANCE.Write(value.Name, stream); - FfiConverterBoolean.INSTANCE.Write(value.IsDefault, stream); - FfiConverterBoolean.INSTANCE.Write(value.IsSystem, stream); + public override void Write(ShareRequestArg value, BigEndianStream stream) { + FfiConverterTypeShareKindTag.INSTANCE.Write(value.Kind, stream); + FfiConverterString.INSTANCE.Write(value.Sql, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Title, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Note, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Dialect, stream); + FfiConverterOptionalTypeShareExpiryTag.INSTANCE.Write(value.Expiry, stream); + FfiConverterBoolean.INSTANCE.Write(value.HideSql, stream); + FfiConverterOptionalBoolean.INSTANCE.Write(value.AllowDownload, stream); + FfiConverterOptionalTypeSecretString.INSTANCE.Write(value.Password, stream); + FfiConverterOptionalString.INSTANCE.Write(value.TeamId, stream); } } -internal record ServerMessage ( - string Message, - string? Code, - string? Sqlstate, - string? Detail, - string? Hint, - uint? Position +internal record SharedLinkInfo ( + string Kind, + string Title, + string Note, + string Dialect, + string? Sql, + long CreatedAtSecs, + long? ExpiresAtSecs, + bool AllowDownload, + ulong? RowCount, + bool? Truncated ) { } -class FfiConverterTypeServerMessage: FfiConverterRustBuffer { - public static FfiConverterTypeServerMessage INSTANCE = new FfiConverterTypeServerMessage(); - - public override ServerMessage Read(BigEndianStream stream) { - return new ServerMessage( - Message: FfiConverterString.INSTANCE.Read(stream), - Code: FfiConverterOptionalString.INSTANCE.Read(stream), - Sqlstate: FfiConverterOptionalString.INSTANCE.Read(stream), - Detail: FfiConverterOptionalString.INSTANCE.Read(stream), - Hint: FfiConverterOptionalString.INSTANCE.Read(stream), - Position: FfiConverterOptionalUInt32.INSTANCE.Read(stream) +class FfiConverterTypeSharedLinkInfo: FfiConverterRustBuffer { + public static FfiConverterTypeSharedLinkInfo INSTANCE = new FfiConverterTypeSharedLinkInfo(); + + public override SharedLinkInfo Read(BigEndianStream stream) { + return new SharedLinkInfo( + Kind: FfiConverterString.INSTANCE.Read(stream), + Title: FfiConverterString.INSTANCE.Read(stream), + Note: FfiConverterString.INSTANCE.Read(stream), + Dialect: FfiConverterString.INSTANCE.Read(stream), + Sql: FfiConverterOptionalString.INSTANCE.Read(stream), + CreatedAtSecs: FfiConverterInt64.INSTANCE.Read(stream), + ExpiresAtSecs: FfiConverterOptionalInt64.INSTANCE.Read(stream), + AllowDownload: FfiConverterBoolean.INSTANCE.Read(stream), + RowCount: FfiConverterOptionalUInt64.INSTANCE.Read(stream), + Truncated: FfiConverterOptionalBoolean.INSTANCE.Read(stream) ); } - public override int AllocationSize(ServerMessage value) { + public override int AllocationSize(SharedLinkInfo value) { return 0 - + FfiConverterString.INSTANCE.AllocationSize(value.Message) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Code) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Sqlstate) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Detail) - + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Hint) - + FfiConverterOptionalUInt32.INSTANCE.AllocationSize(value.Position); + + FfiConverterString.INSTANCE.AllocationSize(value.Kind) + + FfiConverterString.INSTANCE.AllocationSize(value.Title) + + FfiConverterString.INSTANCE.AllocationSize(value.Note) + + FfiConverterString.INSTANCE.AllocationSize(value.Dialect) + + FfiConverterOptionalString.INSTANCE.AllocationSize(value.Sql) + + FfiConverterInt64.INSTANCE.AllocationSize(value.CreatedAtSecs) + + FfiConverterOptionalInt64.INSTANCE.AllocationSize(value.ExpiresAtSecs) + + FfiConverterBoolean.INSTANCE.AllocationSize(value.AllowDownload) + + FfiConverterOptionalUInt64.INSTANCE.AllocationSize(value.RowCount) + + FfiConverterOptionalBoolean.INSTANCE.AllocationSize(value.Truncated); } - public override void Write(ServerMessage value, BigEndianStream stream) { - FfiConverterString.INSTANCE.Write(value.Message, stream); - FfiConverterOptionalString.INSTANCE.Write(value.Code, stream); - FfiConverterOptionalString.INSTANCE.Write(value.Sqlstate, stream); - FfiConverterOptionalString.INSTANCE.Write(value.Detail, stream); - FfiConverterOptionalString.INSTANCE.Write(value.Hint, stream); - FfiConverterOptionalUInt32.INSTANCE.Write(value.Position, stream); + public override void Write(SharedLinkInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Kind, stream); + FfiConverterString.INSTANCE.Write(value.Title, stream); + FfiConverterString.INSTANCE.Write(value.Note, stream); + FfiConverterString.INSTANCE.Write(value.Dialect, stream); + FfiConverterOptionalString.INSTANCE.Write(value.Sql, stream); + FfiConverterInt64.INSTANCE.Write(value.CreatedAtSecs, stream); + FfiConverterOptionalInt64.INSTANCE.Write(value.ExpiresAtSecs, stream); + FfiConverterBoolean.INSTANCE.Write(value.AllowDownload, stream); + FfiConverterOptionalUInt64.INSTANCE.Write(value.RowCount, stream); + FfiConverterOptionalBoolean.INSTANCE.Write(value.Truncated, stream); } } @@ -9647,6 +11482,36 @@ public override void Write(TagRecord value, BigEndianStream stream) { +internal record TeamInfo ( + string Id, + string Name +) { +} + +class FfiConverterTypeTeamInfo: FfiConverterRustBuffer { + public static FfiConverterTypeTeamInfo INSTANCE = new FfiConverterTypeTeamInfo(); + + public override TeamInfo Read(BigEndianStream stream) { + return new TeamInfo( + Id: FfiConverterString.INSTANCE.Read(stream), + Name: FfiConverterString.INSTANCE.Read(stream) + ); + } + + public override int AllocationSize(TeamInfo value) { + return 0 + + FfiConverterString.INSTANCE.AllocationSize(value.Id) + + FfiConverterString.INSTANCE.AllocationSize(value.Name); + } + + public override void Write(TeamInfo value, BigEndianStream stream) { + FfiConverterString.INSTANCE.Write(value.Id, stream); + FfiConverterString.INSTANCE.Write(value.Name, stream); + } +} + + + internal record TlsSettings ( TlsModeTag Mode, string? CaFile, @@ -9691,6 +11556,45 @@ public override void Write(TlsSettings value, BigEndianStream stream) { +internal enum AccountStateTag: int { + SignedOut, + SignedIn, + Offline +} + +class FfiConverterTypeAccountStateTag: FfiConverterRustBuffer { + public static FfiConverterTypeAccountStateTag INSTANCE = new FfiConverterTypeAccountStateTag(); + + public override AccountStateTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return AccountStateTag.SignedOut; + case 2: return AccountStateTag.SignedIn; + case 3: return AccountStateTag.Offline; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeAccountStateTag.Read()", value)); + } + } + + public override int AllocationSize(AccountStateTag value) { + return 4; + } + + public override void Write(AccountStateTag value, BigEndianStream stream) { + switch (value) { + case AccountStateTag.SignedOut: stream.WriteInt(1); break; + case AccountStateTag.SignedIn: stream.WriteInt(2); break; + case AccountStateTag.Offline: stream.WriteInt(3); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeAccountStateTag.Write()", value)); + } + } +} + + + + + + + internal record CellEdit { public record Text ( @@ -10198,6 +12102,85 @@ public override void Write(EngineCategoryTag value, BigEndianStream stream) { +internal record EntitlementProblemTag { + + public record Expired: EntitlementProblemTag {} + + + public record RefreshFailed ( + string Code + ) : EntitlementProblemTag {} + + public record DeviceLimitReached ( + DeviceInfo[] Devices + ) : EntitlementProblemTag {} + + + +} + +class FfiConverterTypeEntitlementProblemTag : FfiConverterRustBuffer{ + public static FfiConverterRustBuffer INSTANCE = new FfiConverterTypeEntitlementProblemTag(); + + public override EntitlementProblemTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new EntitlementProblemTag.Expired( + ); + case 2: + return new EntitlementProblemTag.RefreshFailed( + FfiConverterString.INSTANCE.Read(stream) + ); + case 3: + return new EntitlementProblemTag.DeviceLimitReached( + FfiConverterSequenceTypeDeviceInfo.INSTANCE.Read(stream) + ); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEntitlementProblemTag.Read()", value)); + } + } + + public override int AllocationSize(EntitlementProblemTag value) { + switch (value) { + case EntitlementProblemTag.Expired variant_value: + return 4; + case EntitlementProblemTag.RefreshFailed variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.Code); + case EntitlementProblemTag.DeviceLimitReached variant_value: + return 4 + + FfiConverterSequenceTypeDeviceInfo.INSTANCE.AllocationSize(variant_value.Devices); + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEntitlementProblemTag.AllocationSize()", value)); + } + } + + public override void Write(EntitlementProblemTag value, BigEndianStream stream) { + switch (value) { + case EntitlementProblemTag.Expired variant_value: + stream.WriteInt(1); + break; + case EntitlementProblemTag.RefreshFailed variant_value: + stream.WriteInt(2); + FfiConverterString.INSTANCE.Write(variant_value.Code, stream); + break; + case EntitlementProblemTag.DeviceLimitReached variant_value: + stream.WriteInt(3); + FfiConverterSequenceTypeDeviceInfo.INSTANCE.Write(variant_value.Devices, stream); + break; + default: + throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeEntitlementProblemTag.Write()", value)); + } + } +} + + + + + + + internal enum ExportFormatTag: int { Csv, Json, @@ -10291,6 +12274,54 @@ public override void Write(FailureCauseTag value, BigEndianStream stream) { +internal enum FeatureAccessTag: int { + Available, + SignedOut, + NotIncluded, + Expired, + RefreshFailed, + DeviceLimitReached +} + +class FfiConverterTypeFeatureAccessTag: FfiConverterRustBuffer { + public static FfiConverterTypeFeatureAccessTag INSTANCE = new FfiConverterTypeFeatureAccessTag(); + + public override FeatureAccessTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return FeatureAccessTag.Available; + case 2: return FeatureAccessTag.SignedOut; + case 3: return FeatureAccessTag.NotIncluded; + case 4: return FeatureAccessTag.Expired; + case 5: return FeatureAccessTag.RefreshFailed; + case 6: return FeatureAccessTag.DeviceLimitReached; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeFeatureAccessTag.Read()", value)); + } + } + + public override int AllocationSize(FeatureAccessTag value) { + return 4; + } + + public override void Write(FeatureAccessTag value, BigEndianStream stream) { + switch (value) { + case FeatureAccessTag.Available: stream.WriteInt(1); break; + case FeatureAccessTag.SignedOut: stream.WriteInt(2); break; + case FeatureAccessTag.NotIncluded: stream.WriteInt(3); break; + case FeatureAccessTag.Expired: stream.WriteInt(4); break; + case FeatureAccessTag.RefreshFailed: stream.WriteInt(5); break; + case FeatureAccessTag.DeviceLimitReached: stream.WriteInt(6); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeFeatureAccessTag.Write()", value)); + } + } +} + + + + + + + internal enum FilterOpTag: int { Eq, NotEq, @@ -10534,6 +12565,71 @@ public override void Write(HistoryOutcomeTag value, BigEndianStream stream) { +internal class HostBrowserException: UniffiException { + HostBrowserException() : base() {} + HostBrowserException(String @Message) : base(@Message) {} + + // Each variant is a nested class + + + public class Failed : HostBrowserException { + // Members + public string @detail; + + // Constructor + public Failed( + string @detail) : base( + "@detail" + "=" + @detail) { + + this.@detail = @detail; + } + } + + + +} + +class FfiConverterTypeHostBrowserError : FfiConverterRustBuffer, CallStatusErrorHandler { + public static FfiConverterTypeHostBrowserError INSTANCE = new FfiConverterTypeHostBrowserError(); + + public override HostBrowserException Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: + return new HostBrowserException.Failed( + FfiConverterString.INSTANCE.Read(stream)); + default: + throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeHostBrowserError.Read()", value)); + } + } + + public override int AllocationSize(HostBrowserException value) { + switch (value) { + + case HostBrowserException.Failed variant_value: + return 4 + + FfiConverterString.INSTANCE.AllocationSize(variant_value.@detail); + default: + throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeHostBrowserError.AllocationSize()", value)); + } + } + + public override void Write(HostBrowserException value, BigEndianStream stream) { + switch (value) { + case HostBrowserException.Failed variant_value: + stream.WriteInt(1); + FfiConverterString.INSTANCE.Write(variant_value.@detail, stream); + break; + default: + throw new InternalException(String.Format("invalid error value '{0}' in FfiConverterTypeHostBrowserError.Write()", value)); + } + } +} + + + + + internal class HostSecretException: UniffiException { HostSecretException() : base() {} HostSecretException(String @Message) : base(@Message) {} @@ -11754,26 +13850,83 @@ internal enum SaveGate: int { class FfiConverterTypeSaveGate: FfiConverterRustBuffer { public static FfiConverterTypeSaveGate INSTANCE = new FfiConverterTypeSaveGate(); - public override SaveGate Read(BigEndianStream stream) { + public override SaveGate Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return SaveGate.Run; + case 2: return SaveGate.Confirm; + case 3: return SaveGate.Refuse; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSaveGate.Read()", value)); + } + } + + public override int AllocationSize(SaveGate value) { + return 4; + } + + public override void Write(SaveGate value, BigEndianStream stream) { + switch (value) { + case SaveGate.Run: stream.WriteInt(1); break; + case SaveGate.Confirm: stream.WriteInt(2); break; + case SaveGate.Refuse: stream.WriteInt(3); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSaveGate.Write()", value)); + } + } +} + + + + + + + +internal enum SecretHitKindTag: int { + AwsAccessKey, + PrivateKey, + JsonWebToken, + GitHubToken, + SlackToken, + StripeKey, + GoogleApiKey, + UrlCredentials, + AssignedSecret +} + +class FfiConverterTypeSecretHitKindTag: FfiConverterRustBuffer { + public static FfiConverterTypeSecretHitKindTag INSTANCE = new FfiConverterTypeSecretHitKindTag(); + + public override SecretHitKindTag Read(BigEndianStream stream) { var value = stream.ReadInt(); switch (value) { - case 1: return SaveGate.Run; - case 2: return SaveGate.Confirm; - case 3: return SaveGate.Refuse; - default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSaveGate.Read()", value)); + case 1: return SecretHitKindTag.AwsAccessKey; + case 2: return SecretHitKindTag.PrivateKey; + case 3: return SecretHitKindTag.JsonWebToken; + case 4: return SecretHitKindTag.GitHubToken; + case 5: return SecretHitKindTag.SlackToken; + case 6: return SecretHitKindTag.StripeKey; + case 7: return SecretHitKindTag.GoogleApiKey; + case 8: return SecretHitKindTag.UrlCredentials; + case 9: return SecretHitKindTag.AssignedSecret; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSecretHitKindTag.Read()", value)); } } - public override int AllocationSize(SaveGate value) { + public override int AllocationSize(SecretHitKindTag value) { return 4; } - public override void Write(SaveGate value, BigEndianStream stream) { + public override void Write(SecretHitKindTag value, BigEndianStream stream) { switch (value) { - case SaveGate.Run: stream.WriteInt(1); break; - case SaveGate.Confirm: stream.WriteInt(2); break; - case SaveGate.Refuse: stream.WriteInt(3); break; - default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSaveGate.Write()", value)); + case SecretHitKindTag.AwsAccessKey: stream.WriteInt(1); break; + case SecretHitKindTag.PrivateKey: stream.WriteInt(2); break; + case SecretHitKindTag.JsonWebToken: stream.WriteInt(3); break; + case SecretHitKindTag.GitHubToken: stream.WriteInt(4); break; + case SecretHitKindTag.SlackToken: stream.WriteInt(5); break; + case SecretHitKindTag.StripeKey: stream.WriteInt(6); break; + case SecretHitKindTag.GoogleApiKey: stream.WriteInt(7); break; + case SecretHitKindTag.UrlCredentials: stream.WriteInt(8); break; + case SecretHitKindTag.AssignedSecret: stream.WriteInt(9); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSecretHitKindTag.Write()", value)); } } } @@ -11788,7 +13941,8 @@ internal enum SecretItemTag: int { McpToken, AnthropicKey, OpenAiKey, - OpenAiCompatibleKey + OpenAiCompatibleKey, + AccountRefreshToken } class FfiConverterTypeSecretItemTag: FfiConverterRustBuffer { @@ -11801,6 +13955,7 @@ public override SecretItemTag Read(BigEndianStream stream) { case 2: return SecretItemTag.AnthropicKey; case 3: return SecretItemTag.OpenAiKey; case 4: return SecretItemTag.OpenAiCompatibleKey; + case 5: return SecretItemTag.AccountRefreshToken; default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSecretItemTag.Read()", value)); } } @@ -11815,6 +13970,7 @@ public override void Write(SecretItemTag value, BigEndianStream stream) { case SecretItemTag.AnthropicKey: stream.WriteInt(2); break; case SecretItemTag.OpenAiKey: stream.WriteInt(3); break; case SecretItemTag.OpenAiCompatibleKey: stream.WriteInt(4); break; + case SecretItemTag.AccountRefreshToken: stream.WriteInt(5); break; default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeSecretItemTag.Write()", value)); } } @@ -12001,6 +14157,84 @@ public override void Write(SessionHealthTag value, BigEndianStream stream) { +internal enum ShareExpiryTag: int { + OneDay, + SevenDays, + ThirtyDays, + Never +} + +class FfiConverterTypeShareExpiryTag: FfiConverterRustBuffer { + public static FfiConverterTypeShareExpiryTag INSTANCE = new FfiConverterTypeShareExpiryTag(); + + public override ShareExpiryTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return ShareExpiryTag.OneDay; + case 2: return ShareExpiryTag.SevenDays; + case 3: return ShareExpiryTag.ThirtyDays; + case 4: return ShareExpiryTag.Never; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeShareExpiryTag.Read()", value)); + } + } + + public override int AllocationSize(ShareExpiryTag value) { + return 4; + } + + public override void Write(ShareExpiryTag value, BigEndianStream stream) { + switch (value) { + case ShareExpiryTag.OneDay: stream.WriteInt(1); break; + case ShareExpiryTag.SevenDays: stream.WriteInt(2); break; + case ShareExpiryTag.ThirtyDays: stream.WriteInt(3); break; + case ShareExpiryTag.Never: stream.WriteInt(4); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeShareExpiryTag.Write()", value)); + } + } +} + + + + + + + +internal enum ShareKindTag: int { + Query, + Result +} + +class FfiConverterTypeShareKindTag: FfiConverterRustBuffer { + public static FfiConverterTypeShareKindTag INSTANCE = new FfiConverterTypeShareKindTag(); + + public override ShareKindTag Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return ShareKindTag.Query; + case 2: return ShareKindTag.Result; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeShareKindTag.Read()", value)); + } + } + + public override int AllocationSize(ShareKindTag value) { + return 4; + } + + public override void Write(ShareKindTag value, BigEndianStream stream) { + switch (value) { + case ShareKindTag.Query: stream.WriteInt(1); break; + case ShareKindTag.Result: stream.WriteInt(2); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeShareKindTag.Write()", value)); + } + } +} + + + + + + + internal record SshAuthTag { public record Agent: SshAuthTag {} @@ -12386,74 +14620,319 @@ internal enum ValueKind: byte { Undecodable = 22 } -class FfiConverterTypeValueKind: FfiConverterRustBuffer { - public static FfiConverterTypeValueKind INSTANCE = new FfiConverterTypeValueKind(); +class FfiConverterTypeValueKind: FfiConverterRustBuffer { + public static FfiConverterTypeValueKind INSTANCE = new FfiConverterTypeValueKind(); + + public override ValueKind Read(BigEndianStream stream) { + var value = stream.ReadInt(); + switch (value) { + case 1: return ValueKind.Other; + case 2: return ValueKind.Bool; + case 3: return ValueKind.Integer; + case 4: return ValueKind.UnsignedInteger; + case 5: return ValueKind.WideInteger; + case 6: return ValueKind.Float; + case 7: return ValueKind.Decimal; + case 8: return ValueKind.Text; + case 9: return ValueKind.Bytes; + case 10: return ValueKind.Uuid; + case 11: return ValueKind.Json; + case 12: return ValueKind.Date; + case 13: return ValueKind.Time; + case 14: return ValueKind.TimeWithOffset; + case 15: return ValueKind.Timestamp; + case 16: return ValueKind.TimestampWithOffset; + case 17: return ValueKind.Interval; + case 18: return ValueKind.Bits; + case 19: return ValueKind.Array; + case 20: return ValueKind.Network; + case 21: return ValueKind.Spatial; + case 22: return ValueKind.Xml; + case 23: return ValueKind.Undecodable; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeValueKind.Read()", value)); + } + } + + public override int AllocationSize(ValueKind value) { + return 4; + } + + public override void Write(ValueKind value, BigEndianStream stream) { + switch (value) { + case ValueKind.Other: stream.WriteInt(1); break; + case ValueKind.Bool: stream.WriteInt(2); break; + case ValueKind.Integer: stream.WriteInt(3); break; + case ValueKind.UnsignedInteger: stream.WriteInt(4); break; + case ValueKind.WideInteger: stream.WriteInt(5); break; + case ValueKind.Float: stream.WriteInt(6); break; + case ValueKind.Decimal: stream.WriteInt(7); break; + case ValueKind.Text: stream.WriteInt(8); break; + case ValueKind.Bytes: stream.WriteInt(9); break; + case ValueKind.Uuid: stream.WriteInt(10); break; + case ValueKind.Json: stream.WriteInt(11); break; + case ValueKind.Date: stream.WriteInt(12); break; + case ValueKind.Time: stream.WriteInt(13); break; + case ValueKind.TimeWithOffset: stream.WriteInt(14); break; + case ValueKind.Timestamp: stream.WriteInt(15); break; + case ValueKind.TimestampWithOffset: stream.WriteInt(16); break; + case ValueKind.Interval: stream.WriteInt(17); break; + case ValueKind.Bits: stream.WriteInt(18); break; + case ValueKind.Array: stream.WriteInt(19); break; + case ValueKind.Network: stream.WriteInt(20); break; + case ValueKind.Spatial: stream.WriteInt(21); break; + case ValueKind.Xml: stream.WriteInt(22); break; + case ValueKind.Undecodable: stream.WriteInt(23); break; + default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeValueKind.Write()", value)); + } + } +} + + + + + +internal interface AccountListener { + void StatusChanged(); +} + +class UniffiCallbackInterfaceAccountListener { + static void StatusChanged(ulong @uniffiHandle,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeAccountListener.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + uniffiObject.StatusChanged(); + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + + static void UniffiFree(ulong @handle) { + FfiConverterTypeAccountListener.INSTANCE.handleMap.Remove(@handle); + } + + static ulong UniffiClone(ulong @handle) { + try { + if (!FfiConverterTypeAccountListener.INSTANCE.handleMap.TryGet(@handle, out var obj)) { + throw new InternalException($"No callback in handlemap '{@handle}'"); + } + return FfiConverterTypeAccountListener.INSTANCE.handleMap.Insert(obj); + } catch (System.Exception) { + return 0; // 0 is never a valid handle; ConcurrentHandleMap starts at 1 + } + } + static _UniFFILib.UniffiCallbackInterfaceAccountListenerMethod0 _m0 = new _UniFFILib.UniffiCallbackInterfaceAccountListenerMethod0(StatusChanged); + static _UniFFILib.UniffiCallbackInterfaceFree _callback_interface_free = new _UniFFILib.UniffiCallbackInterfaceFree(UniffiFree); + static _UniFFILib.UniffiCallbackInterfaceClone _callback_interface_clone = new _UniFFILib.UniffiCallbackInterfaceClone(UniffiClone); + + private static GCHandle? _vtablePin; + + public static void Register() { + if (_vtablePin.HasValue) return; + _UniFFILib.UniffiVTableCallbackInterfaceAccountListener _vtable = new _UniFFILib.UniffiVTableCallbackInterfaceAccountListener { + @statusChanged = Marshal.GetFunctionPointerForDelegate(_m0), + @uniffiFree = Marshal.GetFunctionPointerForDelegate(_callback_interface_free), + @uniffiClone = Marshal.GetFunctionPointerForDelegate(_callback_interface_clone), + }; + + // Pin the vtable so the GC never moves it. The GCHandle is intentionally never freed — + // this pin must remain valid for the process lifetime. + _vtablePin = GCHandle.Alloc(_vtable, GCHandleType.Pinned); + _UniFFILib.uniffi_tablepro_ffi_fn_init_callback_vtable_accountlistener(_vtablePin.Value.AddrOfPinnedObject()); + } +} + + + +class ConcurrentHandleMap where T: notnull { + readonly ConcurrentDictionary _map = new(); + + // Handles are odd numbers (1, 3, 5, ...) — the lowest bit must always be set. + // Rust uses (handle & 1) to distinguish foreign-language handles from Rust Arc + // pointers, which are always even due to memory alignment. See uniffi_core/src/ffi/handle.rs. + const long HANDLE_INITIAL = 1; + const long HANDLE_DELTA = 2; + long _currentHandle = HANDLE_INITIAL - HANDLE_DELTA; + + public ulong Insert(T obj) { + var handle = (ulong)Interlocked.Add(ref _currentHandle, HANDLE_DELTA); + if (!_map.TryAdd(handle, obj)) { + throw new InternalException("ConcurrentHandleMap: Duplicate handle"); + } + return handle; + } + + public bool TryGet(ulong handle, [NotNullWhen(true)] out T? result) { + return _map.TryGetValue(handle, out result); + } + + public T Get(ulong handle) { + if (_map.TryGetValue(handle, out var result)) { + return result; + } else { + throw new InternalException("ConcurrentHandleMap: Invalid handle"); + } + } + + public bool Remove(ulong handle) { + return _map.TryRemove(handle, out _); + } + + public bool Remove(ulong handle, [NotNullWhen(true)] out T? result) { + return _map.TryRemove(handle, out result); + } +} +static class UniffiCallbackResponseStatus { + public static sbyte SUCCESS = 0; + public static sbyte ERROR = 1; + public static sbyte UNEXPECTED_ERROR = 2; +} + +// The ffiConverter which transforms the Callbacks in to Handles to pass to Rust. +class FfiConverterTypeAccountListener: FfiConverter { + public static FfiConverterTypeAccountListener INSTANCE = new FfiConverterTypeAccountListener(); + + public ConcurrentHandleMap handleMap = new ConcurrentHandleMap(); + + public override ulong Lower(AccountListener value) { + return handleMap.Insert(value); + } + + public override AccountListener Lift(ulong value) { + if (handleMap.TryGet(value, out var uniffiCallback)) { + return uniffiCallback; + } else { + throw new InternalException($"No callback in handlemap '{value}'"); + } + } + + public override AccountListener Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(AccountListener value) { + return 8; + } + + public override void Write(AccountListener value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} + + + +internal interface HostBrowser { + /// + void OpenUrl(string @url); +} + +class UniffiCallbackInterfaceHostBrowser { + static void OpenUrl(ulong @uniffiHandle,RustBuffer @url,IntPtr @uniffiOutReturn,ref UniffiRustCallStatus _uniffi_out_err) { + var handle = @uniffiHandle; + try { + if (!FfiConverterTypeHostBrowser.INSTANCE.handleMap.TryGet(handle, out var uniffiObject)) { + throw new InternalException($"No callback in handlemap '{handle}'"); + } + uniffiObject.OpenUrl( + FfiConverterString.INSTANCE.Lift(@url)); + + _uniffi_out_err.code = UniffiCallbackResponseStatus.SUCCESS; + } + catch (HostBrowserException e) { + try { + _uniffi_out_err.code = UniffiCallbackResponseStatus.ERROR; + _uniffi_out_err.error_buf = FfiConverterTypeHostBrowserError.INSTANCE.Lower(e); + } catch { + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + } + } + catch (System.Exception e){ + _uniffi_out_err.code = UniffiCallbackResponseStatus.UNEXPECTED_ERROR; + try { + _uniffi_out_err.error_buf = FfiConverterString.INSTANCE.Lower(e.Message); + } + catch { + } + } + } + + static void UniffiFree(ulong @handle) { + FfiConverterTypeHostBrowser.INSTANCE.handleMap.Remove(@handle); + } - public override ValueKind Read(BigEndianStream stream) { - var value = stream.ReadInt(); - switch (value) { - case 1: return ValueKind.Other; - case 2: return ValueKind.Bool; - case 3: return ValueKind.Integer; - case 4: return ValueKind.UnsignedInteger; - case 5: return ValueKind.WideInteger; - case 6: return ValueKind.Float; - case 7: return ValueKind.Decimal; - case 8: return ValueKind.Text; - case 9: return ValueKind.Bytes; - case 10: return ValueKind.Uuid; - case 11: return ValueKind.Json; - case 12: return ValueKind.Date; - case 13: return ValueKind.Time; - case 14: return ValueKind.TimeWithOffset; - case 15: return ValueKind.Timestamp; - case 16: return ValueKind.TimestampWithOffset; - case 17: return ValueKind.Interval; - case 18: return ValueKind.Bits; - case 19: return ValueKind.Array; - case 20: return ValueKind.Network; - case 21: return ValueKind.Spatial; - case 22: return ValueKind.Xml; - case 23: return ValueKind.Undecodable; - default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeValueKind.Read()", value)); + static ulong UniffiClone(ulong @handle) { + try { + if (!FfiConverterTypeHostBrowser.INSTANCE.handleMap.TryGet(@handle, out var obj)) { + throw new InternalException($"No callback in handlemap '{@handle}'"); + } + return FfiConverterTypeHostBrowser.INSTANCE.handleMap.Insert(obj); + } catch (System.Exception) { + return 0; // 0 is never a valid handle; ConcurrentHandleMap starts at 1 } } + static _UniFFILib.UniffiCallbackInterfaceHostBrowserMethod0 _m0 = new _UniFFILib.UniffiCallbackInterfaceHostBrowserMethod0(OpenUrl); + static _UniFFILib.UniffiCallbackInterfaceFree _callback_interface_free = new _UniFFILib.UniffiCallbackInterfaceFree(UniffiFree); + static _UniFFILib.UniffiCallbackInterfaceClone _callback_interface_clone = new _UniFFILib.UniffiCallbackInterfaceClone(UniffiClone); - public override int AllocationSize(ValueKind value) { - return 4; + private static GCHandle? _vtablePin; + + public static void Register() { + if (_vtablePin.HasValue) return; + _UniFFILib.UniffiVTableCallbackInterfaceHostBrowser _vtable = new _UniFFILib.UniffiVTableCallbackInterfaceHostBrowser { + @openUrl = Marshal.GetFunctionPointerForDelegate(_m0), + @uniffiFree = Marshal.GetFunctionPointerForDelegate(_callback_interface_free), + @uniffiClone = Marshal.GetFunctionPointerForDelegate(_callback_interface_clone), + }; + + // Pin the vtable so the GC never moves it. The GCHandle is intentionally never freed — + // this pin must remain valid for the process lifetime. + _vtablePin = GCHandle.Alloc(_vtable, GCHandleType.Pinned); + _UniFFILib.uniffi_tablepro_ffi_fn_init_callback_vtable_hostbrowser(_vtablePin.Value.AddrOfPinnedObject()); } +} - public override void Write(ValueKind value, BigEndianStream stream) { - switch (value) { - case ValueKind.Other: stream.WriteInt(1); break; - case ValueKind.Bool: stream.WriteInt(2); break; - case ValueKind.Integer: stream.WriteInt(3); break; - case ValueKind.UnsignedInteger: stream.WriteInt(4); break; - case ValueKind.WideInteger: stream.WriteInt(5); break; - case ValueKind.Float: stream.WriteInt(6); break; - case ValueKind.Decimal: stream.WriteInt(7); break; - case ValueKind.Text: stream.WriteInt(8); break; - case ValueKind.Bytes: stream.WriteInt(9); break; - case ValueKind.Uuid: stream.WriteInt(10); break; - case ValueKind.Json: stream.WriteInt(11); break; - case ValueKind.Date: stream.WriteInt(12); break; - case ValueKind.Time: stream.WriteInt(13); break; - case ValueKind.TimeWithOffset: stream.WriteInt(14); break; - case ValueKind.Timestamp: stream.WriteInt(15); break; - case ValueKind.TimestampWithOffset: stream.WriteInt(16); break; - case ValueKind.Interval: stream.WriteInt(17); break; - case ValueKind.Bits: stream.WriteInt(18); break; - case ValueKind.Array: stream.WriteInt(19); break; - case ValueKind.Network: stream.WriteInt(20); break; - case ValueKind.Spatial: stream.WriteInt(21); break; - case ValueKind.Xml: stream.WriteInt(22); break; - case ValueKind.Undecodable: stream.WriteInt(23); break; - default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeValueKind.Write()", value)); + + + +// The ffiConverter which transforms the Callbacks in to Handles to pass to Rust. +class FfiConverterTypeHostBrowser: FfiConverter { + public static FfiConverterTypeHostBrowser INSTANCE = new FfiConverterTypeHostBrowser(); + + public ConcurrentHandleMap handleMap = new ConcurrentHandleMap(); + + public override ulong Lower(HostBrowser value) { + return handleMap.Insert(value); + } + + public override HostBrowser Lift(ulong value) { + if (handleMap.TryGet(value, out var uniffiCallback)) { + return uniffiCallback; + } else { + throw new InternalException($"No callback in handlemap '{value}'"); } } -} + public override HostBrowser Read(BigEndianStream stream) { + return Lift(stream.ReadULong()); + } + + public override int AllocationSize(HostBrowser value) { + return 8; + } + public override void Write(HostBrowser value, BigEndianStream stream) { + stream.WriteULong(Lower(value)); + } +} @@ -12524,49 +15003,6 @@ public static void Register() { -class ConcurrentHandleMap where T: notnull { - readonly ConcurrentDictionary _map = new(); - - // Handles are odd numbers (1, 3, 5, ...) — the lowest bit must always be set. - // Rust uses (handle & 1) to distinguish foreign-language handles from Rust Arc - // pointers, which are always even due to memory alignment. See uniffi_core/src/ffi/handle.rs. - const long HANDLE_INITIAL = 1; - const long HANDLE_DELTA = 2; - long _currentHandle = HANDLE_INITIAL - HANDLE_DELTA; - - public ulong Insert(T obj) { - var handle = (ulong)Interlocked.Add(ref _currentHandle, HANDLE_DELTA); - if (!_map.TryAdd(handle, obj)) { - throw new InternalException("ConcurrentHandleMap: Duplicate handle"); - } - return handle; - } - - public bool TryGet(ulong handle, [NotNullWhen(true)] out T? result) { - return _map.TryGetValue(handle, out result); - } - - public T Get(ulong handle) { - if (_map.TryGetValue(handle, out var result)) { - return result; - } else { - throw new InternalException("ConcurrentHandleMap: Invalid handle"); - } - } - - public bool Remove(ulong handle) { - return _map.TryRemove(handle, out _); - } - - public bool Remove(ulong handle, [NotNullWhen(true)] out T? result) { - return _map.TryRemove(handle, out result); - } -} -static class UniffiCallbackResponseStatus { - public static sbyte SUCCESS = 0; - public static sbyte ERROR = 1; - public static sbyte UNEXPECTED_ERROR = 2; -} // The ffiConverter which transforms the Callbacks in to Handles to pass to Rust. class FfiConverterTypeHostPrompter: FfiConverter { @@ -13180,6 +15616,37 @@ public override void Write(long? value, BigEndianStream stream) { +class FfiConverterOptionalBoolean: FfiConverterRustBuffer { + public static FfiConverterOptionalBoolean INSTANCE = new FfiConverterOptionalBoolean(); + + public override bool? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterBoolean.INSTANCE.Read(stream); + } + + public override int AllocationSize(bool? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterBoolean.INSTANCE.AllocationSize((bool)value); + } + } + + public override void Write(bool? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterBoolean.INSTANCE.Write((bool)value, stream); + } + } +} + + + + class FfiConverterOptionalString: FfiConverterRustBuffer { public static FfiConverterOptionalString INSTANCE = new FfiConverterOptionalString(); @@ -13552,6 +16019,37 @@ public override void Write(TableName? value, BigEndianStream stream) { +class FfiConverterOptionalTypeTeamInfo: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeTeamInfo INSTANCE = new FfiConverterOptionalTypeTeamInfo(); + + public override TeamInfo? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeTeamInfo.INSTANCE.Read(stream); + } + + public override int AllocationSize(TeamInfo? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeTeamInfo.INSTANCE.AllocationSize((TeamInfo)value); + } + } + + public override void Write(TeamInfo? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeTeamInfo.INSTANCE.Write((TeamInfo)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeEditLock: FfiConverterRustBuffer { public static FfiConverterOptionalTypeEditLock INSTANCE = new FfiConverterOptionalTypeEditLock(); @@ -13583,6 +16081,37 @@ public override void Write(EditLock? value, BigEndianStream stream) { +class FfiConverterOptionalTypeEntitlementProblemTag: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeEntitlementProblemTag INSTANCE = new FfiConverterOptionalTypeEntitlementProblemTag(); + + public override EntitlementProblemTag? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeEntitlementProblemTag.INSTANCE.Read(stream); + } + + public override int AllocationSize(EntitlementProblemTag? value) { + if (value == null) { + return 1; + } else { + return 1 + FfiConverterTypeEntitlementProblemTag.INSTANCE.AllocationSize((EntitlementProblemTag)value); + } + } + + public override void Write(EntitlementProblemTag? value, BigEndianStream stream) { + if (value == null) { + stream.WriteByte(0); + } else { + stream.WriteByte(1); + FfiConverterTypeEntitlementProblemTag.INSTANCE.Write((EntitlementProblemTag)value, stream); + } + } +} + + + + class FfiConverterOptionalTypeFilterValueArg: FfiConverterRustBuffer { public static FfiConverterOptionalTypeFilterValueArg INSTANCE = new FfiConverterOptionalTypeFilterValueArg(); @@ -13590,23 +16119,54 @@ class FfiConverterOptionalTypeFilterValueArg: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeSecretKindTag INSTANCE = new FfiConverterOptionalTypeSecretKindTag(); + + public override SecretKindTag? Read(BigEndianStream stream) { + if (stream.ReadByte() == 0) { + return null; + } + return FfiConverterTypeSecretKindTag.INSTANCE.Read(stream); } - public override int AllocationSize(FilterValueArg? value) { + public override int AllocationSize(SecretKindTag? value) { if (value == null) { return 1; } else { - return 1 + FfiConverterTypeFilterValueArg.INSTANCE.AllocationSize((FilterValueArg)value); + return 1 + FfiConverterTypeSecretKindTag.INSTANCE.AllocationSize((SecretKindTag)value); } } - public override void Write(FilterValueArg? value, BigEndianStream stream) { + public override void Write(SecretKindTag? value, BigEndianStream stream) { if (value == null) { stream.WriteByte(0); } else { stream.WriteByte(1); - FfiConverterTypeFilterValueArg.INSTANCE.Write((FilterValueArg)value, stream); + FfiConverterTypeSecretKindTag.INSTANCE.Write((SecretKindTag)value, stream); } } } @@ -13614,30 +16174,30 @@ public override void Write(FilterValueArg? value, BigEndianStream stream) { -class FfiConverterOptionalTypeSecretKindTag: FfiConverterRustBuffer { - public static FfiConverterOptionalTypeSecretKindTag INSTANCE = new FfiConverterOptionalTypeSecretKindTag(); +class FfiConverterOptionalTypeShareExpiryTag: FfiConverterRustBuffer { + public static FfiConverterOptionalTypeShareExpiryTag INSTANCE = new FfiConverterOptionalTypeShareExpiryTag(); - public override SecretKindTag? Read(BigEndianStream stream) { + public override ShareExpiryTag? Read(BigEndianStream stream) { if (stream.ReadByte() == 0) { return null; } - return FfiConverterTypeSecretKindTag.INSTANCE.Read(stream); + return FfiConverterTypeShareExpiryTag.INSTANCE.Read(stream); } - public override int AllocationSize(SecretKindTag? value) { + public override int AllocationSize(ShareExpiryTag? value) { if (value == null) { return 1; } else { - return 1 + FfiConverterTypeSecretKindTag.INSTANCE.AllocationSize((SecretKindTag)value); + return 1 + FfiConverterTypeShareExpiryTag.INSTANCE.AllocationSize((ShareExpiryTag)value); } } - public override void Write(SecretKindTag? value, BigEndianStream stream) { + public override void Write(ShareExpiryTag? value, BigEndianStream stream) { if (value == null) { stream.WriteByte(0); } else { stream.WriteByte(1); - FfiConverterTypeSecretKindTag.INSTANCE.Write((SecretKindTag)value, stream); + FfiConverterTypeShareExpiryTag.INSTANCE.Write((ShareExpiryTag)value, stream); } } } @@ -14199,6 +16759,52 @@ public override void Write(ConnectionRecord[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeDeviceInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeDeviceInfo INSTANCE = new FfiConverterSequenceTypeDeviceInfo(); + + public override DeviceInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new DeviceInfo[length]; + var readFn = FfiConverterTypeDeviceInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(DeviceInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeDeviceInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(DeviceInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeDeviceInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeDriverInfo: FfiConverterRustBuffer { public static FfiConverterSequenceTypeDriverInfo INSTANCE = new FfiConverterSequenceTypeDriverInfo(); @@ -14475,6 +17081,98 @@ public override void Write(HistoryEntryInfo[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeLicenseInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeLicenseInfo INSTANCE = new FfiConverterSequenceTypeLicenseInfo(); + + public override LicenseInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new LicenseInfo[length]; + var readFn = FfiConverterTypeLicenseInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(LicenseInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeLicenseInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(LicenseInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeLicenseInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeMembershipInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeMembershipInfo INSTANCE = new FfiConverterSequenceTypeMembershipInfo(); + + public override MembershipInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new MembershipInfo[length]; + var readFn = FfiConverterTypeMembershipInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(MembershipInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeMembershipInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(MembershipInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeMembershipInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeObjectEntry: FfiConverterRustBuffer { public static FfiConverterSequenceTypeObjectEntry INSTANCE = new FfiConverterSequenceTypeObjectEntry(); @@ -14705,6 +17403,98 @@ public override void Write(SchemaEntry[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeSecretHitInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeSecretHitInfo INSTANCE = new FfiConverterSequenceTypeSecretHitInfo(); + + public override SecretHitInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new SecretHitInfo[length]; + var readFn = FfiConverterTypeSecretHitInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(SecretHitInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeSecretHitInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(SecretHitInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeSecretHitInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + +class FfiConverterSequenceTypeShareInfo: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeShareInfo INSTANCE = new FfiConverterSequenceTypeShareInfo(); + + public override ShareInfo[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new ShareInfo[length]; + var readFn = FfiConverterTypeShareInfo.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(ShareInfo[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeShareInfo.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(ShareInfo[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeShareInfo.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeStructureColumn: FfiConverterRustBuffer { public static FfiConverterSequenceTypeStructureColumn INSTANCE = new FfiConverterSequenceTypeStructureColumn(); @@ -15119,6 +17909,52 @@ public override void Write(RunEvent[] value, BigEndianStream stream) { +class FfiConverterSequenceTypeShareExpiryTag: FfiConverterRustBuffer { + public static FfiConverterSequenceTypeShareExpiryTag INSTANCE = new FfiConverterSequenceTypeShareExpiryTag(); + + public override ShareExpiryTag[] Read(BigEndianStream stream) { + var length = stream.ReadInt(); + if (length == 0) { + return []; + } + + var result = new ShareExpiryTag[length]; + var readFn = FfiConverterTypeShareExpiryTag.INSTANCE.Read; + for (int i = 0; i < length; i++) { + result[i] = readFn(stream); + } + return result; + } + + public override int AllocationSize(ShareExpiryTag[] value) { + var sizeForLength = 4; + + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + return sizeForLength; + } + + var allocationSizeFn = FfiConverterTypeShareExpiryTag.INSTANCE.AllocationSize; + var sizeForItems = value.Sum(item => allocationSizeFn(item)); + return sizeForLength + sizeForItems; + } + + public override void Write(ShareExpiryTag[] value, BigEndianStream stream) { + // details/1-empty-list-as-default-method-parameter.md + if (value == null) { + stream.WriteInt(0); + return; + } + + stream.WriteInt(value.Length); + var writerFn = FfiConverterTypeShareExpiryTag.INSTANCE.Write; + value.ForEach(item => writerFn(item, stream)); + } +} + + + + class FfiConverterSequenceTypeTlsModeTag: FfiConverterRustBuffer { public static FfiConverterSequenceTypeTlsModeTag INSTANCE = new FfiConverterSequenceTypeTlsModeTag(); @@ -15358,6 +18194,30 @@ CallStatusErrorHandler errorHandler } #pragma warning restore 8625 internal static class CoreMethods { + public static string[] ScanColumnsForSecrets(string[] @names) { + return FfiConverterSequenceString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_func_scan_columns_for_secrets(FfiConverterSequenceString.INSTANCE.Lower(@names), ref _status) +)); + } + + + public static SecretHitInfo[] ScanSqlForSecrets(string @sql) { + return FfiConverterSequenceTypeSecretHitInfo.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_func_scan_sql_for_secrets(FfiConverterString.INSTANCE.Lower(@sql), ref _status) +)); + } + + + public static string? ShareTokenFromLink(string @link) { + return FfiConverterOptionalString.INSTANCE.Lift( + _UniffiHelpers.RustCall( (ref UniffiRustCallStatus _status) => + _UniFFILib.uniffi_tablepro_ffi_fn_func_share_token_from_link(FfiConverterString.INSTANCE.Lower(@link), ref _status) +)); + } + + /// public static ParsedConnectionUrl ParseConnectionUrl(SecretString @url) { return FfiConverterTypeParsedConnectionUrl.INSTANCE.Lift( diff --git a/windows/src/TablePro.Interop/Mapping.Account.cs b/windows/src/TablePro.Interop/Mapping.Account.cs new file mode 100644 index 0000000000..9372d15917 --- /dev/null +++ b/windows/src/TablePro.Interop/Mapping.Account.cs @@ -0,0 +1,184 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +// The account and share records; times cross as seconds from the Unix epoch. +internal static partial class Mapping +{ + public static Native.AccountConfig Account(AccountConfiguration configuration) => new( + configuration.AccountUrl, + configuration.ApiUrl, + [.. configuration.EntitlementKeys], + configuration.DeviceName, + configuration.AppVersion, + configuration.OsVersion, + configuration.AccountFile, + configuration.CallbackFinished, + configuration.CallbackUnknown, + configuration.MachineGuid); + + public static AccountStatus Status(Native.AccountStatusInfo status) => new( + status.State switch + { + Native.AccountStateTag.SignedIn => AccountState.SignedIn, + Native.AccountStateTag.Offline => AccountState.Offline, + _ => AccountState.SignedOut, + }, + status.AccountId, + status.Email, + status.Name, + [.. status.Features], + [.. status.Licenses.Select(License)], + Time(status.EntitlementExpiresAtSecs), + status.Problem switch + { + Native.EntitlementProblemTag.Expired => EntitlementProblem.Expired.Instance, + Native.EntitlementProblemTag.RefreshFailed failed => new EntitlementProblem.RefreshFailed(failed.Code), + Native.EntitlementProblemTag.DeviceLimitReached limit => + new EntitlementProblem.DeviceLimitReached([.. limit.Devices.Select(Device)]), + _ => null, + }, + status.Remembered); + + public static FeatureAccess Access(Native.FeatureAccessTag access) => access switch + { + Native.FeatureAccessTag.Available => FeatureAccess.Available, + Native.FeatureAccessTag.NotIncluded => FeatureAccess.NotIncluded, + Native.FeatureAccessTag.Expired => FeatureAccess.Expired, + Native.FeatureAccessTag.RefreshFailed => FeatureAccess.RefreshFailed, + Native.FeatureAccessTag.DeviceLimitReached => FeatureAccess.DeviceLimitReached, + _ => FeatureAccess.SignedOut, + }; + + public static AccountProfile Profile(Native.ProfileInfo profile) => new( + profile.Id, + profile.Email, + profile.Name, + [.. profile.Licenses.Select(License)], + [.. profile.Teams.Select(team => new AccountMembership(Team(team.Team), team.Role, team.HasSeat))]); + + public static AccountDevice Device(Native.DeviceInfo device) => new( + device.Id, + device.Platform, + device.Name, + device.AppVersion, + device.OsVersion, + DateTimeOffset.FromUnixTimeSeconds(device.LastSeenAtSecs), + Time(device.LicensedAtSecs), + Time(device.OfflineUntilSecs), + device.IsThisMachine); + + public static ShareLimits Limits(Native.ShareLimitsInfo limits) => new( + limits.Plan, + Count(limits.Live), + Count(limits.LiveLimit), + Count(limits.MaxRows), + [.. limits.Expiries.Select(Expiry)], + limits.DefaultExpiry is { } expiry ? Expiry(expiry) : null, + limits.Password, + limits.DisableDownload, + limits.Team, + limits.EmailVerified, + limits.SharingDisabled); + + public static Native.ShareRequestArg Request(ShareRequest request) => new( + request.Kind == ShareKind.Result ? Native.ShareKindTag.Result : Native.ShareKindTag.Query, + request.Sql, + request.Title, + request.Note, + request.Dialect, + request.Expiry is { } expiry ? Expiry(expiry) : null, + request.HideSql, + request.AllowDownload, + request.Password, + request.TeamId); + + public static Native.ShareExpiryTag Expiry(ShareExpiry expiry) => expiry switch + { + ShareExpiry.OneDay => Native.ShareExpiryTag.OneDay, + ShareExpiry.SevenDays => Native.ShareExpiryTag.SevenDays, + ShareExpiry.ThirtyDays => Native.ShareExpiryTag.ThirtyDays, + ShareExpiry.Never => Native.ShareExpiryTag.Never, + _ => throw new ArgumentOutOfRangeException(nameof(expiry), expiry, null), + }; + + public static SharedLink Link(Native.ShareInfo share) => new( + share.Id, + share.Kind, + share.Scope, + share.TeamId, + share.Title, + share.Note, + share.Dialect, + share.Sql, + share.HasSnapshot, + share.RowCount is { } rows ? Count(rows) : null, + share.Truncated, + share.HideSql, + share.AllowDownload, + share.HasPassword, + share.State, + share.RemovedReason, + Count(share.ViewCount), + DateTimeOffset.FromUnixTimeSeconds(share.CreatedAtSecs), + DateTimeOffset.FromUnixTimeSeconds(share.UpdatedAtSecs), + Time(share.ExpiresAtSecs), + Time(share.RevokedAtSecs), + Time(share.RemovedAtSecs), + share.Url); + + public static CreatedShare Created(Native.CreatedShareInfo created) => new(Link(created.Share), created.Url); + + public static SharePage Page(Native.SharePageInfo page) => + new([.. page.Shares.Select(Link)], page.NextCursor); + + public static PublicShare Public(Native.SharedLinkInfo shared) => new( + shared.Kind, + shared.Title, + shared.Note, + shared.Dialect, + shared.Sql, + DateTimeOffset.FromUnixTimeSeconds(shared.CreatedAtSecs), + Time(shared.ExpiresAtSecs), + shared.AllowDownload, + shared.RowCount is { } rows ? Count(rows) : null, + shared.Truncated); + + public static SecretHit Hit(Native.SecretHitInfo hit) => new( + hit.Kind switch + { + Native.SecretHitKindTag.AwsAccessKey => SecretHitKind.AwsAccessKey, + Native.SecretHitKindTag.PrivateKey => SecretHitKind.PrivateKey, + Native.SecretHitKindTag.JsonWebToken => SecretHitKind.JsonWebToken, + Native.SecretHitKindTag.GitHubToken => SecretHitKind.GitHubToken, + Native.SecretHitKindTag.SlackToken => SecretHitKind.SlackToken, + Native.SecretHitKindTag.StripeKey => SecretHitKind.StripeKey, + Native.SecretHitKindTag.GoogleApiKey => SecretHitKind.GoogleApiKey, + Native.SecretHitKindTag.UrlCredentials => SecretHitKind.UrlCredentials, + _ => SecretHitKind.AssignedSecret, + }, + checked((int)hit.Line)); + + private static ShareExpiry Expiry(Native.ShareExpiryTag expiry) => expiry switch + { + Native.ShareExpiryTag.OneDay => ShareExpiry.OneDay, + Native.ShareExpiryTag.SevenDays => ShareExpiry.SevenDays, + Native.ShareExpiryTag.ThirtyDays => ShareExpiry.ThirtyDays, + _ => ShareExpiry.Never, + }; + + private static AccountLicense License(Native.LicenseInfo license) => new( + license.Id, + license.Plan, + license.Cycle, + license.Source, + license.Status, + Time(license.RenewsAtSecs), + Time(license.EndsAtSecs), + license.Team is { } team ? Team(team) : null); + + private static AccountTeam Team(Native.TeamInfo team) => new(team.Id, team.Name); + + private static DateTimeOffset? Time(long? seconds) => + seconds is { } at ? DateTimeOffset.FromUnixTimeSeconds(at) : null; +} diff --git a/windows/src/TablePro.Interop/Mapping.cs b/windows/src/TablePro.Interop/Mapping.cs index 37f4fd862a..3308cbb069 100644 --- a/windows/src/TablePro.Interop/Mapping.cs +++ b/windows/src/TablePro.Interop/Mapping.cs @@ -3,7 +3,7 @@ namespace TablePro.Interop; // Generated types stay internal so a generator upgrade cannot change the API. Counts cross unsigned and fit a long. -internal static class Mapping +internal static partial class Mapping { public static CoreError Error(Native.ErrorInfo info) => new( info.Code, @@ -375,12 +375,15 @@ error.HostKey is { } key _ => Native.TlsFailureTag.Other, }; + // Every tag named: a tag this build does not know must not land in another item's slot. public static SecretItem Item(Native.SecretItemTag item) => item switch { + Native.SecretItemTag.McpToken => SecretItem.McpToken, Native.SecretItemTag.AnthropicKey => SecretItem.AnthropicKey, Native.SecretItemTag.OpenAiKey => SecretItem.OpenAIKey, Native.SecretItemTag.OpenAiCompatibleKey => SecretItem.OpenAICompatibleKey, - _ => SecretItem.McpToken, + Native.SecretItemTag.AccountRefreshToken => SecretItem.AccountRefreshToken, + _ => throw new ArgumentOutOfRangeException(nameof(item), item, "A secret item the core added after this build."), }; public static Native.HostConfig Host(HostConfiguration configuration) => diff --git a/windows/src/TablePro.Interop/SecretStore.cs b/windows/src/TablePro.Interop/SecretStore.cs index ac1e43c9ca..a3667cbee7 100644 --- a/windows/src/TablePro.Interop/SecretStore.cs +++ b/windows/src/TablePro.Interop/SecretStore.cs @@ -37,6 +37,9 @@ public enum SecretItem AnthropicKey, OpenAIKey, OpenAICompatibleKey, + + // The TablePro account's refresh token, which only the account asks for. + AccountRefreshToken, } public enum SecretStoreFailure diff --git a/windows/src/TablePro.Interop/ShareLinks.cs b/windows/src/TablePro.Interop/ShareLinks.cs new file mode 100644 index 0000000000..cc200c89a9 --- /dev/null +++ b/windows/src/TablePro.Interop/ShareLinks.cs @@ -0,0 +1,143 @@ +using Native = TablePro.Interop.Native; + +namespace TablePro.Interop; + +public enum ShareKind +{ + Query, + Result, +} + +// The server counts the expiry from its own clock. +public enum ShareExpiry +{ + OneDay, + SevenDays, + ThirtyDays, + Never, +} + +// What the plan allows now (core ADR 0025). Plan is the server's code, "free" or "pro". +public sealed record ShareLimits( + string Plan, + long Live, + long LiveLimit, + long MaxRows, + IReadOnlyList Expiries, + ShareExpiry? DefaultExpiry, + bool Password, + bool DisableDownload, + bool Team, + bool EmailVerified, + bool SharingDisabled); + +// Sql is always stored; a result share's snapshot is built by the core from the set it is given. +public sealed record ShareRequest(ShareKind Kind, string Sql) +{ + public string? Title { get; init; } + + public string? Note { get; init; } + + public string? Dialect { get; init; } + + // Null takes the plan's default. + public ShareExpiry? Expiry { get; init; } + + // Only for a result. + public bool HideSql { get; init; } + + // Null leaves downloads on. + public bool? AllowDownload { get; init; } + + public string? Password { get; init; } + + public string? TeamId { get; init; } +} + +// A link as its owner sees it. Kind, Scope and State stay the server's codes; Sql only when read on its own. +public sealed record SharedLink( + string Id, + string Kind, + string Scope, + string? TeamId, + string Title, + string Note, + string Dialect, + string? Sql, + bool HasSnapshot, + long? RowCount, + bool? Truncated, + bool HideSql, + bool AllowDownload, + bool HasPassword, + string State, + string? RemovedReason, + long ViewCount, + DateTimeOffset CreatedAt, + DateTimeOffset UpdatedAt, + DateTimeOffset? ExpiresAt, + DateTimeOffset? RevokedAt, + DateTimeOffset? RemovedAt, + string? Url) +{ + public bool IsLive => State == "live"; +} + +public sealed record CreatedShare(SharedLink Share, string Url); + +// NextCursor is null on the last page. +public sealed record SharePage(IReadOnlyList Shares, string? NextCursor); + +// A link as anyone with it reads it. Sql is null when the owner hid it, so there is nothing to open. +public sealed record PublicShare( + string Kind, + string Title, + string Note, + string Dialect, + string? Sql, + DateTimeOffset CreatedAt, + DateTimeOffset? ExpiresAt, + bool AllowDownload, + long? RowCount, + bool? Truncated); + +public enum SecretHitKind +{ + AwsAccessKey, + PrivateKey, + JsonWebToken, + GitHubToken, + SlackToken, + StripeKey, + GoogleApiKey, + UrlCredentials, + AssignedSecret, +} + +// Line counts from 1. +public sealed record SecretHit(SecretHitKind Kind, int Line); + +// The core's secret scan and deep link rule, the same for every app. A hit warns and never blocks a share. +public static class ShareLinks +{ + // Each kind once per line, by line. + public static IReadOnlyList ScanSql(string sql) + { + ArgumentNullException.ThrowIfNull(sql); + return [.. Native.CoreMethods.ScanSqlForSecrets(sql).Select(Mapping.Hit)]; + } + + // The names of the columns that may hold a secret, in their order, each once. + public static IReadOnlyList ScanColumns(IEnumerable names) + { + ArgumentNullException.ThrowIfNull(names); + return Native.CoreMethods.ScanColumnsForSecrets([.. names]); + } + + // The token of tablepro://share?token=, null for any other link or a malformed token. + public static string? TokenFromLink(string link) + { + ArgumentNullException.ThrowIfNull(link); + return Native.CoreMethods.ShareTokenFromLink(link); + } +} diff --git a/windows/src/TablePro.Interop/TableProCore.cs b/windows/src/TablePro.Interop/TableProCore.cs index ee5ca5423e..a2d1404ad2 100644 --- a/windows/src/TablePro.Interop/TableProCore.cs +++ b/windows/src/TablePro.Interop/TableProCore.cs @@ -56,6 +56,19 @@ public async Task OpenHistoryAsync(CancellationToken cancellationT return new QueryHistory(store); } + // Keeps the entitlement fresh until disposed; account.no_machine_id or ffi.account_config when it cannot start. + public async Task OpenAccountAsync(AccountConfiguration configuration, IAccountBrowser browser) + { + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(browser); + var native = Mapping.Account(configuration); + var wake = new AccountWake(); + var service = await CoreCall.RunAsync( + () => _core.OpenAccount(native, new AccountBrowserAdapter(browser), wake)) + .ConfigureAwait(false); + return new TableProAccount(service, wake); + } + public async Task OpenFileAsync( FileOpenOptions options, CancellationToken cancellationToken = default) diff --git a/windows/tests/TablePro.Interop.Tests/AccountTests.cs b/windows/tests/TablePro.Interop.Tests/AccountTests.cs new file mode 100644 index 0000000000..be5dbc42e9 --- /dev/null +++ b/windows/tests/TablePro.Interop.Tests/AccountTests.cs @@ -0,0 +1,349 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; + +namespace TablePro.Interop.Tests; + +// The account against a stand-in for tablepro-cloud on a loopback port; nothing here reaches tablepro.app. +public sealed class AccountTests : IAsyncDisposable +{ + private const string MachineGuid = "d3b07384-d113-4ec6-a2f1-6a3f0c2e9b7a"; + private const string Token = "Ab3dEf6hIj9kLm2nOp5qRs8tUv1wXy4zAb7dEf0hIjK"; + private static readonly TimeSpan Patience = TimeSpan.FromSeconds(20); + + private readonly string _directory = Directory.CreateTempSubdirectory("tablepro-account-").FullName; + private readonly ItemLog _secrets = new(); + private readonly TableProCore _core; + private Stub? _cloud; + + public AccountTests() + { + _core = TableProCore.Create(new HostConfiguration("test"), _secrets); + } + + [Fact] + public async Task ANewMachineStartsSignedOutAndIsToldSo() + { + using var account = await OpenAsync(Unreachable(), new RecordingBrowser()); + + var first = await FirstChangeAsync(account); + var limits = await Assert.ThrowsAsync(account.GetShareLimitsAsync); + var profile = await Assert.ThrowsAsync(account.GetProfileAsync); + + Assert.Equal(AccountState.SignedOut, first.State); + Assert.Equal(AccountState.SignedOut, account.Status.State); + Assert.Null(account.Status.Email); + Assert.Equal(FeatureAccess.SignedOut, account.Access("shared_links")); + Assert.Equal("account.signed_out", limits.Code); + Assert.Equal("account.signed_out", profile.Code); + Assert.Null(_secrets.LoadItem(SecretItem.AccountRefreshToken)); + } + + [Fact] + public async Task AKeptSignInAsksTheHostForTheRefreshTokenItem() + { + await File.WriteAllTextAsync(Path.Combine(_directory, "account.json"), "{}", TestContext.Current.CancellationToken); + using var account = await OpenAsync(Unreachable(), new RecordingBrowser()); + + await FirstChangeAsync(account); + + Assert.Contains(SecretItem.AccountRefreshToken, _secrets.Asked); + Assert.DoesNotContain(SecretItem.McpToken, _secrets.Asked); + Assert.Equal(AccountState.SignedOut, account.Status.State); + } + + [Fact] + public async Task ASignInOpensTheBrowserForTheWindowsClientAndACancelEndsTheWait() + { + var browser = new RecordingBrowser(); + var cloud = Unreachable(); + using var account = await OpenAsync(cloud, browser); + using var cancel = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + + var signingIn = account.SignInAsync(cancel.Token); + var opened = await browser.Opened.Task.WaitAsync(Patience, TestContext.Current.CancellationToken); + await cancel.CancelAsync(); + + await Assert.ThrowsAnyAsync(() => signingIn); + var query = Uri.UnescapeDataString(opened.Query); + Assert.Equal(new Uri(cloud).Authority, opened.Authority); + Assert.Contains("client_id=tablepro-windows", query, StringComparison.Ordinal); + Assert.Contains("redirect_uri=http://127.0.0.1:", query, StringComparison.Ordinal); + Assert.Equal(AccountState.SignedOut, account.Status.State); + } + + [Fact] + public async Task ABrowserThatDoesNotOpenEndsTheSignInWithItsCode() + { + using var account = await OpenAsync(Unreachable(), new RecordingBrowser(opens: false)); + + var refused = await Assert.ThrowsAsync( + () => account.SignInAsync(TestContext.Current.CancellationToken)); + + Assert.Equal("account.browser", refused.Code); + } + + [Fact] + public async Task ASharedLinkIsReadSignedOutAndAsksForItsPassword() + { + _cloud = Stub.Start(request => request switch + { + { Path: var path } when path != $"/v2/shared/{Token}" => (404, Problem(404, "not_found")), + { Password: null } => (401, Problem(401, "share_password_required")), + { Password: "hunter2" } => (200, """ + {"kind":"query","title":"Orders","note":"","dialect":"sqlite","sql":"SELECT 1", + "created_at":"2026-11-13T00:00:00Z","allow_download":true,"made_with":"TablePro"} + """), + _ => (401, Problem(401, "share_password_wrong")), + }); + using var account = await OpenAsync(_cloud.Base, new RecordingBrowser()); + + var required = await Assert.ThrowsAsync(() => account.FetchSharedAsync(Token)); + var wrong = await Assert.ThrowsAsync(() => account.FetchSharedAsync(Token, "nope")); + var opened = await account.FetchSharedAsync(Token, "hunter2"); + var gone = await Assert.ThrowsAsync(() => account.FetchSharedAsync(Token[..^1] + "x")); + var malformed = await Assert.ThrowsAsync(() => account.FetchSharedAsync("short")); + + Assert.Equal("account.share_password_required", required.Code); + Assert.Equal("account.share_password_wrong", wrong.Code); + Assert.Equal("SELECT 1", opened.Sql); + Assert.Equal("Orders", opened.Title); + Assert.Equal(new DateTimeOffset(2026, 11, 13, 0, 0, 0, TimeSpan.Zero), opened.CreatedAt); + Assert.Null(opened.ExpiresAt); + Assert.Equal("account.not_found", gone.Code); + Assert.Equal("account.not_found", malformed.Code); + Assert.All(_cloud.Requests, request => Assert.False(request.Authorized)); + } + + [Fact] + public async Task AMachineGuidThatIsNotAGuidIsRefusedBeforeTheAccountStarts() + { + var refused = await Assert.ThrowsAsync(() => _core.OpenAccountAsync( + Configuration(Unreachable()) with { MachineGuid = "not a guid" }, + new RecordingBrowser())); + + Assert.Equal("account.no_machine_id", refused.Code); + } + + [Fact] + public void TheSecretScanNamesEachKindByLineAndTheColumnsThatMayHoldOne() + { + var hits = ShareLinks.ScanSql("SELECT 1;\nSELECT 'AKIAIOSFODNN7EXAMPLE', 'postgres://ada:pw@db/app';"); + var columns = ShareLinks.ScanColumns(["id", "api_key", "password", "name"]); + + Assert.Equal([new SecretHit(SecretHitKind.AwsAccessKey, 2), new SecretHit(SecretHitKind.UrlCredentials, 2)], hits); + Assert.Equal(["api_key", "password"], columns); + Assert.Empty(ShareLinks.ScanSql("SELECT name FROM people")); + } + + [Fact] + public void OnlyAShareLinkWithAWellFormedTokenGivesItsToken() + { + Assert.Equal(Token, ShareLinks.TokenFromLink($"tablepro://share?token={Token}")); + Assert.Null(ShareLinks.TokenFromLink("tablepro://share?token=short")); + Assert.Null(ShareLinks.TokenFromLink($"https://s.tablepro.app/{Token}")); + Assert.Null(ShareLinks.TokenFromLink($"tablepro://open?token={Token}")); + } + + public async ValueTask DisposeAsync() + { + if (_cloud is not null) + { + await _cloud.DisposeAsync(); + } + + _core.Dispose(); + Directory.Delete(_directory, recursive: true); + } + + private static async Task FirstChangeAsync(TableProAccount account) + { + using var waiting = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + waiting.CancelAfter(Patience); + await foreach (var status in account.ReadStatusChangesAsync(waiting.Token)) + { + return status; + } + + throw new InvalidOperationException("The account was disposed before it said anything."); + } + + private static string Problem(int status, string code) => + $$"""{"type":"about:blank","title":"Refused","status":{{status}},"code":"{{code}}"}"""; + + // Nothing listens once the listener is stopped, so every request is refused. + private static string Unreachable() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return $"http://127.0.0.1:{port}"; + } + + private Task OpenAsync(string cloud, IAccountBrowser browser) => + _core.OpenAccountAsync(Configuration(cloud), browser); + + private AccountConfiguration Configuration(string cloud) => + new("Lab", "1.0.0", "Windows 11", Path.Combine(_directory, "account.json"), "Done", "Unknown") + { + AccountUrl = cloud, + ApiUrl = cloud + "/v2", + MachineGuid = MachineGuid, + }; + + // Notes which items the core asks for, so a tag mapped to the wrong item shows. + private sealed class ItemLog : ISecretStore + { + private readonly MemorySecretStore _store = new(); + private readonly Lock _gate = new(); + private readonly List _asked = []; + + public IReadOnlyList Asked + { + get + { + lock (_gate) + { + return [.. _asked]; + } + } + } + + public string? Load(Guid connectionId, SecretKind kind) => _store.Load(connectionId, kind); + + public void Store(Guid connectionId, SecretKind kind, string secret, string label) => + _store.Store(connectionId, kind, secret, label); + + public void Relabel(Guid connectionId, SecretKind kind, string label) => + _store.Relabel(connectionId, kind, label); + + public void Delete(Guid connectionId, SecretKind kind) => _store.Delete(connectionId, kind); + + public void DeleteConnection(Guid connectionId) => _store.DeleteConnection(connectionId); + + public string? LoadItem(SecretItem item) + { + lock (_gate) + { + _asked.Add(item); + } + + return _store.LoadItem(item); + } + + public void StoreItem(SecretItem item, string secret) => _store.StoreItem(item, secret); + + public void DeleteItem(SecretItem item) => _store.DeleteItem(item); + } + + private sealed class RecordingBrowser(bool opens = true) : IAccountBrowser + { + public TaskCompletionSource Opened { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Task OpenAsync(Uri url) + { + Opened.TrySetResult(url); + return Task.FromResult(opens); + } + } + + private sealed record StubRequest(string Path, string? Password, bool Authorized); + + // One request per connection, answered as the core's own tests answer: JSON, then close. + private sealed class Stub : IAsyncDisposable + { + private readonly TcpListener _listener; + private readonly Func _answer; + private readonly CancellationTokenSource _stop = new(); + private readonly Task _serving; + private readonly Lock _gate = new(); + private readonly List _requests = []; + + private Stub(Func answer) + { + _answer = answer; + _listener = new TcpListener(IPAddress.Loopback, 0); + _listener.Start(); + Base = $"http://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}"; + _serving = ServeAsync(); + } + + public string Base { get; } + + public IReadOnlyList Requests + { + get + { + lock (_gate) + { + return [.. _requests]; + } + } + } + + public static Stub Start(Func answer) => new(answer); + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + try + { + await _serving; + } + catch (Exception exception) when (exception is OperationCanceledException or SocketException or ObjectDisposedException) + { + // The listener stopped under the accept. + } + + _stop.Dispose(); + } + + private async Task ServeAsync() + { + while (!_stop.IsCancellationRequested) + { + using var client = await _listener.AcceptTcpClientAsync(_stop.Token); + await AnswerAsync(client); + } + } + + private async Task AnswerAsync(TcpClient client) + { + var stream = client.GetStream(); + using var reader = new StreamReader(stream, Encoding.ASCII, leaveOpen: true); + var line = await reader.ReadLineAsync(_stop.Token) ?? string.Empty; + var path = line.Split(' ') is [_, var target, ..] ? target : string.Empty; + string? password = null; + var authorized = false; + while (await reader.ReadLineAsync(_stop.Token) is { Length: > 0 } header) + { + var colon = header.IndexOf(':', StringComparison.Ordinal); + var name = colon < 0 ? header : header[..colon].Trim(); + var value = colon < 0 ? string.Empty : header[(colon + 1)..].Trim(); + if (name.Equals("x-share-password", StringComparison.OrdinalIgnoreCase)) + { + password = value; + } + else if (name.Equals("authorization", StringComparison.OrdinalIgnoreCase)) + { + authorized = true; + } + } + + var request = new StubRequest(path, password, authorized); + lock (_gate) + { + _requests.Add(request); + } + + var (status, body) = _answer(request); + var bytes = Encoding.UTF8.GetBytes(body); + var head = $"HTTP/1.1 {status} Stub\r\ncontent-type: application/json\r\ncontent-length: {bytes.Length}\r\nconnection: close\r\n\r\n"; + await stream.WriteAsync(Encoding.ASCII.GetBytes(head), _stop.Token); + await stream.WriteAsync(bytes, _stop.Token); + await stream.FlushAsync(_stop.Token); + } + } +} From 36615820c910ae5da43c157efc2aee57a711f1ff Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Fri, 13 Nov 2026 16:10:20 +0700 Subject: [PATCH 016/126] feat(windows): sign in to the TablePro account from Settings --- .../docs/decisions/0008-tablepro-account.md | 40 +++ windows/docs/decisions/README.md | 1 + .../src/TablePro.App.Model/AccountPanel.cs | 95 +++++++ windows/src/TablePro.App/App.xaml.cs | 8 +- .../src/TablePro.App/Services/AccountSetup.cs | 91 +++++++ .../src/TablePro.App/Services/Workbench.cs | 108 ++++++++ .../TablePro.App/Strings/en-US/Resources.resw | 219 +++++++++++++++ .../TablePro.App/Views/DeviceLimitDialog.cs | 105 ++++++++ .../src/TablePro.App/Views/SettingsView.xaml | 28 +- .../TablePro.App/Views/SettingsView.xaml.cs | 255 ++++++++++++++++++ .../AccountPanelTests.cs | 114 ++++++++ .../AccountSettingsTests.cs | 22 ++ 12 files changed, 1084 insertions(+), 2 deletions(-) create mode 100644 windows/docs/decisions/0008-tablepro-account.md create mode 100644 windows/src/TablePro.App.Model/AccountPanel.cs create mode 100644 windows/src/TablePro.App/Services/AccountSetup.cs create mode 100644 windows/src/TablePro.App/Views/DeviceLimitDialog.cs create mode 100644 windows/tests/TablePro.App.Model.Tests/AccountPanelTests.cs create mode 100644 windows/tests/TablePro.App.UITests/AccountSettingsTests.cs diff --git a/windows/docs/decisions/0008-tablepro-account.md b/windows/docs/decisions/0008-tablepro-account.md new file mode 100644 index 0000000000..b4551a107f --- /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 0024](../../../core/docs/decisions/0024-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`, or `SecretItem.AccountRefreshToken` of a host's `ISecretStore`. 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 and asks the account again once one is removed), 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. +- The refresh token's target is per Windows user, not per data folder: two data folders signed in at once write the same credential, and the last sign-in's token is the one kept. diff --git a/windows/docs/decisions/README.md b/windows/docs/decisions/README.md index 5f547dbf3e..5e9c89039d 100644 --- a/windows/docs/decisions/README.md +++ b/windows/docs/decisions/README.md @@ -15,3 +15,4 @@ 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 0024); Settings shows it with sign in, sign out, refresh, devices and the device limit; every `account.*` code has its sentence. | diff --git a/windows/src/TablePro.App.Model/AccountPanel.cs b/windows/src/TablePro.App.Model/AccountPanel.cs new file mode 100644 index 0000000000..874fd1eb53 --- /dev/null +++ b/windows/src/TablePro.App.Model/AccountPanel.cs @@ -0,0 +1,95 @@ +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 static class AccountDevices +{ + // 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/App.xaml.cs b/windows/src/TablePro.App/App.xaml.cs index 98b25a93a8..d1c18f7023 100644 --- a/windows/src/TablePro.App/App.xaml.cs +++ b/windows/src/TablePro.App/App.xaml.cs @@ -1,3 +1,4 @@ +using Microsoft.UI.Dispatching; using Microsoft.UI.Xaml; using TablePro.App.Services; using TablePro.DataGrid; @@ -29,7 +30,12 @@ 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(); 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/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..56d09faca3 100644 --- a/windows/src/TablePro.App/Strings/en-US/Resources.resw +++ b/windows/src/TablePro.App/Strings/en-US/Resources.resw @@ -2595,4 +2595,223 @@ 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} + + + Windows + + + macOS + + + Linux + + + iOS + + + 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..c971d3cb6a --- /dev/null +++ b/windows/src/TablePro.App/Views/DeviceLimitDialog.cs @@ -0,0 +1,105 @@ +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, then the account asks 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"); + foreach (var device in AccountDevices.Ordered(devices)) + { + list.Children.Add(Row(device, async button => + { + button.IsEnabled = false; + error.Visibility = Visibility.Collapsed; + error.IsOpen = false; + try + { + if (await workbench.GetAccountAsync().ConfigureAwait(true) is { } account) + { + await account.RemoveDeviceAsync(device.Id).ConfigureAwait(true); + await account.RefreshPastDeviceLimitAsync().ConfigureAwait(true); + workbench.ShowAccount(account.Status); + } + + dialog.Hide(); + } + catch (TableProException exception) + { + button.IsEnabled = true; + error.Message = Strings.Error(exception.Error); + error.Visibility = Visibility.Visible; + error.IsOpen = true; + } + })); + } + + 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(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/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}" /> - + + + + + + +