Sign scoped Telegram Mini App purchase requests
This commit is contained in:
1 parent
c1ac6095d0
commit
08062f44b6
5 files changed
+471
-30
No files matched your search
+47
-4
@@ -61,7 +61,50 @@ can renew an expired session before its first mutation, and holds all request
|
||||
buffers until polling completes or its owned transfer is cancelled.
|
||||
|
||||
This is a custom Mesh wire protocol using sender-bound proof and replay
|
||||
principles, not OAuth DPoP. Server revocation, current app visibility/status and
|
||||
issuing-node checks remain authoritative on every request. Grants do not authorize
|
||||
other nodes, grant chaining, exports, deletion, payments or owner routes. Revocation
|
||||
blocks future access; it cannot erase already received keys or plaintext.
|
||||
principles. Server revocation, current app visibility/status and issuing-node
|
||||
checks remain authoritative on every request. Each grant applies to its issuing
|
||||
node, exact scopes and expressly approved capabilities. Revocation blocks
|
||||
future access. Keys and plaintext already received remain with the recipient.
|
||||
|
||||
## Telegram Mini App purchases
|
||||
|
||||
The owner may explicitly approve Telegram Stars purchases and a read-only Dew
|
||||
balance for the same linked account and app. Set `Grant.telegram_stars` on the
|
||||
Telegram-linked grant before calling the existing `PrepareGrantApproval`.
|
||||
The canonical message gains exactly one `telegram-stars-purchases` line ending
|
||||
in LF after the last collection scope, and the body gains `telegram_stars:true`.
|
||||
A grant without that permission keeps its original bytes. `AcceptSessionAnswer`
|
||||
verifies the owner signature before storing the flag. Read the installed grant
|
||||
via `GrantStorage` or call `DelegateTelegramStarsAllowed` for a local permission
|
||||
and expiry check. The issuer verifies current policy when handling each request.
|
||||
|
||||
Call `BeginTelegramDelegateRequest` from `mesh_client/async_delegated` with
|
||||
a `PendingDelegate`, the linked `DelegateClient`, its `DelegateSession`, and an
|
||||
`AsyncTransport`. The operation selects the exact route and method.
|
||||
|
||||
| Operation | `invoice_id` | Body |
|
||||
| --- | --- | --- |
|
||||
| `.Launch` | Empty | `{app_id, init_data}` |
|
||||
| `.Catalog`, `.Balance` | Empty | Empty |
|
||||
| `.CreateInvoice` | Empty | `{app_id, init_data, product_id, request_id}` |
|
||||
| `.InvoiceStatus`, `.CancelInvoice` | Issuer's 32-digit lowercase hex invoice ID | Empty |
|
||||
|
||||
The bound app ID determines the `app_id=APP` query on catalog and balance.
|
||||
The client signs the exact permitted request with `Authorization: Delegate
|
||||
ds1.<session_id>` and the JSON `X-Mesh-Delegate` proof. Empty bodies use the SHA-256
|
||||
digest of zero bytes. Hosts that already have a valid session may use
|
||||
`PrepareTelegramDelegateHeaders` with the same exact method, path, query and body.
|
||||
The existing `PrepareDelegateHeaders` continues to sign sync and scoped WebSocket
|
||||
requests. A linked Lumi-only grant can verify launch. Catalog, balance and all
|
||||
invoice operations require the Stars permission. The issuer binds invoice status
|
||||
and cancellation to the authenticated purchaser.
|
||||
|
||||
Use `PollDelegate` and read `pending.result` and `pending.status` on completion.
|
||||
The host provides a response buffer of at least 8192 bytes with enough space to
|
||||
hold the full signed grant response when renewal is needed. Keep request and
|
||||
response buffers alive through completion or cancellation. Parse successful
|
||||
responses with the Entity Mini App contract. `CancelDelegate` releases the
|
||||
local transfer. Use `.CancelInvoice` for intentional issuer cancellation. Keep
|
||||
raw Telegram `initData` and request credentials in memory, and exclude them
|
||||
from logs and persistent storage. A browser `invoiceClosed` callback can trigger
|
||||
a status read. The issuer alone settles purchases and refunds.
|
||||
+98
-14
@@ -4,9 +4,20 @@
|
||||
#import "mesh_client/async_client"
|
||||
#import "mesh_client/auth"
|
||||
#import "mesh_client/url"
|
||||
#import "mesh_client/wire"
|
||||
#import "net_http"
|
||||
#import "text_buffer"
|
||||
|
||||
TelegramDelegateOperation :: enum {
|
||||
Unspecified :: 0
|
||||
Launch
|
||||
Catalog
|
||||
Balance
|
||||
CreateInvoice
|
||||
InvoiceStatus
|
||||
CancelInvoice
|
||||
}
|
||||
|
||||
PendingDelegate :: struct {
|
||||
client: DelegateClient
|
||||
session: *DelegateSession
|
||||
@@ -15,6 +26,10 @@ PendingDelegate :: struct {
|
||||
body: string
|
||||
output: []u8
|
||||
session_only: bool
|
||||
telegram: bool
|
||||
method: string
|
||||
path: [105]u8
|
||||
query: [72]u8
|
||||
address: [768]u8
|
||||
session_body: [512]u8
|
||||
challenge_json: [2048]u8
|
||||
@@ -31,16 +46,28 @@ FinishDelegate :: (pending: *PendingDelegate, result: AuthResult) {
|
||||
pending.waiting = false
|
||||
pending.done = true
|
||||
pending.result = result
|
||||
if pending.telegram {
|
||||
pending.body = ""
|
||||
}
|
||||
}
|
||||
StartDelegateTransfer :: (pending: *PendingDelegate, path: string,
|
||||
body: string, output: []u8, stage: s32, headers: []HttpHeader) {
|
||||
body: string, output: []u8, stage: s32, headers: []HttpHeader,
|
||||
method: string = "POST", query: string = "") {
|
||||
pending.now = CurrentDelegateTime(pending.client)
|
||||
if pending.now <= 0 || output.count == 0 || !JoinUrl(pending.client.server_url, path, pending.address[:]) {
|
||||
FinishDelegate(pending, cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED)
|
||||
return
|
||||
}
|
||||
if query != "" {
|
||||
address: Writer = .{pending.address[:], TextUntilNul(pending.address[:]).count, true}
|
||||
address = WriteText(WriteByte(address, cast(u8)63), query)
|
||||
if !address.valid {
|
||||
FinishDelegate(pending, cast(AuthResult)AuthResult.AUTH_INVALID_URL)
|
||||
return
|
||||
}
|
||||
}
|
||||
request: HttpRequest
|
||||
request.method = "POST"
|
||||
request.method = method
|
||||
request.url = TextUntilNul(pending.address[:])
|
||||
request.accept = "application/json"
|
||||
request.content_type = "application/json"
|
||||
@@ -64,24 +91,70 @@ StartDelegateChallenge :: (pending: *PendingDelegate) {
|
||||
StartDelegateTransfer(pending, "/api/v1/authorization/challenge",
|
||||
TextUntilNul(pending.session_body[:]), pending.challenge_json[:], 1, pending.headers[0:0])
|
||||
}
|
||||
StartDelegateSync :: (pending: *PendingDelegate) {
|
||||
result := PrepareDelegateHeaders(pending.client, pending.session, pending.now,
|
||||
"POST", "/api/v1/delegated/sync", "", pending.body,
|
||||
pending.proof[:], pending.credential[:])
|
||||
StartDelegateRequest :: (pending: *PendingDelegate) {
|
||||
method := "POST"
|
||||
path := "/api/v1/delegated/sync"
|
||||
query := ""
|
||||
result: AuthResult
|
||||
telegram_path := pending.path
|
||||
telegram_query := pending.query
|
||||
if pending.telegram {
|
||||
method = pending.method
|
||||
path = TextUntilNul(telegram_path[:])
|
||||
query = TextUntilNul(telegram_query[:])
|
||||
result = PrepareTelegramDelegateHeaders(pending.client, pending.session, method, path, query,
|
||||
pending.body, pending.proof[:], pending.credential[:])
|
||||
} else {
|
||||
result = PrepareDelegateHeaders(pending.client, pending.session, pending.now, method, path, query,
|
||||
pending.body, pending.proof[:], pending.credential[:])
|
||||
}
|
||||
if result != cast(AuthResult)AuthResult.AUTH_OK {
|
||||
FinishDelegate(pending, result)
|
||||
return
|
||||
}
|
||||
pending.headers[0].name = "Authorization"
|
||||
pending.headers[0].value = TextUntilNul(pending.credential[:])
|
||||
pending.headers[1].name = "X-Daochi-Delegate"
|
||||
pending.headers[1].name = ifx pending.telegram then "X-Mesh-Delegate" else "X-Daochi-Delegate"
|
||||
pending.headers[1].value = TextUntilNul(pending.proof[:])
|
||||
StartDelegateTransfer(pending, "/api/v1/delegated/sync", pending.body,
|
||||
pending.output, 3, pending.headers[:])
|
||||
StartDelegateTransfer(pending, path, pending.body, pending.output, 3, pending.headers[:], method, query)
|
||||
}
|
||||
|
||||
ConfigureTelegramRequest :: (pending: *PendingDelegate, operation: TelegramDelegateOperation,
|
||||
invoice_id: string) -> bool {
|
||||
invoice := operation == .InvoiceStatus || operation == .CancelInvoice
|
||||
if (invoice && !LowerHex(invoice_id, 32)) || (!invoice && invoice_id != "") {
|
||||
return false
|
||||
}
|
||||
path: Writer = .{pending.path[:], 0, true}
|
||||
query: Writer = .{pending.query[:], 0, true}
|
||||
pending.method = "POST"
|
||||
if operation == .Launch {
|
||||
path = WriteText(path, TelegramDelegateLaunchPath)
|
||||
} else if operation == .Catalog || operation == .Balance {
|
||||
pending.method = "GET"
|
||||
path = WriteText(path, ifx operation == .Catalog then TelegramDelegateCatalogPath else TelegramDelegateBalancePath)
|
||||
query = WriteText(WriteText(query, "app_id="), pending.client.app_id)
|
||||
} else if operation == .CreateInvoice || invoice {
|
||||
path = WriteText(path, TelegramDelegateInvoicesPath)
|
||||
if invoice {
|
||||
path = WriteText(WriteByte(path, cast(u8)47), invoice_id)
|
||||
if operation == .CancelInvoice {
|
||||
path = WriteText(path, "/cancel")
|
||||
} else {
|
||||
pending.method = "GET"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
return path.valid && query.valid && TelegramDelegateRequestValid(pending.client, pending.method,
|
||||
TextUntilNul(pending.path[:]), TextUntilNul(pending.query[:]), pending.body)
|
||||
}
|
||||
|
||||
InitializeDelegate :: (pending: *PendingDelegate, client: DelegateClient,
|
||||
session: *DelegateSession, now: s64, transport: AsyncTransport,
|
||||
output: []u8, session_only: bool, body: string) -> bool {
|
||||
output: []u8, session_only: bool, body: string,
|
||||
operation: TelegramDelegateOperation = .Unspecified, invoice_id: string = "") -> bool {
|
||||
if pending == null || session == null || pending.waiting ||
|
||||
transport.start == null || transport.poll == null || transport.cancel == null {
|
||||
return false
|
||||
@@ -95,7 +168,10 @@ InitializeDelegate :: (pending: *PendingDelegate, client: DelegateClient,
|
||||
pending.output = output
|
||||
pending.session_only = session_only
|
||||
pending.body = body
|
||||
if pending.now <= 0 || !DelegateClientValid(client) || output.count < 8192 || (!session_only && body.count == 0) {
|
||||
pending.telegram = operation != .Unspecified
|
||||
if pending.now <= 0 || !DelegateClientValid(client) || output.count < 8192 ||
|
||||
(pending.telegram && !ConfigureTelegramRequest(pending, operation, invoice_id)) ||
|
||||
(!pending.telegram && !session_only && body.count == 0) {
|
||||
FinishDelegate(pending, cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED)
|
||||
return true
|
||||
}
|
||||
@@ -103,7 +179,7 @@ InitializeDelegate :: (pending: *PendingDelegate, client: DelegateClient,
|
||||
if session_only {
|
||||
FinishDelegate(pending, cast(AuthResult)AuthResult.AUTH_OK)
|
||||
} else {
|
||||
StartDelegateSync(pending)
|
||||
StartDelegateRequest(pending)
|
||||
}
|
||||
} else {
|
||||
StartDelegateChallenge(pending)
|
||||
@@ -120,6 +196,14 @@ BeginDelegateRequest :: (pending: *PendingDelegate, client: DelegateClient,
|
||||
body: string, output: []u8) -> bool {
|
||||
return InitializeDelegate(pending, client, session, now, transport, output, false, body)
|
||||
}
|
||||
|
||||
BeginTelegramDelegateRequest :: (pending: *PendingDelegate, client: DelegateClient,
|
||||
session: *DelegateSession, transport: AsyncTransport, operation: TelegramDelegateOperation,
|
||||
invoice_id: string, body: string, output: []u8) -> bool {
|
||||
return operation != .Unspecified && InitializeDelegate(pending, client, session,
|
||||
0, transport, output, false, body, operation, invoice_id)
|
||||
}
|
||||
|
||||
PollDelegate :: (pending: *PendingDelegate) -> bool {
|
||||
if pending == null || pending.done {
|
||||
return true
|
||||
@@ -163,14 +247,14 @@ PollDelegate :: (pending: *PendingDelegate) -> bool {
|
||||
FinishDelegate(pending, result)
|
||||
return true
|
||||
}
|
||||
StartDelegateSync(pending)
|
||||
StartDelegateRequest(pending)
|
||||
} else if pending.stage == 3 {
|
||||
if pending.status == 401 || pending.status == 403 {
|
||||
ClearDelegateSession(pending.session)
|
||||
FinishDelegate(pending, cast(AuthResult)AuthResult.AUTH_FAILED)
|
||||
} else if pending.status < 200 || pending.status >= 300 {
|
||||
FinishDelegate(pending, cast(AuthResult)AuthResult.AUTH_REQUEST_FAILED)
|
||||
} else if !ResponseMatchesRequest(pending.client, pending.body, TextUntilNul(pending.output)) {
|
||||
} else if !pending.telegram && !ResponseMatchesRequest(pending.client, pending.body, TextUntilNul(pending.output)) {
|
||||
FinishDelegate(pending, cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED)
|
||||
} else {
|
||||
FinishDelegate(pending, cast(AuthResult)AuthResult.AUTH_OK)
|
||||
|
||||
+18
-5
@@ -34,6 +34,7 @@ Grant :: struct {
|
||||
nonce: string
|
||||
bot_id: s64
|
||||
telegram_id: s64
|
||||
telegram_stars: bool
|
||||
scopes: []GrantScope
|
||||
signature: string
|
||||
}
|
||||
@@ -62,6 +63,7 @@ GrantStorage :: struct {
|
||||
nonce: [33]u8
|
||||
bot_id: s64
|
||||
telegram_id: s64
|
||||
telegram_stars: bool
|
||||
scope_count: s32
|
||||
scopes: [16]ScopeStorage
|
||||
signature: [4841]u8
|
||||
@@ -223,7 +225,8 @@ GrantValid :: (grant: Grant, now: s64) -> bool {
|
||||
grant.scopes.count < 1 || grant.scopes.count > 16 ||
|
||||
grant.bot_id < 0 || grant.telegram_id < 0 ||
|
||||
grant.bot_id > 9007199254740991 || grant.telegram_id > 4503599627370495 ||
|
||||
((grant.bot_id == 0) != (grant.telegram_id == 0)) {
|
||||
((grant.bot_id == 0) != (grant.telegram_id == 0)) ||
|
||||
(grant.telegram_stars && grant.bot_id == 0) {
|
||||
return false
|
||||
}
|
||||
previous: string = ""
|
||||
@@ -266,6 +269,7 @@ ViewGrant :: (storage: *GrantStorage, scopes: []GrantScope, grant: *Grant) -> bo
|
||||
grant.nonce = TextUntilNul(storage.nonce[:])
|
||||
grant.bot_id = storage.bot_id
|
||||
grant.telegram_id = storage.telegram_id
|
||||
grant.telegram_stars = storage.telegram_stars
|
||||
grant.signature = TextUntilNul(storage.signature[:])
|
||||
for index: 0..storage.scope_count - 1 {
|
||||
source := *storage.scopes[index]
|
||||
@@ -324,6 +328,9 @@ BuildGrantMessage :: (grant: Grant, output: []u8) -> bool {
|
||||
writer = Line(writer, scope.key_id)
|
||||
writer = Line(writer, TextUntilNul(digest[:]))
|
||||
}
|
||||
if grant.telegram_stars {
|
||||
writer = Line(writer, "telegram-stars-purchases")
|
||||
}
|
||||
return writer.valid
|
||||
}
|
||||
JsonTextField :: (writer: Writer, name: string, value: string) -> Writer {
|
||||
@@ -396,6 +403,9 @@ BuildGrantBody :: (grant: Grant, output: []u8) -> bool {
|
||||
index += 1
|
||||
}
|
||||
writer = WriteText(writer, "],")
|
||||
if grant.telegram_stars {
|
||||
writer = WriteText(writer, "\"telegram_stars\":true,")
|
||||
}
|
||||
writer = JsonTextField(writer, "signature", grant.signature)
|
||||
writer = WriteByte(writer, cast(u8)125)
|
||||
return writer.valid
|
||||
@@ -516,13 +526,15 @@ ReadGrantAt :: (json: string, at: s32, storage: *GrantStorage) -> bool {
|
||||
return false
|
||||
}
|
||||
storage.* = GrantStorage.{}
|
||||
names: [18]string = .["version", "account_id", "grant_id", "request_id",
|
||||
names: [19]string = .["version", "account_id", "grant_id", "request_id",
|
||||
"app_id", "client_id", "node_id", "audience", "signing_key", "encryption_key",
|
||||
"issued_at", "not_before", "expires_at", "nonce", "bot_id", "telegram_id",
|
||||
"scopes", "signature"]
|
||||
positions: [18]s32
|
||||
"scopes", "signature", "telegram_stars"]
|
||||
positions: [19]s32
|
||||
version: s64
|
||||
if !ObjectFields(json, at, names[:], positions[:]) ||
|
||||
telegram_stars: bool
|
||||
if !ObjectFieldsMinimum(json, at, names[:], positions[:], 18) ||
|
||||
(positions[18] >= 0 && !ReadBool(json, positions[18], *telegram_stars)) ||
|
||||
!ReadInteger(json, positions[0], *version) || version != 1 ||
|
||||
ReadStringText(json, positions[1], storage.account_id[:]) < 0 ||
|
||||
ReadStringText(json, positions[2], storage.grant_id[:]) < 0 ||
|
||||
@@ -562,6 +574,7 @@ ReadGrantAt :: (json: string, at: s32, storage: *GrantStorage) -> bool {
|
||||
}
|
||||
}
|
||||
storage.scope_count = count
|
||||
storage.telegram_stars = telegram_stars
|
||||
return true
|
||||
}
|
||||
#scope_export
|
||||
|
||||
+97
-7
@@ -227,13 +227,76 @@ RequestRoute :: (method: string, path: string, query: string) -> bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
#scope_export
|
||||
TelegramDelegateLaunchPath :: "/api/v1/telegram/launch"
|
||||
TelegramDelegateCatalogPath :: "/api/v1/tokens/purchases/telegram/catalog"
|
||||
TelegramDelegateBalancePath :: "/api/v1/tokens/purchases/telegram/balance"
|
||||
TelegramDelegateInvoicesPath :: "/api/v1/tokens/purchases/telegram/invoices"
|
||||
|
||||
TelegramDelegateRequestValid :: (client: DelegateClient, method: string, path: string,
|
||||
query: string, body: string) -> bool {
|
||||
if client.bot_id <= 0 || client.telegram_id <= 0 {
|
||||
return false
|
||||
}
|
||||
if path == TelegramDelegateCatalogPath || path == TelegramDelegateBalancePath {
|
||||
prefix := "app_id="
|
||||
return method == "GET" && body == "" && Namespace(client.app_id) &&
|
||||
query.count > prefix.count && query[:prefix.count] == prefix && query[prefix.count:] == client.app_id
|
||||
}
|
||||
if query != "" {
|
||||
return false
|
||||
}
|
||||
if path == TelegramDelegateLaunchPath || path == TelegramDelegateInvoicesPath {
|
||||
if method != "POST" || body.count > 32768 || !WholeJson(body) {
|
||||
return false
|
||||
}
|
||||
names: [4]string = .["app_id", "init_data", "product_id", "request_id"]
|
||||
positions: [4]s32
|
||||
count := ifx path == TelegramDelegateLaunchPath then 2 else 4
|
||||
app: [65]u8
|
||||
return ObjectFields(body, 0, names[:count], positions[:count]) &&
|
||||
ReadStringText(body, positions[0], app[:]) >= 0 && TextUntilNul(app[:]) == client.app_id
|
||||
}
|
||||
prefix := "/api/v1/tokens/purchases/telegram/invoices/"
|
||||
if body != "" || path.count <= prefix.count || path[:prefix.count] != prefix {
|
||||
return false
|
||||
}
|
||||
id := path[prefix.count:]
|
||||
if method == "GET" {
|
||||
return LowerHex(id, 32)
|
||||
}
|
||||
return method == "POST" && id.count == 39 && id[32:] == "/cancel" && LowerHex(id[:32], 32)
|
||||
}
|
||||
|
||||
DelegateTelegramStarsAllowed :: (client: DelegateClient) -> bool {
|
||||
if !DelegateClientValid(client) || client.bot_id <= 0 || client.telegram_id <= 0 {
|
||||
return false
|
||||
}
|
||||
grant := client.grant
|
||||
now := CurrentDelegateTime(client)
|
||||
return now > 0 && grant.version == 1 && grant.telegram_stars &&
|
||||
grant.not_before <= now && grant.expires_at > now &&
|
||||
grant.bot_id == client.bot_id && grant.telegram_id == client.telegram_id &&
|
||||
TextUntilNul(grant.account_id[:]) == client.account_id && TextUntilNul(grant.app_id[:]) == client.app_id &&
|
||||
TextUntilNul(grant.grant_id[:]) == client.grant_id && TextUntilNul(grant.client_id[:]) == client.client_id &&
|
||||
TextUntilNul(grant.node_id[:]) == client.node_id && TextUntilNul(grant.audience[:]) == client.audience &&
|
||||
TextUntilNul(grant.signing_key[:]) == client.signing_key &&
|
||||
TextUntilNul(grant.encryption_key[:]) == client.encryption_key
|
||||
}
|
||||
|
||||
#scope_export
|
||||
BuildProofMessage :: (proof: RequestProof, output: []u8) -> bool {
|
||||
return RequestRoute(proof.method, proof.path, proof.query) && BuildBoundProofMessage(proof, output)
|
||||
}
|
||||
|
||||
#scope_file
|
||||
BuildBoundProofMessage :: (proof: RequestProof, output: []u8) -> bool {
|
||||
if output.count == 0 || !LowerHex(proof.grant_id, 32) ||
|
||||
!LowerHex(proof.session_id, 32) || !LowerHex(proof.account_id, 64) ||
|
||||
!Namespace(proof.app_id) || !LowerHex(proof.client_id, 64) ||
|
||||
!LowerHex(proof.node_id, 64) || !LineText(proof.audience, 512) ||
|
||||
!LowerHex(proof.challenge, 32) || !RequestRoute(proof.method, proof.path, proof.query) ||
|
||||
!LowerHex(proof.challenge, 32) ||
|
||||
!LowerHex(proof.body_sha256, 64) || proof.expires_at <= 0 || !LowerHex(proof.nonce, 32) {
|
||||
return false
|
||||
}
|
||||
@@ -258,11 +321,13 @@ BuildProofMessage :: (proof: RequestProof, output: []u8) -> bool {
|
||||
}
|
||||
#scope_export
|
||||
BuildProofHeader :: (proof: RequestProof, signature: string, output: []u8) -> bool {
|
||||
if output.count == 0 || !LowerHex(signature, 128) {
|
||||
return false
|
||||
}
|
||||
checked: [2048]u8
|
||||
if !BuildProofMessage(proof, checked[:]) {
|
||||
return BuildProofMessage(proof, checked[:]) && WriteProofHeader(proof, signature, output)
|
||||
}
|
||||
|
||||
#scope_file
|
||||
WriteProofHeader :: (proof: RequestProof, signature: string, output: []u8) -> bool {
|
||||
if output.count == 0 || !LowerHex(signature, 128) {
|
||||
return false
|
||||
}
|
||||
output[0] = 0
|
||||
@@ -516,6 +581,30 @@ PrepareDelegateHeaders :: (client: DelegateClient, session: *DelegateSession, no
|
||||
(method == "GET" && (body != "" || ScopeIndex(client, query[11:query.count], false) < 0)) {
|
||||
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
||||
}
|
||||
return PrepareBoundDelegateHeaders(client, session, now, method, path, query, body, proof_header, credential)
|
||||
}
|
||||
|
||||
#scope_export
|
||||
PrepareTelegramDelegateHeaders :: (client: DelegateClient, session: *DelegateSession,
|
||||
method: string, path: string, query: string, body: string,
|
||||
proof_header: []u8, credential: []u8) -> AuthResult {
|
||||
now := CurrentDelegateTime(client)
|
||||
if proof_header.count > 0 { proof_header[0] = 0 }
|
||||
if credential.count > 0 { credential[0] = 0 }
|
||||
if now <= 0 || !SessionValid(client, session, now) || proof_header.count == 0 || credential.count < 46 ||
|
||||
!TelegramDelegateRequestValid(client, method, path, query, body) {
|
||||
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
|
||||
}
|
||||
if path != TelegramDelegateLaunchPath && !DelegateTelegramStarsAllowed(client) {
|
||||
return cast(AuthResult)AuthResult.AUTH_FAILED
|
||||
}
|
||||
return PrepareBoundDelegateHeaders(client, session, now, method, path, query, body, proof_header, credential)
|
||||
}
|
||||
|
||||
#scope_file
|
||||
PrepareBoundDelegateHeaders :: (client: DelegateClient, session: *DelegateSession, now: s64,
|
||||
method: string, path: string, query: string, body: string,
|
||||
proof_header: []u8, credential: []u8) -> AuthResult {
|
||||
nonce: [33]u8
|
||||
digest: [65]u8
|
||||
if !client.random(client.random_context, nonce[:]) ||
|
||||
@@ -543,10 +632,10 @@ PrepareDelegateHeaders :: (client: DelegateClient, session: *DelegateSession, no
|
||||
proof.nonce = TextUntilNul(nonce[:])
|
||||
message: [2048]u8
|
||||
signature: [129]u8
|
||||
if !BuildProofMessage(proof, message[:]) ||
|
||||
if !BuildBoundProofMessage(proof, message[:]) ||
|
||||
!client.signer(client.signing_context, TextUntilNul(message[:]), signature[:]) ||
|
||||
!LowerHex(TextUntilNul(signature[:]), 128) ||
|
||||
!BuildProofHeader(proof, TextUntilNul(signature[:]), proof_header) ||
|
||||
!WriteProofHeader(proof, TextUntilNul(signature[:]), proof_header) ||
|
||||
!DelegateExpiryCurrent(client, proof.expires_at) {
|
||||
return cast(AuthResult)AuthResult.AUTH_SIGN_FAILED
|
||||
}
|
||||
@@ -558,6 +647,7 @@ PrepareDelegateHeaders :: (client: DelegateClient, session: *DelegateSession, no
|
||||
}
|
||||
return cast(AuthResult)AuthResult.AUTH_OK
|
||||
}
|
||||
|
||||
#scope_export
|
||||
RenewDelegateSession :: (client: DelegateClient, session: *DelegateSession,
|
||||
now: s64, response: []u8) -> AuthResult {
|
||||
|
||||
@@ -24,6 +24,28 @@ static bool active, failed_transport;
|
||||
static int64_t clock_now = 1791400000;
|
||||
static int64_t server_advance, challenge_delivery_delay, session_delivery_delay, sign_advance;
|
||||
static bool dynamic_timing;
|
||||
|
||||
typedef struct {
|
||||
TelegramDelegateOperation operation;
|
||||
const char *method, *path, *query, *invoice_id, *body;
|
||||
int32_t status;
|
||||
} TelegramRequestCase;
|
||||
|
||||
static const TelegramRequestCase telegram_cases[] = {
|
||||
{TelegramDelegateOperation_Launch, "POST", "/api/v1/telegram/launch", "", "",
|
||||
"{\"app_id\":\"inbe\",\"init_data\":\"synthetic\"}", 200},
|
||||
{TelegramDelegateOperation_Catalog, "GET", "/api/v1/tokens/purchases/telegram/catalog", "app_id=inbe", "", "", 200},
|
||||
{TelegramDelegateOperation_Balance, "GET", "/api/v1/tokens/purchases/telegram/balance", "app_id=inbe", "", "", 200},
|
||||
{TelegramDelegateOperation_CreateInvoice, "POST", "/api/v1/tokens/purchases/telegram/invoices", "", "",
|
||||
"{\"app_id\":\"inbe\",\"init_data\":\"synthetic\",\"product_id\":\"dew_10\",\"request_id\":\"test-order\"}", 201},
|
||||
{TelegramDelegateOperation_InvoiceStatus, "GET", "/api/v1/tokens/purchases/telegram/invoices/0123456789abcdef0123456789abcdef",
|
||||
"", "0123456789abcdef0123456789abcdef", "", 200},
|
||||
{TelegramDelegateOperation_CancelInvoice, "POST", "/api/v1/tokens/purchases/telegram/invoices/0123456789abcdef0123456789abcdef/cancel",
|
||||
"", "0123456789abcdef0123456789abcdef", "", 200},
|
||||
};
|
||||
|
||||
static const TelegramRequestCase *expected_telegram_request;
|
||||
static char telegram_signed_message[2048];
|
||||
static int64_t current_time(void *context)
|
||||
{
|
||||
(void)context;
|
||||
@@ -88,6 +110,10 @@ static bool sign_delegate(void *context, String message, Slice output)
|
||||
if (StringEqual(message, text(expected_session_message))) {
|
||||
copy_output(output, session_signature);
|
||||
} else {
|
||||
if (expected_telegram_request && message.length < sizeof telegram_signed_message) {
|
||||
memcpy(telegram_signed_message, message.data, message.length);
|
||||
telegram_signed_message[message.length] = 0;
|
||||
}
|
||||
clock_now += sign_advance;
|
||||
memset(output.data, 'a', 128);
|
||||
((char *)output.data)[128] = 0;
|
||||
@@ -150,6 +176,54 @@ static bool start(void *context, HttpRequest request, Slice output)
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool start_telegram(void *context, HttpRequest request, Slice output)
|
||||
{
|
||||
const TelegramRequestCase *expected = expected_telegram_request;
|
||||
assert(expected);
|
||||
if (strstr(request.url.data, "/api/v1/authorization/")) {
|
||||
return start(context, request, output);
|
||||
}
|
||||
DelegateClient *linked = context;
|
||||
assert(!active && request.token.length == 0 && request.headers.length == 2);
|
||||
assert(StringEqual(request.method, text(expected->method)) && StringEqual(request.body, text(expected->body)));
|
||||
char url[768];
|
||||
int length = snprintf(url, sizeof url, "%.*s%s%s%s", (int)linked->audience.length, linked->audience.data,
|
||||
expected->path, *expected->query ? "?" : "", expected->query);
|
||||
assert(length > 0 && length < (int)sizeof url && StringEqual(request.url, text(url)));
|
||||
HttpHeader *headers = request.headers.data;
|
||||
assert(StringEqual(headers[0].name, text("Authorization")) && headers[0].value.length == 45);
|
||||
assert(strncmp(headers[0].value.data, "Delegate ds1.", 13) == 0);
|
||||
assert(StringEqual(headers[1].name, text("X-Mesh-Delegate")));
|
||||
String proof = headers[1].value;
|
||||
char method[8], path[105], query[72], digest[65], computed[65], nonce[33], challenge[33];
|
||||
field(proof, "method", method, sizeof method);
|
||||
field(proof, "path", path, sizeof path);
|
||||
field(proof, "query", query, sizeof query);
|
||||
field(proof, "body_sha256", digest, sizeof digest);
|
||||
field(proof, "nonce", nonce, sizeof nonce);
|
||||
field(proof, "challenge", challenge, sizeof challenge);
|
||||
Sha256Hex((uint8_t *)expected->body, strlen(expected->body), (uint8_t *)computed);
|
||||
assert(strcmp(method, expected->method) == 0 && strcmp(path, expected->path) == 0 && strcmp(query, expected->query) == 0);
|
||||
assert(strcmp(digest, computed) == 0);
|
||||
int64_t expires;
|
||||
assert(MESH_AUTHORIZATION_SYMBOL(ReadInteger)(proof, FieldAt(proof, 0, text("expires_at")), &expires));
|
||||
assert(expires > clock_now && expires <= clock_now + 60);
|
||||
char canonical[2048];
|
||||
length = snprintf(canonical, sizeof canonical,
|
||||
"daochi-delegate-request-v1\n1\n%s\n%.32s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%lld\n%s\n",
|
||||
(char *)linked->grant->grant_id, headers[0].value.data + 13, (char *)linked->grant->account_id,
|
||||
(char *)linked->grant->app_id, (char *)linked->grant->client_id, (char *)linked->grant->node_id,
|
||||
(char *)linked->grant->audience, challenge,
|
||||
method, path, query, digest, (long long)expires, nonce);
|
||||
assert(length > 0 && length < (int)sizeof canonical && strcmp(canonical, telegram_signed_message) == 0);
|
||||
active = true;
|
||||
transfers++;
|
||||
polls = 0;
|
||||
stage = 3;
|
||||
copy_output(output, "{\"fixture\":true}");
|
||||
return true;
|
||||
}
|
||||
|
||||
static int32_t poll(void *context, int32_t *status)
|
||||
{
|
||||
(void)context;
|
||||
@@ -193,6 +267,11 @@ static bool start_async(void *closure, void *context, HttpRequest request, Slice
|
||||
(void)closure;
|
||||
return start(context, request, output);
|
||||
}
|
||||
static bool start_telegram_async(void *closure, void *context, HttpRequest request, Slice output)
|
||||
{
|
||||
(void)closure;
|
||||
return start_telegram(context, request, output);
|
||||
}
|
||||
static int32_t poll_async(void *closure, void *context, int32_t *status)
|
||||
{
|
||||
(void)closure;
|
||||
@@ -589,6 +668,70 @@ static void check_advancing_clock(void)
|
||||
dynamic_timing = false;
|
||||
}
|
||||
|
||||
static void check_telegram_async(DelegateClient *linked, DelegateSession *session, bool stars)
|
||||
{
|
||||
PendingDelegate pending = {0};
|
||||
AsyncTransport transport = {.context = linked, .start = {.call = start_telegram_async},
|
||||
.poll = {.call = poll_async}, .cancel = {.call = cancel_async}};
|
||||
char output[18000], proof[4096] = "previous", credential[46] = "previous";
|
||||
assert(MESH_DELEGATED_SYMBOL(DelegateTelegramStarsAllowed)(*linked) == stars);
|
||||
for (size_t i = 0; i < sizeof telegram_cases / sizeof telegram_cases[0]; i++) {
|
||||
const TelegramRequestCase *test = &telegram_cases[i];
|
||||
expected_telegram_request = test;
|
||||
response_status = test->status;
|
||||
int before = transfers;
|
||||
assert(MESH_ASYNC_DELEGATED_SYMBOL(BeginTelegramDelegateRequest)(&pending, *linked, session, transport,
|
||||
test->operation, text(test->invoice_id), text(test->body), bytes(output, sizeof output)));
|
||||
if (stars || test->operation == TelegramDelegateOperation_Launch) {
|
||||
assert(!MESH_ASYNC_DELEGATED_SYMBOL(PollDelegate)(&pending));
|
||||
assert(MESH_ASYNC_DELEGATED_SYMBOL(PollDelegate)(&pending));
|
||||
assert(pending.result == AuthResult_AUTH_OK && pending.status == test->status && transfers == before + 1);
|
||||
assert(strcmp(output, "{\"fixture\":true}") == 0 && pending.body.length == 0);
|
||||
} else {
|
||||
assert(MESH_ASYNC_DELEGATED_SYMBOL(PollDelegate)(&pending));
|
||||
assert(pending.result == AuthResult_AUTH_FAILED && transfers == before);
|
||||
}
|
||||
}
|
||||
assert(MESH_DELEGATED_SYMBOL(PrepareDelegateHeaders)(*linked, session, 0, text("GET"), text(telegram_cases[2].path),
|
||||
text("app_id=inbe"), text(""), bytes(proof, sizeof proof), bytes(credential, sizeof credential)) != AuthResult_AUTH_OK);
|
||||
const char *bad[][4] = {
|
||||
{"POST", "/api/v1/tokens/purchases/telegram/balance", "app_id=inbe", ""},
|
||||
{"GET", "/api/v1/tokens/purchases/telegram/balance", "app_id=other", ""},
|
||||
{"GET", "/api/v1/tokens/purchases/telegram/balance", "app_id=inbe&app_id=inbe", ""},
|
||||
{"GET", "/api/v1/tokens/balance", "app_id=inbe", ""},
|
||||
{"POST", "/api/v1/tokens/purchases/telegram/invoices/0123456789abcdef0123456789abcdef", "", ""},
|
||||
{"GET", "/api/v1/tokens/purchases/telegram/invoices/0123456789abcdef0123456789abcdef/cancel", "", ""},
|
||||
{"POST", "/api/v1/telegram/launch", "", "{\"app_id\":\"other\",\"init_data\":\"synthetic\"}"},
|
||||
};
|
||||
for (size_t i = 0; i < sizeof bad / sizeof bad[0]; i++) {
|
||||
assert(MESH_DELEGATED_SYMBOL(PrepareTelegramDelegateHeaders)(*linked, session, text(bad[i][0]), text(bad[i][1]),
|
||||
text(bad[i][2]), text(bad[i][3]), bytes(proof, sizeof proof), bytes(credential, sizeof credential)) == AuthResult_AUTH_PAYLOAD_FAILED);
|
||||
assert(!proof[0] && !credential[0]);
|
||||
}
|
||||
if (stars) {
|
||||
expected_telegram_request = &telegram_cases[2];
|
||||
assert(MESH_ASYNC_DELEGATED_SYMBOL(BeginTelegramDelegateRequest)(&pending, *linked, session, transport,
|
||||
TelegramDelegateOperation_Balance, text(""), text(""), bytes(output, sizeof output)));
|
||||
int previous_cancels = cancels;
|
||||
MESH_ASYNC_DELEGATED_SYMBOL(CancelDelegate)(&pending);
|
||||
MESH_ASYNC_DELEGATED_SYMBOL(CancelDelegate)(&pending);
|
||||
assert(!active && cancels == previous_cancels + 1 && pending.result == AuthResult_AUTH_REQUEST_FAILED);
|
||||
failed_transport = true;
|
||||
assert(MESH_ASYNC_DELEGATED_SYMBOL(BeginTelegramDelegateRequest)(&pending, *linked, session, transport,
|
||||
TelegramDelegateOperation_Balance, text(""), text(""), bytes(output, sizeof output)));
|
||||
assert(!MESH_ASYNC_DELEGATED_SYMBOL(PollDelegate)(&pending));
|
||||
assert(MESH_ASYNC_DELEGATED_SYMBOL(PollDelegate)(&pending) && pending.result == AuthResult_AUTH_REQUEST_FAILED);
|
||||
failed_transport = false;
|
||||
response_status = 403;
|
||||
assert(MESH_ASYNC_DELEGATED_SYMBOL(BeginTelegramDelegateRequest)(&pending, *linked, session, transport,
|
||||
TelegramDelegateOperation_Balance, text(""), text(""), bytes(output, sizeof output)));
|
||||
assert(!MESH_ASYNC_DELEGATED_SYMBOL(PollDelegate)(&pending));
|
||||
assert(MESH_ASYNC_DELEGATED_SYMBOL(PollDelegate)(&pending));
|
||||
assert(pending.status == 403 && pending.result == AuthResult_AUTH_FAILED && !session->session_id[0]);
|
||||
}
|
||||
expected_telegram_request = NULL;
|
||||
}
|
||||
|
||||
static void check_telegram_binding(String document)
|
||||
{
|
||||
AccountKeys owner;
|
||||
@@ -616,6 +759,74 @@ static void check_telegram_binding(String document)
|
||||
DelegateSession session;
|
||||
assert(MESH_DELEGATED_SYMBOL(AcceptSessionAnswer)(telegram, 200, text(telegram_answer), 1,
|
||||
&session) == AuthResult_AUTH_OK);
|
||||
assert(!telegram.grant->telegram_stars);
|
||||
check_telegram_async(&telegram, &session, false);
|
||||
|
||||
char explicit_false[18000];
|
||||
count = snprintf(explicit_false, sizeof explicit_false,
|
||||
"{\"credential\":%.*s,\"grant\":%.*s,\"telegram_stars\":false},\"owner_public_key\":\"%s\"}",
|
||||
(int)credential.length, credential.data, (int)strlen(grant_json) - 1, grant_json, owner.public_key_hex);
|
||||
assert(count > 0 && count < (int)sizeof explicit_false);
|
||||
assert(MESH_DELEGATED_SYMBOL(AcceptSessionAnswer)(telegram, 200, text(explicit_false), 1,
|
||||
&session) == AuthResult_AUTH_OK && !telegram.grant->telegram_stars);
|
||||
|
||||
grant.telegram_stars = true;
|
||||
char extended_message[8192];
|
||||
assert(MESH_AUTHORIZATION_SYMBOL(BuildGrantMessage)(grant, bytes(extended_message, sizeof extended_message)));
|
||||
assert(strncmp(message, extended_message, strlen(message)) == 0);
|
||||
assert(strcmp(extended_message + strlen(message), "telegram-stars-purchases\n") == 0);
|
||||
assert(!MESH_AUTHORIZATION_SYMBOL(VerifyGrantSignature)(grant, text((char *)owner.public_key_hex), clock_now));
|
||||
Client approval = {.app_id = grant.app_id, .identity = {.account_id = grant.account_id, .signing_context = &owner},
|
||||
.signer = SignAccountMessage};
|
||||
assert(MESH_AUTHORIZATION_OWNER_SYMBOL(PrepareGrantApproval)(approval, grant, bytes(grant_json, sizeof grant_json)) == AuthResult_AUTH_OK);
|
||||
assert(strstr(grant_json, "\"telegram_stars\":true"));
|
||||
count = snprintf(telegram_answer, sizeof telegram_answer,
|
||||
"{\"credential\":%.*s,\"grant\":%s,\"owner_public_key\":\"%s\"}",
|
||||
(int)credential.length, credential.data, grant_json, owner.public_key_hex);
|
||||
assert(count > 0 && count < (int)sizeof telegram_answer);
|
||||
char edited_answer[18000];
|
||||
strcpy(edited_answer, telegram_answer);
|
||||
char *modified_flag = strstr(edited_answer, "\"telegram_stars\":true");
|
||||
assert(modified_flag);
|
||||
memcpy(strchr(modified_flag, ':') + 1, "null", 4);
|
||||
assert(MESH_DELEGATED_SYMBOL(AcceptSessionAnswer)(telegram, 200, text(edited_answer), 1,
|
||||
&session) == AuthResult_AUTH_PAYLOAD_FAILED);
|
||||
memcpy(strchr(modified_flag, ':') + 1, "0 ", 4);
|
||||
assert(MESH_DELEGATED_SYMBOL(AcceptSessionAnswer)(telegram, 200, text(edited_answer), 1,
|
||||
&session) == AuthResult_AUTH_PAYLOAD_FAILED);
|
||||
memcpy(strchr(modified_flag, ':') + 1, "true", 4);
|
||||
char *next_field = strchr(strchr(modified_flag, ':') + 1, ',');
|
||||
const char duplicate[] = ",\"telegram_\\u0073tars\":false";
|
||||
memmove(next_field + sizeof duplicate - 1, next_field, strlen(next_field) + 1);
|
||||
memcpy(next_field, duplicate, sizeof duplicate - 1);
|
||||
assert(MESH_DELEGATED_SYMBOL(AcceptSessionAnswer)(telegram, 200, text(edited_answer), 1,
|
||||
&session) == AuthResult_AUTH_PAYLOAD_FAILED);
|
||||
assert(MESH_DELEGATED_SYMBOL(AcceptSessionAnswer)(telegram, 200, text(telegram_answer), 1,
|
||||
&session) == AuthResult_AUTH_OK);
|
||||
assert(telegram.grant->telegram_stars);
|
||||
check_telegram_async(&telegram, &session, true);
|
||||
|
||||
strcpy(answer, telegram_answer);
|
||||
char output[18000];
|
||||
PendingDelegate pending = {0};
|
||||
AsyncTransport transport = {.context = &telegram, .start = {.call = start_telegram_async},
|
||||
.poll = {.call = poll_async}, .cancel = {.call = cancel_async}};
|
||||
expected_telegram_request = &telegram_cases[2];
|
||||
response_status = 200;
|
||||
int before = transfers;
|
||||
assert(!session.session_id[0]);
|
||||
assert(MESH_ASYNC_DELEGATED_SYMBOL(BeginTelegramDelegateRequest)(&pending, telegram, &session, transport,
|
||||
TelegramDelegateOperation_Balance, text(""), text(""), bytes(output, sizeof output)));
|
||||
for (int i = 0; i < 9 && !pending.done; i++) {
|
||||
MESH_ASYNC_DELEGATED_SYMBOL(PollDelegate)(&pending);
|
||||
}
|
||||
assert(pending.done && pending.result == AuthResult_AUTH_OK && transfers == before + 3);
|
||||
expected_telegram_request = NULL;
|
||||
|
||||
int64_t previous_clock = clock_now;
|
||||
clock_now = telegram.grant->expires_at;
|
||||
assert(!MESH_DELEGATED_SYMBOL(DelegateTelegramStarsAllowed)(telegram));
|
||||
clock_now = previous_clock;
|
||||
telegram.bot_id = 123457;
|
||||
assert(MESH_DELEGATED_SYMBOL(AcceptSessionAnswer)(telegram, 200, text(telegram_answer), 1,
|
||||
&session) == AuthResult_AUTH_FAILED);
|
||||
|
||||
Reference in new issue
Block a user